language stringclasses 1
value | repo stringclasses 346
values | path stringlengths 6 201 | class_span dict | source stringlengths 21 2.38M | target stringlengths 1 96 |
|---|---|---|---|---|---|
python | ray-project__ray | python/ray/serve/_private/benchmarks/streaming/streaming_core_throughput.py | {
"start": 173,
"end": 277
} | class ____(Endpoint):
pass
# @ray.remote(runtime_env=GRPC_DEBUG_RUNTIME_ENV)
@ray.remote
| EndpointActor |
python | django__django | tests/model_fields/models.py | {
"start": 5123,
"end": 5236
} | class ____(models.Model):
modelname = models.IntegerField(name="fieldname", choices=((1, "One"),))
| RenamedField |
python | mahmoud__boltons | boltons/iterutils.py | {
"start": 44503,
"end": 49886
} | class ____(KeyError, IndexError, TypeError):
"""An amalgamation of KeyError, IndexError, and TypeError,
representing what can occur when looking up a path in a nested
object.
"""
def __init__(self, exc, seg, path):
self.exc = exc
self.seg = seg
self.path = path
def __repr__(self):
cn = self.__class__.__name__
return f'{cn}({self.exc!r}, {self.seg!r}, {self.path!r})'
def __str__(self):
return ('could not access %r from path %r, got error: %r'
% (self.seg, self.path, self.exc))
def get_path(root, path, default=_UNSET):
"""Retrieve a value from a nested object via a tuple representing the
lookup path.
>>> root = {'a': {'b': {'c': [[1], [2], [3]]}}}
>>> get_path(root, ('a', 'b', 'c', 2, 0))
3
The path tuple format is intentionally consistent with that of
:func:`remap`, but a single dotted string can also be passed.
One of get_path's chief aims is improved error messaging. EAFP is
great, but the error messages are not.
For instance, ``root['a']['b']['c'][2][1]`` gives back
``IndexError: list index out of range``
What went out of range where? get_path currently raises
``PathAccessError: could not access 2 from path ('a', 'b', 'c', 2,
1), got error: IndexError('list index out of range',)``, a
subclass of IndexError and KeyError.
You can also pass a default that covers the entire operation,
should the lookup fail at any level.
Args:
root: The target nesting of dictionaries, lists, or other
objects supporting ``__getitem__``.
path (tuple): A sequence of strings and integers to be successively
looked up within *root*. A dot-separated (``a.b``) string may
also be passed.
default: The value to be returned should any
``PathAccessError`` exceptions be raised.
"""
if isinstance(path, str):
path = path.split('.')
cur = root
try:
for seg in path:
try:
cur = cur[seg]
except (KeyError, IndexError) as exc:
raise PathAccessError(exc, seg, path)
except TypeError as exc:
# either string index in a list, or a parent that
# doesn't support indexing
try:
seg = int(seg)
cur = cur[seg]
except (ValueError, KeyError, IndexError, TypeError):
if not is_iterable(cur):
exc = TypeError('%r object is not indexable'
% type(cur).__name__)
raise PathAccessError(exc, seg, path)
except PathAccessError:
if default is _UNSET:
raise
return default
return cur
def research(root, query=lambda p, k, v: True, reraise=False, enter=default_enter):
"""The :func:`research` function uses :func:`remap` to recurse over
any data nested in *root*, and find values which match a given
criterion, specified by the *query* callable.
Results are returned as a list of ``(path, value)`` pairs. The
paths are tuples in the same format accepted by
:func:`get_path`. This can be useful for comparing values nested
in two or more different structures.
Here's a simple example that finds all integers:
>>> root = {'a': {'b': 1, 'c': (2, 'd', 3)}, 'e': None}
>>> res = research(root, query=lambda p, k, v: isinstance(v, int))
>>> print(sorted(res))
[(('a', 'b'), 1), (('a', 'c', 0), 2), (('a', 'c', 2), 3)]
Note how *query* follows the same, familiar ``path, key, value``
signature as the ``visit`` and ``enter`` functions on
:func:`remap`, and returns a :class:`bool`.
Args:
root: The target object to search. Supports the same types of
objects as :func:`remap`, including :class:`list`,
:class:`tuple`, :class:`dict`, and :class:`set`.
query (callable): The function called on every object to
determine whether to include it in the search results. The
callable must accept three arguments, *path*, *key*, and
*value*, commonly abbreviated *p*, *k*, and *v*, same as
*enter* and *visit* from :func:`remap`.
reraise (bool): Whether to reraise exceptions raised by *query*
or to simply drop the result that caused the error.
With :func:`research` it's easy to inspect the details of a data
structure, like finding values that are at a certain depth (using
``len(p)``) and much more. If more advanced functionality is
needed, check out the code and make your own :func:`remap`
wrapper, and consider `submitting a patch`_!
.. _submitting a patch: https://github.com/mahmoud/boltons/pulls
"""
ret = []
if not callable(query):
raise TypeError('query expected callable, not: %r' % query)
def _enter(path, key, value):
try:
if query(path, key, value):
ret.append((path + (key,), value))
except Exception:
if reraise:
raise
return enter(path, key, value)
remap(root, enter=_enter)
return ret
# TODO: recollect()
# TODO: refilter()
# TODO: reiter()
# GUID iterators: 10x faster and somewhat more compact than uuid.
| PathAccessError |
python | getsentry__sentry | tests/sentry/db/postgres/schema/safe_migrations/integration/test_migrations.py | {
"start": 12753,
"end": 13118
} | class ____(BaseSafeMigrationTest):
app = "bad_flow_delete_field_double_pending_app"
migrate_from = "0001"
migrate_to = "0003"
def test(self) -> None:
with pytest.raises(
FieldDoesNotExist,
match="TestTable has no field named 'field'",
):
self.run_migration()
| DeletionFieldBadDeleteDoublePendingTest |
python | getsentry__sentry | tests/sentry/web/frontend/test_auth_login.py | {
"start": 1458,
"end": 20746
} | class ____(TestCase, HybridCloudTestMixin):
@cached_property
def path(self) -> str:
return reverse("sentry-login")
def allow_registration(self):
return self.options({"auth.allow-registration": True})
def test_renders_correct_template(self) -> None:
resp = self.client.get(self.path)
assert resp.status_code == 200
self.assertTemplateUsed("sentry/login.html")
def test_cannot_request_access(self) -> None:
resp = self.client.get(self.path)
assert resp.status_code == 200
assert resp.context["join_request_link"] is None
def test_renders_session_expire_message(self) -> None:
self.client.cookies["session_expired"] = "1"
resp = self.client.get(self.path)
assert resp.status_code == 200
self.assertTemplateUsed(resp, "sentry/login.html")
messages = list(resp.context["messages"])
assert len(messages) == 1
assert messages[0].message == "Your session has expired."
def test_login_invalid_password(self) -> None:
# load it once for test cookie
self.client.get(self.path)
resp = self.client.post(
self.path, {"username": self.user.username, "password": "bizbar", "op": "login"}
)
assert resp.status_code == 200
assert resp.context["login_form"].errors["__all__"] == [
"Please enter a correct username and password. Note that both fields may be case-sensitive."
]
@override_settings(SENTRY_SELF_HOSTED=False)
def test_login_ratelimited_ip_gets(self) -> None:
url = reverse("sentry-login")
with freeze_time("2000-01-01"):
for _ in range(25):
self.client.get(url)
resp = self.client.get(url)
assert resp.status_code == 429
def test_login_ratelimited_user(self) -> None:
self.client.get(self.path)
# Make sure user gets ratelimited
for i in range(5):
self.client.post(
self.path,
{"username": self.user.username, "password": "wront_password", "op": "login"},
follow=True,
)
resp = self.client.post(
self.path,
{"username": self.user.username, "password": "admin", "op": "login"},
follow=True,
)
assert resp.status_code == 200
assert resp.redirect_chain == []
assert (
"You have made too many login attempts. Please try again later."
in resp.content.decode()
)
def test_login_valid_credentials(self) -> None:
# load it once for test cookie
self.client.get(self.path)
resp = self.client.post(
self.path,
{"username": self.user.username, "password": "admin", "op": "login"},
follow=True,
)
assert resp.status_code == 200
assert resp.redirect_chain == [
(reverse("sentry-login"), 302),
("/organizations/new/", 302),
]
def test_login_valid_credentials_with_org(self) -> None:
org = self.create_organization(owner=self.user)
# load it once for test cookie
self.client.get(self.path)
resp = self.client.post(
self.path,
{"username": self.user.username, "password": "admin", "op": "login"},
follow=True,
)
assert resp.status_code == 200
assert resp.redirect_chain == [
(reverse("sentry-login"), 302),
(f"/organizations/{org.slug}/issues/", 302),
]
def test_login_valid_credentials_2fa_redirect(self) -> None:
user = self.create_user("bar@example.com")
RecoveryCodeInterface().enroll(user)
TotpInterface().enroll(user)
self.create_member(organization=self.organization, user=user)
self.client.get(self.path)
resp = self.client.post(
self.path,
{"username": user.username, "password": "admin", "op": "login"},
follow=True,
)
assert resp.status_code == 200
assert resp.redirect_chain == [(reverse("sentry-2fa-dialog"), 302)]
with mock.patch("sentry.auth.authenticators.TotpInterface.validate_otp", return_value=True):
resp = self.client.post(reverse("sentry-2fa-dialog"), {"otp": "something"}, follow=True)
assert resp.status_code == 200
assert resp.redirect_chain == [
(reverse("sentry-login"), 302),
("/organizations/baz/issues/", 302),
]
@with_feature("system:multi-region")
def test_login_valid_credentials_with_org_and_customer_domains(self) -> None:
org = self.create_organization(owner=self.user)
# load it once for test cookie
self.client.get(self.path)
resp = self.client.post(
self.path,
{"username": self.user.username, "password": "admin", "op": "login"},
follow=True,
)
assert resp.status_code == 200
assert resp.redirect_chain == [
(f"http://{org.slug}.testserver/auth/login/", 302),
(f"http://{org.slug}.testserver/issues/", 302),
]
@with_feature("system:multi-region")
def test_redirect_to_login_with_org_and_customer_domains(self) -> None:
org = self.create_organization(owner=self.user)
self.create_project(organization=org, name="project")
# load it once for test cookie
self.client.get(self.path)
project_path = reverse("project-details", kwargs={"project_slug": "project"})
resp = self.client.get(project_path, HTTP_HOST=f"{org.slug}.testserver")
assert resp.status_code == 302
# redirect to auth org login page by parsing customer domain
redirect_url = getattr(resp, "url", None)
assert redirect_url == reverse("sentry-auth-organization", args=[org.slug])
# get redirect
resp = self.client.get(redirect_url, HTTP_HOST=f"{org.slug}.testserver")
assert resp.status_code == 200
def test_registration_disabled(self) -> None:
with self.feature({"auth:register": False}), self.allow_registration():
resp = self.client.get(self.path)
assert resp.context["register_form"] is None
@mock.patch("sentry.analytics.record")
def test_registration_valid(self, mock_record: mock.MagicMock) -> None:
with self.feature("auth:register"), self.allow_registration():
resp = self.client.post(
self.path,
{
"username": "test-a-really-long-email-address@example.com",
"password": "foobar",
"name": "Foo Bar",
"op": "register",
},
)
assert resp.status_code == 302, (
resp.context["register_form"].errors if resp.status_code == 200 else None
)
frontend_events = {"event_name": "Sign Up"}
marketing_query = urlencode({"frontend_events": json.dumps(frontend_events)})
assert marketing_query in resp.headers["Location"]
user = User.objects.get(username="test-a-really-long-email-address@example.com")
assert user.email == "test-a-really-long-email-address@example.com"
assert user.check_password("foobar")
assert user.name == "Foo Bar"
with assume_test_silo_mode(SiloMode.REGION):
assert not OrganizationMember.objects.filter(user_id=user.id).exists()
assert_last_analytics_event(
mock_record,
UserSignUpEvent(
user_id=user.id,
source="register-form",
provider=None,
referrer="in-app",
),
)
@override_settings(SENTRY_SINGLE_ORGANIZATION=True)
def test_registration_single_org(self) -> None:
with assume_test_silo_mode(SiloMode.MONOLITH):
create_default_projects()
with self.feature("auth:register"), self.allow_registration():
resp = self.client.post(
self.path,
{
"username": "test-a-really-long-email-address@example.com",
"password": "foobar",
"name": "Foo Bar",
"op": "register",
},
)
assert resp.status_code == 302, (
resp.context["register_form"].errors if resp.status_code == 200 else None
)
user = User.objects.get(username="test-a-really-long-email-address@example.com")
# User is part of the default org
with assume_test_silo_mode(SiloMode.REGION):
default_org = Organization.get_default()
org_member = OrganizationMember.objects.get(
organization_id=default_org.id, user_id=user.id
)
assert org_member.role == default_org.default_role
self.assert_org_member_mapping(org_member=org_member)
@override_settings(SENTRY_SINGLE_ORGANIZATION=True)
@mock.patch("sentry.web.frontend.auth_login.ApiInviteHelper.from_session")
def test_registration_single_org_with_invite(self, from_session: mock.MagicMock) -> None:
with assume_test_silo_mode(SiloMode.MONOLITH):
create_default_projects()
self.session["can_register"] = True
self.save_session()
self.client.get(self.path)
invite_helper = mock.Mock(valid_request=True, organization_id=self.organization.id)
from_session.return_value = invite_helper
resp = self.client.post(
self.path,
{
"username": "test@example.com",
"password": "foobar",
"name": "Foo Bar",
"op": "register",
},
)
user = User.objects.get(username="test@example.com")
# An organization member should NOT have been created, even though
# we're in single org mode, accepting the invite will handle that
# (which we assert next)
with assume_test_silo_mode(SiloMode.REGION):
assert not OrganizationMember.objects.filter(user_id=user.id).exists()
# Invitation was accepted
assert len(invite_helper.accept_invite.mock_calls) == 1
assert resp.status_code == 302
assert "/organizations/new/" in resp["Location"]
def test_register_renders_correct_template(self) -> None:
with self.allow_registration():
register_path = reverse("sentry-register")
resp = self.client.get(register_path)
assert resp.status_code == 200
assert resp.context["op"] == "register"
self.assertTemplateUsed("sentry/login.html")
def test_register_prefills_invite_email(self) -> None:
self.session["invite_email"] = "foo@example.com"
self.session["can_register"] = True
self.save_session()
register_path = reverse("sentry-register")
resp = self.client.get(register_path)
assert resp.status_code == 200
assert resp.context["op"] == "register"
assert resp.context["register_form"].initial["username"] == "foo@example.com"
self.assertTemplateUsed("sentry/login.html")
@mock.patch("sentry.web.frontend.auth_login.ApiInviteHelper.from_session")
def test_register_accepts_invite(self, from_session: mock.MagicMock) -> None:
self.session["can_register"] = True
self.save_session()
self.client.get(self.path)
invite_helper = mock.Mock(valid_request=True, organization_id=self.organization.id)
from_session.return_value = invite_helper
resp = self.client.post(
self.path,
{
"username": "test@example.com",
"password": "foobar",
"name": "Foo Bar",
"op": "register",
},
)
assert resp.status_code == 302
assert len(invite_helper.accept_invite.mock_calls) == 1
def test_register_new_user_accepts_invite_using_session(self) -> None:
invite = self.create_member(
email="member@example.com",
token="abcdef",
token_expires_at=timezone.now() + timedelta(hours=24),
organization_id=self.organization.id,
)
self.session["can_register"] = True
self.session["invite_token"] = invite.token
self.session["invite_member_id"] = invite.id
self.session["invite_organization_id"] = invite.organization_id
self.save_session()
self.client.get(self.path)
resp = self.client.post(
self.path,
{
"username": "member@example.com",
"password": "foobar",
"name": "Foo Bar",
"op": "register",
},
)
assert resp.status_code == 302
assert f"/organizations/{self.organization.slug}/issues/" in resp["Location"]
invite.refresh_from_db()
assert invite.user_id
assert invite.token is None
assert User.objects.get(id=invite.user_id).username == "member@example.com"
def test_redirects_to_relative_next_url(self) -> None:
next = "/welcome"
self.client.get(self.path + "?next=" + next)
resp = self.client.post(
self.path, {"username": self.user.username, "password": "admin", "op": "login"}
)
assert resp.status_code == 302
assert resp.get("Location", "").endswith(next)
def test_doesnt_redirect_to_external_next_url(self) -> None:
next = "http://example.com"
self.client.get(self.path + "?next=" + urlquote(next))
resp = self.client.post(
self.path,
{"username": self.user.username, "password": "admin", "op": "login"},
follow=True,
)
assert resp.redirect_chain == [
(reverse("sentry-login"), 302),
("/organizations/new/", 302),
]
def test_redirects_already_authed_non_superuser(self) -> None:
self.user.update(is_superuser=False)
self.login_as(self.user)
with self.feature("organizations:create"):
resp = self.client.get(self.path)
self.assertRedirects(resp, "/organizations/new/")
def test_redirects_authenticated_user_to_custom_next_url(self) -> None:
self.user.update(is_superuser=False)
self.login_as(self.user)
resp = self.client.get(self.path + "?next=testserver")
assert resp.status_code == 302
assert resp.get("Location", "").endswith("testserver")
def test_redirect_superuser(self) -> None:
self.login_as(self.user, superuser=False)
resp = self.client.get(self.path)
with self.feature("organizations:create"):
resp = self.client.get(self.path)
self.assertRedirects(resp, "/organizations/new/")
self.login_as(self.user, superuser=True)
resp = self.client.get(self.path)
with self.feature("organizations:create"):
resp = self.client.get(self.path)
self.assertRedirects(resp, "/organizations/new/")
@override_settings(
AUTH_PASSWORD_VALIDATORS=[
{"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator"}
]
)
def test_unable_to_set_weak_password_via_registration_form(self) -> None:
with self.feature("auth:register"), self.options({"auth.allow-registration": True}):
resp = self.client.post(
self.path,
{
"username": "hello@example.com",
"password": "hello@example.com",
"name": "Hello World",
"op": "register",
},
)
assert resp.status_code == 200
assert b"The password is too similar to the username." in resp.content
@override_options({"demo-mode.enabled": True, "demo-mode.users": [1]})
def test_login_demo_mode(self) -> None:
demo_user = self.create_user(
is_staff=False,
email="readonly@example.com",
password="foo",
id=1,
)
self.client.get(self.path)
resp = self.client.post(
self.path,
# login with any password
{"username": demo_user.username, "password": "bar", "op": "login"},
follow=True,
)
assert resp.status_code == 200
# successful login redirects to organizations/new
assert resp.redirect_chain == [(reverse("sentry-login"), 302), ("/organizations/new/", 302)]
@override_options({"demo-mode.enabled": False, "demo-mode.users": [1]})
def test_login_demo_mode_disabled(self) -> None:
demo_user = self.create_user(
is_staff=False,
id=1,
email="readonly@example.com",
password="foo",
)
self.client.get(self.path)
resp = self.client.post(
self.path,
# login with any password
{"username": demo_user.username, "password": "bar", "op": "login"},
follow=True,
)
assert resp.status_code == 200
assert resp.redirect_chain == []
assert "Please enter a correct username and password" in resp.content.decode()
@override_options({"demo-mode.enabled": True, "demo-mode.users": []})
def test_login_demo_mode_not_demo_user(self) -> None:
demo_user = self.create_user(
is_staff=False,
id=1,
email="readonly@example.com",
password="foo",
)
self.client.get(self.path)
resp = self.client.post(
self.path,
# login with any password
{"username": demo_user.username, "password": "bar", "op": "login"},
follow=True,
)
assert resp.status_code == 200
assert resp.redirect_chain == []
assert "Please enter a correct username and password" in resp.content.decode()
@override_options(
{
"demo-mode.enabled": True,
"demo-mode.users": [1],
"demo-mode.orgs": [1],
}
)
def test_login_demo_mode_with_org(self) -> None:
demo_user = self.create_user(
is_staff=False,
id=1,
email="readonly@example.com",
password="foo",
)
demo_org = self.create_organization(owner=demo_user, id=1)
self.client.get(self.path)
resp = self.client.post(
self.path,
# login with any password
{"username": demo_user.username, "password": "bar", "op": "login"},
follow=True,
)
assert resp.status_code == 200
# successful login redirects to demo orgs issue stream
assert resp.redirect_chain == [
(reverse("sentry-login"), 302),
(f"/organizations/{demo_org.slug}/issues/", 302),
]
@pytest.mark.skipif(
settings.SENTRY_NEWSLETTER != "sentry.newsletter.dummy.DummyNewsletter",
reason="Requires DummyNewsletter.",
)
@control_silo_test
| AuthLoginTest |
python | scrapy__scrapy | tests/test_spiderloader/test_spiders/spider1.py | {
"start": 36,
"end": 133
} | class ____(Spider):
name = "spider1"
allowed_domains = ["scrapy1.org", "scrapy3.org"]
| Spider1 |
python | cython__cython | Cython/Compiler/PyrexTypes.py | {
"start": 185584,
"end": 198292
} | class ____(PyrexType):
"""
A C lock type that can be used in with statements
(within Cython - it can't be returned to Python) and
safely acquired while holding the GIL.
"""
is_cython_lock_type = True
has_attributes = True
exception_value = None
scope = None
# Create a reference type that we can use in the definitions of acquire and release
# to override the general prohibition of assigning anything to this
class SpecialAssignableReferenceType(CReferenceType):
def assignable_from(self, src_type):
return src_type is self.ref_base_type
@property
def declaration_value(self):
return f"__Pyx_Locks_{self.cname_part}_DECL"
def __init__(self, cname_part):
self.cname_part = cname_part
self._special_assignable_reference_type = CythonLockType.SpecialAssignableReferenceType(self)
def declaration_code(self, entity_code, for_display=0, dll_linkage=None, pyrex=0):
if for_display or pyrex:
if self.cname_part == "PyThreadTypeLock":
return "cython.pythread_type_lock"
else:
return "cython.pymutex"
return f"__Pyx_Locks_{self.cname_part} {entity_code}"
def assignable_from(self, src_type):
# Singleton, cannot be copied.
return src_type is self._special_assignable_reference_type
def get_decl_utility_code(self):
return UtilityCode.load_cached(f"{self.cname_part}Decl", "Synchronization.c")
def get_usage_utility_code(self):
return UtilityCode.load_cached(self.cname_part, "Synchronization.c")
def needs_explicit_construction(self, scope):
# Where possible we use mutex types that don't require
# explicit construction (e.g. PyMutex). However, on older
# versions this isn't possible, and we fall back to types
# that do need non-static initialization.
return True
def needs_explicit_destruction(self, scope):
return True
def generate_explicit_construction(self, code, entry, extra_access_code=""):
code.globalstate.use_utility_code(
self.get_usage_utility_code()
)
code.putln(f"__Pyx_Locks_{self.cname_part}_Init({extra_access_code}{entry.cname});")
def generate_explicit_destruction(self, code, entry, extra_access_code=""):
code.putln(
f"__Pyx_Locks_{self.cname_part}_Delete({extra_access_code}{entry.cname});")
def attributes_known(self):
if self.scope is None:
from . import Symtab
self.scope = scope = Symtab.CClassScope(
self.empty_declaration_code(pyrex=True),
None,
visibility='extern',
parent_type=self)
scope.directives = {}
# The functions don't really take a reference, but saying they do passes the "assignable_from" check
self_type = self._special_assignable_reference_type
scope.declare_cfunction(
"acquire",
CFuncType(c_void_type, [CFuncTypeArg("self", self_type, None)],
nogil=True),
pos=None,
defining=1,
cname=f"__Pyx_Locks_{self.cname_part}_Lock",
utility_code=self.get_usage_utility_code())
scope.declare_cfunction(
"release",
CFuncType(c_void_type, [CFuncTypeArg("self", self_type, None)],
nogil=True),
pos=None,
defining=1,
cname=f"__Pyx_Locks_{self.cname_part}_Unlock",
utility_code=self.get_usage_utility_code())
scope.declare_cfunction(
"locked",
CFuncType(c_bint_type, [CFuncTypeArg("self", self_type, None)],
nogil=True),
pos=None,
defining=1,
cname=f"__Pyx_Locks_{self.cname_part}_Locked",
utility_code=self.get_usage_utility_code())
scope.declare_cfunction(
"can_check_locked",
CFuncType(c_bint_type, [CFuncTypeArg("self", self_type, None)],
nogil=True),
pos=None,
defining=1,
cname=f"__Pyx_Locks_{self.cname_part}_CanCheckLocked",
utility_code=self.get_usage_utility_code())
return True
def create_to_py_utility_code(self, env):
return False
def create_from_py_utility_code(self, env):
return False
def __eq__(self, other):
if type(other) is not type(self):
return NotImplemented
return other.cname_part == self.cname_part
def __hash__(self):
return hash(self.cname_part)
rank_to_type_name = (
"char", # 0
"short", # 1
"int", # 2
"long", # 3
"PY_LONG_LONG", # 4
"float", # 5
"double", # 6
"long double", # 7
)
RANK_INT = rank_to_type_name.index('int')
RANK_LONG = rank_to_type_name.index('long')
RANK_FLOAT = rank_to_type_name.index('float')
UNSIGNED = 0
SIGNED = 2
error_type = ErrorType()
unspecified_type = UnspecifiedType()
py_object_type = PyObjectType()
c_void_type = CVoidType()
c_uchar_type = CIntType(0, UNSIGNED)
c_ushort_type = CIntType(1, UNSIGNED)
c_uint_type = CIntType(2, UNSIGNED)
c_ulong_type = CIntType(3, UNSIGNED)
c_ulonglong_type = CIntType(4, UNSIGNED)
c_char_type = CIntType(0)
c_short_type = CIntType(1)
c_int_type = CIntType(2)
c_long_type = CIntType(3)
c_longlong_type = CIntType(4)
c_schar_type = CIntType(0, SIGNED)
c_sshort_type = CIntType(1, SIGNED)
c_sint_type = CIntType(2, SIGNED)
c_slong_type = CIntType(3, SIGNED)
c_slonglong_type = CIntType(4, SIGNED)
c_float_type = CFloatType(5, math_h_modifier='f')
c_double_type = CFloatType(6)
c_longdouble_type = CFloatType(7, math_h_modifier='l')
c_float_complex_type = CComplexType(c_float_type)
c_double_complex_type = CComplexType(c_double_type)
c_longdouble_complex_type = CComplexType(c_longdouble_type)
soft_complex_type = SoftCComplexType()
c_anon_enum_type = CAnonEnumType(-1)
c_returncode_type = CReturnCodeType(RANK_INT)
c_bint_type = CBIntType(RANK_INT)
c_py_unicode_type = CPyUnicodeIntType(RANK_INT-0.5, UNSIGNED)
c_py_ucs4_type = CPyUCS4IntType(RANK_LONG-0.5, UNSIGNED)
c_py_hash_t_type = CPyHashTType(RANK_LONG+0.5, SIGNED)
c_py_ssize_t_type = CPySSizeTType(RANK_LONG+0.5, SIGNED)
c_ssize_t_type = CSSizeTType(RANK_LONG+0.5, SIGNED)
c_size_t_type = CSizeTType(RANK_LONG+0.5, UNSIGNED)
c_ptrdiff_t_type = CPtrdiffTType(RANK_LONG+0.75, SIGNED)
c_null_ptr_type = CNullPtrType(c_void_type)
c_void_ptr_type = CPtrType(c_void_type)
c_void_ptr_ptr_type = CPtrType(c_void_ptr_type)
c_char_ptr_type = CPtrType(c_char_type)
c_const_char_ptr_type = CPtrType(c_const_type(c_char_type))
c_uchar_ptr_type = CPtrType(c_uchar_type)
c_const_uchar_ptr_type = CPtrType(c_const_type(c_uchar_type))
c_char_ptr_ptr_type = CPtrType(c_char_ptr_type)
c_int_ptr_type = CPtrType(c_int_type)
c_py_unicode_ptr_type = CPtrType(c_py_unicode_type)
c_const_py_unicode_ptr_type = CPtrType(c_const_type(c_py_unicode_type))
c_py_ssize_t_ptr_type = CPtrType(c_py_ssize_t_type)
c_ssize_t_ptr_type = CPtrType(c_ssize_t_type)
c_size_t_ptr_type = CPtrType(c_size_t_type)
# GIL state
c_gilstate_type = CEnumType("PyGILState_STATE", "PyGILState_STATE", True)
c_threadstate_type = CStructOrUnionType("PyThreadState", "struct", None, 1, "PyThreadState")
c_threadstate_ptr_type = CPtrType(c_threadstate_type)
# Critical section
c_py_critical_section_type = CStructOrUnionType(
"__Pyx_PyCriticalSection", "struct", None, 1, "__Pyx_PyCriticalSection")
c_py_critical_section2_type = CStructOrUnionType(
"__Pyx_PyCriticalSection2", "struct", None, 1, "__Pyx_PyCriticalSection2")
# PEP-539 "Py_tss_t" type
c_pytss_t_type = CPyTSSTType()
# Py3.10+ "PySendResult" for "am_send" slot functions: ["PYGEN_RETURN", "PYGEN_ERROR", "PYGEN_NEXT"]
PySendResult_type = CEnumType("PySendResult", "__Pyx_PySendResult", typedef_flag=True)
py_objptr_type = CPtrType(CStructOrUnionType(
"PyObject", "struct", scope=None, typedef_flag=True, cname="PyObject"))
# the Py_buffer type is defined in Builtin.py
c_py_buffer_type = CStructOrUnionType("Py_buffer", "struct", None, 1, "Py_buffer")
c_py_buffer_ptr_type = CPtrType(c_py_buffer_type)
# Not sure whether the unsigned versions and 'long long' should be in there
# long long requires C99 and might be slow, and would always get preferred
# when specialization happens through calling and not indexing
cy_integral_type = FusedType([c_short_type, c_int_type, c_long_type],
name="integral")
# Omitting long double as it might be slow
cy_floating_type = FusedType([c_float_type, c_double_type], name="floating")
cy_numeric_type = FusedType([c_short_type,
c_int_type,
c_long_type,
c_float_type,
c_double_type,
c_float_complex_type,
c_double_complex_type], name="numeric")
# buffer-related structs
c_buf_diminfo_type = CStructOrUnionType("__Pyx_Buf_DimInfo", "struct",
None, 1, "__Pyx_Buf_DimInfo")
c_pyx_buffer_type = CStructOrUnionType("__Pyx_Buffer", "struct", None, 1, "__Pyx_Buffer")
c_pyx_buffer_ptr_type = CPtrType(c_pyx_buffer_type)
c_pyx_buffer_nd_type = CStructOrUnionType("__Pyx_LocalBuf_ND", "struct",
None, 1, "__Pyx_LocalBuf_ND")
cython_memoryview_type = CStructOrUnionType("__pyx_memoryview_obj", "struct",
None, 0, "__pyx_memoryview_obj")
memoryviewslice_type = CStructOrUnionType("memoryviewslice", "struct",
None, 1, "__Pyx_memviewslice")
# Don't declare these as globals - it interferes with our ability to check if it's
# used in a particular scope.
def get_cy_pymutex_type():
return CythonLockType("PyMutex")
def get_cy_pythread_type_lock_type():
return CythonLockType("PyThreadTypeLock")
fixed_sign_int_types = {
"bint": (1, c_bint_type),
"Py_UNICODE": (0, c_py_unicode_type),
"Py_UCS4": (0, c_py_ucs4_type),
"Py_hash_t": (2, c_py_hash_t_type),
"Py_ssize_t": (2, c_py_ssize_t_type),
"ssize_t": (2, c_ssize_t_type),
"size_t": (0, c_size_t_type),
"ptrdiff_t": (2, c_ptrdiff_t_type),
}
modifiers_and_name_to_type = {
#(signed, longness, name) : type
(0, 0, "char"): c_uchar_type,
(1, 0, "char"): c_char_type,
(2, 0, "char"): c_schar_type,
(0, -1, "int"): c_ushort_type,
(0, 0, "int"): c_uint_type,
(0, 1, "int"): c_ulong_type,
(0, 2, "int"): c_ulonglong_type,
(1, -1, "int"): c_short_type,
(1, 0, "int"): c_int_type,
(1, 1, "int"): c_long_type,
(1, 2, "int"): c_longlong_type,
(2, -1, "int"): c_sshort_type,
(2, 0, "int"): c_sint_type,
(2, 1, "int"): c_slong_type,
(2, 2, "int"): c_slonglong_type,
(1, 0, "short"): c_short_type,
(1, 0, "long"): c_long_type,
(1, 0, "float"): c_float_type,
(1, 0, "double"): c_double_type,
(1, 1, "double"): c_longdouble_type,
(1, 0, "complex"): c_double_complex_type, # C: float, Python: double => Python wins
(1, 0, "floatcomplex"): c_float_complex_type,
(1, 0, "doublecomplex"): c_double_complex_type,
(1, 1, "doublecomplex"): c_longdouble_complex_type,
#
(1, 0, "void"): c_void_type,
(1, 0, "Py_tss_t"): c_pytss_t_type,
(1, 0, "object"): py_object_type,
}
modifiers_and_name_to_type.update({
(signed, 0, name): tp
for name, (signed, tp) in fixed_sign_int_types.items()
})
def is_promotion(src_type, dst_type):
# It's hard to find a hard definition of promotion, but empirical
# evidence suggests that the below is all that's allowed.
if src_type.is_numeric:
if dst_type.same_as(c_int_type):
unsigned = (not src_type.signed)
return (src_type.is_enum or
(src_type.is_int and
unsigned + src_type.rank < dst_type.rank))
elif dst_type.same_as(c_double_type):
return src_type.is_float and src_type.rank <= dst_type.rank
return False
| CythonLockType |
python | doocs__leetcode | solution/1300-1399/1301.Number of Paths with Max Score/Solution.py | {
"start": 0,
"end": 927
} | class ____:
def pathsWithMaxScore(self, board: List[str]) -> List[int]:
def update(i, j, x, y):
if x >= n or y >= n or f[x][y] == -1 or board[i][j] in "XS":
return
if f[x][y] > f[i][j]:
f[i][j] = f[x][y]
g[i][j] = g[x][y]
elif f[x][y] == f[i][j]:
g[i][j] += g[x][y]
n = len(board)
f = [[-1] * n for _ in range(n)]
g = [[0] * n for _ in range(n)]
f[-1][-1], g[-1][-1] = 0, 1
for i in range(n - 1, -1, -1):
for j in range(n - 1, -1, -1):
update(i, j, i + 1, j)
update(i, j, i, j + 1)
update(i, j, i + 1, j + 1)
if f[i][j] != -1 and board[i][j].isdigit():
f[i][j] += int(board[i][j])
mod = 10**9 + 7
return [0, 0] if f[0][0] == -1 else [f[0][0], g[0][0] % mod]
| Solution |
python | doocs__leetcode | solution/0200-0299/0268.Missing Number/Solution2.py | {
"start": 0,
"end": 135
} | class ____:
def missingNumber(self, nums: List[int]) -> int:
n = len(nums)
return (1 + n) * n // 2 - sum(nums)
| Solution |
python | getsentry__sentry | tests/sentry/workflow_engine/processors/test_workflow_fire_history.py | {
"start": 298,
"end": 2088
} | class ____(BaseWorkflowTest):
def setUp(self) -> None:
(
self.workflow,
self.detector,
self.detector_workflow,
self.workflow_triggers,
) = self.create_detector_and_workflow()
self.action_group, self.action = self.create_workflow_action(workflow=self.workflow)
self.group, self.event, self.group_event = self.create_group_event(
occurrence=self.build_occurrence(evidence_data={"detector_id": self.detector.id})
)
self.event_data = WorkflowEventData(event=self.group_event, group=self.group)
def test_create_workflow_fire_histories(self) -> None:
create_workflow_fire_histories(
Action.objects.filter(id=self.action.id),
self.event_data,
is_single_processing=True,
is_delayed=False,
)
assert (
WorkflowFireHistory.objects.filter(
detector=None,
workflow=self.workflow,
group=self.group,
event_id=self.group_event.event_id,
).count()
== 1
)
def test_create_workflow_fire_histories_only_canonical(self) -> None:
initial_count = WorkflowFireHistory.objects.count()
result = create_workflow_fire_histories(
Action.objects.filter(id=self.action.id),
self.event_data,
is_single_processing=False,
is_delayed=False,
)
assert result == []
assert WorkflowFireHistory.objects.count() == initial_count
assert not WorkflowFireHistory.objects.filter(
workflow=self.workflow,
group=self.group,
event_id=self.group_event.event_id,
).exists()
| TestWorkflowFireHistory |
python | spack__spack | lib/spack/spack/test/concretization/core.py | {
"start": 6118,
"end": 6616
} | class ____(Package):
homepage = "http://www.example.com"
url = "http://www.example.com/root-1.0.tar.gz"
version("1.0", sha256="abcde")
depends_on("middle")
depends_on("changing")
conflicts("^changing~foo")
"""
package_py = packages_dir / "root" / "package.py"
package_py.parent.mkdir(parents=True)
package_py.write_text(root_pkg_str)
middle_pkg_str = """
from spack_repo.builtin_mock.build_systems.generic import Package
from spack.package import *
| Root |
python | plotly__plotly.py | plotly/graph_objs/_deprecations.py | {
"start": 6347,
"end": 7219
} | class ____(dict):
"""
plotly.graph_objs.ErrorX is deprecated.
Please replace it with one of the following more specific types
- plotly.graph_objs.scatter.ErrorX
- plotly.graph_objs.histogram.ErrorX
- etc.
"""
def __init__(self, *args, **kwargs):
"""
plotly.graph_objs.ErrorX is deprecated.
Please replace it with one of the following more specific types
- plotly.graph_objs.scatter.ErrorX
- plotly.graph_objs.histogram.ErrorX
- etc.
"""
warnings.warn(
"""plotly.graph_objs.ErrorX is deprecated.
Please replace it with one of the following more specific types
- plotly.graph_objs.scatter.ErrorX
- plotly.graph_objs.histogram.ErrorX
- etc.
""",
DeprecationWarning,
)
super().__init__(*args, **kwargs)
| ErrorX |
python | scikit-learn__scikit-learn | sklearn/ensemble/_voting.py | {
"start": 1242,
"end": 6142
} | class ____(TransformerMixin, _BaseHeterogeneousEnsemble):
"""Base class for voting.
Warning: This class should not be used directly. Use derived classes
instead.
"""
_parameter_constraints: dict = {
"estimators": [list],
"weights": ["array-like", None],
"n_jobs": [None, Integral],
"verbose": ["verbose"],
}
def _log_message(self, name, idx, total):
if not self.verbose:
return None
return f"({idx} of {total}) Processing {name}"
@property
def _weights_not_none(self):
"""Get the weights of not `None` estimators."""
if self.weights is None:
return None
return [w for est, w in zip(self.estimators, self.weights) if est[1] != "drop"]
def _predict(self, X):
"""Collect results from clf.predict calls."""
return np.asarray([est.predict(X) for est in self.estimators_]).T
@abstractmethod
def fit(self, X, y, **fit_params):
"""Get common fit operations."""
names, clfs = self._validate_estimators()
if self.weights is not None and len(self.weights) != len(self.estimators):
raise ValueError(
"Number of `estimators` and weights must be equal; got"
f" {len(self.weights)} weights, {len(self.estimators)} estimators"
)
if _routing_enabled():
routed_params = process_routing(self, "fit", **fit_params)
else:
routed_params = Bunch()
for name in names:
routed_params[name] = Bunch(fit={})
if "sample_weight" in fit_params:
routed_params[name].fit["sample_weight"] = fit_params[
"sample_weight"
]
self.estimators_ = Parallel(n_jobs=self.n_jobs)(
delayed(_fit_single_estimator)(
clone(clf),
X,
y,
fit_params=routed_params[name]["fit"],
message_clsname="Voting",
message=self._log_message(name, idx + 1, len(clfs)),
)
for idx, (name, clf) in enumerate(zip(names, clfs))
if clf != "drop"
)
self.named_estimators_ = Bunch()
# Uses 'drop' as placeholder for dropped estimators
est_iter = iter(self.estimators_)
for name, est in self.estimators:
current_est = est if est == "drop" else next(est_iter)
self.named_estimators_[name] = current_est
if hasattr(current_est, "feature_names_in_"):
self.feature_names_in_ = current_est.feature_names_in_
return self
def fit_transform(self, X, y=None, **fit_params):
"""Return class labels or probabilities for each estimator.
Return predictions for X for each estimator.
Parameters
----------
X : {array-like, sparse matrix, dataframe} of shape \
(n_samples, n_features)
Input samples.
y : ndarray of shape (n_samples,), default=None
Target values (None for unsupervised transformations).
**fit_params : dict
Additional fit parameters.
Returns
-------
X_new : ndarray array of shape (n_samples, n_features_new)
Transformed array.
"""
return super().fit_transform(X, y, **fit_params)
@property
def n_features_in_(self):
"""Number of features seen during :term:`fit`."""
# For consistency with other estimators we raise an AttributeError so
# that hasattr() fails if the estimator isn't fitted.
try:
check_is_fitted(self)
except NotFittedError as nfe:
raise AttributeError(
"{} object has no n_features_in_ attribute.".format(
self.__class__.__name__
)
) from nfe
return self.estimators_[0].n_features_in_
def _sk_visual_block_(self):
names, estimators = zip(*self.estimators)
return _VisualBlock("parallel", estimators, names=names)
def get_metadata_routing(self):
"""Get metadata routing of this object.
Please check :ref:`User Guide <metadata_routing>` on how the routing
mechanism works.
.. versionadded:: 1.5
Returns
-------
routing : MetadataRouter
A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating
routing information.
"""
router = MetadataRouter(owner=self)
# `self.estimators` is a list of (name, est) tuples
for name, estimator in self.estimators:
router.add(
**{name: estimator},
method_mapping=MethodMapping().add(callee="fit", caller="fit"),
)
return router
| _BaseVoting |
python | pytorch__pytorch | test/inductor/test_triton_kernels.py | {
"start": 97341,
"end": 126212
} | class ____(torch._inductor.test_case.TestCase):
# Tests injected below
@make_mutation_test
def test_out_of_order_kernel():
@triton.jit
def add_kernel_out_of_order(
in_ptr0,
n_elements,
in_ptr1,
out_ptr,
BLOCK_SIZE: "tl.constexpr",
):
pid = tl.program_id(axis=0)
block_start = pid * BLOCK_SIZE
offsets = block_start + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
x = tl.load(in_ptr0 + offsets, mask=mask)
y = tl.load(in_ptr1 + offsets, mask=mask)
output = x + y
tl.store(out_ptr + offsets, output, mask=mask)
t = torch.randn(4)
return (
add_kernel_out_of_order,
{
"in_ptr0": t,
"n_elements": 4,
"in_ptr1": t,
"out_ptr": t,
"BLOCK_SIZE": 4,
},
{},
["out_ptr"],
)
@make_mutation_test
def test_out_of_order_kernel_call():
@triton.jit
def add_kernel_out_of_order_fn1(
in_ptr0,
n_elements,
in_ptr1,
out_ptr,
BLOCK_SIZE: "tl.constexpr",
):
pid = tl.program_id(axis=0)
block_start = pid * BLOCK_SIZE
offsets = block_start + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
add_kernel_out_of_order_fn2(
in_ptr0, in_ptr1, n_elements, out_ptr, BLOCK_SIZE=BLOCK_SIZE
)
t = torch.randn(4)
return (
add_kernel_out_of_order_fn1,
{
"in_ptr0": t,
"n_elements": 4,
"in_ptr1": t,
"out_ptr": t,
"BLOCK_SIZE": 4,
},
{},
["out_ptr"],
)
@make_mutation_test
def test_reduce_sum():
@triton.jit
def reduce_sum_kernel(a_ptr, c_ptr, stride_am, stride_an):
offs_am = tl.arange(0, 4)
offs_an = tl.arange(0, 4)
a_ptrs = a_ptr + (
offs_am[:, None] * stride_am + offs_an[None, :] * stride_an
)
a = tl.load(a_ptrs)
m = tl.sum(a, axis=1)
tl.store(c_ptr + tl.arange(0, 4), m)
t = torch.randn(4)
kernel = reduce_sum_kernel
kwargs = {
"a_ptr": t,
"c_ptr": t,
"stride_am": 4,
"stride_an": 4,
}
# TODO(aakhundov): tt.reduce is now supported, but only
# in the new MLIR-based Triton analysis pass (not in the
# old TTIR string parsing-based one). remove this gating
# and use ["c_ptr"] as `expected` after the new Triton
# pin lands both in OSS and internally.
ttir_module, _ = generate_ttir(kernel, kwargs, tma_descriptor_metadata={})
if hasattr(ttir_module, "walk"):
# with MLIR-based Triton analysis pass
expected = ["c_ptr"]
else:
# with TTIR string parsing-based Triton analysis pass
expected = ["a_ptr", "c_ptr"]
return (
kernel,
kwargs,
{},
expected,
)
@make_mutation_test
def test_argmax():
@triton.jit
def argmax_kernel(a_ptr, c_ptr, stride_am, stride_an):
offs_am = tl.arange(0, 4)
offs_an = tl.arange(0, 4)
a_ptrs = a_ptr + (
offs_am[:, None] * stride_am + offs_an[None, :] * stride_an
)
a = tl.load(a_ptrs)
m = tl.argmax(a, axis=1)
tl.store(c_ptr + tl.arange(0, 4), m)
t = torch.randn(4)
kernel = argmax_kernel
kwargs = {
"a_ptr": t,
"c_ptr": t,
"stride_am": 4,
"stride_an": 4,
}
# TODO(aakhundov): tt.reduce is now supported, but only
# in the new MLIR-based Triton analysis pass (not in the
# old TTIR string parsing-based one). remove this gating
# and use ["c_ptr"] as `expected` after the new Triton
# pin lands both in OSS and internally.
ttir_module, _ = generate_ttir(kernel, kwargs, tma_descriptor_metadata={})
if hasattr(ttir_module, "walk"):
# with MLIR-based Triton analysis pass
expected = ["c_ptr"]
else:
# with TTIR string parsing-based Triton analysis pass
expected = ["a_ptr", "c_ptr"]
return (
kernel,
kwargs,
{},
expected,
)
@requires_gpu
def test_triton_kernel_inference_mode(self):
def f(x, y, out):
n_elements = x.numel()
grid = lambda meta: (triton.cdiv(n_elements, meta["BLOCK_SIZE"]),)
add_kernel[grid](x, y, out, n_elements, BLOCK_SIZE=4)
with torch.inference_mode():
x = torch.ones(32, device=GPU_TYPE)
y = torch.ones(32, device=GPU_TYPE)
out_ref = torch.zeros_like(x)
out_test = torch.zeros_like(x)
f(x, y, out_ref)
torch.compile(f)(x, y, out_test)
self.assertEqual(out_ref, out_test)
@make_mutation_test
def test_cumsum():
@triton.jit
def cumsum_kernel(in_ptr, out_ptr, XBLOCK: tl.constexpr, RBLOCK: tl.constexpr):
rindex = tl.arange(0, RBLOCK)[None, :]
xindex = tl.arange(0, XBLOCK)[:, None]
data = tl.load(in_ptr + rindex)
scan = tl.cumsum(data, 1)
expected_max = tl.sum(data, 1)
tl.device_assert(scan <= expected_max)
tl.store(out_ptr + xindex * RBLOCK + rindex, scan)
t = torch.randn(4)
kernel = cumsum_kernel
kwargs = {
"in_ptr": t,
"out_ptr": t,
"XBLOCK": 4,
"RBLOCK": 16,
}
# TODO(aakhundov): tt.scan is now supported, but only
# in the new MLIR-based Triton analysis pass (not in the
# old TTIR string parsing-based one). remove this gating
# and use ["out_ptr"] as `expected` after the new Triton
# pin lands both in OSS and internally.
ttir_module, _ = generate_ttir(kernel, kwargs, tma_descriptor_metadata={})
if hasattr(ttir_module, "walk"):
# with MLIR-based Triton analysis pass
expected = ["out_ptr"]
else:
# with TTIR string parsing-based Triton analysis pass
expected = ["in_ptr", "out_ptr"]
return (
kernel,
kwargs,
{},
expected,
)
@make_mutation_test
def test_fn_call_one_return():
@triton.jit
def add_kernel_with_fn_call(
in_ptr0,
in_ptr1,
n_elements,
out_ptr,
BLOCK_SIZE: "tl.constexpr",
):
pid = tl.program_id(axis=0)
block_start = pid * BLOCK_SIZE
offsets = block_start + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
x = tl.load(in_ptr0 + offsets, mask=mask)
y = tl.load(in_ptr1 + offsets, mask=mask)
output = x + y
out = helper_id(out_ptr)
tl.store(out + offsets, output, mask=mask)
t = torch.randn(4)
return (
add_kernel_with_fn_call,
{
"in_ptr0": t,
"in_ptr1": t,
"n_elements": 4,
"out_ptr": t,
"BLOCK_SIZE": 4,
},
{},
["out_ptr"],
)
@make_mutation_test
def test_fn_call_multi_return():
@triton.jit
def add_kernel_with_fn_call(
in_ptr0,
in_ptr1,
n_elements,
out_ptr,
BLOCK_SIZE: "tl.constexpr",
):
pid = tl.program_id(axis=0)
block_start = pid * BLOCK_SIZE
offsets = block_start + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
x = tl.load(in_ptr0 + offsets, mask=mask)
y = tl.load(in_ptr1 + offsets, mask=mask)
output, out = helper_add_and_out(x, y, out_ptr)
tl.store(out + offsets, output, mask=mask)
t = torch.randn(4)
return (
add_kernel_with_fn_call,
{
"in_ptr0": t,
"in_ptr1": t,
"n_elements": 4,
"out_ptr": t,
"BLOCK_SIZE": 4,
},
{},
["out_ptr"],
)
@make_mutation_test
def test_nested_cond_op_kernel():
@triton.jit
def nested_cond_op_kernel(
in_ptr0,
in_ptr1,
out_ptr,
n_elements,
BLOCK_SIZE: "tl.constexpr",
):
pid = tl.program_id(axis=0)
block_start = pid * BLOCK_SIZE
offsets = block_start + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
x = tl.load(in_ptr0 + offsets, mask=mask)
y = tl.load(in_ptr1 + offsets, mask=mask)
if tl.program_id(0) == 0:
if tl.program_id(1) == 0:
output = x + y
tl.store(out_ptr + offsets, output, mask=mask)
else:
pass
t = torch.randn(4)
return (
nested_cond_op_kernel,
{
"in_ptr0": t,
"in_ptr1": t,
"out_ptr": t,
"n_elements": 4,
"BLOCK_SIZE": 4,
},
{},
["out_ptr"],
)
@make_mutation_test
def test_add_for_loop():
@triton.jit
def add_4_times_kernel(
in_ptr0,
in_ptr1,
out_ptr,
n_elements,
BLOCK_SIZE: "tl.constexpr",
):
pid = tl.program_id(axis=0)
block_start = pid * BLOCK_SIZE
offsets = block_start + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
x = tl.load(in_ptr0 + offsets, mask=mask)
y = tl.load(in_ptr1 + offsets, mask=mask)
output = tl.zeros((n_elements,), dtype=tl.float32)
for _ in range(4):
output += x + y
tl.store(out_ptr + offsets, output, mask=mask)
t = torch.randn(4)
return (
add_4_times_kernel,
{
"in_ptr0": t,
"in_ptr1": t,
"out_ptr": t,
"n_elements": 4,
"BLOCK_SIZE": 4,
},
{},
["out_ptr"],
)
@make_mutation_test
def test_add_for_loop2():
@triton.jit
def add_1_time_kernel(
in_ptr0,
in_ptr1,
out_ptr,
n_elements,
BLOCK_SIZE: "tl.constexpr",
):
pid = tl.program_id(axis=0)
block_start = pid * BLOCK_SIZE
offsets = block_start + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
x = tl.load(in_ptr0 + offsets, mask=mask)
y = tl.load(in_ptr1 + offsets, mask=mask)
for i in range(BLOCK_SIZE):
i = tl.multiple_of(i, 1)
output = x + y
tl.store(out_ptr + offsets, output, mask=mask)
t = torch.randn(4)
return (
add_1_time_kernel,
{
"in_ptr0": t,
"in_ptr1": t,
"out_ptr": t,
"n_elements": 4,
"BLOCK_SIZE": 4,
},
{},
["out_ptr"],
)
@make_mutation_test
def test_add_nested_for_loop():
@triton.jit
def add_4_times_kernel(
in_ptr0,
in_ptr1,
out_ptr,
n_elements,
BLOCK_SIZE: "tl.constexpr",
):
pid = tl.program_id(axis=0)
block_start = pid * BLOCK_SIZE
offsets = block_start + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
x = tl.load(in_ptr0 + offsets, mask=mask)
y = tl.load(in_ptr1 + offsets, mask=mask)
output = tl.zeros((n_elements,), dtype=tl.float32)
for _ in range(2):
for _ in range(2):
output += x + y
tl.store(out_ptr + offsets, output, mask=mask)
t = torch.randn(4)
return (
add_4_times_kernel,
{
"in_ptr0": t,
"in_ptr1": t,
"out_ptr": t,
"n_elements": 4,
"BLOCK_SIZE": 4,
},
{},
["out_ptr"],
)
@make_mutation_test
def test_add_nested_for_loop_multi_return():
@triton.jit
def add_4_times_kernel(
in_ptr0,
in_ptr1,
out_ptr,
n_elements,
BLOCK_SIZE: "tl.constexpr",
):
pid = tl.program_id(axis=0)
block_start = pid * BLOCK_SIZE
offsets = block_start + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
x = tl.load(in_ptr0 + offsets, mask=mask)
y = tl.load(in_ptr1 + offsets, mask=mask)
output1 = tl.zeros((n_elements,), dtype=tl.float32)
output2 = tl.zeros((n_elements,), dtype=tl.float32)
for _ in range(2):
for _ in range(2):
output1 += y
output2 += x
output = output1 + output2
tl.store(out_ptr + offsets, output, mask=mask)
t = torch.randn(4)
return (
add_4_times_kernel,
{
"in_ptr0": t,
"in_ptr1": t,
"out_ptr": t,
"n_elements": 4,
"BLOCK_SIZE": 4,
},
{},
["out_ptr"],
)
@make_mutation_test
def test_labels():
@triton.jit
def kernel_with_label(
in_ptr0,
in_ptr1,
out_ptr,
n_elements,
BLOCK_SIZE: "tl.constexpr",
):
pid = tl.program_id(axis=0)
if pid > 1:
return
block_start = pid * BLOCK_SIZE
offsets = block_start + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
x = tl.load(in_ptr0 + offsets, mask=mask)
y = tl.load(in_ptr1 + offsets, mask=mask)
output = x + y
tl.store(out_ptr + offsets, output, mask=mask)
t = torch.randn(4)
return (
kernel_with_label,
{
"in_ptr0": t,
"in_ptr1": t,
"out_ptr": t,
"n_elements": 4,
"BLOCK_SIZE": 4,
},
{},
["out_ptr"],
)
@make_mutation_test
def test_for_loop_arg():
@triton.jit
def fwd_kernel(
X_ptr,
W1_ptr,
b1_ptr,
O_ptr,
M: tl.constexpr,
C1: tl.constexpr,
C2: tl.constexpr,
BLOCK_SIZE_M: tl.constexpr,
BLOCK_SIZE_C2: tl.constexpr,
):
# Get program ids
pid_m = tl.program_id(0)
# Compute offsets
offs_c1 = tl.arange(0, C1)
offs_m = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
# Load input data
x_block_ptr = X_ptr + offs_m[:, None] * C1 + offs_c1[None, :]
x = tl.load(x_block_ptr)
# Compute gating
for c2 in range(tl.cdiv(C2, BLOCK_SIZE_C2)):
# Compute block pointers
offs_c2 = c2 * BLOCK_SIZE_C2 + tl.arange(0, BLOCK_SIZE_C2)
o_block_ptr = O_ptr + offs_m[:, None] * C2 + offs_c2[None, :]
w1_block_ptr = W1_ptr + offs_c1[:, None] * C2 + offs_c2[None, :]
b1_block_ptr = b1_ptr + offs_c2
# Compute output
w = tl.load(w1_block_ptr)
b = tl.load(b1_block_ptr)
o = tl.dot(x, w, allow_tf32=False)
o += b[None, :]
# Store output
tl.store(o_block_ptr, o)
t = torch.randn(64)
return (
fwd_kernel,
{
"X_ptr": t,
"W1_ptr": t,
"b1_ptr": t,
"O_ptr": t,
"M": 64,
"C1": 64,
"C2": 64,
"BLOCK_SIZE_M": 64,
"BLOCK_SIZE_C2": 64,
},
{},
["O_ptr"],
)
@make_mutation_test
def test_for_loop_arg_2():
@triton.jit
def fwd_kernel(
x_ptr,
o_ptr,
M,
N,
stride_m,
stride_n,
BLOCK_B: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
):
# Get program ids
pid_m = tl.program_id(0)
X_block_ptr = tl.make_block_ptr(
base=x_ptr,
shape=(M, N),
strides=(stride_m, stride_n),
offsets=(0, 0),
block_shape=(BLOCK_M, BLOCK_N),
order=(1, 0),
)
O_block_ptr = tl.make_block_ptr(
base=o_ptr,
shape=(M, N),
strides=(stride_m, stride_n),
offsets=(0, 0),
block_shape=(BLOCK_M, BLOCK_N),
order=(1, 0),
)
for _ in range(BLOCK_B):
x = tl.load(X_block_ptr)
tl.store(O_block_ptr, x)
X_block_ptr = tl.advance(X_block_ptr, (BLOCK_M, 0))
O_block_ptr = tl.advance(O_block_ptr, (BLOCK_M, 0))
t = torch.randn((32, 64, 128))
o = torch.empty_like(t)
B, M, N = t.shape
return (
fwd_kernel,
{
"x_ptr": t,
"o_ptr": o,
"M": M,
"N": N,
"stride_m": N,
"stride_n": 1,
"BLOCK_B": B,
"BLOCK_M": M,
"BLOCK_N": N,
},
{},
["o_ptr"],
)
@make_mutation_test
def test_while_loop():
@triton.jit
def fwd_kernel(
x_ptr,
o_ptr,
M,
N,
stride_m,
stride_n,
BLOCK_B: tl.constexpr,
BLOCK_M: tl.constexpr,
BLOCK_N: tl.constexpr,
):
# Get program ids
pid_m = tl.program_id(0)
X_block_ptr = tl.make_block_ptr(
base=x_ptr,
shape=(M, N),
strides=(stride_m, stride_n),
offsets=(0, 0),
block_shape=(BLOCK_M, BLOCK_N),
order=(1, 0),
)
O_block_ptr = tl.make_block_ptr(
base=o_ptr,
shape=(M, N),
strides=(stride_m, stride_n),
offsets=(0, 0),
block_shape=(BLOCK_M, BLOCK_N),
order=(1, 0),
)
i = 0
while i < BLOCK_B:
x = tl.load(X_block_ptr)
tl.store(O_block_ptr, x)
X_block_ptr = tl.advance(X_block_ptr, (BLOCK_M, 0))
O_block_ptr = tl.advance(O_block_ptr, (BLOCK_M, 0))
i += 1
t = torch.randn((32, 64, 128))
o = torch.empty_like(t)
B, M, N = t.shape
return (
fwd_kernel,
{
"x_ptr": t,
"o_ptr": o,
"M": M,
"N": N,
"stride_m": N,
"stride_n": 1,
"BLOCK_B": B,
"BLOCK_M": M,
"BLOCK_N": N,
},
{},
["o_ptr"],
)
@make_mutation_test
def test_branch_with_multiple_yield_args():
@triton.jit
def branch_with_multiple_yield_args(
in_ptr0,
in_ptr1,
out_ptr,
conditional_ptr,
n_elements,
BLOCK_SIZE: "tl.constexpr",
):
pid = tl.program_id(axis=0)
block_start = pid * BLOCK_SIZE
offsets = block_start + tl.arange(0, BLOCK_SIZE)
mask = offsets < n_elements
conditional = tl.load(conditional_ptr)
if conditional:
in0 = in_ptr0 + 1
in1 = in_ptr1 + 1
out = out_ptr + 1
else:
in0 = in_ptr0
in1 = in_ptr1
out = out_ptr
x = tl.load(in0 + offsets, mask=mask)
y = tl.load(in1 + offsets, mask=mask)
tl.store(out + offsets, x + y, mask=mask)
x = torch.randn(15)
y = torch.randn(15)
out = torch.zeros(15)
conditional = torch.tensor(True)
return (
branch_with_multiple_yield_args,
{
"in_ptr0": x,
"in_ptr1": y,
"out_ptr": out,
"conditional_ptr": conditional,
"n_elements": 14,
"BLOCK_SIZE": 16,
},
{},
["out_ptr"],
)
def test_get_tma_stores(self):
from torch._higher_order_ops.triton_kernel_wrap import (
get_tma_stores,
Intermediate,
Op,
Param,
)
functions = {
"helper": {
Intermediate(idx=0): [
Op(
"tt.reinterpret_tensor_descriptor",
None,
[Param(idx=0)],
Intermediate(idx=0),
)
],
},
"main": {
Intermediate(idx=-1): [
Op(
"tt.call",
"helper",
[Param(idx=0), Param(idx=1)],
Intermediate(idx=-1),
)
],
},
}
self.assertEqual(get_tma_stores(functions, "helper"), set())
self.assertEqual(get_tma_stores(functions, "main"), set())
functions["helper"][Intermediate(idx=-1)] = [
Op(
"tt.experimental_descriptor_store",
None,
[Intermediate(idx=0), Param(idx=1)],
Intermediate(idx=-1),
)
]
get_tma_stores.reset()
self.assertEqual(
get_tma_stores(functions, "helper"), {Param(idx=0), Intermediate(idx=0)}
)
self.assertEqual(get_tma_stores(functions, "main"), {Param(idx=0)})
@unittest.skipIf(
not has_triton_experimental_host_tma(),
"requires experimental TMA descriptor API",
)
@make_mutation_test
def test_add_kernel_on_device_tma_old_api():
a = torch.randn(1024, 1024)
b = torch.randn(1024, 1024)
c = torch.empty(1024, 1024)
workspace = torch.empty(128 * 3, dtype=torch.int8)
return (
add_kernel_on_device_tma_old_api,
{
"a_ptr": a,
"b_ptr": b,
"c_ptr": c,
"m": 1024,
"n": 1024,
"workspace": workspace,
"BLOCK_SIZE": 32,
},
{},
["c_ptr", "workspace"],
)
@unittest.skipIf(
not has_triton_tensor_descriptor_host_tma(),
"requires TensorDescriptor API in Triton",
)
@make_mutation_test
def test_add_kernel_on_device_tma_new_api():
a = torch.randn(1024, 1024)
b = torch.randn(1024, 1024)
c = torch.empty(1024, 1024)
workspace = torch.empty(
128 * 3, dtype=torch.int8
) # Not used by the new API but kept for consistency
return (
add_kernel_on_device_tma_new_api,
{
"a_ptr": a,
"b_ptr": b,
"c_ptr": c,
"m": 1024,
"n": 1024,
"workspace": workspace,
"BLOCK_SIZE": 32,
},
{},
["c_ptr"],
)
if HAS_GPU:
t = torch.randn(4)
tt = torch.randn(4, 1)
tests = [
[
add_kernel,
{
"in_ptr0": t,
"in_ptr1": t,
"out_ptr": t,
"n_elements": 4,
"BLOCK_SIZE": 4,
},
{},
["out_ptr"],
],
[
add_kernel_2d_autotuned,
{
"in_ptr0": t,
"in_ptr1": t,
"out_ptr": t,
"x_elements": 4,
"y_elements": 4,
},
{},
["out_ptr"],
],
[
indirection_kernel,
{
"in_ptr0": t,
"out_ptr": t,
"n_elements": 4,
"BLOCK_SIZE": 4,
"ACTIVATION": "mul2_inplace_kernel",
},
{},
["in_ptr0", "out_ptr"],
],
[
indirection_kernel,
{
"in_ptr0": t,
"out_ptr": t,
"n_elements": 4,
"BLOCK_SIZE": 4,
"ACTIVATION": "add_kernel",
},
{},
["out_ptr"],
],
[
mul2_inplace_kernel,
{"ptr": t, "n_elements": 4, "BLOCK_SIZE": 4},
{},
["ptr"],
],
[
inline_asm_kernel_is_pure_true,
{"X": t, "Y": t, "Z": t, "n": 4, "BLOCK": 4},
{},
["Z"],
],
[
inline_asm_kernel_is_pure_false,
{"X": t, "Y": t, "Z": t, "n": 4, "BLOCK": 4},
{},
["X", "Y", "Z"],
],
[
add_kernel_with_block_ptr,
{
"x_ptr": t,
"y_ptr": t,
"output_ptr": t,
"n_elements": 4,
"BLOCK_SIZE": 4,
},
{},
["output_ptr"],
],
[
kernel_with_block_ptr_2d,
{
"x_ptr": tt,
"output_ptr": tt,
"n_elements": 4,
"BLOCK_SIZE": 4,
},
{},
["output_ptr"],
],
[
add_kernel_with_import,
{
"in_ptr0": t,
"in_ptr1": t,
"out_ptr": t,
"n_elements": 4,
"BLOCK_SIZE": 4,
},
{},
["out_ptr"],
],
[
atomic_add_kernel,
{
"in_ptr0": t,
"in_ptr1": t,
"out_ptr": t,
"n_elements": 4,
"BLOCK_SIZE": 4,
},
{},
["out_ptr"],
],
[
add_4_times_kernel,
{
"in_ptr0": t,
"in_ptr1": t,
"out_ptr": t,
"n_elements": 4,
"BLOCK_SIZE": 4,
},
{},
["out_ptr"],
],
[
cond_op_kernel,
{
"in_ptr0": t,
"in_ptr1": t,
"out_ptr": t,
"n_elements": 4,
"BLOCK_SIZE": 4,
},
{},
["out_ptr"],
],
]
for kernel, inputs, tma_descriptor_metadata, outputs in tests:
fn = make_mutation_test(
# Add default arguments to avoid Python lambda capture pitfall
# This forces the capture at lambda creation
lambda kernel=kernel,
inputs=inputs,
tma_descriptor_metadata=tma_descriptor_metadata,
outputs=outputs: (
kernel,
inputs,
tma_descriptor_metadata,
outputs,
)
)
name = f"test_mutations_{kernel.fn.__name__}"
# Poor way to make test names be unique
while name in MutationTests.__dict__:
name += "1"
setattr(MutationTests, name, fn)
| MutationTests |
python | pytorch__pytorch | torchgen/code_template.py | {
"start": 678,
"end": 3211
} | class ____:
substitution_str = r"(^[^\n\S]*)?\$([^\d\W]\w*|\{,?[^\d\W]\w*\,?})"
substitution = re.compile(substitution_str, re.MULTILINE)
pattern: str
filename: str
@staticmethod
def from_file(filename: str) -> CodeTemplate:
with open(filename) as f:
return CodeTemplate(f.read(), filename)
def __init__(self, pattern: str, filename: str = "") -> None:
self.pattern = pattern
self.filename = filename
def substitute(
self, env: Mapping[str, object] | None = None, **kwargs: object
) -> str:
if env is None:
env = {}
def lookup(v: str) -> object:
assert env is not None
return kwargs[v] if v in kwargs else env[v]
def indent_lines(indent: str, v: Sequence[object]) -> str:
content = "\n".join(
itertools.chain.from_iterable(str(e).splitlines() for e in v)
)
content = textwrap.indent(content, prefix=indent)
# Remove trailing whitespace on each line
return "\n".join(map(str.rstrip, content.splitlines())).rstrip()
def replace(match: re.Match[str]) -> str:
indent = match.group(1)
key = match.group(2)
comma_before = ""
comma_after = ""
if key[0] == "{":
key = key[1:-1]
if key[0] == ",":
comma_before = ", "
key = key[1:]
if key[-1] == ",":
comma_after = ", "
key = key[:-1]
v = lookup(key)
if indent is not None:
if not isinstance(v, list):
v = [v]
return indent_lines(indent, v)
elif isinstance(v, list):
middle = ", ".join([str(x) for x in v])
if len(v) == 0:
return middle
return comma_before + middle + comma_after
else:
return str(v)
return self.substitution.sub(replace, self.pattern)
if __name__ == "__main__":
c = CodeTemplate(
"""\
int foo($args) {
$bar
$bar
$a+$b
}
int commatest(int a${,stuff})
int notest(int a${,empty,})
"""
)
print(
c.substitute(
args=["hi", 8],
bar=["what", 7],
a=3,
b=4,
stuff=["things...", "others"],
empty=[],
)
)
| CodeTemplate |
python | sqlalchemy__sqlalchemy | lib/sqlalchemy/connectors/asyncio.py | {
"start": 14151,
"end": 14362
} | class ____(EmulatedDBAPIException):
"""Provide for the base of DBAPI ``Error`` base class for dialects
that need to emulate the DBAPI exception hierarchy.
.. versionadded:: 2.1
"""
| AsyncAdapt_Error |
python | tartley__colorama | colorama/ansi.py | {
"start": 489,
"end": 930
} | class ____:
def __init__(self):
# the subclasses declare class attributes which are numbers.
# Upon instantiation we define instance attributes, which are the same
# as the class attributes but wrapped with the ANSI escape sequence
for name in dir(self):
if not name.startswith('_'):
value = getattr(self, name)
setattr(self, name, code_to_chars(value))
| AnsiCodes |
python | oauthlib__oauthlib | oauthlib/oauth2/rfc6749/errors.py | {
"start": 6049,
"end": 6157
} | class ____(InvalidRequestError):
description = 'Missing response_type parameter.'
| MissingResponseTypeError |
python | pytorch__pytorch | torch/_functorch/autograd_function.py | {
"start": 27174,
"end": 28787
} | class ____(HigherOrderOperator):
def __init__(self) -> None:
super().__init__("autograd_function_apply")
def __call__(self, fwd, bwd, *fwd_args, **fwd_kwargs):
saved_values = None
args_tensor_mask = fwd_kwargs["args_tensor_mask"]
non_differentiable_idx = fwd_kwargs["non_differentiable_idx"]
length_of_tensor_args = sum(args_tensor_mask)
# Filter out the original tensor args from fwd_args,
# lifted freevars should not be args of ApplyTemplate.apply
# since we don't need to calculate the gradients of them.
new_fwd_args = fwd_args[:length_of_tensor_args]
class ApplyTemplate(torch.autograd.Function):
@staticmethod
# pyrefly: ignore [bad-override]
def forward(ctx, *args):
nonlocal saved_values
output, saved_values = fwd(None, *fwd_args)
# If users call ctx.mark_non_differentiable() in the original fwd function.
if len(non_differentiable_idx) > 0:
non_differentiable_output = []
for i, x in enumerate(output):
if i in non_differentiable_idx:
non_differentiable_output.append(x)
ctx.mark_non_differentiable(*non_differentiable_output)
return output
@staticmethod
def backward(ctx, *grad):
return bwd(None, *grad, *saved_values)
return ApplyTemplate.apply(*new_fwd_args)
autograd_function_apply = AutogradFunctionApply()
| AutogradFunctionApply |
python | apache__airflow | providers/slack/tests/unit/slack/utils/test_utils.py | {
"start": 4145,
"end": 6391
} | class ____:
SUPPORTED_FORMAT = ("so", "dll", "exe", "sh")
def test_error_parse_without_extension(self):
with pytest.raises(ValueError, match="No file extension specified in filename"):
assert parse_filename("Untitled File", self.SUPPORTED_FORMAT)
@pytest.mark.parametrize(
("filename", "expected_format"),
[
("libc.so", "so"),
("kernel32.dll", "dll"),
("xxx.mp4.exe", "exe"),
("init.sh", "sh"),
],
)
def test_parse_first_level(self, filename, expected_format):
assert parse_filename(filename, self.SUPPORTED_FORMAT) == (expected_format, None)
@pytest.mark.parametrize("filename", ["New File.txt", "cats-memes.mp4"])
def test_error_parse_first_level(self, filename):
with pytest.raises(ValueError, match="Unsupported file format"):
assert parse_filename(filename, self.SUPPORTED_FORMAT)
@pytest.mark.parametrize(
("filename", "expected"),
[
("libc.so.6", ("so", "6")),
("kernel32.dll.zip", ("dll", "zip")),
("explorer.exe.7z", ("exe", "7z")),
("init.sh.gz", ("sh", "gz")),
],
)
def test_parse_second_level(self, filename, expected):
assert parse_filename(filename, self.SUPPORTED_FORMAT) == expected
@pytest.mark.parametrize("filename", ["example.so.tar.gz", "w.i.e.r.d"])
def test_error_parse_second_level(self, filename):
with pytest.raises(ValueError, match="Unsupported file format.*with compression extension."):
assert parse_filename(filename, self.SUPPORTED_FORMAT)
@pytest.mark.parametrize("filename", ["Untitled File", "New File.txt", "example.so.tar.gz"])
@pytest.mark.parametrize("fallback", SUPPORTED_FORMAT)
def test_fallback(self, filename, fallback):
assert parse_filename(filename, self.SUPPORTED_FORMAT, fallback) == (fallback, None)
@pytest.mark.parametrize("filename", ["Untitled File", "New File.txt", "example.so.tar.gz"])
def test_wrong_fallback(self, filename):
with pytest.raises(ValueError, match="Invalid fallback value"):
assert parse_filename(filename, self.SUPPORTED_FORMAT, "mp4")
| TestParseFilename |
python | gevent__gevent | src/gevent/_config.py | {
"start": 11547,
"end": 11781
} | class ____(Setting):
name = 'libev_backend'
environment_key = 'GEVENT_BACKEND'
desc = """\
The backend for libev, such as 'select'
"""
default = None
validate = staticmethod(validate_anything)
| LibevBackend |
python | getsentry__sentry | tests/snuba/api/endpoints/test_organization_events.py | {
"start": 4432,
"end": 235297
} | class ____(OrganizationEventsEndpointTestBase, PerformanceIssueTestCase):
def test_no_projects(self) -> None:
response = self.do_request({})
assert response.status_code == 200, response.content
assert response.data["data"] == []
assert response.data["meta"] == {
"tips": {"query": "Need at least one valid project to query."}
}
def test_environment_filter(self) -> None:
self.create_environment(self.project, name="production")
self.store_event(
data={
"event_id": "a" * 32,
"environment": "staging",
"timestamp": self.ten_mins_ago_iso,
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"environment": "production",
"timestamp": self.ten_mins_ago_iso,
},
project_id=self.project.id,
)
query = {
"field": ["id", "project.id"],
"project": [self.project.id],
"environment": ["staging", "production"],
}
response = self.do_request(query)
assert response.status_code == 200
assert len(response.data["data"]) == 2
def test_performance_view_feature(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group1"],
},
project_id=self.project.id,
)
query = {"field": ["id", "project.id"], "project": [self.project.id]}
response = self.do_request(query)
assert response.status_code == 200
assert len(response.data["data"]) == 1
def test_invalid_search_terms(self) -> None:
self.create_project()
query = {"field": ["id"], "query": "hi \n there"}
response = self.do_request(query)
assert response.status_code == 400, response.content
assert (
response.data["detail"]
== "Parse error at 'hi \n ther' (column 4). This is commonly caused by unmatched parentheses. Enclose any text in double quotes."
)
def test_invalid_field(self) -> None:
self.create_project()
query: dict[str, Any] = {"field": ["foo[…]bar"], "dataset": "transactions"}
model = DiscoverSavedQuery.objects.create(
organization=self.organization,
created_by_id=self.user.id,
name="query name",
query=query,
version=2,
date_created=before_now(minutes=10),
date_updated=before_now(minutes=10),
dataset=DiscoverSavedQueryTypes.TRANSACTION_LIKE,
)
query["discoverSavedQueryId"] = model.id
response = self.do_request(query)
assert response.status_code == 400, response.content
assert response.data["detail"] == "Invalid characters in field foo[…]bar"
def test_invalid_trace_span(self) -> None:
self.create_project()
query = {"field": ["id"], "query": "trace.span:invalid"}
response = self.do_request(query)
assert response.status_code == 400, response.content
assert (
response.data["detail"]
== "`trace.span` must be a valid 16 character hex (containing only digits, or a-f characters)"
)
query = {"field": ["id"], "query": "trace.parent_span:invalid"}
response = self.do_request(query)
assert response.status_code == 400, response.content
assert (
response.data["detail"]
== "`trace.parent_span` must be a valid 16 character hex (containing only digits, or a-f characters)"
)
query = {"field": ["id"], "query": "trace.span:*"}
response = self.do_request(query)
assert response.status_code == 400, response.content
assert (
response.data["detail"] == "Wildcard conditions are not permitted on `trace.span` field"
)
query = {"field": ["id"], "query": "trace.parent_span:*"}
response = self.do_request(query)
assert response.status_code == 400, response.content
assert (
response.data["detail"]
== "Wildcard conditions are not permitted on `trace.parent_span` field"
)
def test_has_trace_context(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"contexts": {
"trace": {
"span_id": "a" * 16,
"trace_id": "b" * 32,
},
},
},
project_id=self.project.id,
)
query = {"field": ["id", "trace.parent_span"], "query": "has:trace.span"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["id"] == "a" * 32
query = {"field": ["id"], "query": "has:trace.parent_span"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 0
def test_treat_status_as_tag_discover_transaction(self) -> None:
event_1 = self.store_event(
data={
"event_id": "a" * 32,
"environment": "staging",
"timestamp": self.ten_mins_ago_iso,
"tags": {"status": "good"},
},
project_id=self.project.id,
)
event_2 = self.store_event(
data={
"event_id": "b" * 32,
"environment": "staging",
"timestamp": self.ten_mins_ago_iso,
"tags": {"status": "bad"},
},
project_id=self.project.id,
)
query = {
"field": ["event_id"],
"query": "!status:good",
"dataset": "discover",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert response.data["data"] == [
{"event_id": "", "id": event_2.event_id, "project.name": self.project.slug}
]
query = {"field": ["event_id"], "query": ["status:good"], "dataset": "discover"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert response.data["data"] == [
{"event_id": "", "id": event_1.event_id, "project.name": self.project.slug}
]
def test_not_has_trace_context(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"contexts": {
"trace": {
"span_id": "a" * 16,
"trace_id": "b" * 32,
},
},
},
project_id=self.project.id,
)
query = {"field": ["id", "trace.parent_span"], "query": "!has:trace.span"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 0
query = {"field": ["id"], "query": "!has:trace.parent_span"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["id"] == "a" * 32
def test_parent_span_id_in_context(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"contexts": {
"trace": {
"span_id": "a" * 16,
"trace_id": "b" * 32,
"parent_span_id": "c" * 16,
},
},
},
project_id=self.project.id,
)
query = {"field": ["id"], "query": f"trace.parent_span:{'c' * 16}"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["id"] == "a" * 32
def test_out_of_retention(self) -> None:
self.create_project()
with self.options({"system.event-retention-days": 10}):
query = {
"field": ["id", "timestamp"],
"orderby": ["-timestamp", "-id"],
"start": before_now(days=20),
"end": before_now(days=15),
}
response = self.do_request(query)
assert response.status_code == 400, response.content
assert response.data["detail"] == "Invalid date range. Please try a more recent date range."
def test_raw_data(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"environment": "staging",
"timestamp": self.eleven_mins_ago_iso,
"user": {"ip_address": "127.0.0.1", "email": "foo@example.com"},
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"environment": "staging",
"timestamp": self.ten_mins_ago_iso,
"user": {"ip_address": "127.0.0.1", "email": "foo@example.com"},
},
project_id=self.project.id,
)
query = {
"field": ["id", "project.id", "user.email", "user.ip", "timestamp"],
"orderby": "-timestamp",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
assert data[0]["id"] == "b" * 32
assert data[0]["project.id"] == self.project.id
assert data[0]["user.email"] == "foo@example.com"
assert "project.name" not in data[0], "project.id does not auto select name"
assert "project" not in data[0]
meta = response.data["meta"]
field_meta = meta["fields"]
assert field_meta["id"] == "string"
assert field_meta["user.email"] == "string"
assert field_meta["user.ip"] == "string"
assert field_meta["timestamp"] == "date"
def test_project_name(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"environment": "staging",
"timestamp": self.ten_mins_ago_iso,
},
project_id=self.project.id,
)
query = {"field": ["project.name", "environment"]}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["project.name"] == self.project.slug
assert "project.id" not in response.data["data"][0]
assert response.data["data"][0]["environment"] == "staging"
def test_project_without_name(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"environment": "staging",
"timestamp": self.ten_mins_ago_iso,
},
project_id=self.project.id,
)
query = {"field": ["project", "environment"]}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["project"] == self.project.slug
assert response.data["meta"]["fields"]["project"] == "string"
assert "project.id" not in response.data["data"][0]
assert response.data["data"][0]["environment"] == "staging"
def test_project_in_query(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"environment": "staging",
"timestamp": self.ten_mins_ago_iso,
},
project_id=self.project.id,
)
query = {
"field": ["project", "count()"],
"query": f'project:"{self.project.slug}"',
"statsPeriod": "14d",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["project"] == self.project.slug
assert "project.id" not in response.data["data"][0]
def test_project_in_query_not_in_header(self) -> None:
project = self.create_project()
other_project = self.create_project()
self.store_event(
data={
"event_id": "a" * 32,
"environment": "staging",
"timestamp": self.ten_mins_ago_iso,
},
project_id=project.id,
)
query = {
"field": ["project", "count()"],
"query": 'project:"%s"' % project.slug,
"statsPeriod": "14d",
"project": other_project.id,
}
response = self.do_request(query)
assert response.status_code == 400, response.content
assert (
response.data["detail"]
== f"Invalid query. Project(s) {project.slug} do not exist or are not actively selected."
)
def test_project_in_query_does_not_exist(self) -> None:
self.create_project()
query = {"field": ["project", "count()"], "query": "project:morty", "statsPeriod": "14d"}
response = self.do_request(query)
assert response.status_code == 400, response.content
assert (
response.data["detail"]
== "Invalid query. Project(s) morty do not exist or are not actively selected."
)
def test_not_project_in_query_but_in_header(self) -> None:
team = self.create_team(organization=self.organization, members=[self.user])
project = self.create_project(organization=self.organization, teams=[team])
project2 = self.create_project(organization=self.organization, teams=[team])
self.store_event(
data={
"event_id": "a" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group1"],
},
project_id=project.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group2"],
},
project_id=project2.id,
)
query = {
"field": ["id", "project.id"],
"project": [project.id],
"query": f"!project:{project2.slug}",
}
response = self.do_request(query)
assert response.status_code == 200
assert response.data["data"] == [{"id": "a" * 32, "project.id": project.id}]
def test_project_condition_used_for_automatic_filters(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"environment": "staging",
"timestamp": self.ten_mins_ago_iso,
},
project_id=self.project.id,
)
query = {
"field": ["project", "count()"],
"query": f'project:"{self.project.slug}"',
"statsPeriod": "14d",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["project"] == self.project.slug
assert "project.id" not in response.data["data"][0]
def test_auto_insert_project_name_when_event_id_present(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"environment": "staging",
"timestamp": self.ten_mins_ago_iso,
},
project_id=self.project.id,
)
query = {"field": ["id"], "statsPeriod": "1h"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert response.data["data"] == [{"project.name": self.project.slug, "id": "a" * 32}]
def test_auto_insert_project_name_when_event_id_present_with_aggregate(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"environment": "staging",
"timestamp": self.ten_mins_ago_iso,
},
project_id=self.project.id,
)
query = {"field": ["id", "count()"], "statsPeriod": "1h"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert response.data["data"] == [
{"project.name": self.project.slug, "id": "a" * 32, "count()": 1}
]
def test_performance_short_group_id(self) -> None:
event = self.create_performance_issue()
assert event.group is not None
query = {
"field": ["count()"],
"statsPeriod": "1h",
"query": f"project:{event.group.project.slug} issue:{event.group.qualified_short_id}",
"dataset": "issuePlatform",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert response.data["data"][0]["count()"] == 1
def test_multiple_performance_short_group_ids_filter(self) -> None:
event1 = self.create_performance_issue()
event2 = self.create_performance_issue()
assert event1.group is not None
assert event2.group is not None
query = {
"field": ["count()"],
"statsPeriod": "1h",
"query": f"project:{event1.group.project.slug} issue:[{event1.group.qualified_short_id},{event2.group.qualified_short_id}]",
"dataset": "issuePlatform",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert response.data["data"][0]["count()"] == 2
def test_event_id_with_in_search(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"environment": "staging1",
"timestamp": self.ten_mins_ago_iso,
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"environment": "staging2",
"timestamp": self.ten_mins_ago_iso,
},
project_id=self.project.id,
)
# Should not show up
self.store_event(
data={
"event_id": "c" * 32,
"environment": "staging3",
"timestamp": self.ten_mins_ago_iso,
},
project_id=self.project.id,
)
query = {
"field": ["id", "environment"],
"statsPeriod": "1h",
"query": f"id:[{'a' * 32}, {'b' * 32}]",
"orderby": "environment",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 2
assert response.data["data"][0]["id"] == "a" * 32
assert response.data["data"][1]["id"] == "b" * 32
def test_user_search(self) -> None:
self.transaction_data["user"] = {
"email": "foo@example.com",
"id": "123",
"ip_address": "127.0.0.1",
"username": "foo",
}
self.store_event(self.transaction_data, project_id=self.project.id)
fields = {
"email": "user.email",
"id": "user.id",
"ip_address": "user.ip",
"username": "user.username",
}
features = {"organizations:discover-basic": True}
for dataset in ["discover", "transactions"]:
for key, value in self.transaction_data["user"].items():
field = fields[key]
query = {
"field": ["project", "user"],
"query": f"{field}:{value}",
"statsPeriod": "14d",
"dataset": dataset,
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["project"] == self.project.slug
assert response.data["data"][0]["user"] == "id:123"
def test_has_user(self) -> None:
self.store_event(self.transaction_data, project_id=self.project.id)
features = {"organizations:discover-basic": True}
for dataset in ["discover", "transactions"]:
for value in self.transaction_data["user"].values():
query = {
"field": ["project", "user"],
"query": "has:user",
"statsPeriod": "14d",
"dataset": dataset,
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["user"] == "ip:{}".format(
self.transaction_data["user"]["ip_address"]
)
def test_team_param_no_access(self) -> None:
org = self.create_organization(
owner=self.user, # use other user as owner
name="foo",
flags=0, # disable default allow_joinleave
)
project = self.create_project(name="baz", organization=org)
user = self.create_user()
self.login_as(user=user, superuser=False)
team = self.create_team(organization=org, name="Team Bar")
project.add_team(team)
self.store_event(
data={
"event_id": "a" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group1"],
},
project_id=project.id,
)
query = {"field": ["id", "project.id"], "project": [project.id], "team": [team.id]}
response = self.do_request(query)
assert response.status_code == 403, response.content
assert response.data["detail"] == "You do not have permission to perform this action."
def test_team_is_nan(self) -> None:
query = {"field": ["id"], "project": [self.project.id], "team": [math.nan]}
response = self.do_request(query)
assert response.status_code == 400, response.content
assert response.data["detail"] == "Invalid Team ID: nan"
def test_comparison_operators_on_numeric_field(self) -> None:
event = self.store_event(
{"timestamp": before_now(minutes=1).isoformat()}, project_id=self.project.id
)
query = {"field": ["issue"], "query": f"issue.id:>{event.group.id - 1}"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["issue"] == event.group.qualified_short_id
query = {"field": ["issue"], "query": f"issue.id:>{event.group.id}"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 0
def test_negation_on_numeric_field_excludes_issue(self) -> None:
event = self.store_event({"timestamp": self.ten_mins_ago_iso}, project_id=self.project.id)
query = {"field": ["issue"], "query": f"issue.id:{event.group.id}"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["issue"] == event.group.qualified_short_id
query = {"field": ["issue"], "query": f"!issue.id:{event.group.id}"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 0
def test_negation_on_numeric_in_filter_excludes_issue(self) -> None:
event = self.store_event({"timestamp": self.ten_mins_ago_iso}, project_id=self.project.id)
query = {"field": ["issue"], "query": f"issue.id:[{event.group.id}]"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["issue"] == event.group.qualified_short_id
query = {"field": ["issue"], "query": f"!issue.id:[{event.group.id}]"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 0
def test_negation_on_duration_filter_excludes_transaction(self) -> None:
event = self.store_event(self.transaction_data, project_id=self.project.id)
duration = int(event.data.get("timestamp") - event.data.get("start_timestamp")) * 1000
for dataset in ["discover", "transactions"]:
query = {
"field": ["transaction"],
"query": f"transaction.duration:{duration}",
"dataset": dataset,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["id"] == event.event_id
query = {"field": ["transaction"], "query": f"!transaction.duration:{duration}"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 0
def test_has_issue(self) -> None:
event = self.store_event({"timestamp": self.ten_mins_ago_iso}, project_id=self.project.id)
self.store_event(self.transaction_data, project_id=self.project.id)
features = {"organizations:discover-basic": True}
# should only show 1 event of type default
query = {"field": ["project", "issue"], "query": "has:issue", "statsPeriod": "14d"}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["issue"] == event.group.qualified_short_id
# should only show 1 event of type default
query = {
"field": ["project", "issue"],
"query": "event.type:default has:issue",
"statsPeriod": "14d",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["issue"] == event.group.qualified_short_id
# should show no results because no the default event has an issue
query = {
"field": ["project", "issue"],
"query": "event.type:default !has:issue",
"statsPeriod": "14d",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 0
# should show no results because no transactions have issues
query = {
"field": ["project", "issue"],
"query": "event.type:transaction has:issue",
"statsPeriod": "14d",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 0
# should only show 1 event of type transaction since they don't have issues
query = {
"field": ["project", "issue"],
"query": "event.type:transaction !has:issue",
"statsPeriod": "14d",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["issue"] == "unknown"
@pytest.mark.skip("Cannot look up group_id of transaction events")
def test_unknown_issue(self) -> None:
event = self.store_event({"timestamp": self.ten_mins_ago_iso}, project_id=self.project.id)
self.store_event(self.transaction_data, project_id=self.project.id)
features = {"organizations:discover-basic": True}
query = {"field": ["project", "issue"], "query": "issue:unknown", "statsPeriod": "14d"}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["issue"] == "unknown"
query = {"field": ["project", "issue"], "query": "!issue:unknown", "statsPeriod": "14d"}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["issue"] == event.group.qualified_short_id
def test_negative_user_search(self) -> None:
user_data = {"email": "foo@example.com", "id": "123", "username": "foo"}
# Load an event with data that shouldn't match
data = self.transaction_data.copy()
data["transaction"] = "/transactions/nomatch"
event_user = user_data.copy()
event_user["id"] = "undefined"
data["user"] = event_user
self.store_event(data, project_id=self.project.id)
# Load a matching event
data = self.transaction_data.copy()
data["transaction"] = "/transactions/matching"
data["user"] = user_data
self.store_event(data, project_id=self.project.id)
features = {"organizations:discover-basic": True}
for dataset in ["discover", "transactions"]:
query = {
"field": ["project", "user"],
"query": '!user:"id:undefined"',
"statsPeriod": "14d",
"dataset": dataset,
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["user"] == "id:{}".format(user_data["id"])
assert "user.email" not in response.data["data"][0]
assert "user.id" not in response.data["data"][0]
def test_not_project_in_query(self) -> None:
project1 = self.create_project()
project2 = self.create_project()
self.store_event(
data={
"event_id": "a" * 32,
"environment": "staging",
"timestamp": self.ten_mins_ago_iso,
},
project_id=project1.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"environment": "staging",
"timestamp": self.ten_mins_ago_iso,
},
project_id=project2.id,
)
features = {"organizations:discover-basic": True}
query = {
"field": ["project", "count()"],
"query": '!project:"%s"' % project1.slug,
"statsPeriod": "14d",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["project"] == project2.slug
assert "project.id" not in response.data["data"][0]
def test_error_handled_condition(self) -> None:
prototype = self.load_data(platform="android-ndk")
events = (
("a" * 32, "not handled", False),
("b" * 32, "was handled", True),
("c" * 32, "undefined", None),
)
for event in events:
prototype["event_id"] = event[0]
prototype["logentry"] = {"formatted": event[1]}
prototype["exception"]["values"][0]["value"] = event[1]
prototype["exception"]["values"][0]["mechanism"]["handled"] = event[2]
prototype["timestamp"] = self.ten_mins_ago_iso
self.store_event(data=prototype, project_id=self.project.id)
with self.feature("organizations:discover-basic"):
query = {
"field": ["message", "error.handled"],
"query": "error.handled:0",
"orderby": "message",
}
response = self.do_request(query)
assert response.status_code == 200, response.data
assert 1 == len(response.data["data"])
assert 0 == response.data["data"][0]["error.handled"]
with self.feature("organizations:discover-basic"):
query = {
"field": ["message", "error.handled"],
"query": "error.handled:1",
"orderby": "message",
}
response = self.do_request(query)
assert response.status_code == 200, response.data
assert 2 == len(response.data["data"])
assert 1 == response.data["data"][0]["error.handled"]
assert 1 == response.data["data"][1]["error.handled"]
def test_error_unhandled_condition(self) -> None:
prototype = self.load_data(platform="android-ndk")
events = (
("a" * 32, "not handled", False),
("b" * 32, "was handled", True),
("c" * 32, "undefined", None),
)
for event in events:
prototype["event_id"] = event[0]
prototype["logentry"] = {"formatted": event[1]}
prototype["exception"]["values"][0]["value"] = event[1]
prototype["exception"]["values"][0]["mechanism"]["handled"] = event[2]
prototype["timestamp"] = self.ten_mins_ago_iso
self.store_event(data=prototype, project_id=self.project.id)
with self.feature("organizations:discover-basic"):
query = {
"field": ["message", "error.unhandled", "error.handled"],
"query": "error.unhandled:true",
"orderby": "message",
}
response = self.do_request(query)
assert response.status_code == 200, response.data
assert 1 == len(response.data["data"])
assert 0 == response.data["data"][0]["error.handled"]
assert 1 == response.data["data"][0]["error.unhandled"]
with self.feature("organizations:discover-basic"):
query = {
"field": ["message", "error.handled", "error.unhandled"],
"query": "error.unhandled:false",
"orderby": "message",
}
response = self.do_request(query)
assert response.status_code == 200, response.data
assert 2 == len(response.data["data"])
assert 1 == response.data["data"][0]["error.handled"]
assert 0 == response.data["data"][0]["error.unhandled"]
assert 1 == response.data["data"][1]["error.handled"]
assert 0 == response.data["data"][1]["error.unhandled"]
def test_groupby_error_handled_and_unhandled(self) -> None:
prototype = self.load_data(platform="android-ndk")
events = (
("a" * 32, "not handled", False),
("b" * 32, "was handled", True),
("c" * 32, "undefined", None),
)
for event in events:
prototype["event_id"] = event[0]
prototype["logentry"] = {"formatted": event[1]}
prototype["exception"]["values"][0]["value"] = event[1]
prototype["exception"]["values"][0]["mechanism"]["handled"] = event[2]
prototype["timestamp"] = self.ten_mins_ago_iso
self.store_event(data=prototype, project_id=self.project.id)
with self.feature("organizations:discover-basic"):
query = {
"field": ["error.handled", "count()"],
"query": "event.type:error",
}
response = self.do_request(query)
assert response.status_code == 200, response.data
assert 2 == len(response.data["data"])
assert 0 == response.data["data"][0]["error.handled"]
assert 1 == response.data["data"][0]["count()"]
assert 1 == response.data["data"][1]["error.handled"]
assert 2 == response.data["data"][1]["count()"]
with self.feature("organizations:discover-basic"):
query = {
"field": ["error.unhandled", "count()"],
"query": "event.type:error",
}
response = self.do_request(query)
assert response.status_code == 200, response.data
assert 2 == len(response.data["data"])
assert 0 == response.data["data"][0]["error.unhandled"]
assert 2 == response.data["data"][0]["count()"]
assert 1 == response.data["data"][1]["error.unhandled"]
assert 1 == response.data["data"][1]["count()"]
def test_error_main_thread_condition(self) -> None:
prototype = self.load_data(platform="android-ndk")
prototype["timestamp"] = self.ten_mins_ago_iso
self.store_event(data=prototype, project_id=self.project.id)
with self.feature("organizations:discover-basic"):
query = {
"field": ["id", "project.id"],
"query": "error.main_thread:true",
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 200, response.data
assert 1 == len(response.data["data"])
with self.feature("organizations:discover-basic"):
query = {
"field": ["id", "project.id"],
"query": "error.main_thread:false",
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 200, response.data
assert 0 == len(response.data["data"])
def test_implicit_groupby(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"timestamp": self.eleven_mins_ago_iso,
"fingerprint": ["group_1"],
},
project_id=self.project.id,
)
event1 = self.store_event(
data={
"event_id": "b" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
},
project_id=self.project.id,
)
event2 = self.store_event(
data={
"event_id": "c" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
},
project_id=self.project.id,
)
query = {"field": ["count(id)", "project.id", "issue.id"], "orderby": "issue.id"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 2
data = response.data["data"]
assert data[0] == {
"project.id": self.project.id,
"issue.id": event1.group_id,
"count(id)": 2,
}
assert data[1] == {
"project.id": self.project.id,
"issue.id": event2.group_id,
"count(id)": 1,
}
meta = response.data["meta"]["fields"]
assert meta["count(id)"] == "integer"
def test_orderby(self) -> None:
self.store_event(
data={"event_id": "a" * 32, "timestamp": self.eleven_mins_ago_iso},
project_id=self.project.id,
)
self.store_event(
data={"event_id": "b" * 32, "timestamp": self.ten_mins_ago_iso},
project_id=self.project.id,
)
self.store_event(
data={"event_id": "c" * 32, "timestamp": self.ten_mins_ago_iso},
project_id=self.project.id,
)
query = {"field": ["id", "timestamp"], "orderby": ["-timestamp", "-id"]}
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert data[0]["id"] == "c" * 32
assert data[1]["id"] == "b" * 32
assert data[2]["id"] == "a" * 32
def test_sort_title(self) -> None:
self.store_event(
data={"event_id": "a" * 32, "message": "zlast", "timestamp": self.eleven_mins_ago_iso},
project_id=self.project.id,
)
self.store_event(
data={"event_id": "b" * 32, "message": "second", "timestamp": self.ten_mins_ago_iso},
project_id=self.project.id,
)
self.store_event(
data={"event_id": "c" * 32, "message": "first", "timestamp": self.ten_mins_ago_iso},
project_id=self.project.id,
)
query = {"field": ["id", "title"], "sort": "title"}
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert data[0]["id"] == "c" * 32
assert data[1]["id"] == "b" * 32
assert data[2]["id"] == "a" * 32
def test_sort_invalid(self) -> None:
self.create_project()
query = {"field": ["id"], "sort": "garbage"}
response = self.do_request(query)
assert response.status_code == 400
assert "sort by" in response.data["detail"]
def test_latest_release_alias(self) -> None:
event1 = self.store_event(
data={"event_id": "a" * 32, "timestamp": self.eleven_mins_ago_iso, "release": "0.8"},
project_id=self.project.id,
)
query = {"field": ["issue.id", "release"], "query": "release:latest"}
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert data[0]["issue.id"] == event1.group_id
assert data[0]["release"] == "0.8"
event2 = self.store_event(
data={"event_id": "a" * 32, "timestamp": self.ten_mins_ago_iso, "release": "0.9"},
project_id=self.project.id,
)
query = {"field": ["issue.id", "release"], "query": "release:latest"}
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert data[0]["issue.id"] == event2.group_id
assert data[0]["release"] == "0.9"
def test_semver(self) -> None:
release_1 = self.create_release(version="test@1.2.3")
release_2 = self.create_release(version="test@1.2.4")
release_3 = self.create_release(version="test@1.2.5")
release_1_e_1 = self.store_event(
data={"release": release_1.version, "timestamp": self.ten_mins_ago_iso},
project_id=self.project.id,
).event_id
release_1_e_2 = self.store_event(
data={"release": release_1.version, "timestamp": self.ten_mins_ago_iso},
project_id=self.project.id,
).event_id
release_2_e_1 = self.store_event(
data={"release": release_2.version, "timestamp": self.ten_mins_ago_iso},
project_id=self.project.id,
).event_id
release_2_e_2 = self.store_event(
data={"release": release_2.version, "timestamp": self.ten_mins_ago_iso},
project_id=self.project.id,
).event_id
release_3_e_1 = self.store_event(
data={"release": release_3.version, "timestamp": self.ten_mins_ago_iso},
project_id=self.project.id,
).event_id
release_3_e_2 = self.store_event(
data={"release": release_3.version, "timestamp": self.ten_mins_ago_iso},
project_id=self.project.id,
).event_id
query = {"field": ["id"], "query": f"{constants.SEMVER_ALIAS}:>1.2.3"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert {r["id"] for r in response.data["data"]} == {
release_2_e_1,
release_2_e_2,
release_3_e_1,
release_3_e_2,
}
query = {"field": ["id"], "query": f"{constants.SEMVER_ALIAS}:>=1.2.3"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert {r["id"] for r in response.data["data"]} == {
release_1_e_1,
release_1_e_2,
release_2_e_1,
release_2_e_2,
release_3_e_1,
release_3_e_2,
}
query = {"field": ["id"], "query": f"{constants.SEMVER_ALIAS}:<1.2.4"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert {r["id"] for r in response.data["data"]} == {
release_1_e_1,
release_1_e_2,
}
query = {"field": ["id"], "query": f"{constants.SEMVER_ALIAS}:1.2.3"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert {r["id"] for r in response.data["data"]} == {
release_1_e_1,
release_1_e_2,
}
query = {"field": ["id"], "query": f"!{constants.SEMVER_ALIAS}:1.2.3"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert {r["id"] for r in response.data["data"]} == {
release_2_e_1,
release_2_e_2,
release_3_e_1,
release_3_e_2,
}
def test_release_stage(self) -> None:
replaced_release = self.create_release(
version="replaced_release",
environments=[self.environment],
adopted=timezone.now(),
unadopted=timezone.now(),
)
adopted_release = self.create_release(
version="adopted_release",
environments=[self.environment],
adopted=timezone.now(),
)
self.create_release(version="not_adopted_release", environments=[self.environment])
adopted_release_e_1 = self.store_event(
data={
"release": adopted_release.version,
"timestamp": self.ten_mins_ago_iso,
"environment": self.environment.name,
},
project_id=self.project.id,
).event_id
adopted_release_e_2 = self.store_event(
data={
"release": adopted_release.version,
"timestamp": self.ten_mins_ago_iso,
"environment": self.environment.name,
},
project_id=self.project.id,
).event_id
replaced_release_e_1 = self.store_event(
data={
"release": replaced_release.version,
"timestamp": self.ten_mins_ago_iso,
"environment": self.environment.name,
},
project_id=self.project.id,
).event_id
replaced_release_e_2 = self.store_event(
data={
"release": replaced_release.version,
"timestamp": self.ten_mins_ago_iso,
"environment": self.environment.name,
},
project_id=self.project.id,
).event_id
query = {
"field": ["id"],
"query": f"{constants.RELEASE_STAGE_ALIAS}:{ReleaseStages.ADOPTED.value}",
"environment": [self.environment.name],
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert {r["id"] for r in response.data["data"]} == {
adopted_release_e_1,
adopted_release_e_2,
}
query = {
"field": ["id"],
"query": f"!{constants.RELEASE_STAGE_ALIAS}:{ReleaseStages.LOW_ADOPTION.value}",
"environment": [self.environment.name],
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert {r["id"] for r in response.data["data"]} == {
adopted_release_e_1,
adopted_release_e_2,
replaced_release_e_1,
replaced_release_e_2,
}
query = {
"field": ["id"],
"query": f"{constants.RELEASE_STAGE_ALIAS}:[{ReleaseStages.ADOPTED.value}, {ReleaseStages.REPLACED.value}]",
"environment": [self.environment.name],
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert {r["id"] for r in response.data["data"]} == {
adopted_release_e_1,
adopted_release_e_2,
replaced_release_e_1,
replaced_release_e_2,
}
def test_semver_package(self) -> None:
release_1 = self.create_release(version="test@1.2.3")
release_2 = self.create_release(version="test2@1.2.4")
release_1_e_1 = self.store_event(
data={"release": release_1.version, "timestamp": self.ten_mins_ago_iso},
project_id=self.project.id,
).event_id
release_1_e_2 = self.store_event(
data={"release": release_1.version, "timestamp": self.ten_mins_ago_iso},
project_id=self.project.id,
).event_id
release_2_e_1 = self.store_event(
data={"release": release_2.version, "timestamp": self.ten_mins_ago_iso},
project_id=self.project.id,
).event_id
query = {"field": ["id"], "query": f"{constants.SEMVER_PACKAGE_ALIAS}:test"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert {r["id"] for r in response.data["data"]} == {
release_1_e_1,
release_1_e_2,
}
query = {"field": ["id"], "query": f"{constants.SEMVER_PACKAGE_ALIAS}:test2"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert {r["id"] for r in response.data["data"]} == {
release_2_e_1,
}
def test_semver_build(self) -> None:
release_1 = self.create_release(version="test@1.2.3+123")
release_2 = self.create_release(version="test2@1.2.4+124")
release_1_e_1 = self.store_event(
data={"release": release_1.version, "timestamp": self.ten_mins_ago_iso},
project_id=self.project.id,
).event_id
release_1_e_2 = self.store_event(
data={"release": release_1.version, "timestamp": self.ten_mins_ago_iso},
project_id=self.project.id,
).event_id
release_2_e_1 = self.store_event(
data={"release": release_2.version, "timestamp": self.ten_mins_ago_iso},
project_id=self.project.id,
).event_id
query = {"field": ["id"], "query": f"{constants.SEMVER_BUILD_ALIAS}:123"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert {r["id"] for r in response.data["data"]} == {
release_1_e_1,
release_1_e_2,
}
query = {"field": ["id"], "query": f"{constants.SEMVER_BUILD_ALIAS}:124"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert {r["id"] for r in response.data["data"]} == {
release_2_e_1,
}
query = {"field": ["id"], "query": f"!{constants.SEMVER_BUILD_ALIAS}:124"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert {r["id"] for r in response.data["data"]} == {
release_1_e_1,
release_1_e_2,
}
def test_aliased_fields(self) -> None:
event1 = self.store_event(
data={
"event_id": "a" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
"user": {"email": "foo@example.com"},
},
project_id=self.project.id,
)
event2 = self.store_event(
data={
"event_id": "b" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"email": "foo@example.com"},
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "c" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"email": "bar@example.com"},
},
project_id=self.project.id,
)
query = {"field": ["issue.id", "count(id)", "count_unique(user)"], "orderby": "issue.id"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 2
data = response.data["data"]
assert data[0]["issue.id"] == event1.group_id
assert data[0]["count(id)"] == 1
assert data[0]["count_unique(user)"] == 1
assert "projectid" not in data[0]
assert "project.id" not in data[0]
assert data[1]["issue.id"] == event2.group_id
assert data[1]["count(id)"] == 2
assert data[1]["count_unique(user)"] == 2
def test_aggregate_field_with_dotted_param(self) -> None:
event1 = self.store_event(
data={
"event_id": "a" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
"user": {"id": "123", "email": "foo@example.com"},
},
project_id=self.project.id,
)
event2 = self.store_event(
data={
"event_id": "b" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"id": "123", "email": "foo@example.com"},
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "c" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"id": "456", "email": "bar@example.com"},
},
project_id=self.project.id,
)
query = {
"field": ["issue.id", "issue_title", "count(id)", "count_unique(user.email)"],
"orderby": "issue.id",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 2
data = response.data["data"]
assert data[0]["issue.id"] == event1.group_id
assert data[0]["count(id)"] == 1
assert data[0]["count_unique(user.email)"] == 1
assert "projectid" not in data[0]
assert "project.id" not in data[0]
assert data[1]["issue.id"] == event2.group_id
assert data[1]["count(id)"] == 2
assert data[1]["count_unique(user.email)"] == 2
def test_failure_rate_alias_field(self) -> None:
data = self.transaction_data.copy()
data["transaction"] = "/failure_rate/success"
self.store_event(data, project_id=self.project.id)
data = self.transaction_data.copy()
data["transaction"] = "/failure_rate/unknown"
data["contexts"]["trace"]["status"] = "unknown_error"
self.store_event(data, project_id=self.project.id)
for i in range(6):
data = self.transaction_data.copy()
data["transaction"] = f"/failure_rate/{i}"
data["contexts"]["trace"]["status"] = "unauthenticated"
self.store_event(data, project_id=self.project.id)
for dataset in ["discover", "transactions"]:
query = {
"field": ["failure_rate()"],
"query": "event.type:transaction",
"dataset": dataset,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
data = response.data["data"]
assert data[0]["failure_rate()"] == 0.875
def test_count_miserable_alias_field(self) -> None:
self._setup_user_misery()
for dataset in ["discover", "transactions"]:
query = {
"field": ["count_miserable(user, 300)"],
"query": "event.type:transaction",
"dataset": dataset,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
data = response.data["data"]
assert data[0]["count_miserable(user, 300)"] == 3
@mock.patch(
"sentry.search.events.fields.MAX_QUERYABLE_TRANSACTION_THRESHOLDS",
MAX_QUERYABLE_TRANSACTION_THRESHOLDS,
)
@mock.patch(
"sentry.search.events.datasets.discover.MAX_QUERYABLE_TRANSACTION_THRESHOLDS",
MAX_QUERYABLE_TRANSACTION_THRESHOLDS,
)
def test_too_many_transaction_thresholds(self) -> None:
project_transaction_thresholds = []
project_ids = []
for i in range(MAX_QUERYABLE_TRANSACTION_THRESHOLDS + 1):
project = self.create_project(name=f"bulk_txn_{i}")
project_ids.append(project.id)
project_transaction_thresholds.append(
ProjectTransactionThreshold(
organization=self.organization,
project=project,
threshold=400,
metric=TransactionMetric.LCP.value,
)
)
ProjectTransactionThreshold.objects.bulk_create(project_transaction_thresholds)
query = {
"field": [
"transaction",
"count_miserable(user)",
],
"query": "event.type:transaction",
"project": project_ids,
}
response = self.do_request(
query,
features={
"organizations:discover-basic": True,
},
)
assert response.status_code == 400
assert (
response.data["detail"]
== "Exceeded 1 configured transaction thresholds limit, try with fewer Projects."
)
def test_count_miserable_new_alias_field(self) -> None:
ProjectTransactionThreshold.objects.create(
project=self.project,
organization=self.project.organization,
threshold=400, # This is higher than the default threshold
metric=TransactionMetric.DURATION.value,
)
self._setup_user_misery()
query = {
"field": [
"transaction",
"count_miserable(user)",
],
"query": "event.type:transaction",
"project": [self.project.id],
"sort": "count_miserable_user",
}
def _expected(index: int, count: int) -> dict[str, Any]:
return {
"transaction": f"/count_miserable/horribilis/{index}",
"project_threshold_config": ["duration", 400],
"count_miserable(user)": count,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
# Sorted by count_miserable_user, however, withing the same count_miserable_user,
# the order is not guaranteed
for expected in [
_expected(0, 0),
_expected(1, 0),
_expected(2, 1),
_expected(3, 1),
_expected(4, 0),
_expected(5, 1),
]:
assert expected in response.data["data"]
# The condition will exclude transactions with count_miserable(user) == 0
query["query"] = "event.type:transaction count_miserable(user):>0"
response = self.do_request(query)
assert response.status_code == 200, response.content
for expected in [_expected(2, 1), _expected(3, 1), _expected(5, 1)]:
assert expected in response.data["data"]
def test_user_misery_denominator(self) -> None:
"""This is to test against a bug where the denominator of misery(total unique users) was wrong
This is because the total unique users for a LCP misery should only count users that have had a txn with lcp,
and not count all transactions (ie. uniq_if(transaction has lcp) not just uniq())
"""
ProjectTransactionThreshold.objects.create(
project=self.project,
organization=self.project.organization,
threshold=600,
metric=TransactionMetric.LCP.value,
)
lcps = [
400,
400,
300,
3000,
3000,
3000,
]
for idx, lcp in enumerate(lcps):
data = self.load_data(
timestamp=before_now(minutes=(10 + idx)),
)
data["event_id"] = f"{idx}" * 32
data["transaction"] = "/misery/new/"
data["user"] = {"email": f"{idx}@example.com"}
data["measurements"] = {
"lcp": {"value": lcp},
}
self.store_event(data, project_id=self.project.id)
# Shouldn't count towards misery
data = self.load_data(timestamp=self.ten_mins_ago, duration=timedelta(milliseconds=0))
data["transaction"] = "/misery/new/"
data["user"] = {"email": "7@example.com"}
data["measurements"] = {}
self.store_event(data, project_id=self.project.id)
query = {
"field": [
"transaction",
"user_misery()",
],
"query": "event.type:transaction",
"project": [self.project.id],
"sort": "-user_misery",
}
response = self.do_request(
query,
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
data = response.data["data"]
# (3 frustrated + 5.8875) / (6 + 117.75)
assert abs(data[0]["user_misery()"] - user_misery_formula(3, 6)) < 0.0001
def test_user_misery_alias_field(self) -> None:
events = [
("one", 300),
("one", 300),
("two", 3000),
("two", 3000),
("three", 300),
("three", 3000),
]
for idx, event in enumerate(events):
data = self.load_data(
timestamp=before_now(minutes=(10 + idx)),
duration=timedelta(milliseconds=event[1]),
)
data["event_id"] = f"{idx}" * 32
data["transaction"] = f"/user_misery/{idx}"
data["user"] = {"email": f"{event[0]}@example.com"}
self.store_event(data, project_id=self.project.id)
query = {"field": ["user_misery(300)"], "query": "event.type:transaction"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
data = response.data["data"]
assert abs(data[0]["user_misery(300)"] - user_misery_formula(2, 3)) < 0.0001
def test_apdex_denominator_correct(self) -> None:
"""This is to test against a bug where the denominator of apdex(total count) was wrong
This is because the total_count for a LCP apdex should only count transactions that have lcp, and not count
all transactions (ie. count_if(transaction has lcp) not just count())
"""
ProjectTransactionThreshold.objects.create(
project=self.project,
organization=self.project.organization,
threshold=600,
metric=TransactionMetric.LCP.value,
)
lcps = [
400,
400,
300,
800,
3000,
3000,
3000,
]
for idx, lcp in enumerate(lcps):
data = self.load_data(
timestamp=before_now(minutes=(10 + idx)),
)
data["event_id"] = f"{idx}" * 32
data["transaction"] = "/apdex/new/"
data["user"] = {"email": f"{idx}@example.com"}
data["measurements"] = {
"lcp": {"value": lcp},
}
self.store_event(data, project_id=self.project.id)
# Shouldn't count towards apdex
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(milliseconds=0),
)
data["transaction"] = "/apdex/new/"
data["user"] = {"email": "7@example.com"}
data["measurements"] = {}
self.store_event(data, project_id=self.project.id)
query = {
"field": [
"transaction",
"apdex()",
],
"query": "event.type:transaction",
"project": [self.project.id],
"sort": "-apdex",
}
response = self.do_request(
query,
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
data = response.data["data"]
# 3 satisfied + 1 tolerated => 3.5/7
assert data[0]["apdex()"] == 0.5
def test_apdex_new_alias_field(self) -> None:
ProjectTransactionThreshold.objects.create(
project=self.project,
organization=self.project.organization,
threshold=400,
metric=TransactionMetric.DURATION.value,
)
events = [
("one", 400),
("one", 400),
("two", 3000),
("two", 3000),
("three", 300),
("three", 3000),
]
for idx, event in enumerate(events):
data = self.load_data(
timestamp=before_now(minutes=(10 + idx)),
duration=timedelta(milliseconds=event[1]),
)
data["event_id"] = f"{idx}" * 32
data["transaction"] = f"/apdex/new/{event[0]}"
data["user"] = {"email": f"{idx}@example.com"}
self.store_event(data, project_id=self.project.id)
query = {
"field": [
"transaction",
"apdex()",
],
"query": "event.type:transaction",
"project": [self.project.id],
"sort": "-apdex",
}
response = self.do_request(
query,
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 3
data = response.data["data"]
assert data[0]["apdex()"] == 1.0
assert data[1]["apdex()"] == 0.5
assert data[2]["apdex()"] == 0.0
query["query"] = "event.type:transaction apdex():>0.50"
response = self.do_request(
query,
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
data = response.data["data"]
assert data[0]["apdex()"] == 1.0
def test_user_misery_alias_field_with_project_threshold(self) -> None:
ProjectTransactionThreshold.objects.create(
project=self.project,
organization=self.project.organization,
threshold=400,
metric=TransactionMetric.DURATION.value,
)
events = [
("one", 400),
("one", 400),
("two", 3000),
("two", 3000),
("three", 300),
("three", 3000),
]
for idx, event in enumerate(events):
data = self.load_data(
timestamp=before_now(minutes=(10 + idx)),
duration=timedelta(milliseconds=event[1]),
)
data["event_id"] = f"{idx}" * 32
data["transaction"] = f"/count_miserable/horribilis/{event[0]}"
data["user"] = {"email": f"{idx}@example.com"}
self.store_event(data, project_id=self.project.id)
query = {
"field": [
"transaction",
"user_misery()",
],
"orderby": "user_misery()",
"query": "event.type:transaction",
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 3
data = response.data["data"]
assert data[0]["user_misery()"] == user_misery_formula(0, 2)
assert data[1]["user_misery()"] == user_misery_formula(1, 2)
assert data[2]["user_misery()"] == user_misery_formula(2, 2)
query["query"] = "event.type:transaction user_misery():>0.050"
response = self.do_request(
query,
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 2
data = response.data["data"]
assert data[0]["user_misery()"] == user_misery_formula(1, 2)
assert data[1]["user_misery()"] == user_misery_formula(2, 2)
def test_user_misery_alias_field_with_transaction_threshold(self) -> None:
self._setup_user_misery(per_transaction_threshold=True)
query = {
"field": [
"transaction",
"user_misery()",
],
"query": "event.type:transaction",
"orderby": "transaction",
"project": [self.project.id],
}
response = self.do_request(
query,
)
assert response.status_code == 200, response.content
expected = [
("/count_miserable/horribilis/0", ["duration", 300], user_misery_formula(0, 1)),
("/count_miserable/horribilis/1", ["duration", 100], user_misery_formula(0, 1)),
("/count_miserable/horribilis/2", ["duration", 300], user_misery_formula(1, 1)),
("/count_miserable/horribilis/3", ["duration", 300], user_misery_formula(1, 1)),
("/count_miserable/horribilis/4", ["duration", 300], user_misery_formula(0, 1)),
("/count_miserable/horribilis/5", ["duration", 500], user_misery_formula(1, 1)),
]
assert len(response.data["data"]) == 6
data = response.data["data"]
for i, record in enumerate(expected):
name, threshold_config, misery = record
assert data[i]["transaction"] == name
assert data[i]["project_threshold_config"] == threshold_config
assert data[i]["user_misery()"] == pytest.approx(misery, rel=1e-3)
query["query"] = "event.type:transaction user_misery():>0.050"
response = self.do_request(
query,
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 3
data = response.data["data"]
assert data[0]["user_misery()"] == user_misery_formula(1, 1)
assert data[1]["user_misery()"] == user_misery_formula(1, 1)
assert data[2]["user_misery()"] == user_misery_formula(1, 1)
def test_user_misery_alias_field_with_transaction_threshold_and_project_threshold(self) -> None:
project = self.create_project()
ProjectTransactionThreshold.objects.create(
project=project,
organization=project.organization,
threshold=100,
metric=TransactionMetric.DURATION.value,
)
self._setup_user_misery(per_transaction_threshold=True, project=project)
project2 = self.create_project()
data = self.load_data()
data["transaction"] = "/count_miserable/horribilis/project2"
data["user"] = {"email": "project2@example.com"}
self.store_event(data, project_id=project2.id)
query = {
"field": [
"transaction",
"user_misery()",
],
"query": "event.type:transaction",
"orderby": "transaction",
"project": [project.id, project2.id],
}
response = self.do_request(
query,
features={
"organizations:discover-basic": True,
},
)
assert response.status_code == 200, response.content
zero_one = user_misery_formula(0, 1)
one_one = user_misery_formula(1, 1)
expected = [
# Uses project threshold
("/count_miserable/horribilis/0", ["duration", 100], zero_one),
("/count_miserable/horribilis/1", ["duration", 100], zero_one), # Uses txn threshold
("/count_miserable/horribilis/2", ["duration", 100], one_one), # Uses project threshold
("/count_miserable/horribilis/3", ["duration", 300], one_one), # Uses txn threshold
# Uses project threshold
("/count_miserable/horribilis/4", ["duration", 100], zero_one),
("/count_miserable/horribilis/5", ["duration", 500], one_one), # Uses txn threshold
("/count_miserable/horribilis/project2", ["duration", 300], one_one), # Uses fallback
]
data = response.data["data"]
for i, record in enumerate(expected):
name, threshold_config, misery = record
assert data[i]["transaction"] == name
assert data[i]["project_threshold_config"] == threshold_config
assert data[i]["user_misery()"] == misery
query["query"] = "event.type:transaction user_misery():>0.050"
response = self.do_request(
query,
features={
"organizations:discover-basic": True,
},
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 4
def test_aggregation(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
"user": {"email": "foo@example.com"},
"environment": "prod",
"tags": {"sub_customer.is-Enterprise-42": "1"},
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"email": "foo@example.com"},
"environment": "staging",
"tags": {"sub_customer.is-Enterprise-42": "1"},
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "c" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"email": "foo@example.com"},
"environment": "prod",
"tags": {"sub_customer.is-Enterprise-42": "0"},
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "d" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"email": "foo@example.com"},
"environment": "prod",
"tags": {"sub_customer.is-Enterprise-42": "1"},
},
project_id=self.project.id,
)
query = {
"field": ["sub_customer.is-Enterprise-42", "count(sub_customer.is-Enterprise-42)"],
"orderby": "sub_customer.is-Enterprise-42",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 2
data = response.data["data"]
assert data[0]["count(sub_customer.is-Enterprise-42)"] == 1
assert data[1]["count(sub_customer.is-Enterprise-42)"] == 3
def test_aggregation_comparison(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
"user": {"email": "foo@example.com"},
},
project_id=self.project.id,
)
event = self.store_event(
data={
"event_id": "b" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"email": "foo@example.com"},
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "c" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"email": "bar@example.com"},
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "d" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_3"],
"user": {"email": "bar@example.com"},
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "e" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_3"],
"user": {"email": "bar@example.com"},
},
project_id=self.project.id,
)
query = {
"field": ["issue.id", "count(id)", "count_unique(user)"],
"query": "count(id):>1 count_unique(user):>1",
"orderby": "issue.id",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
data = response.data["data"]
assert data[0]["issue.id"] == event.group_id
assert data[0]["count(id)"] == 2
assert data[0]["count_unique(user)"] == 2
def test_aggregation_alias_comparison(self) -> None:
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=5),
)
data["transaction"] = "/aggregates/1"
self.store_event(data, project_id=self.project.id)
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=3),
)
data["transaction"] = "/aggregates/2"
event = self.store_event(data, project_id=self.project.id)
query = {
"field": ["transaction", "p95()"],
"query": "event.type:transaction p95():<4000",
"orderby": ["transaction"],
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
data = response.data["data"]
assert data[0]["transaction"] == event.transaction
assert data[0]["p95()"] == 3000
def test_auto_aggregations(self) -> None:
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=5),
)
data["transaction"] = "/aggregates/1"
self.store_event(data, project_id=self.project.id)
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=3),
)
data["transaction"] = "/aggregates/2"
event = self.store_event(data, project_id=self.project.id)
query = {
"field": ["transaction", "p75()"],
"query": "event.type:transaction p95():<4000",
"orderby": ["transaction"],
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
data = response.data["data"]
assert data[0]["transaction"] == event.transaction
query = {
"field": ["transaction"],
"query": "event.type:transaction p95():<4000",
"orderby": ["transaction"],
}
response = self.do_request(query)
assert response.status_code == 400, response.content
def test_aggregation_comparison_with_conditions(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
"user": {"email": "foo@example.com"},
"environment": "prod",
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"email": "foo@example.com"},
"environment": "staging",
},
project_id=self.project.id,
)
event = self.store_event(
data={
"event_id": "c" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"email": "foo@example.com"},
"environment": "prod",
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "d" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"email": "foo@example.com"},
"environment": "prod",
},
project_id=self.project.id,
)
query = {
"field": ["issue.id", "count(id)"],
"query": "count(id):>1 user.email:foo@example.com environment:prod",
"orderby": "issue.id",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
data = response.data["data"]
assert data[0]["issue.id"] == event.group_id
assert data[0]["count(id)"] == 2
def test_aggregation_date_comparison_with_conditions(self) -> None:
event = self.store_event(
data={
"event_id": "a" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
"user": {"email": "foo@example.com"},
"environment": "prod",
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"email": "foo@example.com"},
"environment": "staging",
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "c" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"email": "foo@example.com"},
"environment": "prod",
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "d" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"email": "foo@example.com"},
"environment": "prod",
},
project_id=self.project.id,
)
query = {
"field": ["issue.id", "max(timestamp)"],
"query": "max(timestamp):>1 user.email:foo@example.com environment:prod",
"orderby": "issue.id",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 2
assert response.data["meta"]["fields"]["max(timestamp)"] == "date"
data = response.data["data"]
assert data[0]["issue.id"] == event.group_id
def test_percentile_function(self) -> None:
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=5),
)
data["transaction"] = "/aggregates/1"
event1 = self.store_event(data, project_id=self.project.id)
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=3),
)
data["transaction"] = "/aggregates/2"
event2 = self.store_event(data, project_id=self.project.id)
query = {
"field": ["transaction", "percentile(transaction.duration, 0.95)"],
"query": "event.type:transaction",
"orderby": ["transaction"],
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 2
data = response.data["data"]
assert data[0]["transaction"] == event1.transaction
assert data[0]["percentile(transaction.duration, 0.95)"] == 5000
assert data[1]["transaction"] == event2.transaction
assert data[1]["percentile(transaction.duration, 0.95)"] == 3000
def test_percentile_function_as_condition(self) -> None:
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=5),
)
data["transaction"] = "/aggregates/1"
event1 = self.store_event(data, project_id=self.project.id)
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=3),
)
data["transaction"] = "/aggregates/2"
self.store_event(data, project_id=self.project.id)
query = {
"field": ["transaction", "percentile(transaction.duration, 0.95)"],
"query": "event.type:transaction percentile(transaction.duration, 0.95):>4000",
"orderby": ["transaction"],
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
data = response.data["data"]
assert data[0]["transaction"] == event1.transaction
assert data[0]["percentile(transaction.duration, 0.95)"] == 5000
def test_epm_function(self) -> None:
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=5),
)
data["transaction"] = "/aggregates/1"
event1 = self.store_event(data, project_id=self.project.id)
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=3),
)
data["transaction"] = "/aggregates/2"
event2 = self.store_event(data, project_id=self.project.id)
query = {
"field": ["transaction", "epm()"],
"query": "event.type:transaction",
"orderby": ["transaction"],
"start": self.eleven_mins_ago_iso,
"end": self.nine_mins_ago,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 2
data = response.data["data"]
assert data[0]["transaction"] == event1.transaction
assert data[0]["epm()"] == 0.5
assert data[1]["transaction"] == event2.transaction
assert data[1]["epm()"] == 0.5
meta = response.data["meta"]
assert meta["fields"]["epm()"] == "rate"
assert meta["units"]["epm()"] == "1/minute"
def test_nonexistent_fields(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
},
project_id=self.project.id,
)
query = {"field": ["issue_world.id"]}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert response.data["data"][0]["issue_world.id"] == ""
def test_no_requested_fields_or_grouping(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
},
project_id=self.project.id,
)
query = {"query": "test"}
response = self.do_request(query)
assert response.status_code == 400, response.content
assert response.data["detail"] == "No columns selected"
def test_condition_on_aggregate_misses(self) -> None:
self.store_event(
data={
"event_id": "c" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"email": "bar@example.com"},
},
project_id=self.project.id,
)
query = {"field": ["issue.id"], "query": "event_count:>0", "orderby": "issue.id"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 0
def test_next_prev_link_headers(self) -> None:
events = [("a", "group_1"), ("b", "group_2"), ("c", "group_2"), ("d", "group_2")]
for e in events:
self.store_event(
data={
"event_id": e[0] * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": [e[1]],
"user": {"email": "foo@example.com"},
"tags": {"language": "C++"},
},
project_id=self.project.id,
)
query = {
"field": ["count(id)", "issue.id", "context.key"],
"sort": "-count_id",
"query": "language:C++",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
links = parse_link_header(response["Link"])
for link in links:
assert "field=issue.id" in link
assert "field=count%28id%29" in link
assert "field=context.key" in link
assert "sort=-count_id" in link
assert "query=language%3AC%2B%2B" in link
assert len(response.data["data"]) == 2
data = response.data["data"]
assert data[0]["count(id)"] == 3
assert data[1]["count(id)"] == 1
def test_empty_count_query(self) -> None:
event = self.store_event(
data={
"event_id": "a" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["1123581321"],
"user": {"email": "foo@example.com"},
"tags": {"language": "C++"},
},
project_id=self.project.id,
)
query = {
"field": ["count()"],
"query": f"issue.id:{event.group_id} timestamp:>{self.ten_mins_ago_iso}",
"statsPeriod": "14d",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["count()"] == 0
def test_stack_wildcard_condition(self) -> None:
data = self.load_data(platform="javascript")
data["timestamp"] = self.ten_mins_ago_iso
self.store_event(data=data, project_id=self.project.id)
query = {"field": ["stack.filename", "message"], "query": "stack.filename:*.js"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["meta"]["fields"]["message"] == "string"
def test_email_wildcard_condition(self) -> None:
data = self.load_data(platform="javascript")
data["timestamp"] = self.ten_mins_ago_iso
self.store_event(data=data, project_id=self.project.id)
query = {"field": ["stack.filename", "message"], "query": "user.email:*@example.org"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["meta"]["fields"]["message"] == "string"
def test_release_wildcard_condition(self) -> None:
release = self.create_release(version="test@1.2.3+123")
self.store_event(
data={"release": release.version, "timestamp": self.ten_mins_ago_iso},
project_id=self.project.id,
)
query = {"field": ["stack.filename", "release"], "query": "release:test*"}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["release"] == release.version
def test_transaction_event_type(self) -> None:
self.store_event(data=self.transaction_data, project_id=self.project.id)
for dataset in ["discover", "transactions"]:
query = {
"field": ["transaction", "transaction.duration", "transaction.status"],
"query": "event.type:transaction",
"dataset": dataset,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["meta"]["fields"]["transaction.duration"] == "duration"
assert response.data["meta"]["fields"]["transaction.status"] == "string"
assert response.data["meta"]["units"]["transaction.duration"] == "millisecond"
assert response.data["data"][0]["transaction.status"] == "ok"
def test_trace_columns(self) -> None:
self.store_event(data=self.transaction_data, project_id=self.project.id)
for dataset in ["discover", "transactions"]:
query = {"field": ["trace"], "query": "event.type:transaction", "dataset": dataset}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["meta"]["fields"]["trace"] == "string"
assert (
response.data["data"][0]["trace"]
== self.transaction_data["contexts"]["trace"]["trace_id"]
)
def test_issue_in_columns(self) -> None:
project1 = self.create_project()
project2 = self.create_project()
event1 = self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
},
project_id=project1.id,
)
event2 = self.store_event(
data={
"event_id": "b" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
},
project_id=project2.id,
)
features = {"organizations:discover-basic": True}
query = {"field": ["id", "issue"], "orderby": ["id"]}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
assert data[0]["id"] == event1.event_id
assert data[0]["issue.id"] == event1.group_id
assert data[0]["issue"] == event1.group.qualified_short_id
assert data[1]["id"] == event2.event_id
assert data[1]["issue.id"] == event2.group_id
assert data[1]["issue"] == event2.group.qualified_short_id
def test_issue_in_search_and_columns(self) -> None:
project1 = self.create_project()
project2 = self.create_project()
event1 = self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
},
project_id=project1.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
},
project_id=project2.id,
)
tests = [
("issue", "issue:%s" % event1.group.qualified_short_id),
("issue.id", "issue:%s" % event1.group.qualified_short_id),
("issue", "issue.id:%s" % event1.group_id),
("issue.id", "issue.id:%s" % event1.group_id),
]
features = {"organizations:discover-basic": True}
for testdata in tests:
query = {"field": [testdata[0]], "query": testdata[1]}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["id"] == event1.event_id
assert data[0]["issue.id"] == event1.group_id
if testdata[0] == "issue":
assert data[0]["issue"] == event1.group.qualified_short_id
else:
assert data[0].get("issue", None) is None
def test_issue_negation(self) -> None:
project1 = self.create_project()
project2 = self.create_project()
event1 = self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
},
project_id=project1.id,
)
event2 = self.store_event(
data={
"event_id": "b" * 32,
"transaction": "/example",
"message": "go really fast plz",
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
},
project_id=project2.id,
)
features = {"organizations:discover-basic": True}
query = {
"field": ["title", "issue.id"],
"query": f"!issue:{event1.group.qualified_short_id}",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["title"] == event2.title
assert data[0]["issue.id"] == event2.group_id
def test_search_for_nonexistent_issue(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
},
project_id=self.project.id,
)
features = {"organizations:discover-basic": True}
query = {"field": ["count()"], "query": "issue.id:112358"}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["count()"] == 0
def test_issue_alias_inside_aggregate(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
},
project_id=self.project.id,
)
features = {"organizations:discover-basic": True}
query = {
"field": ["project", "count(id)", "count_unique(issue.id)", "count_unique(issue)"],
"sort": "-count(id)",
"statsPeriod": "24h",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["count(id)"] == 2
assert data[0]["count_unique(issue.id)"] == 2
assert data[0]["count_unique(issue)"] == 2
def test_project_alias_inside_aggregate(self) -> None:
project1 = self.create_project()
project2 = self.create_project()
self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
},
project_id=project1.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
},
project_id=project2.id,
)
features = {"organizations:discover-basic": True}
query = {
"field": [
"event.type",
"count(id)",
"count_unique(project.id)",
"count_unique(project)",
],
"sort": "-count(id)",
"statsPeriod": "24h",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["count(id)"] == 2
assert data[0]["count_unique(project.id)"] == 2
assert data[0]["count_unique(project)"] == 2
def test_user_display(self) -> None:
project1 = self.create_project()
project2 = self.create_project()
self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"user": {"email": "cathy@example.com"},
},
project_id=project1.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"user": {"username": "catherine"},
},
project_id=project2.id,
)
features = {"organizations:discover-basic": True}
query = {
"field": ["event.type", "user.display"],
"query": "user.display:cath*",
"statsPeriod": "24h",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
result = {r["user.display"] for r in data}
assert result == {"catherine", "cathy@example.com"}
def test_user_display_with_aggregates(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"user": {"email": "cathy@example.com"},
},
project_id=self.project.id,
)
features = {"organizations:discover-basic": True}
query = {
"field": ["event.type", "user.display", "count_unique(title)"],
"statsPeriod": "24h",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
result = {r["user.display"] for r in data}
assert result == {"cathy@example.com"}
query = {"field": ["event.type", "count_unique(user.display)"], "statsPeriod": "24h"}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["count_unique(user.display)"] == 1
def test_orderby_user_display(self) -> None:
project1 = self.create_project()
project2 = self.create_project()
self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"user": {"email": "cathy@example.com"},
},
project_id=project1.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"user": {"username": "catherine"},
},
project_id=project2.id,
)
features = {"organizations:discover-basic": True}
query = {
"field": ["event.type", "user.display"],
"query": "user.display:cath*",
"statsPeriod": "24h",
"orderby": "-user.display",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
result = [r["user.display"] for r in data]
# because we're ordering by `-user.display`, we expect the results in reverse sorted order
assert result == ["cathy@example.com", "catherine"]
def test_orderby_user_display_with_aggregates(self) -> None:
project1 = self.create_project()
project2 = self.create_project()
self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"user": {"email": "cathy@example.com"},
},
project_id=project1.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"user": {"username": "catherine"},
},
project_id=project2.id,
)
features = {"organizations:discover-basic": True}
query = {
"field": ["event.type", "user.display", "count_unique(title)"],
"query": "user.display:cath*",
"statsPeriod": "24h",
"orderby": "user.display",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
result = [r["user.display"] for r in data]
# because we're ordering by `user.display`, we expect the results in sorted order
assert result == ["catherine", "cathy@example.com"]
def test_any_field_alias(self) -> None:
day_ago = before_now(days=1).replace(hour=10, minute=11, second=12, microsecond=13)
self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": day_ago.isoformat(),
"user": {"email": "cathy@example.com"},
},
project_id=self.project.id,
)
features = {"organizations:discover-basic": True}
query = {
"field": [
"event.type",
"any(user.display)",
"any(timestamp.to_day)",
"any(timestamp.to_hour)",
],
"statsPeriod": "7d",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
result = {r["any(user.display)"] for r in data}
assert result == {"cathy@example.com"}
result = {r["any(timestamp.to_day)"][:19] for r in data}
assert result == {
day_ago.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=None).isoformat()
}
result = {r["any(timestamp.to_hour)"][:19] for r in data}
assert result == {
day_ago.replace(minute=0, second=0, microsecond=0, tzinfo=None).isoformat()
}
def test_field_aliases_in_conflicting_functions(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": (
before_now(days=1).replace(hour=10, minute=11, second=12, microsecond=13)
).isoformat(),
"user": {"email": "cathy@example.com"},
},
project_id=self.project.id,
)
features = {"organizations:discover-basic": True}
field_aliases = ["user.display", "timestamp.to_day", "timestamp.to_hour"]
for alias in field_aliases:
query = {
"field": [alias, f"any({alias})"],
"statsPeriod": "7d",
}
response = self.do_request(query, features=features)
assert response.status_code == 400, response.content
assert (
response.data["detail"]
== f"A single field cannot be used both inside and outside a function in the same query. To use {alias} you must first remove the function(s): any({alias})"
)
@pytest.mark.skip(
"""
For some reason ClickHouse errors when there are two of the same string literals
(in this case the empty string "") in a query and one is in the prewhere clause.
Does not affect production or ClickHouse versions > 20.4.
"""
)
def test_has_message(self) -> None:
event = self.store_event(
{"timestamp": self.ten_mins_ago_iso, "message": "a"}, project_id=self.project.id
)
features = {"organizations:discover-basic": True}
query = {"field": ["project", "message"], "query": "has:message", "statsPeriod": "14d"}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["message"] == event.message
query = {"field": ["project", "message"], "query": "!has:message", "statsPeriod": "14d"}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 0
def test_has_transaction_status(self) -> None:
self.store_event(self.transaction_data, project_id=self.project.id)
features = {"organizations:discover-basic": True}
for dataset in ["discover", "transactions"]:
query = {
"field": ["event.type", "count(id)"],
"query": "event.type:transaction has:transaction.status",
"sort": "-count(id)",
"statsPeriod": "24h",
"dataset": dataset,
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["count(id)"] == 1
@pytest.mark.xfail(reason="Started failing on ClickHouse 21.8")
def test_not_has_transaction_status(self) -> None:
self.store_event(self.transaction_data, project_id=self.project.id)
features = {"organizations:discover-basic": True}
for dataset in ["discover", "transactions"]:
query = {
"field": ["event.type", "count(id)"],
"query": "event.type:transaction !has:transaction.status",
"sort": "-count(id)",
"statsPeriod": "24h",
"dataset": dataset,
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["count(id)"] == 0
def test_tag_that_looks_like_aggregation(self) -> None:
data = {
"message": "Failure state",
"timestamp": self.ten_mins_ago_iso,
"tags": {"count_diff": 99},
}
self.store_event(data, project_id=self.project.id)
query = {
"field": ["message", "count_diff", "count()"],
"query": "",
"project": [self.project.id],
"statsPeriod": "24h",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
meta = response.data["meta"]["fields"]
assert "string" == meta["count_diff"], "tags should not be counted as integers"
assert "string" == meta["message"]
assert "integer" == meta["count()"]
assert 1 == len(response.data["data"])
data = response.data["data"][0]
assert "99" == data["count_diff"]
assert "Failure state" == data["message"]
assert 1 == data["count()"]
def test_aggregate_negation(self) -> None:
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=5),
)
self.store_event(data, project_id=self.project.id)
features = {"organizations:discover-basic": True}
query = {
"field": ["event.type", "count()"],
"query": "event.type:transaction count():1",
"statsPeriod": "24h",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
query = {
"field": ["event.type", "count()"],
"query": "event.type:transaction !count():1",
"statsPeriod": "24h",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 0
def test_all_aggregates_in_columns(self) -> None:
data = self.load_data(
timestamp=self.eleven_mins_ago,
duration=timedelta(seconds=5),
)
data["transaction"] = "/failure_rate/1"
self.store_event(data, project_id=self.project.id)
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=5),
)
data["transaction"] = "/failure_rate/1"
data["contexts"]["trace"]["status"] = "unauthenticated"
event = self.store_event(data, project_id=self.project.id)
features = {"organizations:discover-basic": True}
query = {
"field": [
"event.type",
"p50()",
"p75()",
"p95()",
"p99()",
"p100()",
"percentile(transaction.duration, 0.99)",
"apdex(300)",
"count_miserable(user, 300)",
"user_misery(300)",
"failure_rate()",
],
"query": "event.type:transaction",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
meta = response.data["meta"]["fields"]
units = response.data["meta"]["units"]
assert meta["p50()"] == "duration"
assert meta["p75()"] == "duration"
assert meta["p95()"] == "duration"
assert meta["p99()"] == "duration"
assert meta["p100()"] == "duration"
assert meta["percentile(transaction.duration, 0.99)"] == "duration"
assert meta["apdex(300)"] == "number"
assert meta["failure_rate()"] == "percentage"
assert meta["user_misery(300)"] == "number"
assert meta["count_miserable(user, 300)"] == "integer"
assert units["p50()"] == "millisecond"
assert units["p75()"] == "millisecond"
assert units["p95()"] == "millisecond"
assert units["p99()"] == "millisecond"
assert units["p100()"] == "millisecond"
assert units["percentile(transaction.duration, 0.99)"] == "millisecond"
data = response.data["data"]
assert len(data) == 1
assert data[0]["p50()"] == 5000
assert data[0]["p75()"] == 5000
assert data[0]["p95()"] == 5000
assert data[0]["p99()"] == 5000
assert data[0]["p100()"] == 5000
assert data[0]["percentile(transaction.duration, 0.99)"] == 5000
assert data[0]["apdex(300)"] == 0.0
assert data[0]["count_miserable(user, 300)"] == 1
assert data[0]["user_misery(300)"] == user_misery_formula(1, 1)
assert data[0]["failure_rate()"] == 0.5
features = {
"organizations:discover-basic": True,
}
query = {
"field": [
"event.type",
"p50()",
"p75()",
"p95()",
"p99()",
"p100()",
"percentile(transaction.duration, 0.99)",
"apdex(300)",
"apdex()",
"count_miserable(user, 300)",
"user_misery(300)",
"failure_rate()",
"count_miserable(user)",
"user_misery()",
],
"query": "event.type:transaction",
"project": [self.project.id],
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
meta = response.data["meta"]["fields"]
units = response.data["meta"]["units"]
assert meta["p50()"] == "duration"
assert meta["p75()"] == "duration"
assert meta["p95()"] == "duration"
assert meta["p99()"] == "duration"
assert meta["p100()"] == "duration"
assert meta["percentile(transaction.duration, 0.99)"] == "duration"
assert meta["apdex(300)"] == "number"
assert meta["apdex()"] == "number"
assert meta["failure_rate()"] == "percentage"
assert meta["user_misery(300)"] == "number"
assert meta["count_miserable(user, 300)"] == "integer"
assert meta["project_threshold_config"] == "string"
assert meta["user_misery()"] == "number"
assert meta["count_miserable(user)"] == "integer"
assert units["p50()"] == "millisecond"
assert units["p75()"] == "millisecond"
assert units["p95()"] == "millisecond"
assert units["p99()"] == "millisecond"
assert units["p100()"] == "millisecond"
assert units["percentile(transaction.duration, 0.99)"] == "millisecond"
data = response.data["data"]
assert len(data) == 1
assert data[0]["p50()"] == 5000
assert data[0]["p75()"] == 5000
assert data[0]["p95()"] == 5000
assert data[0]["p99()"] == 5000
assert data[0]["p100()"] == 5000
assert data[0]["percentile(transaction.duration, 0.99)"] == 5000
assert data[0]["apdex(300)"] == 0.0
assert data[0]["apdex()"] == 0.0
assert data[0]["count_miserable(user, 300)"] == 1
assert data[0]["user_misery(300)"] == user_misery_formula(1, 1)
assert data[0]["failure_rate()"] == 0.5
assert data[0]["project_threshold_config"] == ["duration", 300]
assert data[0]["user_misery()"] == user_misery_formula(1, 1)
assert data[0]["count_miserable(user)"] == 1
query = {
"field": ["event.type", "last_seen()", "latest_event()"],
"query": "event.type:transaction",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert self.ten_mins_ago_iso == data[0]["last_seen()"]
assert data[0]["latest_event()"] == event.event_id
query = {
"field": [
"event.type",
"count()",
"count(id)",
"count_unique(project)",
"min(transaction.duration)",
"max(transaction.duration)",
"avg(transaction.duration)",
"stddev(transaction.duration)",
"var(transaction.duration)",
"cov(transaction.duration, transaction.duration)",
"corr(transaction.duration, transaction.duration)",
"linear_regression(transaction.duration, transaction.duration)",
"sum(transaction.duration)",
],
"query": "event.type:transaction",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["count()"] == 2
assert data[0]["count(id)"] == 2
assert data[0]["count_unique(project)"] == 1
assert data[0]["min(transaction.duration)"] == 5000
assert data[0]["max(transaction.duration)"] == 5000
assert data[0]["avg(transaction.duration)"] == 5000
assert data[0]["stddev(transaction.duration)"] == 0.0
assert data[0]["var(transaction.duration)"] == 0.0
assert data[0]["cov(transaction.duration, transaction.duration)"] == 0.0
assert data[0]["corr(transaction.duration, transaction.duration)"] == 0.0
assert data[0]["linear_regression(transaction.duration, transaction.duration)"] == [0, 0]
assert data[0]["sum(transaction.duration)"] == 10000
def test_null_user_misery_returns_zero(self) -> None:
self.transaction_data["user"] = None
self.transaction_data["transaction"] = "/no_users/1"
self.store_event(self.transaction_data, project_id=self.project.id)
features = {"organizations:discover-basic": True}
for dataset in ["discover", "transactions"]:
query = {
"field": ["user_misery(300)"],
"query": "event.type:transaction",
"dataset": dataset,
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
meta = response.data["meta"]["fields"]
assert meta["user_misery(300)"] == "number"
data = response.data["data"]
assert data[0]["user_misery(300)"] == 0
def test_null_user_misery_new_returns_zero(self) -> None:
self.transaction_data["user"] = None
self.transaction_data["transaction"] = "/no_users/1"
self.store_event(self.transaction_data, project_id=self.project.id)
features = {
"organizations:discover-basic": True,
}
for dataset in ["discover", "transactions"]:
query = {
"field": ["user_misery()"],
"query": "event.type:transaction",
"dataset": dataset,
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
meta = response.data["meta"]["fields"]
assert meta["user_misery()"] == "number"
data = response.data["data"]
assert data[0]["user_misery()"] == 0
def test_all_aggregates_in_query(self) -> None:
data = self.load_data(
timestamp=self.eleven_mins_ago,
duration=timedelta(seconds=5),
)
data["transaction"] = "/failure_rate/1"
self.store_event(data, project_id=self.project.id)
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=5),
)
data["transaction"] = "/failure_rate/2"
data["contexts"]["trace"]["status"] = "unauthenticated"
self.store_event(data, project_id=self.project.id)
features = {"organizations:discover-basic": True}
query = {
"field": [
"event.type",
"p50()",
"p75()",
"p95()",
"percentile(transaction.duration, 0.99)",
"p100()",
],
"query": "event.type:transaction p50():>100 p75():>1000 p95():>1000 p100():>1000 percentile(transaction.duration, 0.99):>1000",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["p50()"] == 5000
assert data[0]["p75()"] == 5000
assert data[0]["p95()"] == 5000
assert data[0]["p100()"] == 5000
assert data[0]["percentile(transaction.duration, 0.99)"] == 5000
query = {
"field": [
"event.type",
"apdex(300)",
"count_miserable(user, 300)",
"user_misery(300)",
"failure_rate()",
],
"query": "event.type:transaction apdex(300):>-1.0 failure_rate():>0.25",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["apdex(300)"] == 0.0
assert data[0]["count_miserable(user, 300)"] == 1
assert data[0]["user_misery(300)"] == user_misery_formula(1, 1)
assert data[0]["failure_rate()"] == 0.5
query = {
"field": ["event.type", "last_seen()", "latest_event()"],
"query": "event.type:transaction last_seen():>1990-12-01T00:00:00",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
query = {
"field": ["event.type", "count()", "count(id)", "count_unique(transaction)"],
"query": "event.type:transaction count():>1 count(id):>1 count_unique(transaction):>1",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["count()"] == 2
assert data[0]["count(id)"] == 2
assert data[0]["count_unique(transaction)"] == 2
query = {
"field": [
"event.type",
"min(transaction.duration)",
"max(transaction.duration)",
"avg(transaction.duration)",
"sum(transaction.duration)",
"stddev(transaction.duration)",
"var(transaction.duration)",
"cov(transaction.duration, transaction.duration)",
"corr(transaction.duration, transaction.duration)",
],
"query": " ".join(
[
"event.type:transaction",
"min(transaction.duration):>1000",
"max(transaction.duration):>1000",
"avg(transaction.duration):>1000",
"sum(transaction.duration):>1000",
"stddev(transaction.duration):>=0.0",
"var(transaction.duration):>=0.0",
"cov(transaction.duration, transaction.duration):>=0.0",
# correlation is nan because variance is 0
# "corr(transaction.duration, transaction.duration):>=0.0",
]
),
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["min(transaction.duration)"] == 5000
assert data[0]["max(transaction.duration)"] == 5000
assert data[0]["avg(transaction.duration)"] == 5000
assert data[0]["sum(transaction.duration)"] == 10000
assert data[0]["stddev(transaction.duration)"] == 0.0
assert data[0]["var(transaction.duration)"] == 0.0
assert data[0]["cov(transaction.duration, transaction.duration)"] == 0.0
assert data[0]["corr(transaction.duration, transaction.duration)"] == 0.0
query = {
"field": ["event.type", "apdex(400)"],
"query": "event.type:transaction apdex(400):0",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["apdex(400)"] == 0
def test_functions_in_orderby(self) -> None:
data = self.load_data(
timestamp=self.eleven_mins_ago,
duration=timedelta(seconds=5),
)
data["transaction"] = "/failure_rate/1"
self.store_event(data, project_id=self.project.id)
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=5),
)
data["transaction"] = "/failure_rate/2"
data["contexts"]["trace"]["status"] = "unauthenticated"
event = self.store_event(data, project_id=self.project.id)
features = {"organizations:discover-basic": True}
query = {
"field": ["event.type", "p75()"],
"sort": "-p75",
"query": "event.type:transaction",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["p75()"] == 5000
query = {
"field": ["event.type", "percentile(transaction.duration, 0.99)"],
"sort": "-percentile_transaction_duration_0_99",
"query": "event.type:transaction",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["percentile(transaction.duration, 0.99)"] == 5000
query = {
"field": ["event.type", "apdex(300)"],
"sort": "-apdex(300)",
"query": "event.type:transaction",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["apdex(300)"] == 0.0
query = {
"field": ["event.type", "latest_event()"],
"query": "event.type:transaction",
"sort": "latest_event",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["latest_event()"] == event.event_id
query = {
"field": ["event.type", "count_unique(transaction)"],
"query": "event.type:transaction",
"sort": "-count_unique_transaction",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["count_unique(transaction)"] == 2
query = {
"field": ["event.type", "min(transaction.duration)"],
"query": "event.type:transaction",
"sort": "-min_transaction_duration",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["min(transaction.duration)"] == 5000
def test_issue_alias_in_aggregate(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"timestamp": self.eleven_mins_ago_iso,
"fingerprint": ["group_1"],
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
},
project_id=self.project.id,
)
query = {"field": ["event.type", "count_unique(issue)"], "query": "count_unique(issue):>1"}
features = {"organizations:discover-basic": True}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["count_unique(issue)"] == 2
def test_deleted_issue_in_results(self) -> None:
event1 = self.store_event(
data={
"event_id": "a" * 32,
"timestamp": self.eleven_mins_ago_iso,
"fingerprint": ["group_1"],
},
project_id=self.project.id,
)
event2 = self.store_event(
data={
"event_id": "b" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
},
project_id=self.project.id,
)
event2.group.delete()
features = {"organizations:discover-basic": True}
query = {"field": ["issue", "count()"], "sort": "issue.id"}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
assert data[0]["issue"] == event1.group.qualified_short_id
assert data[1]["issue"] == "unknown"
def test_last_seen_negative_duration(self) -> None:
self.store_event(
data={
"event_id": "f" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
},
project_id=self.project.id,
)
features = {"organizations:discover-basic": True}
query = {"field": ["id", "last_seen()"], "query": "last_seen():-30d"}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["id"] == "f" * 32
def test_last_seen_aggregate_condition(self) -> None:
self.store_event(
data={
"event_id": "f" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
},
project_id=self.project.id,
)
query = {
"field": ["id", "last_seen()"],
"query": f"last_seen():>{before_now(days=30).isoformat()}",
}
features = {"organizations:discover-basic": True}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["id"] == "f" * 32
def test_conditional_filter(self) -> None:
for v in ["a", "b"]:
self.store_event(
data={
"event_id": v * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
},
project_id=self.project.id,
)
query = {
"field": ["id"],
"query": "id:{} OR id:{}".format("a" * 32, "b" * 32),
"orderby": "id",
}
features = {"organizations:discover-basic": True}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
assert data[0]["id"] == "a" * 32
assert data[1]["id"] == "b" * 32
def test_aggregation_comparison_with_conditional_filter(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
"user": {"email": "foo@example.com"},
"environment": "prod",
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"email": "foo@example.com"},
"environment": "staging",
},
project_id=self.project.id,
)
event = self.store_event(
data={
"event_id": "c" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"email": "foo@example.com"},
"environment": "prod",
},
project_id=self.project.id,
)
self.store_event(
data={
"event_id": "d" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"user": {"email": "foo@example.com"},
"environment": "canary",
},
project_id=self.project.id,
)
query = {
"field": ["issue.id", "count(id)"],
"query": "count(id):>1 user.email:foo@example.com AND (environment:prod OR environment:staging)",
"orderby": "issue.id",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
data = response.data["data"]
assert data[0]["issue.id"] == event.group_id
assert data[0]["count(id)"] == 2
def run_test_in_query(
self, query, expected_events, expected_negative_events=None, dataset="discover"
):
params = {"field": ["id"], "query": query, "orderby": "id", "dataset": dataset}
response = self.do_request(params, {"organizations:discover-basic": True})
assert response.status_code == 200, response.content
assert [row["id"] for row in response.data["data"]] == [e.event_id for e in expected_events]
if expected_negative_events is not None:
params["query"] = f"!{query}"
response = self.do_request(
params,
{"organizations:discover-basic": True},
)
assert response.status_code == 200, response.content
assert [row["id"] for row in response.data["data"]] == [
e.event_id for e in expected_negative_events
]
def test_in_query_events(self) -> None:
project_1 = self.create_project()
event_1 = self.store_event(
data={
"event_id": "a" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
"message": "group1",
"user": {"email": "hello@example.com"},
"environment": "prod",
"tags": {"random": "123"},
"release": "1.0",
},
project_id=project_1.id,
)
project_2 = self.create_project()
event_2 = self.store_event(
data={
"event_id": "b" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_2"],
"message": "group2",
"user": {"email": "bar@example.com"},
"environment": "staging",
"tags": {"random": "456"},
"stacktrace": {"frames": [{"filename": "src/app/group2.py"}]},
"release": "1.2",
},
project_id=project_2.id,
)
project_3 = self.create_project()
event_3 = self.store_event(
data={
"event_id": "c" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_3"],
"message": "group3",
"user": {"email": "foo@example.com"},
"environment": "canary",
"tags": {"random": "789"},
},
project_id=project_3.id,
)
self.run_test_in_query("environment:[prod, staging]", [event_1, event_2], [event_3])
self.run_test_in_query("environment:[staging]", [event_2], [event_1, event_3])
self.run_test_in_query(
"user.email:[foo@example.com, hello@example.com]", [event_1, event_3], [event_2]
)
self.run_test_in_query("user.email:[foo@example.com]", [event_3], [event_1, event_2])
self.run_test_in_query(
"user.display:[foo@example.com, hello@example.com]", [event_1, event_3], [event_2]
)
self.run_test_in_query(
'message:["group2 src/app/group2.py in ?", group1]', [event_1, event_2], [event_3]
)
self.run_test_in_query(
f"issue.id:[{event_1.group_id},{event_2.group_id}]", [event_1, event_2]
)
self.run_test_in_query(
f"issue:[{event_1.group.qualified_short_id},{event_2.group.qualified_short_id}]",
[event_1, event_2],
)
self.run_test_in_query(
f"issue:[{event_1.group.qualified_short_id},{event_2.group.qualified_short_id}, unknown]",
[event_1, event_2],
)
self.run_test_in_query(f"project_id:[{project_3.id},{project_2.id}]", [event_2, event_3])
self.run_test_in_query(
f"project.name:[{project_3.slug},{project_2.slug}]", [event_2, event_3]
)
self.run_test_in_query("random:[789,456]", [event_2, event_3], [event_1])
self.run_test_in_query("tags[random]:[789,456]", [event_2, event_3], [event_1])
self.run_test_in_query("release:[1.0,1.2]", [event_1, event_2], [event_3])
def test_in_query_events_stack(self) -> None:
test_js = self.store_event(
self.load_data(
platform="javascript",
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=5),
),
project_id=self.project.id,
)
test_java = self.store_event(
self.load_data(
platform="java",
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=5),
),
project_id=self.project.id,
)
self.run_test_in_query(
"stack.filename:[../../sentry/scripts/views.js]", [test_js], [test_java]
)
def test_in_query_transactions(self) -> None:
data = self.transaction_data.copy()
data["event_id"] = "a" * 32
data["contexts"]["trace"]["status"] = "ok"
transaction_1 = self.store_event(data, project_id=self.project.id)
data = self.transaction_data.copy()
data["event_id"] = "b" * 32
data["contexts"]["trace"]["status"] = "aborted"
transaction_2 = self.store_event(data, project_id=self.project.id)
data = self.transaction_data.copy()
data["event_id"] = "c" * 32
data["contexts"]["trace"]["status"] = "already_exists"
transaction_3 = self.store_event(data, project_id=self.project.id)
for dataset in ["discover", "transactions"]:
self.run_test_in_query(
"transaction.status:[aborted, already_exists]",
[transaction_2, transaction_3],
[transaction_1],
dataset=dataset,
)
def test_messed_up_function_values(self) -> None:
# TODO (evanh): It would be nice if this surfaced an error to the user.
# The problem: The && causes the parser to treat that term not as a bad
# function call but a valid raw search with parens in it. It's not trivial
# to change the parser to recognize "bad function values" and surface them.
for v in ["a", "b"]:
self.store_event(
data={
"event_id": v * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group_1"],
},
project_id=self.project.id,
)
features = {"organizations:discover-basic": True}
query = {
"field": [
"transaction",
"project",
"epm()",
"p50()",
"p95()",
"failure_rate()",
"apdex(300)",
"count_unique(user)",
"user_misery(300)",
"count_miserable(user, 300)",
],
"query": "failure_rate():>0.003&& users:>10 event.type:transaction",
"sort": "-failure_rate",
"statsPeriod": "24h",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 0
def test_context_fields_between_datasets(self) -> None:
event_data = self.load_data(platform="android")
transaction_data = self.load_data()
event_data["spans"] = transaction_data["spans"]
event_data["contexts"]["trace"] = transaction_data["contexts"]["trace"]
event_data["type"] = "transaction"
event_data["transaction"] = "/failure_rate/1"
event_data["timestamp"] = self.ten_mins_ago.isoformat()
event_data["start_timestamp"] = before_now(minutes=10, seconds=5).isoformat()
event_data["user"]["geo"] = {"country_code": "US", "region": "CA", "city": "San Francisco"}
self.store_event(event_data, project_id=self.project.id)
event_data["type"] = "error"
self.store_event(event_data, project_id=self.project.id)
fields = [
"os.build",
"os.kernel_version",
"device.arch",
# TODO: battery level is not consistent across both datasets
# "device.battery_level",
"device.brand",
"device.charging",
"device.locale",
"device.model_id",
"device.name",
"device.online",
"device.orientation",
"device.simulator",
"device.uuid",
]
data = [
{"field": fields + ["location", "count()"], "query": "event.type:error"},
{"field": fields + ["duration", "count()"], "query": "event.type:transaction"},
]
for datum in data:
response = self.do_request(datum)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1, datum
results = response.data["data"]
assert results[0]["count()"] == 1, datum
for field in fields:
key, value = field.split(".", 1)
expected = str(event_data["contexts"][key][value])
assert results[0][field] == expected, field + str(datum)
def test_http_fields_between_datasets(self) -> None:
event_data = self.load_data(platform="android")
transaction_data = self.load_data()
event_data["spans"] = transaction_data["spans"]
event_data["contexts"]["trace"] = transaction_data["contexts"]["trace"]
event_data["type"] = "transaction"
event_data["transaction"] = "/failure_rate/1"
event_data["timestamp"] = self.ten_mins_ago.isoformat()
event_data["start_timestamp"] = before_now(minutes=10, seconds=5).isoformat()
event_data["user"]["geo"] = {"country_code": "US", "region": "CA", "city": "San Francisco"}
event_data["request"] = transaction_data["request"]
self.store_event(event_data, project_id=self.project.id)
event_data["type"] = "error"
self.store_event(event_data, project_id=self.project.id)
fields = ["http.method", "http.referer", "http.url"]
expected = ["GET", "fixtures.transaction", "http://countries:8010/country_by_code/"]
data = [
{"field": fields + ["location", "count()"], "query": "event.type:error"},
{"field": fields + ["duration", "count()"], "query": "event.type:transaction"},
]
for datum in data:
response = self.do_request(datum)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1, datum
results = response.data["data"]
assert results[0]["count()"] == 1, datum
for field, exp in zip(fields, expected):
assert results[0][field] == exp, field + str(datum)
def test_failure_count_alias_field(self) -> None:
data = self.transaction_data.copy()
data["transaction"] = "/failure_count/success"
self.store_event(data, project_id=self.project.id)
data = self.transaction_data.copy()
data["transaction"] = "/failure_count/unknown"
data["contexts"]["trace"]["status"] = "unknown_error"
self.store_event(data, project_id=self.project.id)
for i in range(6):
data = self.transaction_data.copy()
data["transaction"] = f"/failure_count/{i}"
data["contexts"]["trace"]["status"] = "unauthenticated"
self.store_event(data, project_id=self.project.id)
for dataset in ["discover", "transactions"]:
query = {
"field": ["count()", "failure_count()"],
"query": "event.type:transaction",
"dataset": dataset,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
data = response.data["data"]
assert data[0]["count()"] == 8
assert data[0]["failure_count()"] == 7
@mock.patch("sentry.utils.snuba.quantize_time")
def test_quantize_dates(self, mock_quantize: mock.MagicMock) -> None:
self.create_project()
mock_quantize.return_value = before_now(days=1)
# Don't quantize short time periods
query = {"statsPeriod": "1h", "query": "", "field": ["id", "timestamp"]}
self.do_request(query)
# Don't quantize absolute date periods
self.do_request(query)
query = {
"start": before_now(days=20).isoformat(),
"end": before_now(days=15).isoformat(),
"query": "",
"field": ["id", "timestamp"],
}
self.do_request(query)
assert len(mock_quantize.mock_calls) == 0
# Quantize long date periods
query = {"field": ["id", "timestamp"], "statsPeriod": "90d", "query": ""}
self.do_request(query)
assert len(mock_quantize.mock_calls) == 2
def test_limit_number_of_fields(self) -> None:
self.create_project()
for i in range(1, 60, 10):
response = self.do_request({"field": ["id"] * i})
if i <= 50:
assert response.status_code == 200
else:
assert response.status_code == 400
assert (
response.data["detail"]
== "You can view up to 50 fields at a time. Please delete some and try again."
)
def test_percentile_function_meta_types(self) -> None:
self.store_event(self.transaction_data, project_id=self.project.id)
for dataset in ["discover", "transactions"]:
query = {
"field": [
"transaction",
"percentile(transaction.duration, 0.95)",
"percentile(measurements.fp, 0.95)",
"percentile(measurements.fcp, 0.95)",
"percentile(measurements.lcp, 0.95)",
"percentile(measurements.fid, 0.95)",
"percentile(measurements.ttfb, 0.95)",
"percentile(measurements.ttfb.requesttime, 0.95)",
"percentile(measurements.cls, 0.95)",
"percentile(measurements.foo, 0.95)",
"percentile(measurements.bar, 0.95)",
],
"query": "",
"orderby": ["transaction"],
"dataset": dataset,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
meta = response.data["meta"]["fields"]
assert meta["percentile(transaction.duration, 0.95)"] == "duration"
assert meta["percentile(measurements.fp, 0.95)"] == "duration"
assert meta["percentile(measurements.fcp, 0.95)"] == "duration"
assert meta["percentile(measurements.lcp, 0.95)"] == "duration"
assert meta["percentile(measurements.fid, 0.95)"] == "duration"
assert meta["percentile(measurements.ttfb, 0.95)"] == "duration"
assert meta["percentile(measurements.ttfb.requesttime, 0.95)"] == "duration"
assert meta["percentile(measurements.cls, 0.95)"] == "number"
assert meta["percentile(measurements.foo, 0.95)"] == "number"
assert meta["percentile(measurements.bar, 0.95)"] == "number"
units = response.data["meta"]["units"]
assert units["percentile(transaction.duration, 0.95)"] == "millisecond"
assert units["percentile(measurements.fp, 0.95)"] == "millisecond"
assert units["percentile(measurements.fcp, 0.95)"] == "millisecond"
assert units["percentile(measurements.lcp, 0.95)"] == "millisecond"
assert units["percentile(measurements.fid, 0.95)"] == "millisecond"
assert units["percentile(measurements.ttfb, 0.95)"] == "millisecond"
assert units["percentile(measurements.ttfb.requesttime, 0.95)"] == "millisecond"
def test_count_at_least_query(self) -> None:
self.store_event(self.transaction_data, self.project.id)
for dataset in ["discover", "transactions"]:
response = self.do_request(
{"field": "count_at_least(measurements.fcp, 0)", "dataset": dataset}
)
assert response.status_code == 200
assert len(response.data["data"]) == 1
assert response.data["data"][0]["count_at_least(measurements.fcp, 0)"] == 1
# a value that's a little bigger than the stored fcp
fcp = int(self.transaction_data["measurements"]["fcp"]["value"] + 1)
response = self.do_request(
{"field": f"count_at_least(measurements.fcp, {fcp})", "dataset": dataset}
)
assert response.status_code == 200
assert len(response.data["data"]) == 1
assert response.data["data"][0][f"count_at_least(measurements.fcp, {fcp})"] == 0
def test_measurements_query(self) -> None:
self.store_event(self.transaction_data, self.project.id)
for dataset in ["discover", "transactions"]:
query = {
"field": [
"measurements.fp",
"measurements.fcp",
"measurements.lcp",
"measurements.fid",
],
"dataset": dataset,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
for field in query["field"]:
measure = field.split(".", 1)[1]
assert (
response.data["data"][0][field]
== self.transaction_data["measurements"][measure]["value"]
)
query = {
"field": [
"measurements.fP",
"measurements.Fcp",
"measurements.LcP",
"measurements.FID",
],
"dataset": dataset,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
for field in query["field"]:
measure = field.split(".", 1)[1].lower()
assert (
response.data["data"][0][field]
== self.transaction_data["measurements"][measure]["value"]
)
def test_measurements_aggregations(self) -> None:
self.store_event(self.transaction_data, self.project.id)
# should try all the potential aggregates
# Skipped tests for stddev and var since sampling one data point
# results in nan.
for dataset in ["discover", "transactions"]:
query = {
"field": [
"percentile(measurements.fcp, 0.5)",
"count_unique(measurements.fcp)",
"min(measurements.fcp)",
"max(measurements.fcp)",
"avg(measurements.fcp)",
"sum(measurements.fcp)",
],
"dataset": dataset,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert (
response.data["data"][0]["percentile(measurements.fcp, 0.5)"]
== self.transaction_data["measurements"]["fcp"]["value"]
)
assert response.data["data"][0]["count_unique(measurements.fcp)"] == 1
assert (
response.data["data"][0]["min(measurements.fcp)"]
== self.transaction_data["measurements"]["fcp"]["value"]
)
assert (
response.data["data"][0]["max(measurements.fcp)"]
== self.transaction_data["measurements"]["fcp"]["value"]
)
assert (
response.data["data"][0]["avg(measurements.fcp)"]
== self.transaction_data["measurements"]["fcp"]["value"]
)
assert (
response.data["data"][0]["sum(measurements.fcp)"]
== self.transaction_data["measurements"]["fcp"]["value"]
)
def get_measurement_condition_response(self, query_str, field, dataset="discover"):
query = {
"field": ["transaction", "count()"] + (field if field else []),
"query": query_str,
"dataset": dataset,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
return response
def assert_measurement_condition_without_results(
self, query_str, field=None, dataset="discover"
):
response = self.get_measurement_condition_response(query_str, field, dataset=dataset)
assert len(response.data["data"]) == 0
def assert_measurement_condition_with_results(self, query_str, field=None, dataset="discover"):
response = self.get_measurement_condition_response(query_str, field, dataset=dataset)
assert len(response.data["data"]) == 1
assert response.data["data"][0]["transaction"] == self.transaction_data["metadata"]["title"]
assert response.data["data"][0]["count()"] == 1
def test_measurements_conditions(self) -> None:
self.store_event(self.transaction_data, self.project.id)
fcp = self.transaction_data["measurements"]["fcp"]["value"]
for dataset in ["discover", "transactions"]:
# equality condition
# We use json dumps here to ensure precision when converting from float to str
# This is necessary because equality on floating point values need to be precise
self.assert_measurement_condition_with_results(
f"measurements.fcp:{json.dumps(fcp)}", dataset=dataset
)
# greater than condition
self.assert_measurement_condition_with_results(
f"measurements.fcp:>{fcp - 1}", dataset=dataset
)
self.assert_measurement_condition_without_results(
f"measurements.fcp:>{fcp + 1}", dataset=dataset
)
# less than condition
self.assert_measurement_condition_with_results(
f"measurements.fcp:<{fcp + 1}", dataset=dataset
)
self.assert_measurement_condition_without_results(
f"measurements.fcp:<{fcp - 1}", dataset=dataset
)
# has condition
self.assert_measurement_condition_with_results("has:measurements.fcp", dataset=dataset)
self.assert_measurement_condition_without_results(
"!has:measurements.fcp", dataset=dataset
)
def test_measurements_aggregation_conditions(self) -> None:
self.store_event(self.transaction_data, self.project.id)
fcp = self.transaction_data["measurements"]["fcp"]["value"]
functions = [
"percentile(measurements.fcp, 0.5)",
"min(measurements.fcp)",
"max(measurements.fcp)",
"avg(measurements.fcp)",
"sum(measurements.fcp)",
]
for dataset in ["discover", "transactions"]:
for function in functions:
self.assert_measurement_condition_with_results(
f"{function}:>{fcp - 1}", field=[function], dataset=dataset
)
self.assert_measurement_condition_without_results(
f"{function}:>{fcp + 1}", field=[function], dataset=dataset
)
self.assert_measurement_condition_with_results(
f"{function}:<{fcp + 1}", field=[function], dataset=dataset
)
self.assert_measurement_condition_without_results(
f"{function}:<{fcp - 1}", field=[function], dataset=dataset
)
count_unique = "count_unique(measurements.fcp)"
self.assert_measurement_condition_with_results(
f"{count_unique}:1", field=[count_unique], dataset=dataset
)
self.assert_measurement_condition_without_results(
f"{count_unique}:0", field=[count_unique], dataset=dataset
)
def test_compare_numeric_aggregate(self) -> None:
self.store_event(self.transaction_data, self.project.id)
for dataset in ["discover", "transactions"]:
query = {
"field": [
"p75(measurements.fcp)",
"compare_numeric_aggregate(p75_measurements_fcp,greater,0)",
],
"dataset": dataset,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert (
response.data["data"][0][
"compare_numeric_aggregate(p75_measurements_fcp,greater,0)"
]
== 1
)
query = {
"field": ["p75()", "compare_numeric_aggregate(p75,equals,0)"],
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["compare_numeric_aggregate(p75,equals,0)"] == 0
def test_no_team_key_transactions(self) -> None:
transactions = [
"/blah_transaction/",
"/foo_transaction/",
"/zoo_transaction/",
]
for transaction in transactions:
self.transaction_data["transaction"] = transaction
self.store_event(self.transaction_data, self.project.id)
for dataset in ["discover", "transactions"]:
query = {
"team": "myteams",
"project": [self.project.id],
# use the order by to ensure the result order
"orderby": "transaction",
"field": [
"team_key_transaction",
"transaction",
"transaction.status",
"project",
"epm()",
"failure_rate()",
"percentile(transaction.duration, 0.95)",
],
"dataset": dataset,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 3
assert data[0]["team_key_transaction"] == 0
assert data[0]["transaction"] == "/blah_transaction/"
assert data[1]["team_key_transaction"] == 0
assert data[1]["transaction"] == "/foo_transaction/"
assert data[2]["team_key_transaction"] == 0
assert data[2]["transaction"] == "/zoo_transaction/"
def test_team_key_transactions_my_teams(self) -> None:
team1 = self.create_team(organization=self.organization, name="Team A")
self.create_team_membership(team1, user=self.user)
self.project.add_team(team1)
team2 = self.create_team(organization=self.organization, name="Team B")
self.project.add_team(team2)
transactions = ["/blah_transaction/"]
key_transactions = [
(team1, "/foo_transaction/"),
(team2, "/zoo_transaction/"),
]
for transaction in transactions:
self.transaction_data["transaction"] = transaction
self.store_event(self.transaction_data, self.project.id)
for team, transaction in key_transactions:
self.transaction_data["transaction"] = transaction
self.store_event(self.transaction_data, self.project.id)
TeamKeyTransaction.objects.create(
organization=self.organization,
transaction=transaction,
project_team=ProjectTeam.objects.get(project=self.project, team=team),
)
for dataset in ["discover", "transactions"]:
query = {
"team": "myteams",
"project": [self.project.id],
"field": [
"team_key_transaction",
"transaction",
"transaction.status",
"project",
"epm()",
"failure_rate()",
"percentile(transaction.duration, 0.95)",
],
"dataset": dataset,
}
query["orderby"] = ["team_key_transaction", "transaction"]
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 3
assert data[0]["team_key_transaction"] == 0
assert data[0]["transaction"] == "/blah_transaction/"
assert data[1]["team_key_transaction"] == 0
assert data[1]["transaction"] == "/zoo_transaction/"
assert data[2]["team_key_transaction"] == 1
assert data[2]["transaction"] == "/foo_transaction/"
# not specifying any teams should use my teams
query = {
"project": [self.project.id],
"field": [
"team_key_transaction",
"transaction",
"transaction.status",
"project",
"epm()",
"failure_rate()",
"percentile(transaction.duration, 0.95)",
],
"dataset": dataset,
}
query["orderby"] = ["team_key_transaction", "transaction"]
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 3
assert data[0]["team_key_transaction"] == 0
assert data[0]["transaction"] == "/blah_transaction/"
assert data[1]["team_key_transaction"] == 0
assert data[1]["transaction"] == "/zoo_transaction/"
assert data[2]["team_key_transaction"] == 1
assert data[2]["transaction"] == "/foo_transaction/"
def test_team_key_transactions_orderby(self) -> None:
team1 = self.create_team(organization=self.organization, name="Team A")
team2 = self.create_team(organization=self.organization, name="Team B")
transactions = ["/blah_transaction/"]
key_transactions = [
(team1, "/foo_transaction/"),
(team2, "/zoo_transaction/"),
]
for transaction in transactions:
self.transaction_data["transaction"] = transaction
self.store_event(self.transaction_data, self.project.id)
for team, transaction in key_transactions:
self.create_team_membership(team, user=self.user)
self.project.add_team(team)
self.transaction_data["transaction"] = transaction
self.store_event(self.transaction_data, self.project.id)
TeamKeyTransaction.objects.create(
organization=self.organization,
transaction=transaction,
project_team=ProjectTeam.objects.get(project=self.project, team=team),
)
for dataset in ["discover", "transactions"]:
query = {
"team": "myteams",
"project": [self.project.id],
"field": [
"team_key_transaction",
"transaction",
"transaction.status",
"project",
"epm()",
"failure_rate()",
"percentile(transaction.duration, 0.95)",
],
"dataset": dataset,
}
# test ascending order
query["orderby"] = ["team_key_transaction", "transaction"]
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 3
assert data[0]["team_key_transaction"] == 0
assert data[0]["transaction"] == "/blah_transaction/"
assert data[1]["team_key_transaction"] == 1
assert data[1]["transaction"] == "/foo_transaction/"
assert data[2]["team_key_transaction"] == 1
assert data[2]["transaction"] == "/zoo_transaction/"
# test descending order
query["orderby"] = ["-team_key_transaction", "-transaction"]
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 3
assert data[0]["team_key_transaction"] == 1
assert data[0]["transaction"] == "/zoo_transaction/"
assert data[1]["team_key_transaction"] == 1
assert data[1]["transaction"] == "/foo_transaction/"
assert data[2]["team_key_transaction"] == 0
assert data[2]["transaction"] == "/blah_transaction/"
def test_team_key_transactions_query(self) -> None:
team1 = self.create_team(organization=self.organization, name="Team A")
team2 = self.create_team(organization=self.organization, name="Team B")
transactions = ["/blah_transaction/"]
key_transactions = [
(team1, "/foo_transaction/"),
(team2, "/zoo_transaction/"),
]
for transaction in transactions:
self.transaction_data["transaction"] = transaction
self.store_event(self.transaction_data, self.project.id)
for team, transaction in key_transactions:
self.create_team_membership(team, user=self.user)
self.project.add_team(team)
self.transaction_data["transaction"] = transaction
self.store_event(self.transaction_data, self.project.id)
TeamKeyTransaction.objects.create(
organization=self.organization,
project_team=ProjectTeam.objects.get(
project=self.project,
team=team,
),
transaction=transaction,
)
for dataset in ["discover", "transactions"]:
query = {
"team": "myteams",
"project": [self.project.id],
# use the order by to ensure the result order
"orderby": "transaction",
"field": [
"team_key_transaction",
"transaction",
"transaction.status",
"project",
"epm()",
"failure_rate()",
"percentile(transaction.duration, 0.95)",
],
"dataset": dataset,
}
# key transactions
query["query"] = "has:team_key_transaction"
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
assert data[0]["team_key_transaction"] == 1
assert data[0]["transaction"] == "/foo_transaction/"
assert data[1]["team_key_transaction"] == 1
assert data[1]["transaction"] == "/zoo_transaction/"
# key transactions
query["query"] = "team_key_transaction:true"
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
assert data[0]["team_key_transaction"] == 1
assert data[0]["transaction"] == "/foo_transaction/"
assert data[1]["team_key_transaction"] == 1
assert data[1]["transaction"] == "/zoo_transaction/"
# not key transactions
query["query"] = "!has:team_key_transaction"
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["team_key_transaction"] == 0
assert data[0]["transaction"] == "/blah_transaction/"
# not key transactions
query["query"] = "team_key_transaction:false"
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["team_key_transaction"] == 0
assert data[0]["transaction"] == "/blah_transaction/"
def test_too_many_team_key_transactions(self) -> None:
MAX_QUERYABLE_TEAM_KEY_TRANSACTIONS = 1
with mock.patch(
"sentry.search.events.fields.MAX_QUERYABLE_TEAM_KEY_TRANSACTIONS",
MAX_QUERYABLE_TEAM_KEY_TRANSACTIONS,
):
team = self.create_team(organization=self.organization, name="Team A")
self.create_team_membership(team, user=self.user)
self.project.add_team(team)
project_team = ProjectTeam.objects.get(project=self.project, team=team)
for i in range(MAX_QUERYABLE_TEAM_KEY_TRANSACTIONS + 1):
transaction = f"transaction-{team.id}-{i}"
self.transaction_data["transaction"] = transaction
self.store_event(self.transaction_data, self.project.id)
TeamKeyTransaction.objects.bulk_create(
[
TeamKeyTransaction(
organization=self.organization,
project_team=project_team,
transaction=f"transaction-{team.id}-{i}",
)
for i in range(MAX_QUERYABLE_TEAM_KEY_TRANSACTIONS + 1)
]
)
for dataset in ["discover", "transactions"]:
query = {
"team": "myteams",
"project": [self.project.id],
"orderby": "transaction",
"field": [
"team_key_transaction",
"transaction",
"transaction.status",
"project",
"epm()",
"failure_rate()",
"percentile(transaction.duration, 0.95)",
],
"dataset": dataset,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
assert (
sum(row["team_key_transaction"] for row in data)
== MAX_QUERYABLE_TEAM_KEY_TRANSACTIONS
)
def test_no_pagination_param(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"timestamp": self.ten_mins_ago_iso,
"fingerprint": ["group1"],
},
project_id=self.project.id,
)
query = {"field": ["id", "project.id"], "project": [self.project.id], "noPagination": True}
response = self.do_request(query)
assert response.status_code == 200
assert len(response.data["data"]) == 1
assert "Link" not in response
def test_nan_result(self) -> None:
query = {"field": ["apdex(300)"], "project": [self.project.id], "query": f"id:{'0' * 32}"}
response = self.do_request(query)
assert response.status_code == 200
assert len(response.data["data"]) == 1
assert response.data["data"][0]["apdex(300)"] == 0
def test_equation_simple(self) -> None:
event_data = self.load_data(
timestamp=self.ten_mins_ago,
)
event_data["breakdowns"]["span_ops"]["ops.http"]["value"] = 1500
self.store_event(data=event_data, project_id=self.project.id)
for dataset in ["discover", "transactions"]:
query = {
"field": ["spans.http", "equation|spans.http / 3"],
"project": [self.project.id],
"query": "event.type:transaction",
"dataset": dataset,
}
response = self.do_request(
query,
{
"organizations:discover-basic": True,
},
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert (
response.data["data"][0]["equation|spans.http / 3"]
== event_data["breakdowns"]["span_ops"]["ops.http"]["value"] / 3
)
assert response.data["meta"]["fields"]["equation|spans.http / 3"] == "number"
def test_equation_sort(self) -> None:
event_data = self.transaction_data.copy()
event_data["breakdowns"] = {"span_ops": {"ops.http": {"value": 1500}}}
self.store_event(data=event_data, project_id=self.project.id)
event_data2 = self.transaction_data.copy()
event_data2["breakdowns"] = {"span_ops": {"ops.http": {"value": 2000}}}
self.store_event(data=event_data2, project_id=self.project.id)
for dataset in ["discover", "transactions"]:
query = {
"field": ["spans.http", "equation|spans.http / 3"],
"project": [self.project.id],
"orderby": "equation|spans.http / 3",
"query": "event.type:transaction",
"dataset": dataset,
}
response = self.do_request(
query,
{
"organizations:discover-basic": True,
},
)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 2
assert (
response.data["data"][0]["equation|spans.http / 3"]
== event_data["breakdowns"]["span_ops"]["ops.http"]["value"] / 3
)
assert (
response.data["data"][1]["equation|spans.http / 3"]
== event_data2["breakdowns"]["span_ops"]["ops.http"]["value"] / 3
)
def test_equation_operation_limit(self) -> None:
for dataset in ["discover", "transactions"]:
query = {
"field": ["spans.http", f"equation|spans.http{' * 2' * 11}"],
"project": [self.project.id],
"query": "event.type:transaction",
"dataset": dataset,
}
response = self.do_request(
query,
{
"organizations:discover-basic": True,
},
)
assert response.status_code == 400
@mock.patch("sentry.api.bases.organization_events.MAX_FIELDS", 2)
def test_equation_field_limit(self) -> None:
for dataset in ["discover", "transactions"]:
query = {
"field": ["spans.http", "transaction.duration", "equation|5 * 2"],
"project": [self.project.id],
"query": "event.type:transaction",
"dataset": dataset,
}
response = self.do_request(
query,
{
"organizations:discover-basic": True,
},
)
assert response.status_code == 400
def test_count_if(self) -> None:
unicode_phrase1 = "\u716e\u6211\u66f4\u591a\u7684\u98df\u7269\uff0c\u6211\u9913\u4e86"
for i in range(5):
data = self.load_data(
timestamp=before_now(minutes=(10 + i)),
duration=timedelta(milliseconds=100 if i < 3 else 200),
)
data["tags"] = {
"sub_customer.is-Enterprise-42": "yes" if i == 0 else "no",
"unicode-phrase": unicode_phrase1 if i == 0 else "no",
}
self.store_event(data, project_id=self.project.id)
query = {
"field": [
"count_if(transaction.duration, less, 150)",
"count_if(transaction.duration, greater, 150)",
"count_if(sub_customer.is-Enterprise-42, equals, yes)",
"count_if(sub_customer.is-Enterprise-42, notEquals, yes)",
f"count_if(unicode-phrase, equals, {unicode_phrase1})",
],
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 200
assert len(response.data["data"]) == 1
assert response.data["data"][0]["count_if(transaction.duration, less, 150)"] == 3
assert response.data["data"][0]["count_if(transaction.duration, greater, 150)"] == 2
assert response.data["data"][0]["count_if(sub_customer.is-Enterprise-42, equals, yes)"] == 1
assert (
response.data["data"][0]["count_if(sub_customer.is-Enterprise-42, notEquals, yes)"] == 4
)
assert response.data["data"][0][f"count_if(unicode-phrase, equals, {unicode_phrase1})"] == 1
def test_count_if_array_field(self) -> None:
data = self.load_data(platform="javascript")
data["timestamp"] = self.ten_mins_ago_iso
self.store_event(data=data, project_id=self.project.id)
query = {
"field": [
"count_if(stack.filename, equals, raven.js)",
],
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["count_if(stack.filename, equals, raven.js)"] == 1
def test_count_if_measurements_cls(self) -> None:
data = self.transaction_data.copy()
data["measurements"] = {"cls": {"value": 0.5}}
self.store_event(data, project_id=self.project.id)
data["measurements"] = {"cls": {"value": 0.1}}
self.store_event(data, project_id=self.project.id)
query = {
"field": [
"count_if(measurements.cls, greater, 0.05)",
"count_if(measurements.cls, less, 0.3)",
],
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 200
assert len(response.data["data"]) == 1
assert response.data["data"][0]["count_if(measurements.cls, greater, 0.05)"] == 2
assert response.data["data"][0]["count_if(measurements.cls, less, 0.3)"] == 1
def test_count_if_filter(self) -> None:
for i in range(5):
data = self.load_data(
timestamp=before_now(minutes=(10 + i)),
duration=timedelta(milliseconds=100 if i < 3 else 200),
)
data["tags"] = {"sub_customer.is-Enterprise-42": "yes" if i == 0 else "no"}
self.store_event(data, project_id=self.project.id)
query = {
"field": [
"count_if(transaction.duration, less, 150)",
],
"query": "count_if(transaction.duration, less, 150):>2",
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 200
assert len(response.data["data"]) == 1
assert response.data["data"][0]["count_if(transaction.duration, less, 150)"] == 3
query = {
"field": [
"count_if(transaction.duration, less, 150)",
],
"query": "count_if(transaction.duration, less, 150):<2",
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 200
assert len(response.data["data"]) == 0
def test_filters_with_escaped_asterisk(self) -> None:
self.transaction_data["transaction"] = r"/:a*/:b-:c(\d\.\e+)"
self.store_event(self.transaction_data, project_id=self.project.id)
query = {
"field": ["transaction", "transaction.duration"],
# make sure to escape the asterisk so it's not treated as a wildcard
"query": r'transaction:"/:a\*/:b-:c(\d\.\e+)"',
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 200
assert len(response.data["data"]) == 1
def test_filters_with_back_slashes(self) -> None:
self.transaction_data["transaction"] = r"a\b\c@d"
self.store_event(self.transaction_data, project_id=self.project.id)
query = {
"field": ["transaction", "transaction.duration"],
"query": r'transaction:"a\b\c@d"',
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 200
assert len(response.data["data"]) == 1
def test_mobile_measurements(self) -> None:
self.transaction_data["measurements"]["frames_total"] = {"value": 100}
self.transaction_data["measurements"]["frames_slow"] = {"value": 10}
self.transaction_data["measurements"]["frames_frozen"] = {"value": 5}
self.transaction_data["measurements"]["stall_count"] = {"value": 2}
self.transaction_data["measurements"]["stall_total_time"] = {"value": 12}
self.transaction_data["measurements"]["stall_longest_time"] = {"value": 7}
self.store_event(self.transaction_data, project_id=self.project.id)
query = {
"field": [
"measurements.frames_total",
"measurements.frames_slow",
"measurements.frames_frozen",
"measurements.frames_slow_rate",
"measurements.frames_frozen_rate",
"measurements.stall_count",
"measurements.stall_total_time",
"measurements.stall_longest_time",
"measurements.stall_percentage",
],
"query": "",
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 200
data = response.data["data"]
assert len(data) == 1
assert data[0]["measurements.frames_total"] == 100
assert data[0]["measurements.frames_slow"] == 10
assert data[0]["measurements.frames_frozen"] == 5
assert data[0]["measurements.frames_slow_rate"] == 0.1
assert data[0]["measurements.frames_frozen_rate"] == 0.05
assert data[0]["measurements.stall_count"] == 2
assert data[0]["measurements.stall_total_time"] == 12
assert data[0]["measurements.stall_longest_time"] == 7
assert data[0]["measurements.stall_percentage"] == 0.004
meta = response.data["meta"]["fields"]
assert meta["measurements.frames_total"] == "number"
assert meta["measurements.frames_slow"] == "number"
assert meta["measurements.frames_frozen"] == "number"
assert meta["measurements.frames_slow_rate"] == "percentage"
assert meta["measurements.frames_frozen_rate"] == "percentage"
assert meta["measurements.stall_count"] == "number"
assert meta["measurements.stall_total_time"] == "duration"
assert meta["measurements.stall_longest_time"] == "duration"
assert meta["measurements.stall_percentage"] == "percentage"
query = {
"field": [
"p75(measurements.frames_slow_rate)",
"p75(measurements.frames_frozen_rate)",
"percentile(measurements.frames_slow_rate,0.5)",
"percentile(measurements.frames_frozen_rate,0.5)",
"p75(measurements.stall_percentage)",
"percentile(measurements.stall_percentage,0.5)",
],
"query": "",
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 200
data = response.data["data"]
assert len(data) == 1
assert data[0]["p75(measurements.frames_slow_rate)"] == 0.1
assert data[0]["p75(measurements.frames_frozen_rate)"] == 0.05
assert data[0]["p75(measurements.stall_percentage)"] == 0.004
assert data[0]["percentile(measurements.frames_slow_rate,0.5)"] == 0.1
assert data[0]["percentile(measurements.frames_frozen_rate,0.5)"] == 0.05
assert data[0]["percentile(measurements.stall_percentage,0.5)"] == 0.004
meta = response.data["meta"]["fields"]
assert meta["p75(measurements.frames_slow_rate)"] == "percentage"
assert meta["p75(measurements.frames_frozen_rate)"] == "percentage"
assert meta["p75(measurements.stall_percentage)"] == "percentage"
assert meta["percentile(measurements.frames_slow_rate,0.5)"] == "percentage"
assert meta["percentile(measurements.stall_percentage,0.5)"] == "percentage"
def test_project_auto_fields(self) -> None:
self.store_event(
data={
"event_id": "a" * 32,
"environment": "staging",
"timestamp": self.ten_mins_ago_iso,
},
project_id=self.project.id,
)
query = {"field": ["environment"]}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["environment"] == "staging"
assert response.data["data"][0]["project.name"] == self.project.slug
def test_timestamp_different_from_params(self) -> None:
fifteen_days_ago = before_now(days=15)
fifteen_days_later = before_now(days=-15)
for query_text in [
f"timestamp:<{fifteen_days_ago}",
f"timestamp:<={fifteen_days_ago}",
f"timestamp:>{fifteen_days_later}",
f"timestamp:>={fifteen_days_later}",
]:
query = {
"field": ["count()"],
"query": query_text,
"statsPeriod": "14d",
"project": self.project.id,
}
response = self.do_request(query)
assert response.status_code == 400, query_text
@mock.patch("sentry.search.events.builder.base.raw_snql_query")
def test_removes_unnecessary_default_project_and_transaction_thresholds(
self, mock_snql_query: mock.MagicMock
) -> None:
mock_snql_query.side_effect = [{"meta": {}, "data": []}]
ProjectTransactionThreshold.objects.create(
project=self.project,
organization=self.organization,
# these are the default values that we use
threshold=constants.DEFAULT_PROJECT_THRESHOLD,
metric=TransactionMetric.DURATION.value,
)
ProjectTransactionThresholdOverride.objects.create(
transaction="transaction",
project=self.project,
organization=self.organization,
# these are the default values that we use
threshold=constants.DEFAULT_PROJECT_THRESHOLD,
metric=TransactionMetric.DURATION.value,
)
query = {
"field": ["apdex()", "user_misery()"],
"query": "event.type:transaction",
"project": [self.project.id],
}
response = self.do_request(
query,
features={
"organizations:discover-basic": True,
},
)
assert response.status_code == 200, response.content
assert mock_snql_query.call_count == 1
assert (
Function("tuple", ["duration", 300], "project_threshold_config")
in mock_snql_query.call_args_list[0][0][0].query.select
)
@mock.patch("sentry.search.events.builder.base.raw_snql_query")
def test_removes_unnecessary_default_project_and_transaction_thresholds_keeps_others(
self, mock_snql_query
):
mock_snql_query.side_effect = [{"meta": {}, "data": []}]
ProjectTransactionThreshold.objects.create(
project=self.project,
organization=self.organization,
# these are the default values that we use
threshold=constants.DEFAULT_PROJECT_THRESHOLD,
metric=TransactionMetric.DURATION.value,
)
ProjectTransactionThresholdOverride.objects.create(
transaction="transaction",
project=self.project,
organization=self.organization,
# these are the default values that we use
threshold=constants.DEFAULT_PROJECT_THRESHOLD,
metric=TransactionMetric.DURATION.value,
)
project = self.create_project()
ProjectTransactionThreshold.objects.create(
project=project,
organization=self.organization,
threshold=100,
metric=TransactionMetric.LCP.value,
)
ProjectTransactionThresholdOverride.objects.create(
transaction="transaction",
project=project,
organization=self.organization,
threshold=200,
metric=TransactionMetric.LCP.value,
)
query = {
"field": ["apdex()", "user_misery()"],
"query": "event.type:transaction",
"project": [self.project.id, project.id],
}
response = self.do_request(
query,
features={
"organizations:discover-basic": True,
},
)
assert response.status_code == 200, response.content
assert mock_snql_query.call_count == 1
project_threshold_override_config_index = Function(
"indexOf",
[
# only 1 transaction override is present here
# because the other use to the default values
[(Function("toUInt64", [project.id]), "transaction")],
(Column("project_id"), Column("transaction")),
],
"project_threshold_override_config_index",
)
project_threshold_config_index = Function(
"indexOf",
[
# only 1 project override is present here
# because the other use to the default values
[Function("toUInt64", [project.id])],
Column("project_id"),
],
"project_threshold_config_index",
)
assert (
Function(
"if",
[
Function("equals", [project_threshold_override_config_index, 0]),
Function(
"if",
[
Function("equals", [project_threshold_config_index, 0]),
("duration", 300),
Function(
"arrayElement", [[("lcp", 100)], project_threshold_config_index]
),
],
),
Function(
"arrayElement",
[[("lcp", 200)], project_threshold_override_config_index],
),
],
"project_threshold_config",
)
in mock_snql_query.call_args_list[0][0][0].query.select
)
def test_count_web_vitals(self) -> None:
# Good
self.transaction_data["measurements"] = {
"lcp": {"value": constants.VITAL_THRESHOLDS["lcp"]["meh"] - 100},
}
self.store_event(self.transaction_data, self.project.id)
# Meh
self.transaction_data["measurements"] = {
"lcp": {"value": constants.VITAL_THRESHOLDS["lcp"]["meh"] + 100},
}
self.store_event(self.transaction_data, self.project.id)
self.store_event(self.transaction_data, self.project.id)
query = {
"field": [
"count_web_vitals(measurements.lcp, poor)",
"count_web_vitals(measurements.lcp, meh)",
"count_web_vitals(measurements.lcp, good)",
]
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0] == {
"count_web_vitals(measurements.lcp, poor)": 0,
"count_web_vitals(measurements.lcp, meh)": 2,
"count_web_vitals(measurements.lcp, good)": 1,
}
def test_count_web_vitals_invalid_vital(self) -> None:
query = {
"field": [
"count_web_vitals(measurements.foo, poor)",
],
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 400, response.content
query = {
"field": [
"count_web_vitals(tags[lcp], poor)",
],
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 400, response.content
query = {
"field": [
"count_web_vitals(transaction.duration, poor)",
],
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 400, response.content
query = {
"field": [
"count_web_vitals(measurements.lcp, bad)",
],
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 400, response.content
def test_tag_that_looks_like_aggregate(self) -> None:
data = self.load_data()
data["tags"] = {"p95": "<5k"}
self.store_event(data, project_id=self.project.id)
query = {
"field": ["p95"],
"query": "p95:<5k",
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["p95"] == "<5k"
def test_chained_or_query_meta_tip(self) -> None:
query = {
"field": ["transaction"],
"query": "transaction:a OR transaction:b",
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 200, response.content
meta = response.data["meta"]
assert meta["tips"] == {
"query": "Did you know you can replace chained or conditions like `field:a OR field:b OR field:c` with `field:[a,b,c]`",
"columns": None,
}
@override_settings(SENTRY_SELF_HOSTED=False)
def test_no_ratelimit(self) -> None:
query = {
"field": ["transaction"],
"project": [self.project.id],
}
with freeze_time("2000-01-01"):
for _ in range(15):
self.do_request(query)
response = self.do_request(query)
assert response.status_code == 200, response.content
def test_transaction_source(self) -> None:
query = {
"field": ["transaction"],
"query": "transaction.source:task",
"project": [self.project.id],
}
response = self.do_request(query)
assert response.status_code == 200, response.content
def test_readable_device_name(self) -> None:
data = self.load_data()
data["tags"] = {"device": "iPhone14,3"}
self.store_event(data, project_id=self.project.id)
query = {
"field": ["device"],
"query": "",
"project": [self.project.id],
"readable": True,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["device"] == "iPhone14,3"
assert data[0]["readable"] == "iPhone 13 Pro Max"
def test_http_status_code(self) -> None:
project1 = self.create_project()
project2 = self.create_project()
self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"tags": {"http.status_code": "200"},
},
project_id=project1.id,
)
self.store_event(
data={
"event_id": "b" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"contexts": {"response": {"status_code": 400}},
},
project_id=project2.id,
)
features = {"organizations:discover-basic": True}
query = {
"field": ["event.type", "http.status_code"],
"query": "",
"statsPeriod": "24h",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
result = {r["http.status_code"] for r in data}
assert result == {"200", "400"}
def test_http_status_code_context_priority(self) -> None:
project1 = self.create_project()
self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"tags": {"http.status_code": "200"},
"contexts": {"response": {"status_code": 400}},
},
project_id=project1.id,
)
features = {"organizations:discover-basic": True}
query = {
"field": ["event.type", "http.status_code"],
"query": "",
"statsPeriod": "24h",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["http.status_code"] == "400"
def test_total_count(self) -> None:
project1 = self.create_project()
for i in range(3):
self.store_event(data=self.load_data(platform="javascript"), project_id=project1.id)
self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
},
project_id=project1.id,
)
features = {"organizations:discover-basic": True}
query = {
"field": ["transaction", "total.count", "count()"],
"query": "!transaction:/example",
"statsPeriod": "24h",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["total.count"] == 3
def test_total_count_by_itself(self) -> None:
project1 = self.create_project()
for i in range(3):
self.store_event(data=self.load_data(platform="javascript"), project_id=project1.id)
features = {"organizations:discover-basic": True}
query = {
"field": ["total.count"],
"statsPeriod": "24h",
}
response = self.do_request(query, features=features)
assert response.status_code == 400, response.content
def test_total_count_equation(self) -> None:
project1 = self.create_project()
for i in range(3):
self.store_event(data=self.load_data(platform="javascript"), project_id=project1.id)
self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
},
project_id=project1.id,
)
features = {"organizations:discover-basic": True}
query = {
"field": ["transaction", "count()", "total.count", "equation|count()/total.count"],
"query": "",
"orderby": "equation|count()/total.count",
"statsPeriod": "24h",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
assert data[0]["equation|count()/total.count"] == 0.25
assert data[1]["equation|count()/total.count"] == 0.75
def test_total_count_filter(self) -> None:
project1 = self.create_project()
for i in range(3):
self.store_event(data=self.load_data(platform="javascript"), project_id=project1.id)
self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"tags": {"total.count": ">45"},
},
project_id=project1.id,
)
features = {"organizations:discover-basic": True}
query = {
"field": ["transaction", "count()", "total.count"],
"query": "total.count:>45",
"orderby": "count()",
"statsPeriod": "24h",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["total.count"] == 1
def test_total_sum_transaction_duration_equation(self) -> None:
for i in range(3):
data = self.load_data(
timestamp=self.eleven_mins_ago,
duration=timedelta(seconds=5),
)
data["transaction"] = "/endpoint/1"
self.store_event(data, project_id=self.project.id)
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=5),
)
data["transaction"] = "/endpoint/2"
self.store_event(data, project_id=self.project.id)
features = {"organizations:discover-basic": True}
query = {
"field": [
"transaction",
"sum(transaction.duration)",
"total.transaction_duration",
"equation|sum(transaction.duration)/total.transaction_duration",
],
"query": "",
"orderby": "-equation|sum(transaction.duration)/total.transaction_duration",
"statsPeriod": "24h",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 2
assert data[0]["equation|sum(transaction.duration)/total.transaction_duration"] == 0.75
assert data[1]["equation|sum(transaction.duration)/total.transaction_duration"] == 0.25
def test_device_class(self) -> None:
project1 = self.create_project()
for i in range(3):
self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"tags": {"device.class": f"{i + 1}"},
},
project_id=project1.id,
)
features = {"organizations:discover-basic": True}
query = {
"field": ["device.class"],
"statsPeriod": "24h",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 3
result = (*map(lambda columns: columns["device.class"], data),)
assert "low" in result
assert "medium" in result
assert "high" in result
def test_device_class_filter_low(self) -> None:
project1 = self.create_project()
for i in range(3):
self.store_event(data=self.load_data(platform="javascript"), project_id=project1.id)
self.store_event(
data={
"event_id": "a" * 32,
"transaction": "/example",
"message": "how to make fast",
"timestamp": self.ten_mins_ago_iso,
"tags": {"device.class": "1"},
},
project_id=project1.id,
)
features = {"organizations:discover-basic": True}
query = {
"field": ["device.class", "count()"],
"query": "device.class:low",
"orderby": "count()",
"statsPeriod": "24h",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
data = response.data["data"]
assert len(data) == 1
assert data[0]["count()"] == 1
def test_group_id_as_custom_tag(self) -> None:
project1 = self.create_project()
self.store_event(
data={
"event_id": "a" * 32,
"message": "poof",
"timestamp": self.ten_mins_ago_iso,
"user": {"email": self.user.email},
"tags": {"group_id": "this should just get returned"},
},
project_id=project1.id,
)
query = {
"field": ["group_id"],
"query": "",
"orderby": "group_id",
"statsPeriod": "24h",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert response.data["data"][0]["group_id"] == "this should just get returned"
@pytest.mark.skip(reason="flaky: #96444")
def test_floored_epm(self) -> None:
for _ in range(5):
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=5),
)
data["transaction"] = "/aggregates/1"
event1 = self.store_event(data, project_id=self.project.id)
query = {
"field": ["transaction", "floored_epm()", "epm()"],
"query": "event.type:transaction",
"orderby": ["transaction"],
"start": self.eleven_mins_ago_iso,
"end": self.nine_mins_ago,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
data = response.data["data"]
assert data[0]["transaction"] == event1.transaction
assert data[0]["floored_epm()"] == 1
assert data[0]["epm()"] == 2.5
def test_floored_epm_more_events(self) -> None:
for _ in range(25):
data = self.load_data(
timestamp=self.ten_mins_ago,
duration=timedelta(seconds=5),
)
data["transaction"] = "/aggregates/1"
event1 = self.store_event(data, project_id=self.project.id)
query = {
"field": ["transaction", "floored_epm()", "epm()"],
"query": "event.type:transaction",
"orderby": ["transaction"],
"start": self.eleven_mins_ago_iso,
"end": self.nine_mins_ago,
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
data = response.data["data"]
assert data[0]["transaction"] == event1.transaction
assert data[0]["epm()"] == 12.5
assert data[0]["floored_epm()"] == 10
def test_saves_discover_saved_query_split_flag(self) -> None:
self.store_event(self.transaction_data, project_id=self.project.id)
query = {"fields": ["message"], "query": "", "limit": 10}
model = DiscoverSavedQuery.objects.create(
organization=self.organization,
created_by_id=self.user.id,
name="query name",
query=query,
version=2,
date_created=before_now(minutes=10),
date_updated=before_now(minutes=10),
)
assert model.dataset == DiscoverSavedQueryTypes.DISCOVER
assert model.dataset_source == DatasetSourcesTypes.UNKNOWN.value
def test_saves_discover_saved_query_split_transaction(self) -> None:
self.store_event(self.transaction_data, project_id=self.project.id)
query = {"fields": ["message"], "query": "", "limit": 10}
model = DiscoverSavedQuery.objects.create(
organization=self.organization,
created_by_id=self.user.id,
name="query name",
query=query,
version=2,
date_created=before_now(minutes=10),
date_updated=before_now(minutes=10),
)
assert model.dataset == DiscoverSavedQueryTypes.DISCOVER
features = {
"organizations:discover-basic": True,
}
query = {
"field": ["project", "user"],
"query": "has:user event.type:transaction",
"statsPeriod": "14d",
"discoverSavedQueryId": model.id,
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["meta"]["discoverSplitDecision"] == "transaction-like"
model = DiscoverSavedQuery.objects.get(id=model.id)
assert model.dataset == DiscoverSavedQueryTypes.TRANSACTION_LIKE
assert model.dataset_source == DatasetSourcesTypes.INFERRED.value
def test_saves_discover_saved_query_split_error(self) -> None:
self.store_event(self.transaction_data, project_id=self.project.id)
data = self.load_data(platform="javascript")
data["timestamp"] = self.ten_mins_ago_iso
self.store_event(data=data, project_id=self.project.id)
query = {"fields": ["message"], "query": "", "limit": 10}
model = DiscoverSavedQuery.objects.create(
organization=self.organization,
created_by_id=self.user.id,
name="query name",
query=query,
version=2,
date_created=before_now(minutes=10),
date_updated=before_now(minutes=10),
)
assert model.dataset == DiscoverSavedQueryTypes.DISCOVER
features = {
"organizations:discover-basic": True,
}
query = {
"field": ["project", "user"],
"query": "has:user event.type:error",
"statsPeriod": "14d",
"discoverSavedQueryId": model.id,
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["meta"]["discoverSplitDecision"] == "error-events"
model = DiscoverSavedQuery.objects.get(id=model.id)
assert model.dataset == DiscoverSavedQueryTypes.ERROR_EVENTS
def test_saves_discover_saved_query_ambiguous_as_error(self) -> None:
self.store_event(self.transaction_data, project_id=self.project.id)
data = self.load_data(platform="javascript")
data["timestamp"] = self.ten_mins_ago_iso
self.store_event(data=data, project_id=self.project.id)
query = {"fields": ["message"], "query": "", "limit": 10}
model = DiscoverSavedQuery.objects.create(
organization=self.organization,
created_by_id=self.user.id,
name="query name",
query=query,
version=2,
date_created=before_now(minutes=10),
date_updated=before_now(minutes=10),
)
assert model.dataset == DiscoverSavedQueryTypes.DISCOVER
features = {
"organizations:discover-basic": True,
}
query = {
"field": ["transaction"],
"query": "",
"statsPeriod": "14d",
"discoverSavedQueryId": model.id,
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["meta"]["discoverSplitDecision"] == "error-events"
model = DiscoverSavedQuery.objects.get(id=model.id)
assert model.dataset == DiscoverSavedQueryTypes.ERROR_EVENTS
def test_applies_inferred_dataset_by_columns(self) -> None:
self.store_event(self.transaction_data, project_id=self.project.id)
data = self.load_data(platform="javascript")
data["timestamp"] = self.ten_mins_ago_iso
self.store_event(data=data, project_id=self.project.id)
query = {"fields": ["message"], "query": "", "limit": 10}
model = DiscoverSavedQuery.objects.create(
organization=self.organization,
created_by_id=self.user.id,
name="query name",
query=query,
version=2,
date_created=before_now(minutes=10),
date_updated=before_now(minutes=10),
)
assert model.dataset == DiscoverSavedQueryTypes.DISCOVER
features = {
"organizations:discover-basic": True,
}
query = {
"field": ["transaction.status"],
"query": "",
"statsPeriod": "14d",
"discoverSavedQueryId": model.id,
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["meta"]["discoverSplitDecision"] == "transaction-like"
model = DiscoverSavedQuery.objects.get(id=model.id)
assert model.dataset == DiscoverSavedQueryTypes.TRANSACTION_LIKE
def test_issues_with_transaction_dataset(self) -> None:
self.store_event(self.transaction_data, project_id=self.project.id)
features = {"organizations:discover-basic": True}
query = {
"field": ["issue", "count()"],
"query": "",
"statsPeriod": "14d",
"dataset": "transactions",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
assert response.data["data"][0]["issue"] == "unknown"
assert response.data["data"][0]["count()"] == 1
def test_metrics_enhanced_defaults_to_transactions_with_feature_flag(self) -> None:
# Store an error
self.store_event(
data={
"event_id": "a" * 32,
"message": "poof",
"timestamp": self.ten_mins_ago_iso,
"user": {"email": self.user.email},
"tags": {"notMetrics": "this makes it not metrics"},
},
project_id=self.project.id,
)
# Store a transaction
self.store_event(
{**self.transaction_data, "tags": {"notMetrics": "this makes it not metrics"}},
project_id=self.project.id,
)
features = {
"organizations:discover-basic": True,
}
query = {
"field": ["count()"],
"query": 'notMetrics:"this makes it not metrics"',
"statsPeriod": "14d",
"dataset": "metricsEnhanced",
}
response = self.do_request(query, features=features)
assert response.status_code == 200, response.content
assert len(response.data["data"]) == 1
# count() is 1 because it falls back to transactions
assert response.data["data"][0]["count()"] == 1
def test_profiled_transaction_condition(self) -> None:
no_profile = load_data("transaction", timestamp=self.ten_mins_ago)
self.store_event(no_profile, project_id=self.project.id)
profile_id = uuid.uuid4().hex
transaction_profile = load_data("transaction", timestamp=self.ten_mins_ago)
transaction_profile.setdefault("contexts", {}).setdefault("profile", {})[
"profile_id"
] = profile_id
transaction_profile["event_id"] = uuid.uuid4().hex
self.store_event(transaction_profile, project_id=self.project.id)
profiler_id = uuid.uuid4().hex
continuous_profile = load_data("transaction", timestamp=self.ten_mins_ago)
continuous_profile.setdefault("contexts", {}).setdefault("profile", {})[
"profiler_id"
] = profiler_id
continuous_profile.setdefault("contexts", {}).setdefault("trace", {}).setdefault(
"data", {}
)["thread.id"] = "12345"
continuous_profile["event_id"] = uuid.uuid4().hex
self.store_event(continuous_profile, project_id=self.project.id)
query = {
"field": ["id", "profile.id", "profiler.id"],
"query": "has:profile.id OR (has:profiler.id has:thread.id)",
"dataset": "discover",
"orderby": "id",
}
response = self.do_request(query)
assert response.status_code == 200, response.content
assert response.data["data"] == sorted(
[
{
"id": transaction_profile["event_id"],
"profile.id": profile_id,
"profiler.id": None,
"project.name": self.project.slug,
},
{
"id": continuous_profile["event_id"],
"profile.id": None,
"profiler.id": profiler_id,
"project.name": self.project.slug,
},
],
key=lambda row: row["id"],
)
def test_debug_param(self) -> None:
self.user = self.create_user("user@example.com", is_superuser=False)
query = {
"field": ["spans.http"],
"project": [self.project.id],
"query": "event.type:transaction",
"dataset": "discover",
"debug": True,
}
response = self.do_request(
query,
{
"organizations:discover-basic": True,
},
)
assert response.status_code == 200, response.content
# Debug should be ignored without superuser
assert "query" not in response.data["meta"]
self.user = self.create_user("superuser@example.com", is_superuser=True)
self.create_team(organization=self.organization, members=[self.user])
response = self.do_request(
query,
{
"organizations:discover-basic": True,
},
)
assert response.status_code == 200, response.content
assert "debug_info" in response.data["meta"]
# We should get the snql query back in the query key
assert "MATCH" in response.data["meta"]["debug_info"]["query"]
@mock.patch("sentry.utils.snuba_rpc.table_rpc")
def test_debug_param_with_error(self, mock_query) -> None:
mock_query.side_effect = SnubaRPCError("test")
self.user = self.create_user("superuser@example.com", is_superuser=True)
self.create_team(organization=self.organization, members=[self.user])
response = self.do_request(
{
"field": ["spans.http"],
"project": [self.project.id],
"query": "event.type:transaction",
"dataset": "spans",
"debug": True,
},
{
"organizations:discover-basic": True,
},
)
assert response.status_code == 500, response.content
assert "debug_info" in response.data["meta"]
# We should get the snql query back in the query key
assert "virtualColumnContexts" in response.data["meta"]["debug_info"]["query"]
# Need to reset the mock, otherwise previous query is still attached
mock_query.side_effect = SnubaRPCError("test")
response = self.do_request(
{
"field": ["spans.http"],
"project": [self.project.id],
"query": "event.type:transaction",
"dataset": "spans",
},
{
"organizations:discover-basic": True,
},
)
assert response.status_code == 500, response.content
assert "meta" not in response.data
assert "debug_info" not in response.data
| OrganizationEventsEndpointTest |
python | vyperlang__vyper | vyper/ast/nodes.py | {
"start": 29188,
"end": 29522
} | class ____(ExprNode):
__slots__ = ("elements",)
_translated_fields = {"elts": "elements"}
@property
def is_literal_value(self):
return all(e.is_literal_value for e in self.elements)
def validate(self):
if not self.elements:
raise InvalidLiteral("Cannot have an empty tuple", self)
| Tuple |
python | PrefectHQ__prefect | tests/workers/test_base_worker.py | {
"start": 69431,
"end": 75461
} | class ____:
async def test_worker_heartbeat_sends_integrations(
self, work_pool, hosted_api_server
):
async with WorkerTestImpl(work_pool_name=work_pool.name) as worker:
await worker.start(run_once=True)
with (
mock.patch(
"prefect.workers.base.load_prefect_collections"
) as mock_load_prefect_collections,
mock.patch(
"prefect.client.orchestration._work_pools.client.WorkPoolAsyncClient.send_worker_heartbeat",
) as mock_send_worker_heartbeat_post,
mock.patch("prefect.workers.base.distributions") as mock_distributions,
):
mock_load_prefect_collections.return_value = {
"prefect_aws": "1.0.0",
}
mock_distributions.return_value = [
mock.MagicMock(
metadata={"Name": "prefect-aws"},
version="1.0.0",
)
]
async with get_client() as client:
worker._client = client
worker._client.server_type = ServerType.CLOUD
await worker.sync_with_backend()
mock_send_worker_heartbeat_post.assert_called_once_with(
work_pool_name=work_pool.name,
worker_name=worker.name,
heartbeat_interval_seconds=30.0,
get_worker_id=True,
worker_metadata=WorkerMetadata(
integrations=[Integration(name="prefect-aws", version="1.0.0")]
),
)
assert worker._worker_metadata_sent
async def test_custom_worker_can_send_arbitrary_metadata(
self, work_pool, hosted_api_server
):
class CustomWorker(BaseWorker):
type: str = "test-custom-metadata"
job_configuration: Type[BaseJobConfiguration] = BaseJobConfiguration
async def run(self):
pass
async def _worker_metadata(self) -> WorkerMetadata:
return WorkerMetadata(
**{
"integrations": [{"name": "prefect-aws", "version": "1.0.0"}],
"custom_field": "heya",
}
)
async with CustomWorker(work_pool_name=work_pool.name) as worker:
await worker.start(run_once=True)
with (
mock.patch(
"prefect.workers.base.load_prefect_collections"
) as mock_load_prefect_collections,
mock.patch(
"prefect.client.orchestration._work_pools.client.WorkPoolAsyncClient.send_worker_heartbeat",
) as mock_send_worker_heartbeat_post,
mock.patch("prefect.workers.base.distributions") as mock_distributions,
):
mock_load_prefect_collections.return_value = {
"prefect_aws": "1.0.0",
}
mock_distributions.return_value = [
mock.MagicMock(
metadata={"Name": "prefect-aws"},
version="1.0.0",
)
]
async with get_client() as client:
worker._client = client
worker._client.server_type = ServerType.CLOUD
await worker.sync_with_backend()
mock_send_worker_heartbeat_post.assert_called_once_with(
work_pool_name=work_pool.name,
worker_name=worker.name,
heartbeat_interval_seconds=30.0,
get_worker_id=True,
worker_metadata=WorkerMetadata(
integrations=[Integration(name="prefect-aws", version="1.0.0")],
custom_field="heya",
),
)
assert worker._worker_metadata_sent
async def test_worker_gives_labels_to_flow_runs_when_using_cloud_api(
prefect_client: PrefectClient,
worker_deployment_wq1: Deployment,
work_pool: WorkPool,
):
def create_run_with_deployment(state: State):
return prefect_client.create_flow_run_from_deployment(
worker_deployment_wq1.id, state=state
)
flow_run = await create_run_with_deployment(
Scheduled(scheduled_time=now_fn("UTC") - timedelta(days=1))
)
async with WorkerTestImpl(work_pool_name=work_pool.name) as worker:
assert worker._client is not None
worker._client.server_type = ServerType.CLOUD
worker._work_pool = work_pool
worker.run = AsyncMock()
await worker.get_and_submit_flow_runs()
flow_run = await prefect_client.read_flow_run(flow_run.id)
expected_labels = {
"prefect.worker.name": worker.name,
"prefect.worker.type": worker.type,
"prefect.work-pool.name": work_pool.name,
"prefect.work-pool.id": str(work_pool.id),
}
for key, value in expected_labels.items():
assert flow_run.labels[key] == value
async def test_worker_removes_flow_run_from_submitting_when_not_ready(
prefect_client: PrefectClient,
worker_deployment_wq1: Deployment,
work_pool: WorkPool,
):
"""
Regression test for https://github.com/PrefectHQ/prefect/issues/16027
"""
flow_run = await prefect_client.create_flow_run_from_deployment(
worker_deployment_wq1.id, state=Pending()
)
async with WorkerTestImpl(work_pool_name=work_pool.name) as worker:
# Mock _propose_pending_state to return False
worker._propose_pending_state = AsyncMock(return_value=False)
await worker.get_and_submit_flow_runs()
# Verify the flow run was removed from _submitting_flow_run_ids
assert flow_run.id not in worker._submitting_flow_run_ids
| TestBaseWorkerHeartbeat |
python | getsentry__sentry | src/sentry/release_health/base.py | {
"start": 2285,
"end": 2471
} | class ____(TypedDict):
by: GroupKeyDict
series: dict[SessionsQueryFunction, list[SessionsQueryValue]]
totals: dict[SessionsQueryFunction, SessionsQueryValue]
| SessionsQueryGroup |
python | airbytehq__airbyte | airbyte-ci/connectors/metadata_service/orchestrator/orchestrator/assets/registry_entry.py | {
"start": 1796,
"end": 2210
} | class ____(str, Enum, metaclass=CaseInsensitveKeys):
SOURCE = "sourceDefinitionId"
DESTINATION = "destinationDefinitionId"
PolymorphicRegistryEntry = Union[ConnectorRegistrySourceDefinition, ConnectorRegistryDestinationDefinition]
TaggedRegistryEntry = Tuple[ConnectorTypes, PolymorphicRegistryEntry]
metadata_partitions_def = DynamicPartitionsDefinition(name="metadata")
# ERRORS
| ConnectorTypePrimaryKey |
python | getsentry__sentry | src/sentry/api/endpoints/debug_files.py | {
"start": 15776,
"end": 20955
} | class ____(ProjectEndpoint):
owner = ApiOwner.OWNERS_INGEST
publish_status = {
"POST": ApiPublishStatus.PRIVATE,
}
permission_classes = (ProjectReleasePermission,)
# Legacy endpoint, kept for backwards compatibility
def post(self, request: Request, project: Project) -> Response:
return Response({"associatedDsymFiles": []})
def get_file_info(files, checksum):
"""
Extracts file information from files given a checksum.
"""
file = files.get(checksum)
if file is None:
return None
name = file.get("name")
debug_id = file.get("debug_id")
chunks = file.get("chunks", [])
return name, debug_id, chunks
def batch_assemble(project, files):
"""
Performs assembling in a batch fashion, issuing queries that span multiple files.
"""
# We build a set of all the checksums that still need checks.
checksums_to_check = {checksum for checksum in files.keys()}
file_response = {}
# 1. Exclude all files that have already an assemble status.
checksums_with_status = set()
for checksum in checksums_to_check:
# First, check the cached assemble status. During assembling, a
# `ProjectDebugFile` will be created, and we need to prevent a race
# condition.
state, detail = get_assemble_status(AssembleTask.DIF, project.id, checksum)
if state == ChunkFileState.OK:
file_response[checksum] = {
"state": state,
"detail": None,
"missingChunks": [],
"dif": detail,
}
checksums_with_status.add(checksum)
elif state is not None:
file_response[checksum] = {"state": state, "detail": detail, "missingChunks": []}
checksums_with_status.add(checksum)
checksums_to_check -= checksums_with_status
# 2. Check if this project already owns the `ProjectDebugFile` for each file.
debug_files = ProjectDebugFile.objects.filter(
project_id=project.id,
checksum__in=checksums_to_check,
).select_related("file")
checksums_with_debug_files = set()
for debug_file in debug_files:
file_response[debug_file.checksum] = {
"state": ChunkFileState.OK,
"detail": None,
"missingChunks": [],
"dif": serialize(debug_file),
}
checksums_with_debug_files.add(debug_file.checksum)
checksums_to_check -= checksums_with_debug_files
# 3. Compute all the chunks that have to be checked for existence.
chunks_to_check = {}
checksums_without_chunks = set()
for checksum in checksums_to_check:
file_info = get_file_info(files, checksum)
name, debug_id, chunks = file_info or (None, None, None)
# If we don't have any chunks, this is likely a poll request
# checking for file status, so return NOT_FOUND.
if not chunks:
file_response[checksum] = {"state": ChunkFileState.NOT_FOUND, "missingChunks": []}
checksums_without_chunks.add(checksum)
continue
# Map each chunk back to its source file checksum.
for chunk in chunks:
chunks_to_check[chunk] = checksum
checksums_to_check -= checksums_without_chunks
# 4. Find missing chunks and group them per checksum.
all_missing_chunks = find_missing_chunks(project.organization.id, set(chunks_to_check.keys()))
missing_chunks_per_checksum: dict[str, set[str]] = {}
for chunk in all_missing_chunks:
# We access the chunk via `[]` since the chunk must be there since `all_missing_chunks` must be a subset of
# `chunks_to_check.keys()`.
missing_chunks_per_checksum.setdefault(chunks_to_check[chunk], set()).add(chunk)
# 5. Report missing chunks per checksum.
checksums_with_missing_chunks = set()
for checksum, missing_chunks in missing_chunks_per_checksum.items():
file_response[checksum] = {
"state": ChunkFileState.NOT_FOUND,
"missingChunks": list(missing_chunks),
}
checksums_with_missing_chunks.add(checksum)
checksums_to_check -= checksums_with_missing_chunks
from sentry.tasks.assemble import assemble_dif
# 6. Kickstart async assembling for all remaining chunks that have passed all checks.
for checksum in checksums_to_check:
file_info = get_file_info(files, checksum)
if file_info is None:
continue
# We don't have a state yet, this means we can now start an assemble job in the background and mark
# this in the state.
set_assemble_status(AssembleTask.DIF, project.id, checksum, ChunkFileState.CREATED)
name, debug_id, chunks = file_info
assemble_dif.apply_async(
kwargs={
"project_id": project.id,
"name": name,
"debug_id": debug_id,
"checksum": checksum,
"chunks": chunks,
}
)
file_response[checksum] = {"state": ChunkFileState.CREATED, "missingChunks": []}
return file_response
@region_silo_endpoint
| AssociateDSymFilesEndpoint |
python | protocolbuffers__protobuf | python/google/protobuf/internal/unknown_fields_test.py | {
"start": 1338,
"end": 6116
} | class ____(unittest.TestCase):
def setUp(self):
self.descriptor = unittest_pb2.TestAllTypes.DESCRIPTOR
self.all_fields = unittest_pb2.TestAllTypes()
test_util.SetAllFields(self.all_fields)
self.all_fields_data = self.all_fields.SerializeToString()
self.empty_message = unittest_pb2.TestEmptyMessage()
self.empty_message.ParseFromString(self.all_fields_data)
def testSerialize(self):
data = self.empty_message.SerializeToString()
# Don't use assertEqual because we don't want to dump raw binary data to
# stdout.
self.assertTrue(data == self.all_fields_data)
def testSerializeProto3(self):
# Verify proto3 unknown fields behavior.
message = unittest_proto3_arena_pb2.TestEmptyMessage()
message.ParseFromString(self.all_fields_data)
self.assertEqual(self.all_fields_data, message.SerializeToString())
def testByteSize(self):
self.assertEqual(self.all_fields.ByteSize(), self.empty_message.ByteSize())
def testListFields(self):
# Make sure ListFields doesn't return unknown fields.
self.assertEqual(0, len(self.empty_message.ListFields()))
def testSerializeMessageSetWireFormatUnknownExtension(self):
# Create a message using the message set wire format with an unknown
# message.
raw = unittest_mset_pb2.RawMessageSet()
# Add an unknown extension.
item = raw.item.add()
item.type_id = 98218603
message1 = message_set_extensions_pb2.TestMessageSetExtension1()
message1.i = 12345
item.message = message1.SerializeToString()
serialized = raw.SerializeToString()
# Parse message using the message set wire format.
proto = message_set_extensions_pb2.TestMessageSet()
proto.MergeFromString(serialized)
unknown_field_set = unknown_fields.UnknownFieldSet(proto)
self.assertEqual(len(unknown_field_set), 1)
# Unknown field should have wire format data which can be parsed back to
# original message.
self.assertEqual(unknown_field_set[0].field_number, item.type_id)
self.assertEqual(unknown_field_set[0].wire_type,
wire_format.WIRETYPE_LENGTH_DELIMITED)
d = unknown_field_set[0].data
message_new = message_set_extensions_pb2.TestMessageSetExtension1()
message_new.ParseFromString(d)
self.assertEqual(message1, message_new)
# Verify that the unknown extension is serialized unchanged
reserialized = proto.SerializeToString()
new_raw = unittest_mset_pb2.RawMessageSet()
new_raw.MergeFromString(reserialized)
self.assertEqual(raw, new_raw)
def testEquals(self):
message = unittest_pb2.TestEmptyMessage()
message.ParseFromString(self.all_fields_data)
self.assertEqual(self.empty_message, message)
self.all_fields.ClearField('optional_string')
message.ParseFromString(self.all_fields.SerializeToString())
self.assertNotEqual(self.empty_message, message)
def testDiscardUnknownFields(self):
self.empty_message.DiscardUnknownFields()
self.assertEqual(b'', self.empty_message.SerializeToString())
# Test message field and repeated message field.
message = unittest_pb2.TestAllTypes()
other_message = unittest_pb2.TestAllTypes()
other_message.optional_string = 'discard'
message.optional_nested_message.ParseFromString(
other_message.SerializeToString())
message.repeated_nested_message.add().ParseFromString(
other_message.SerializeToString())
self.assertNotEqual(
b'', message.optional_nested_message.SerializeToString())
self.assertNotEqual(
b'', message.repeated_nested_message[0].SerializeToString())
message.DiscardUnknownFields()
self.assertEqual(b'', message.optional_nested_message.SerializeToString())
self.assertEqual(
b'', message.repeated_nested_message[0].SerializeToString())
msg = map_unittest_pb2.TestMap()
msg.map_int32_all_types[1].optional_nested_message.ParseFromString(
other_message.SerializeToString())
msg.map_string_string['1'] = 'test'
self.assertNotEqual(
b'',
msg.map_int32_all_types[1].optional_nested_message.SerializeToString())
msg.DiscardUnknownFields()
self.assertEqual(
b'',
msg.map_int32_all_types[1].optional_nested_message.SerializeToString())
def testUnknownFieldsInExtension(self):
msg = message_set_extensions_pb2.TestMessageSet()
ext3 = message_set_extensions_pb2.message_set_extension3
sub_message = unittest_pb2.TestAllTypes()
sub_message.optional_string = 'discard'
msg.Extensions[ext3].ParseFromString(sub_message.SerializeToString())
msg.DiscardUnknownFields()
self.assertNotIn(
'discard', text_format.MessageToString(msg, print_unknown_fields=True)
)
@testing_refleaks.TestCase
| UnknownFieldsTest |
python | milvus-io__pymilvus | pymilvus/client/abstract.py | {
"start": 5048,
"end": 6159
} | class ____:
def __init__(self, raw: Any):
self._raw = raw
self.name = None
self.fields = []
self.description = None
self.params = {}
self.__pack(self._raw)
def __pack(self, raw: Any):
self.name = raw.name
self.field_id = raw.fieldID
self.description = raw.description
self.fields = [FieldSchema(f) for f in raw.fields]
self.params = {}
for kv in raw.type_params:
key = kv.key if kv.key != "mmap.enabled" else "mmap_enabled"
try:
value = orjson.loads(kv.value)
except (orjson.JSONDecodeError, ValueError):
value = kv.value
self.params[key] = value
def dict(self):
result = {
"field_id": self.field_id,
"name": self.name,
"description": self.description,
"type": DataType._ARRAY_OF_STRUCT,
"fields": [f.dict() for f in self.fields],
}
if self.params:
result["params"] = self.params
return result
| StructArrayFieldSchema |
python | django__django | tests/db_functions/math/test_sqrt.py | {
"start": 269,
"end": 2346
} | class ____(TestCase):
def test_null(self):
IntegerModel.objects.create()
obj = IntegerModel.objects.annotate(null_sqrt=Sqrt("normal")).first()
self.assertIsNone(obj.null_sqrt)
def test_decimal(self):
DecimalModel.objects.create(n1=Decimal("12.9"), n2=Decimal("0.6"))
obj = DecimalModel.objects.annotate(
n1_sqrt=Sqrt("n1"), n2_sqrt=Sqrt("n2")
).first()
self.assertIsInstance(obj.n1_sqrt, Decimal)
self.assertIsInstance(obj.n2_sqrt, Decimal)
self.assertAlmostEqual(obj.n1_sqrt, Decimal(math.sqrt(obj.n1)))
self.assertAlmostEqual(obj.n2_sqrt, Decimal(math.sqrt(obj.n2)))
def test_float(self):
FloatModel.objects.create(f1=27.5, f2=0.33)
obj = FloatModel.objects.annotate(
f1_sqrt=Sqrt("f1"), f2_sqrt=Sqrt("f2")
).first()
self.assertIsInstance(obj.f1_sqrt, float)
self.assertIsInstance(obj.f2_sqrt, float)
self.assertAlmostEqual(obj.f1_sqrt, math.sqrt(obj.f1))
self.assertAlmostEqual(obj.f2_sqrt, math.sqrt(obj.f2))
def test_integer(self):
IntegerModel.objects.create(small=20, normal=15, big=1)
obj = IntegerModel.objects.annotate(
small_sqrt=Sqrt("small"),
normal_sqrt=Sqrt("normal"),
big_sqrt=Sqrt("big"),
).first()
self.assertIsInstance(obj.small_sqrt, float)
self.assertIsInstance(obj.normal_sqrt, float)
self.assertIsInstance(obj.big_sqrt, float)
self.assertAlmostEqual(obj.small_sqrt, math.sqrt(obj.small))
self.assertAlmostEqual(obj.normal_sqrt, math.sqrt(obj.normal))
self.assertAlmostEqual(obj.big_sqrt, math.sqrt(obj.big))
def test_transform(self):
with register_lookup(DecimalField, Sqrt):
DecimalModel.objects.create(n1=Decimal("6.0"), n2=Decimal("0"))
DecimalModel.objects.create(n1=Decimal("1.0"), n2=Decimal("0"))
obj = DecimalModel.objects.filter(n1__sqrt__gt=2).get()
self.assertEqual(obj.n1, Decimal("6.0"))
| SqrtTests |
python | xlwings__xlwings | xlwings/conversion/standard.py | {
"start": 6604,
"end": 7706
} | class ____(Accessor):
@staticmethod
def reader(options):
return (
BaseAccessor.reader(options)
.append_stage(ReadValueFromRangeStage(options))
.append_stage(Ensure2DStage())
.append_stage(CleanDataFromReadStage(options))
.append_stage(TransposeStage(), only_if=options.get("transpose", False))
.append_stage(AdjustDimensionsStage(options))
)
@staticmethod
def writer(options):
return (
Pipeline()
.prepend_stage(FormatStage(options))
.prepend_stage(WriteValueToRangeStage(options))
.prepend_stage(CleanDataForWriteStage(options))
.prepend_stage(TransposeStage(), only_if=options.get("transpose", False))
.prepend_stage(Ensure2DStage())
)
@classmethod
def router(cls, value, rng, options):
return accessors.get(type(value), cls)
ValueAccessor.register(
None,
"default",
Any,
Sequence,
list,
tuple,
str,
float,
int,
bool,
dt.datetime,
)
| ValueAccessor |
python | great-expectations__great_expectations | great_expectations/expectations/metrics/table_metrics/table_columns.py | {
"start": 725,
"end": 3028
} | class ____(TableMetricProvider):
metric_name = "table.columns"
@metric_value(engine=PandasExecutionEngine)
def _pandas(
cls,
execution_engine: PandasExecutionEngine,
metric_domain_kwargs: dict,
metric_value_kwargs: dict,
metrics: Dict[str, Any],
runtime_configuration: dict,
):
column_metadata = metrics["table.column_types"]
return [col["name"] for col in column_metadata]
@metric_value(engine=SqlAlchemyExecutionEngine)
def _sqlalchemy(
cls,
execution_engine: SqlAlchemyExecutionEngine,
metric_domain_kwargs: dict,
metric_value_kwargs: dict,
metrics: Dict[str, Any],
runtime_configuration: dict,
):
column_metadata = metrics["table.column_types"]
return [col["name"] for col in column_metadata]
@metric_value(engine=SparkDFExecutionEngine)
def _spark(
cls,
execution_engine: SparkDFExecutionEngine,
metric_domain_kwargs: dict,
metric_value_kwargs: dict,
metrics: Dict[str, Any],
runtime_configuration: dict,
):
column_metadata = metrics["table.column_types"]
return [col["name"] for col in column_metadata]
@classmethod
@override
def _get_evaluation_dependencies(
cls,
metric: MetricConfiguration,
configuration: Optional[ExpectationConfiguration] = None,
execution_engine: Optional[ExecutionEngine] = None,
runtime_configuration: Optional[dict] = None,
):
dependencies: dict = super()._get_evaluation_dependencies(
metric=metric,
configuration=configuration,
execution_engine=execution_engine,
runtime_configuration=runtime_configuration,
)
table_domain_kwargs: dict = {
k: v for k, v in metric.metric_domain_kwargs.items() if k != "column"
}
metric_value_kwargs = {
"include_nested": True,
}
dependencies["table.column_types"] = MetricConfiguration(
metric_name="table.column_types",
metric_domain_kwargs=table_domain_kwargs,
metric_value_kwargs=metric.metric_value_kwargs or metric_value_kwargs,
)
return dependencies
| TableColumns |
python | pydantic__pydantic | pydantic/root_model.py | {
"start": 1135,
"end": 6311
} | class ____(BaseModel, Generic[RootModelRootType], metaclass=_RootModelMetaclass):
"""!!! abstract "Usage Documentation"
[`RootModel` and Custom Root Types](../concepts/models.md#rootmodel-and-custom-root-types)
A Pydantic `BaseModel` for the root object of the model.
Attributes:
root: The root object of the model.
__pydantic_root_model__: Whether the model is a RootModel.
__pydantic_private__: Private fields in the model.
__pydantic_extra__: Extra fields in the model.
"""
__pydantic_root_model__ = True
__pydantic_private__ = None
__pydantic_extra__ = None
root: RootModelRootType
def __init_subclass__(cls, **kwargs):
extra = cls.model_config.get('extra')
if extra is not None:
raise PydanticUserError(
"`RootModel` does not support setting `model_config['extra']`", code='root-model-extra'
)
super().__init_subclass__(**kwargs)
def __init__(self, /, root: RootModelRootType = PydanticUndefined, **data) -> None: # type: ignore
__tracebackhide__ = True
if data:
if root is not PydanticUndefined:
raise ValueError(
'"RootModel.__init__" accepts either a single positional argument or arbitrary keyword arguments'
)
root = data # type: ignore
self.__pydantic_validator__.validate_python(root, self_instance=self)
__init__.__pydantic_base_init__ = True # pyright: ignore[reportFunctionMemberAccess]
@classmethod
def model_construct(cls, root: RootModelRootType, _fields_set: set[str] | None = None) -> Self: # type: ignore
"""Create a new model using the provided root object and update fields set.
Args:
root: The root object of the model.
_fields_set: The set of fields to be updated.
Returns:
The new model.
Raises:
NotImplemented: If the model is not a subclass of `RootModel`.
"""
return super().model_construct(root=root, _fields_set=_fields_set)
def __getstate__(self) -> dict[Any, Any]:
return {
'__dict__': self.__dict__,
'__pydantic_fields_set__': self.__pydantic_fields_set__,
}
def __setstate__(self, state: dict[Any, Any]) -> None:
_object_setattr(self, '__pydantic_fields_set__', state['__pydantic_fields_set__'])
_object_setattr(self, '__dict__', state['__dict__'])
def __copy__(self) -> Self:
"""Returns a shallow copy of the model."""
cls = type(self)
m = cls.__new__(cls)
_object_setattr(m, '__dict__', copy(self.__dict__))
_object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))
return m
def __deepcopy__(self, memo: dict[int, Any] | None = None) -> Self:
"""Returns a deep copy of the model."""
cls = type(self)
m = cls.__new__(cls)
_object_setattr(m, '__dict__', deepcopy(self.__dict__, memo=memo))
# This next line doesn't need a deepcopy because __pydantic_fields_set__ is a set[str],
# and attempting a deepcopy would be marginally slower.
_object_setattr(m, '__pydantic_fields_set__', copy(self.__pydantic_fields_set__))
return m
if TYPE_CHECKING:
def model_dump( # type: ignore
self,
*,
mode: Literal['json', 'python'] | str = 'python',
include: Any = None,
exclude: Any = None,
context: dict[str, Any] | None = None,
by_alias: bool | None = None,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
exclude_computed_fields: bool = False,
round_trip: bool = False,
warnings: bool | Literal['none', 'warn', 'error'] = True,
serialize_as_any: bool = False,
) -> Any:
"""This method is included just to get a more accurate return type for type checkers.
It is included in this `if TYPE_CHECKING:` block since no override is actually necessary.
See the documentation of `BaseModel.model_dump` for more details about the arguments.
Generally, this method will have a return type of `RootModelRootType`, assuming that `RootModelRootType` is
not a `BaseModel` subclass. If `RootModelRootType` is a `BaseModel` subclass, then the return
type will likely be `dict[str, Any]`, as `model_dump` calls are recursive. The return type could
even be something different, in the case of a custom serializer.
Thus, `Any` is used here to catch all of these cases.
"""
...
def __eq__(self, other: Any) -> bool:
if not isinstance(other, RootModel):
return NotImplemented
return self.__pydantic_fields__['root'].annotation == other.__pydantic_fields__[
'root'
].annotation and super().__eq__(other)
def __repr_args__(self) -> _repr.ReprArgs:
yield 'root', self.root
| RootModel |
python | Lightning-AI__lightning | tests/tests_pytorch/callbacks/test_callbacks.py | {
"start": 3872,
"end": 6067
} | class ____(Callback):
def __init__(self, state):
self.state = state
@property
def state_key(self):
return type(self)
def state_dict(self):
return {"state": self.state}
def load_state_dict(self, state_dict) -> None:
self.state = state_dict["state"]
@patch("lightning.pytorch.trainer.connectors.callback_connector._RICH_AVAILABLE", False)
def test_resume_callback_state_saved_by_type_stateful(tmp_path):
"""Test that a legacy checkpoint that didn't use a state key before can still be loaded, using
state_dict/load_state_dict."""
model = BoringModel()
callback = OldStatefulCallback(state=111)
trainer = Trainer(default_root_dir=tmp_path, max_steps=1, callbacks=[callback])
trainer.fit(model)
ckpt_path = Path(trainer.checkpoint_callback.best_model_path)
assert ckpt_path.exists()
callback = OldStatefulCallback(state=222)
trainer = Trainer(default_root_dir=tmp_path, max_steps=2, callbacks=[callback])
weights_only = False if _TORCH_GREATER_EQUAL_2_6 else None
trainer.fit(model, ckpt_path=ckpt_path, weights_only=weights_only)
assert callback.state == 111
def test_resume_incomplete_callbacks_list_warning(tmp_path):
model = BoringModel()
callback0 = ModelCheckpoint(monitor="epoch")
callback1 = ModelCheckpoint(monitor="global_step")
trainer = Trainer(
default_root_dir=tmp_path,
max_steps=1,
callbacks=[callback0, callback1],
)
trainer.fit(model)
ckpt_path = trainer.checkpoint_callback.best_model_path
trainer = Trainer(
default_root_dir=tmp_path,
max_steps=1,
callbacks=[callback1], # one callback is missing!
)
with pytest.warns(UserWarning, match=escape(f"Please add the following callbacks: [{repr(callback0.state_key)}]")):
trainer.fit(model, ckpt_path=ckpt_path)
trainer = Trainer(
default_root_dir=tmp_path,
max_steps=1,
callbacks=[callback1, callback0], # all callbacks here, order switched
)
with no_warning_call(UserWarning, match="Please add the following callbacks:"):
trainer.fit(model, ckpt_path=ckpt_path)
| OldStatefulCallback |
python | huggingface__transformers | src/transformers/models/mobilevit/modeling_mobilevit.py | {
"start": 30310,
"end": 31281
} | class ____(nn.Module):
"""
DeepLabv3 architecture: https://huggingface.co/papers/1706.05587
"""
def __init__(self, config: MobileViTConfig) -> None:
super().__init__()
self.aspp = MobileViTASPP(config)
self.dropout = nn.Dropout2d(config.classifier_dropout_prob)
self.classifier = MobileViTConvLayer(
config,
in_channels=config.aspp_out_channels,
out_channels=config.num_labels,
kernel_size=1,
use_normalization=False,
use_activation=False,
bias=True,
)
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
features = self.aspp(hidden_states[-1])
features = self.dropout(features)
features = self.classifier(features)
return features
@auto_docstring(
custom_intro="""
MobileViT model with a semantic segmentation head on top, e.g. for Pascal VOC.
"""
)
| MobileViTDeepLabV3 |
python | keras-team__keras | keras/src/metrics/confusion_metrics_test.py | {
"start": 35620,
"end": 41099
} | class ____(testing.TestCase):
def test_config(self):
s_obj = metrics.RecallAtPrecision(
0.4, num_thresholds=100, class_id=12, name="recall_at_precision_1"
)
self.assertEqual(s_obj.name, "recall_at_precision_1")
self.assertLen(s_obj.variables, 4)
self.assertEqual(s_obj.precision, 0.4)
self.assertEqual(s_obj.num_thresholds, 100)
self.assertEqual(s_obj.class_id, 12)
# Check save and restore config
s_obj2 = metrics.RecallAtPrecision.from_config(s_obj.get_config())
self.assertEqual(s_obj2.name, "recall_at_precision_1")
self.assertLen(s_obj2.variables, 4)
self.assertEqual(s_obj2.precision, 0.4)
self.assertEqual(s_obj2.num_thresholds, 100)
self.assertEqual(s_obj.class_id, 12)
def test_unweighted_all_correct(self):
s_obj = metrics.RecallAtPrecision(0.7)
inputs = np.random.randint(0, 2, size=(100, 1))
y_pred = np.array(inputs, dtype="float32")
y_true = np.array(inputs)
self.assertAlmostEqual(1, s_obj(y_true, y_pred))
def test_unweighted_high_precision(self):
s_obj = metrics.RecallAtPrecision(0.75)
pred_values = [
0.05,
0.1,
0.2,
0.3,
0.3,
0.35,
0.4,
0.45,
0.5,
0.6,
0.9,
0.95,
]
label_values = [0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1]
# precisions: [1/2, 6/11, 1/2, 5/9, 5/8, 5/7, 2/3, 3/5, 3/5, 2/3, 1/2,
# 1].
# recalls: [1, 1, 5/6, 5/6, 5/6, 5/6, 2/3, 1/2, 1/2, 1/3, 1/6,
# 1/6].
y_pred = np.array(pred_values, dtype="float32")
y_true = np.array(label_values)
# The precision 0.75 can be reached at thresholds 0.4<=t<0.45.
self.assertAlmostEqual(0.5, s_obj(y_true, y_pred))
def test_unweighted_low_precision(self):
s_obj = metrics.RecallAtPrecision(2.0 / 3)
pred_values = [
0.05,
0.1,
0.2,
0.3,
0.3,
0.35,
0.4,
0.45,
0.5,
0.6,
0.9,
0.95,
]
label_values = [0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 1]
# precisions: [1/2, 6/11, 1/2, 5/9, 5/8, 5/7, 2/3, 3/5, 3/5, 2/3, 1/2,
# 1].
# recalls: [1, 1, 5/6, 5/6, 5/6, 5/6, 2/3, 1/2, 1/2, 1/3, 1/6,
# 1/6].
y_pred = np.array(pred_values, dtype="float32")
y_true = np.array(label_values)
# The precision 5/7 can be reached at thresholds 00.3<=t<0.35.
self.assertAlmostEqual(5.0 / 6, s_obj(y_true, y_pred))
def test_unweighted_class_id(self):
s_obj = metrics.RecallAtPrecision(2.0 / 3, class_id=2)
pred_values = [
0.05,
0.1,
0.2,
0.3,
0.3,
0.35,
0.4,
0.45,
0.5,
0.6,
0.9,
0.95,
]
label_values = [0, 2, 0, 0, 0, 2, 2, 0, 2, 2, 0, 2]
# precisions: [1/2, 6/11, 1/2, 5/9, 5/8, 5/7, 2/3, 3/5, 3/5, 2/3, 1/2,
# 1].
# recalls: [1, 1, 5/6, 5/6, 5/6, 5/6, 2/3, 1/2, 1/2, 1/3, 1/6,
# 1/6].
y_pred = ops.transpose(np.array([pred_values] * 3))
y_true = ops.one_hot(np.array(label_values), num_classes=3)
# The precision 5/7 can be reached at thresholds 00.3<=t<0.35.
self.assertAlmostEqual(5.0 / 6, s_obj(y_true, y_pred))
@parameterized.parameters(["bool", "int32", "float32"])
def test_weighted(self, label_dtype):
s_obj = metrics.RecallAtPrecision(0.75)
pred_values = [0.1, 0.2, 0.3, 0.5, 0.6, 0.9, 0.9]
label_values = [0, 1, 0, 0, 0, 1, 1]
weight_values = [1, 2, 1, 2, 1, 2, 1]
y_pred = np.array(pred_values, dtype="float32")
y_true = ops.cast(label_values, dtype=label_dtype)
weights = np.array(weight_values)
result = s_obj(y_true, y_pred, sample_weight=weights)
self.assertAlmostEqual(0.6, result)
def test_unachievable_precision(self):
s_obj = metrics.RecallAtPrecision(2.0 / 3)
pred_values = [0.1, 0.2, 0.3, 0.9]
label_values = [1, 1, 0, 0]
y_pred = np.array(pred_values, dtype="float32")
y_true = np.array(label_values)
# The highest possible precision is 1/2 which is below the required
# value, expect 0 recall.
self.assertAlmostEqual(0, s_obj(y_true, y_pred))
def test_invalid_sensitivity(self):
with self.assertRaisesRegex(
ValueError, r"`precision` must be in the range \[0, 1\]."
):
metrics.RecallAtPrecision(-1)
def test_invalid_num_thresholds(self):
with self.assertRaisesRegex(
ValueError, "Argument `num_thresholds` must be an integer > 0"
):
metrics.RecallAtPrecision(0.4, num_thresholds=-1)
@pytest.mark.requires_trainable_backend
def test_end_to_end(self):
# Test for https://github.com/keras-team/keras/issues/718
model = models.Sequential(
[
layers.Input((1,)),
layers.Dense(1),
]
)
model.compile(
optimizer="rmsprop", loss="mse", metrics=[metrics.Precision()]
)
model.fit(np.ones((5, 1)), np.ones((5, 1)))
| RecallAtPrecisionTest |
python | davidhalter__jedi | jedi/inference/recursion.py | {
"start": 2791,
"end": 4932
} | class ____:
"""
Catches recursions of executions.
"""
def __init__(self, inference_state):
self._inference_state = inference_state
self._recursion_level = 0
self._parent_execution_funcs = []
self._funcdef_execution_counts = {}
self._execution_count = 0
def pop_execution(self):
self._parent_execution_funcs.pop()
self._recursion_level -= 1
def push_execution(self, execution):
funcdef = execution.tree_node
# These two will be undone in pop_execution.
self._recursion_level += 1
self._parent_execution_funcs.append(funcdef)
module_context = execution.get_root_context()
if module_context.is_builtins_module():
# We have control over builtins so we know they are not recursing
# like crazy. Therefore we just let them execute always, because
# they usually just help a lot with getting good results.
return False
if self._recursion_level > recursion_limit:
debug.warning('Recursion limit (%s) reached', recursion_limit)
return True
if self._execution_count >= total_function_execution_limit:
debug.warning('Function execution limit (%s) reached', total_function_execution_limit)
return True
self._execution_count += 1
if self._funcdef_execution_counts.setdefault(funcdef, 0) >= per_function_execution_limit:
if module_context.py__name__() == 'typing':
return False
debug.warning(
'Per function execution limit (%s) reached: %s',
per_function_execution_limit,
funcdef
)
return True
self._funcdef_execution_counts[funcdef] += 1
if self._parent_execution_funcs.count(funcdef) > per_function_recursion_limit:
debug.warning(
'Per function recursion limit (%s) reached: %s',
per_function_recursion_limit,
funcdef
)
return True
return False
| ExecutionRecursionDetector |
python | doocs__leetcode | solution/1200-1299/1219.Path with Maximum Gold/Solution.py | {
"start": 0,
"end": 519
} | class ____:
def getMaximumGold(self, grid: List[List[int]]) -> int:
def dfs(i: int, j: int) -> int:
if not (0 <= i < m and 0 <= j < n and grid[i][j]):
return 0
v = grid[i][j]
grid[i][j] = 0
ans = max(dfs(i + a, j + b) for a, b in pairwise(dirs)) + v
grid[i][j] = v
return ans
m, n = len(grid), len(grid[0])
dirs = (-1, 0, 1, 0, -1)
return max(dfs(i, j) for i in range(m) for j in range(n))
| Solution |
python | python-markdown__markdown | markdown/blockparser.py | {
"start": 2519,
"end": 5728
} | class ____:
""" Parse Markdown blocks into an `ElementTree` object.
A wrapper class that stitches the various `BlockProcessors` together,
looping through them and creating an `ElementTree` object.
"""
def __init__(self, md: Markdown):
""" Initialize the block parser.
Arguments:
md: A Markdown instance.
Attributes:
BlockParser.md (Markdown): A Markdown instance.
BlockParser.state (State): Tracks the nesting level of current location in document being parsed.
BlockParser.blockprocessors (util.Registry): A collection of
[`blockprocessors`][markdown.blockprocessors].
"""
self.blockprocessors: util.Registry[BlockProcessor] = util.Registry()
self.state = State()
self.md = md
def parseDocument(self, lines: Iterable[str]) -> etree.ElementTree:
""" Parse a Markdown document into an `ElementTree`.
Given a list of lines, an `ElementTree` object (not just a parent
`Element`) is created and the root element is passed to the parser
as the parent. The `ElementTree` object is returned.
This should only be called on an entire document, not pieces.
Arguments:
lines: A list of lines (strings).
Returns:
An element tree.
"""
# Create an `ElementTree` from the lines
self.root = etree.Element(self.md.doc_tag)
self.parseChunk(self.root, '\n'.join(lines))
return etree.ElementTree(self.root)
def parseChunk(self, parent: etree.Element, text: str) -> None:
""" Parse a chunk of Markdown text and attach to given `etree` node.
While the `text` argument is generally assumed to contain multiple
blocks which will be split on blank lines, it could contain only one
block. Generally, this method would be called by extensions when
block parsing is required.
The `parent` `etree` Element passed in is altered in place.
Nothing is returned.
Arguments:
parent: The parent element.
text: The text to parse.
"""
self.parseBlocks(parent, text.split('\n\n'))
def parseBlocks(self, parent: etree.Element, blocks: list[str]) -> None:
""" Process blocks of Markdown text and attach to given `etree` node.
Given a list of `blocks`, each `blockprocessor` is stepped through
until there are no blocks left. While an extension could potentially
call this method directly, it's generally expected to be used
internally.
This is a public method as an extension may need to add/alter
additional `BlockProcessors` which call this method to recursively
parse a nested block.
Arguments:
parent: The parent element.
blocks: The blocks of text to parse.
"""
while blocks:
for processor in self.blockprocessors:
if processor.test(parent, blocks[0]):
if processor.run(parent, blocks) is not False:
# run returns True or None
break
| BlockParser |
python | django__django | django/contrib/admin/filters.py | {
"start": 17497,
"end": 21446
} | class ____(FieldListFilter):
def __init__(self, field, request, params, model, model_admin, field_path):
self.field_generic = "%s__" % field_path
self.date_params = {
k: v[-1] for k, v in params.items() if k.startswith(self.field_generic)
}
now = timezone.now()
# When time zone support is enabled, convert "now" to the user's time
# zone so Django's definition of "Today" matches what the user expects.
if timezone.is_aware(now):
now = timezone.localtime(now)
if isinstance(field, models.DateTimeField):
today = now.replace(hour=0, minute=0, second=0, microsecond=0)
else: # field is a models.DateField
today = now.date()
tomorrow = today + datetime.timedelta(days=1)
if today.month == 12:
next_month = today.replace(year=today.year + 1, month=1, day=1)
else:
next_month = today.replace(month=today.month + 1, day=1)
next_year = today.replace(year=today.year + 1, month=1, day=1)
self.lookup_kwarg_since = "%s__gte" % field_path
self.lookup_kwarg_until = "%s__lt" % field_path
self.links = (
(_("Any date"), {}),
(
_("Today"),
{
self.lookup_kwarg_since: today,
self.lookup_kwarg_until: tomorrow,
},
),
(
_("Past 7 days"),
{
self.lookup_kwarg_since: today - datetime.timedelta(days=7),
self.lookup_kwarg_until: tomorrow,
},
),
(
_("This month"),
{
self.lookup_kwarg_since: today.replace(day=1),
self.lookup_kwarg_until: next_month,
},
),
(
_("This year"),
{
self.lookup_kwarg_since: today.replace(month=1, day=1),
self.lookup_kwarg_until: next_year,
},
),
)
if field.null:
self.lookup_kwarg_isnull = "%s__isnull" % field_path
self.links += (
(_("No date"), {self.field_generic + "isnull": True}),
(_("Has date"), {self.field_generic + "isnull": False}),
)
super().__init__(field, request, params, model, model_admin, field_path)
def expected_parameters(self):
params = [self.lookup_kwarg_since, self.lookup_kwarg_until]
if self.field.null:
params.append(self.lookup_kwarg_isnull)
return params
def get_facet_counts(self, pk_attname, filtered_qs):
return {
f"{i}__c": models.Count(pk_attname, filter=models.Q(**param_dict))
for i, (_, param_dict) in enumerate(self.links)
}
def choices(self, changelist):
add_facets = changelist.add_facets
facet_counts = self.get_facet_queryset(changelist) if add_facets else None
for i, (title, param_dict) in enumerate(self.links):
param_dict_str = {key: str(value) for key, value in param_dict.items()}
if add_facets:
count = facet_counts[f"{i}__c"]
title = f"{title} ({count})"
yield {
"selected": self.date_params == param_dict_str,
"query_string": changelist.get_query_string(
param_dict_str, [self.field_generic]
),
"display": title,
}
FieldListFilter.register(lambda f: isinstance(f, models.DateField), DateFieldListFilter)
# This should be registered last, because it's a last resort. For example,
# if a field is eligible to use the BooleanFieldListFilter, that'd be much
# more appropriate, and the AllValuesFieldListFilter won't get used for it.
| DateFieldListFilter |
python | getsentry__sentry | tests/snuba/tagstore/test_tagstore_backend.py | {
"start": 46459,
"end": 47296
} | class ____(TestCase, SnubaTestCase):
__test__ = Abstract(__module__, __qualname__)
KEY: str
def setUp(self) -> None:
super().setUp()
self.ts = SnubaTagStorage()
def run_test(self, query, expected_versions, environment=None, project=None):
if project is None:
project = self.project
assert list(
self.ts.get_tag_value_paginator(
project.id,
environment.id if environment else None,
self.KEY,
query=query,
).get_result(10)
) == [
TagValue(
key=self.KEY,
value=v,
times_seen=None,
first_seen=None,
last_seen=None,
)
for v in expected_versions
]
| BaseSemverTest |
python | modin-project__modin | modin/config/envvars.py | {
"start": 28881,
"end": 29066
} | class ____(EnvironmentVariable, type=ExactStr):
"""Allows to override default size of data (shapes)."""
varname = "MODIN_ASV_DATASIZE_CONFIG"
default = None
| AsvDataSizeConfig |
python | bokeh__bokeh | tests/unit/bokeh/core/property/test_either.py | {
"start": 1474,
"end": 3749
} | class ____:
def test_init(self) -> None:
with pytest.raises(TypeError):
bcpe.Either() # type: ignore
def test_valid(self) -> None:
prop = bcpe.Either(Interval(Int, 0, 100), Regex("^x*$"), List(Int))
assert prop.is_valid(0)
assert prop.is_valid(1)
assert prop.is_valid("")
assert prop.is_valid("xxx")
assert prop.is_valid([])
assert prop.is_valid([1, 2, 3])
assert prop.is_valid(100)
def test_invalid(self) -> None:
prop = bcpe.Either(Interval(Int, 0, 100), Regex("^x*$"), List(Int))
assert not prop.is_valid(None)
assert not prop.is_valid(False)
assert not prop.is_valid(True)
assert not prop.is_valid(0.0)
assert not prop.is_valid(1.0)
assert not prop.is_valid(1.0+1.0j)
assert not prop.is_valid(())
assert not prop.is_valid({})
assert not prop.is_valid(_TestHasProps())
assert not prop.is_valid(_TestModel())
assert not prop.is_valid(-100)
assert not prop.is_valid("yyy")
assert not prop.is_valid([1, 2, ""])
def test_has_ref(self) -> None:
prop = bcpe.Either(Int, Int)
assert not prop.has_ref
def test_str(self) -> None:
prop = bcpe.Either(Int, Int)
assert str(prop) == "Either(Int, Int)"
def test_wrap(self) -> None:
prop = bcpe.Either(List(Int), Dict(String, Int))
wrapped = prop.wrap([10, 20])
assert isinstance(wrapped, PropertyValueList)
assert prop.wrap(wrapped) is wrapped
wrapped = prop.wrap({"foo": 10})
assert isinstance(wrapped, PropertyValueDict)
assert prop.wrap(wrapped) is wrapped
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
Test___all__ = verify_all(bcpe, ALL)
| Test_Either |
python | facebook__pyre-check | client/tests/find_directories_test.py | {
"start": 2042,
"end": 6209
} | class ____(testslide.TestCase):
def assert_find_parent_directory_containing_file(
self, files: Iterable[str], base: str, target: str, expected: Optional[str]
) -> None:
depth = len(base.split("/"))
with tempfile.TemporaryDirectory() as outer_root:
with tempfile.TemporaryDirectory(dir=outer_root) as root:
root_path = Path(root).resolve()
ensure_files_exist(root_path, files)
self.assertEqual(
find_parent_directory_containing_file(
root_path / base,
target,
stop_search_after=depth,
),
(root_path / expected) if expected is not None else None,
)
def test_find_parent_directory_containing_file(self) -> None:
self.assert_find_parent_directory_containing_file(
files=[], base=".", target="a", expected=None
)
self.assert_find_parent_directory_containing_file(
files=["a"], base=".", target="a", expected="."
)
self.assert_find_parent_directory_containing_file(
files=["a"], base=".", target="b", expected=None
)
self.assert_find_parent_directory_containing_file(
files=["a", "b/c"], base="b", target="a", expected="."
)
self.assert_find_parent_directory_containing_file(
files=["a", "b/c"], base="b", target="b", expected=None
)
self.assert_find_parent_directory_containing_file(
files=["a", "b/c"], base="b", target="c", expected="b"
)
self.assert_find_parent_directory_containing_file(
files=["a", "b/c"], base="b", target="d", expected=None
)
self.assert_find_parent_directory_containing_file(
files=["a/b", "a/c/d"], base="a", target="b", expected="a"
)
self.assert_find_parent_directory_containing_file(
files=["a/b", "a/c/d"], base="a", target="c", expected=None
)
self.assert_find_parent_directory_containing_file(
files=["a/b", "a/c/d"], base="a/c", target="b", expected="a"
)
self.assert_find_parent_directory_containing_file(
files=["a/b", "a/c/d"], base="a/c", target="d", expected="a/c"
)
self.assert_find_parent_directory_containing_file(
files=["a/d", "a/b/d", "a/b/c/d"], base=".", target="d", expected=None
)
self.assert_find_parent_directory_containing_file(
files=["a/d", "a/b/d", "a/b/c/d"], base="a", target="d", expected="a"
)
self.assert_find_parent_directory_containing_file(
files=["a/d", "a/b/d", "a/b/c/d"], base="a", target="d", expected="a"
)
self.assert_find_parent_directory_containing_file(
files=["a/d", "a/b/d", "a/b/c/d"], base="a/b", target="d", expected="a/b"
)
self.assert_find_parent_directory_containing_file(
files=["a/d", "a/b/d", "a/b/c/d"],
base="a/b/c",
target="d",
expected="a/b/c",
)
self.assert_find_parent_directory_containing_file(
files=["a/d", "a/b/d", "a/b/c/d"],
base="a/b/c/d",
target="d",
expected="a/b/c",
)
self.assert_find_parent_directory_containing_file(
files=["a/d", "a/b/e", "a/b/c/f"], base="a", target="d", expected="a"
)
self.assert_find_parent_directory_containing_file(
files=["a/d", "a/b/e", "a/b/c/f"], base="a/b", target="d", expected="a"
)
self.assert_find_parent_directory_containing_file(
files=["a/d", "a/b/e", "a/b/c/f"], base="a/b/c", target="d", expected="a"
)
self.assert_find_parent_directory_containing_file(
files=["a/d", "a/b/e", "a/b/c/f"], base="a/b/e", target="d", expected="a"
)
self.assert_find_parent_directory_containing_file(
files=["a/d", "a/b/e", "a/b/c/f"], base="a/b/c/f", target="d", expected="a"
)
| FindParentDirectoryContainingFileTest |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 847252,
"end": 848000
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for ProjectV2Field."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("ProjectV2FieldEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sgqlc.types.Field(sgqlc.types.list_of("ProjectV2Field"), graphql_name="nodes")
"""A list of nodes."""
page_info = sgqlc.types.Field(sgqlc.types.non_null(PageInfo), graphql_name="pageInfo")
"""Information to aid in pagination."""
total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalCount")
"""Identifies the total count of items in the connection."""
| ProjectV2FieldConnection |
python | mwaskom__seaborn | seaborn/axisgrid.py | {
"start": 43514,
"end": 62164
} | class ____(Grid):
"""Subplot grid for plotting pairwise relationships in a dataset.
This object maps each variable in a dataset onto a column and row in a
grid of multiple axes. Different axes-level plotting functions can be
used to draw bivariate plots in the upper and lower triangles, and the
marginal distribution of each variable can be shown on the diagonal.
Several different common plots can be generated in a single line using
:func:`pairplot`. Use :class:`PairGrid` when you need more flexibility.
See the :ref:`tutorial <grid_tutorial>` for more information.
"""
def __init__(
self, data, *, hue=None, vars=None, x_vars=None, y_vars=None,
hue_order=None, palette=None, hue_kws=None, corner=False, diag_sharey=True,
height=2.5, aspect=1, layout_pad=.5, despine=True, dropna=False,
):
"""Initialize the plot figure and PairGrid object.
Parameters
----------
data : DataFrame
Tidy (long-form) dataframe where each column is a variable and
each row is an observation.
hue : string (variable name)
Variable in ``data`` to map plot aspects to different colors. This
variable will be excluded from the default x and y variables.
vars : list of variable names
Variables within ``data`` to use, otherwise use every column with
a numeric datatype.
{x, y}_vars : lists of variable names
Variables within ``data`` to use separately for the rows and
columns of the figure; i.e. to make a non-square plot.
hue_order : list of strings
Order for the levels of the hue variable in the palette
palette : dict or seaborn color palette
Set of colors for mapping the ``hue`` variable. If a dict, keys
should be values in the ``hue`` variable.
hue_kws : dictionary of param -> list of values mapping
Other keyword arguments to insert into the plotting call to let
other plot attributes vary across levels of the hue variable (e.g.
the markers in a scatterplot).
corner : bool
If True, don't add axes to the upper (off-diagonal) triangle of the
grid, making this a "corner" plot.
height : scalar
Height (in inches) of each facet.
aspect : scalar
Aspect * height gives the width (in inches) of each facet.
layout_pad : scalar
Padding between axes; passed to ``fig.tight_layout``.
despine : boolean
Remove the top and right spines from the plots.
dropna : boolean
Drop missing values from the data before plotting.
See Also
--------
pairplot : Easily drawing common uses of :class:`PairGrid`.
FacetGrid : Subplot grid for plotting conditional relationships.
Examples
--------
.. include:: ../docstrings/PairGrid.rst
"""
super().__init__()
data = handle_data_source(data)
# Sort out the variables that define the grid
numeric_cols = self._find_numeric_cols(data)
if hue in numeric_cols:
numeric_cols.remove(hue)
if vars is not None:
x_vars = list(vars)
y_vars = list(vars)
if x_vars is None:
x_vars = numeric_cols
if y_vars is None:
y_vars = numeric_cols
if np.isscalar(x_vars):
x_vars = [x_vars]
if np.isscalar(y_vars):
y_vars = [y_vars]
self.x_vars = x_vars = list(x_vars)
self.y_vars = y_vars = list(y_vars)
self.square_grid = self.x_vars == self.y_vars
if not x_vars:
raise ValueError("No variables found for grid columns.")
if not y_vars:
raise ValueError("No variables found for grid rows.")
# Create the figure and the array of subplots
figsize = len(x_vars) * height * aspect, len(y_vars) * height
with _disable_autolayout():
fig = plt.figure(figsize=figsize)
axes = fig.subplots(len(y_vars), len(x_vars),
sharex="col", sharey="row",
squeeze=False)
# Possibly remove upper axes to make a corner grid
# Note: setting up the axes is usually the most time-intensive part
# of using the PairGrid. We are foregoing the speed improvement that
# we would get by just not setting up the hidden axes so that we can
# avoid implementing fig.subplots ourselves. But worth thinking about.
self._corner = corner
if corner:
hide_indices = np.triu_indices_from(axes, 1)
for i, j in zip(*hide_indices):
axes[i, j].remove()
axes[i, j] = None
self._figure = fig
self.axes = axes
self.data = data
# Save what we are going to do with the diagonal
self.diag_sharey = diag_sharey
self.diag_vars = None
self.diag_axes = None
self._dropna = dropna
# Label the axes
self._add_axis_labels()
# Sort out the hue variable
self._hue_var = hue
if hue is None:
self.hue_names = hue_order = ["_nolegend_"]
self.hue_vals = pd.Series(["_nolegend_"] * len(data),
index=data.index)
else:
# We need hue_order and hue_names because the former is used to control
# the order of drawing and the latter is used to control the order of
# the legend. hue_names can become string-typed while hue_order must
# retain the type of the input data. This is messy but results from
# the fact that PairGrid can implement the hue-mapping logic itself
# (and was originally written exclusively that way) but now can delegate
# to the axes-level functions, while always handling legend creation.
# See GH2307
hue_names = hue_order = categorical_order(data[hue], hue_order)
if dropna:
# Filter NA from the list of unique hue names
hue_names = list(filter(pd.notnull, hue_names))
self.hue_names = hue_names
self.hue_vals = data[hue]
# Additional dict of kwarg -> list of values for mapping the hue var
self.hue_kws = hue_kws if hue_kws is not None else {}
self._orig_palette = palette
self._hue_order = hue_order
self.palette = self._get_palette(data, hue, hue_order, palette)
self._legend_data = {}
# Make the plot look nice
for ax in axes[:-1, :].flat:
if ax is None:
continue
for label in ax.get_xticklabels():
label.set_visible(False)
ax.xaxis.offsetText.set_visible(False)
ax.xaxis.label.set_visible(False)
for ax in axes[:, 1:].flat:
if ax is None:
continue
for label in ax.get_yticklabels():
label.set_visible(False)
ax.yaxis.offsetText.set_visible(False)
ax.yaxis.label.set_visible(False)
self._tight_layout_rect = [.01, .01, .99, .99]
self._tight_layout_pad = layout_pad
self._despine = despine
if despine:
utils.despine(fig=fig)
self.tight_layout(pad=layout_pad)
def map(self, func, **kwargs):
"""Plot with the same function in every subplot.
Parameters
----------
func : callable plotting function
Must take x, y arrays as positional arguments and draw onto the
"currently active" matplotlib Axes. Also needs to accept kwargs
called ``color`` and ``label``.
"""
row_indices, col_indices = np.indices(self.axes.shape)
indices = zip(row_indices.flat, col_indices.flat)
self._map_bivariate(func, indices, **kwargs)
return self
def map_lower(self, func, **kwargs):
"""Plot with a bivariate function on the lower diagonal subplots.
Parameters
----------
func : callable plotting function
Must take x, y arrays as positional arguments and draw onto the
"currently active" matplotlib Axes. Also needs to accept kwargs
called ``color`` and ``label``.
"""
indices = zip(*np.tril_indices_from(self.axes, -1))
self._map_bivariate(func, indices, **kwargs)
return self
def map_upper(self, func, **kwargs):
"""Plot with a bivariate function on the upper diagonal subplots.
Parameters
----------
func : callable plotting function
Must take x, y arrays as positional arguments and draw onto the
"currently active" matplotlib Axes. Also needs to accept kwargs
called ``color`` and ``label``.
"""
indices = zip(*np.triu_indices_from(self.axes, 1))
self._map_bivariate(func, indices, **kwargs)
return self
def map_offdiag(self, func, **kwargs):
"""Plot with a bivariate function on the off-diagonal subplots.
Parameters
----------
func : callable plotting function
Must take x, y arrays as positional arguments and draw onto the
"currently active" matplotlib Axes. Also needs to accept kwargs
called ``color`` and ``label``.
"""
if self.square_grid:
self.map_lower(func, **kwargs)
if not self._corner:
self.map_upper(func, **kwargs)
else:
indices = []
for i, (y_var) in enumerate(self.y_vars):
for j, (x_var) in enumerate(self.x_vars):
if x_var != y_var:
indices.append((i, j))
self._map_bivariate(func, indices, **kwargs)
return self
def map_diag(self, func, **kwargs):
"""Plot with a univariate function on each diagonal subplot.
Parameters
----------
func : callable plotting function
Must take an x array as a positional argument and draw onto the
"currently active" matplotlib Axes. Also needs to accept kwargs
called ``color`` and ``label``.
"""
# Add special diagonal axes for the univariate plot
if self.diag_axes is None:
diag_vars = []
diag_axes = []
for i, y_var in enumerate(self.y_vars):
for j, x_var in enumerate(self.x_vars):
if x_var == y_var:
# Make the density axes
diag_vars.append(x_var)
ax = self.axes[i, j]
diag_ax = ax.twinx()
diag_ax.set_axis_off()
diag_axes.append(diag_ax)
# Work around matplotlib bug
# https://github.com/matplotlib/matplotlib/issues/15188
if not plt.rcParams.get("ytick.left", True):
for tick in ax.yaxis.majorTicks:
tick.tick1line.set_visible(False)
# Remove main y axis from density axes in a corner plot
if self._corner:
ax.yaxis.set_visible(False)
if self._despine:
utils.despine(ax=ax, left=True)
# TODO add optional density ticks (on the right)
# when drawing a corner plot?
if self.diag_sharey and diag_axes:
for ax in diag_axes[1:]:
share_axis(diag_axes[0], ax, "y")
self.diag_vars = diag_vars
self.diag_axes = diag_axes
if "hue" not in signature(func).parameters:
return self._map_diag_iter_hue(func, **kwargs)
# Loop over diagonal variables and axes, making one plot in each
for var, ax in zip(self.diag_vars, self.diag_axes):
plot_kwargs = kwargs.copy()
if str(func.__module__).startswith("seaborn"):
plot_kwargs["ax"] = ax
else:
plt.sca(ax)
vector = self.data[var]
if self._hue_var is not None:
hue = self.data[self._hue_var]
else:
hue = None
if self._dropna:
not_na = vector.notna()
if hue is not None:
not_na &= hue.notna()
vector = vector[not_na]
if hue is not None:
hue = hue[not_na]
plot_kwargs.setdefault("hue", hue)
plot_kwargs.setdefault("hue_order", self._hue_order)
plot_kwargs.setdefault("palette", self._orig_palette)
func(x=vector, **plot_kwargs)
ax.legend_ = None
self._add_axis_labels()
return self
def _map_diag_iter_hue(self, func, **kwargs):
"""Put marginal plot on each diagonal axes, iterating over hue."""
# Plot on each of the diagonal axes
fixed_color = kwargs.pop("color", None)
for var, ax in zip(self.diag_vars, self.diag_axes):
hue_grouped = self.data[var].groupby(self.hue_vals, observed=True)
plot_kwargs = kwargs.copy()
if str(func.__module__).startswith("seaborn"):
plot_kwargs["ax"] = ax
else:
plt.sca(ax)
for k, label_k in enumerate(self._hue_order):
# Attempt to get data for this level, allowing for empty
try:
data_k = hue_grouped.get_group(label_k)
except KeyError:
data_k = pd.Series([], dtype=float)
if fixed_color is None:
color = self.palette[k]
else:
color = fixed_color
if self._dropna:
data_k = utils.remove_na(data_k)
if str(func.__module__).startswith("seaborn"):
func(x=data_k, label=label_k, color=color, **plot_kwargs)
else:
func(data_k, label=label_k, color=color, **plot_kwargs)
self._add_axis_labels()
return self
def _map_bivariate(self, func, indices, **kwargs):
"""Draw a bivariate plot on the indicated axes."""
# This is a hack to handle the fact that new distribution plots don't add
# their artists onto the axes. This is probably superior in general, but
# we'll need a better way to handle it in the axisgrid functions.
from .distributions import histplot, kdeplot
if func is histplot or func is kdeplot:
self._extract_legend_handles = True
kws = kwargs.copy() # Use copy as we insert other kwargs
for i, j in indices:
x_var = self.x_vars[j]
y_var = self.y_vars[i]
ax = self.axes[i, j]
if ax is None: # i.e. we are in corner mode
continue
self._plot_bivariate(x_var, y_var, ax, func, **kws)
self._add_axis_labels()
if "hue" in signature(func).parameters:
self.hue_names = list(self._legend_data)
def _plot_bivariate(self, x_var, y_var, ax, func, **kwargs):
"""Draw a bivariate plot on the specified axes."""
if "hue" not in signature(func).parameters:
self._plot_bivariate_iter_hue(x_var, y_var, ax, func, **kwargs)
return
kwargs = kwargs.copy()
if str(func.__module__).startswith("seaborn"):
kwargs["ax"] = ax
else:
plt.sca(ax)
if x_var == y_var:
axes_vars = [x_var]
else:
axes_vars = [x_var, y_var]
if self._hue_var is not None and self._hue_var not in axes_vars:
axes_vars.append(self._hue_var)
data = self.data[axes_vars]
if self._dropna:
data = data.dropna()
x = data[x_var]
y = data[y_var]
if self._hue_var is None:
hue = None
else:
hue = data.get(self._hue_var)
if "hue" not in kwargs:
kwargs.update({
"hue": hue, "hue_order": self._hue_order, "palette": self._orig_palette,
})
func(x=x, y=y, **kwargs)
self._update_legend_data(ax)
def _plot_bivariate_iter_hue(self, x_var, y_var, ax, func, **kwargs):
"""Draw a bivariate plot while iterating over hue subsets."""
kwargs = kwargs.copy()
if str(func.__module__).startswith("seaborn"):
kwargs["ax"] = ax
else:
plt.sca(ax)
if x_var == y_var:
axes_vars = [x_var]
else:
axes_vars = [x_var, y_var]
hue_grouped = self.data.groupby(self.hue_vals, observed=True)
for k, label_k in enumerate(self._hue_order):
kws = kwargs.copy()
# Attempt to get data for this level, allowing for empty
try:
data_k = hue_grouped.get_group(label_k)
except KeyError:
data_k = pd.DataFrame(columns=axes_vars,
dtype=float)
if self._dropna:
data_k = data_k[axes_vars].dropna()
x = data_k[x_var]
y = data_k[y_var]
for kw, val_list in self.hue_kws.items():
kws[kw] = val_list[k]
kws.setdefault("color", self.palette[k])
if self._hue_var is not None:
kws["label"] = label_k
if str(func.__module__).startswith("seaborn"):
func(x=x, y=y, **kws)
else:
func(x, y, **kws)
self._update_legend_data(ax)
def _add_axis_labels(self):
"""Add labels to the left and bottom Axes."""
for ax, label in zip(self.axes[-1, :], self.x_vars):
ax.set_xlabel(label)
for ax, label in zip(self.axes[:, 0], self.y_vars):
ax.set_ylabel(label)
def _find_numeric_cols(self, data):
"""Find which variables in a DataFrame are numeric."""
numeric_cols = []
for col in data:
if variable_type(data[col]) == "numeric":
numeric_cols.append(col)
return numeric_cols
| PairGrid |
python | agronholm__apscheduler | src/apscheduler/_structures.py | {
"start": 866,
"end": 3056
} | class ____:
"""
Represents a callable and its surrounding configuration parameters.
:var str id: the unique identifier of this task
:var ~collections.abc.Callable func: the callable that is called when this task is
run
:var str job_executor: name of the job executor that will run this task
:var int | None max_running_jobs: maximum number of instances of this task that are
allowed to run concurrently
:var ~datetime.timedelta | None misfire_grace_time: maximum number of seconds the
run time of jobs created for this task are allowed to be late, compared to the
scheduled run time
:var metadata: key-value pairs for storing JSON compatible custom information
"""
id: str = attrs.field(validator=[instance_of(str), min_len(1)], on_setattr=frozen)
func: str | None = attrs.field(
validator=optional(and_(instance_of(str), matches_re(r".+:.+"))),
on_setattr=frozen,
)
job_executor: str = attrs.field(validator=instance_of(str), on_setattr=frozen)
max_running_jobs: int | None = attrs.field(
default=None,
validator=optional(and_(instance_of(int), gt(0))),
on_setattr=frozen,
)
misfire_grace_time: timedelta | None = attrs.field(
default=None,
converter=as_timedelta,
validator=optional(instance_of(timedelta)),
on_setattr=frozen,
)
metadata: MetadataType = attrs.field(validator=valid_metadata, factory=dict)
running_jobs: int = attrs.field(default=0)
def marshal(self, serializer: Serializer) -> dict[str, Any]:
return attrs.asdict(self, value_serializer=serialize)
@classmethod
def unmarshal(cls, serializer: Serializer, marshalled: dict[str, Any]) -> Task:
return cls(**marshalled)
def __hash__(self) -> int:
return hash(self.id)
def __eq__(self, other: object) -> bool:
if isinstance(other, Task):
return self.id == other.id
return NotImplemented
def __lt__(self, other: object) -> bool:
if isinstance(other, Task):
return self.id < other.id
return NotImplemented
@attrs.define(kw_only=True)
| Task |
python | great-expectations__great_expectations | tests/integration/test_utils/data_source_config/pandas_data_frame.py | {
"start": 548,
"end": 1289
} | class ____(DataSourceTestConfig):
@property
@override
def label(self) -> str:
return "pandas-data-frame"
@property
@override
def pytest_mark(self) -> pytest.MarkDecorator:
return pytest.mark.unit
@override
def create_batch_setup(
self,
request: pytest.FixtureRequest,
data: pd.DataFrame,
extra_data: Mapping[str, pd.DataFrame],
context: AbstractDataContext,
engine_manager: Optional[SessionSQLEngineManager] = None,
) -> BatchTestSetup:
assert not extra_data, "extra_data is not supported for this data source."
return PandasDataFrameBatchTestSetup(data=data, config=self, context=context)
| PandasDataFrameDatasourceTestConfig |
python | pytorch__pytorch | torch/_inductor/fx_passes/micro_pipeline_tp.py | {
"start": 6159,
"end": 12679
} | class ____:
match: Match
input_node: torch.fx.Node
reduce_scatter_node: torch.fx.Node
wait_tensor_node: torch.fx.Node
reduce_op: str
scatter_dim: int
group_name: str
def replace_with(self, new_node: torch.fx.Node) -> None:
# Replace all uses of the result node (wait_tensor) with the fused node.
self.wait_tensor_node.replace_all_uses_with(new_node)
# If the reduce-scatter result is saved for backward, save the fused node for backward instead.
self._update_save_for_backward(new_node)
def _update_save_for_backward(self, new_node: torch.fx.Node) -> None:
"""
If the output node is a user of the reduce_scatter node (indicating the reduce_scatter
result is saved for backward), this method will update the output node to use the fused node instead.
"""
output_node = None
for user in self.reduce_scatter_node.users:
if user.target == "output":
output_node = user
break
if output_node is not None:
output_node.replace_input_with(self.reduce_scatter_node, new_node)
# Assert that now the reduce scatter node has only one user (the wait_tensor) and it's not
# saved for backward anymore.
assert len(self.reduce_scatter_node.users) == 1, (
"Reduce scatter node has multiple users, this is not expected"
)
def erase(self) -> None:
for node in reversed(self.match.nodes):
if len(node.users) == 0:
node.graph.erase_node(node)
def find_reduce_scatter_patterns(graph: torch.fx.Graph):
c10d = torch.ops._c10d_functional
def reduce_scatter_template(inp: PatternExpr, users: int):
return CallFunction(
c10d.wait_tensor.default,
CallFunction(
c10d.reduce_scatter_tensor.default,
inp,
KeywordArg("reduce_op"),
Ignored(),
KeywordArg("group_name"),
_users=users,
),
)
# Matches funcol.reduce_scatter_tensor with scatter_dim == 0
zero_dim_reduce_scatter_pattern_single_user = reduce_scatter_template(
KeywordArg("input"), users=1
)
# Two users will occur when the reduce-scatter result is saved for backward
zero_dim_reduce_scatter_pattern_multi_user = reduce_scatter_template(
KeywordArg("input"), users=2
)
# Matches funcol.reduce_scatter_tensor with scatter_dim > 0
non_zero_dim_reduce_scatter_pattern_single_user = reduce_scatter_template(
CallFunction(
aten.cat.default,
ListOf(
CallFunction(
operator.getitem,
CallFunction(
aten.split.Tensor,
KeywordArg("input"),
Ignored(),
KeywordArg("scatter_dim"),
_users=MULTIPLE,
),
Ignored(),
)
),
),
users=1,
)
# Two users will occur when the reduce-scatter result is saved for backward
non_zero_dim_reduce_scatter_pattern_multi_user = reduce_scatter_template(
CallFunction(
aten.cat.default,
ListOf(
CallFunction(
operator.getitem,
CallFunction(
aten.split.Tensor,
KeywordArg("input"),
Ignored(),
KeywordArg("scatter_dim"),
_users=MULTIPLE,
),
Ignored(),
)
),
),
users=2,
)
reduce_scatters = []
for node in reversed(graph.nodes):
if node.target == c10d.wait_tensor.default:
if match := non_zero_dim_reduce_scatter_pattern_single_user.match(node):
assert isinstance(match, Match)
reduce_scatters.append(
_ReduceScatterMatch(
match=match,
input_node=match.kwargs["input"],
reduce_scatter_node=match.nodes[-2],
wait_tensor_node=node,
reduce_op=match.kwargs["reduce_op"],
scatter_dim=match.kwargs["scatter_dim"],
group_name=match.kwargs["group_name"],
)
)
elif match := zero_dim_reduce_scatter_pattern_single_user.match(node):
assert isinstance(match, Match)
reduce_scatters.append(
_ReduceScatterMatch(
match=match,
input_node=match.kwargs["input"],
reduce_scatter_node=match.nodes[0],
wait_tensor_node=node,
reduce_op=match.kwargs["reduce_op"],
scatter_dim=0,
group_name=match.kwargs["group_name"],
)
)
elif match := non_zero_dim_reduce_scatter_pattern_multi_user.match(node):
assert isinstance(match, Match)
reduce_scatters.append(
_ReduceScatterMatch(
match=match,
input_node=match.kwargs["input"],
reduce_scatter_node=match.nodes[-2],
wait_tensor_node=node,
reduce_op=match.kwargs["reduce_op"],
scatter_dim=match.kwargs["scatter_dim"],
group_name=match.kwargs["group_name"],
)
)
elif match := zero_dim_reduce_scatter_pattern_multi_user.match(node):
assert isinstance(match, Match)
reduce_scatters.append(
_ReduceScatterMatch(
match=match,
input_node=match.kwargs["input"],
reduce_scatter_node=match.nodes[0],
wait_tensor_node=node,
reduce_op=match.kwargs["reduce_op"],
scatter_dim=0,
group_name=match.kwargs["group_name"],
)
)
return list(reversed(reduce_scatters))
@dataclass
| _ReduceScatterMatch |
python | fluentpython__example-code | 20-descriptor/descriptorkinds.py | {
"start": 5579,
"end": 5798
} | class ____: # <5>
over = Overriding()
over_no_get = OverridingNoGet()
non_over = NonOverriding()
def spam(self): # <6>
print('-> Managed.spam({})'.format(display(self)))
# END DESCR_KINDS
| Managed |
python | tensorflow__tensorflow | tensorflow/tools/ci_build/linux/mkl/set-build-env.py | {
"start": 7267,
"end": 7901
} | class ____(IntelPlatform):
def __init__(self):
IntelPlatform.__init__(self, 8, 4)
def get_bazel_gcc_flags(self):
ICELAKE_ARCH_OLD = "skylake-avx512"
ICELAKE_ARCH_NEW = "icelake-server"
AVX512_FLAGS = ["avx512f", "avx512cd"]
if IntelPlatform.use_old_arch_names(self, 8, 4):
ret_val = self.BAZEL_PREFIX_ + self.ARCH_PREFIX_ + \
ICELAKE_ARCH_OLD + " "
for flag in AVX512_FLAGS:
ret_val += self.BAZEL_PREFIX_ + self.FLAG_PREFIX_ + flag + " "
return ret_val
else:
return self.BAZEL_PREFIX_ + self.ARCH_PREFIX_ + \
ICELAKE_ARCH_NEW + " "
| IcelakeServerPlatform |
python | doocs__leetcode | solution/1700-1799/1782.Count Pairs Of Nodes/Solution.py | {
"start": 0,
"end": 727
} | class ____:
def countPairs(
self, n: int, edges: List[List[int]], queries: List[int]
) -> List[int]:
cnt = [0] * n
g = defaultdict(int)
for a, b in edges:
a, b = a - 1, b - 1
a, b = min(a, b), max(a, b)
cnt[a] += 1
cnt[b] += 1
g[(a, b)] += 1
s = sorted(cnt)
ans = [0] * len(queries)
for i, t in enumerate(queries):
for j, x in enumerate(s):
k = bisect_right(s, t - x, lo=j + 1)
ans[i] += n - k
for (a, b), v in g.items():
if cnt[a] + cnt[b] > t and cnt[a] + cnt[b] - v <= t:
ans[i] -= 1
return ans
| Solution |
python | viewflow__viewflow | tests/json/test_json__nullboolean.py | {
"start": 223,
"end": 1013
} | class ____(TestCase):
def test_crud(self):
model = NullBooleanFieldModel(nullboolean_field=False)
self.assertIsInstance(
model._meta.get_field('nullboolean_field'),
models.NullBooleanField
)
self.assertEqual(model.data, {
'nullboolean_field': False
})
model.save()
model = NullBooleanFieldModel.objects.get()
self.assertEqual(model.data, {
'nullboolean_field': False
})
self.assertEqual(model.nullboolean_field, False)
def test_null_value(self):
model = NullBooleanFieldModel(nullboolean_field=None)
self.assertEqual(model.nullboolean_field, None)
self.assertEqual(model.data, {
'nullboolean_field': None
})
| Test |
python | apache__airflow | providers/elasticsearch/src/airflow/providers/elasticsearch/log/es_response.py | {
"start": 3430,
"end": 6046
} | class ____(AttributeDict):
"""
The ElasticSearchResponse class is used to manage and access the response from an Elasticsearch search.
This class can be iterated over directly to access hits in the response. Indexing the class instance
with an integer or slice will also access the hits. The class also evaluates to True
if there are any hits in the response.
The hits property returns an AttributeList of hits in the response, with each hit transformed into
an instance of the doc_class if provided.
The response parameter stores the dictionary returned by the Elasticsearch client search method.
"""
def __init__(self, search, response, doc_class=None):
super().__setattr__("_search", search)
super().__setattr__("_doc_class", doc_class)
super().__init__(response)
def __iter__(self) -> Iterator[Hit]:
"""Provide an iterator over the hits in the Elasticsearch response."""
return iter(self.hits)
def __getitem__(self, key):
"""Retrieve a specific hit or a slice of hits from the Elasticsearch response."""
if isinstance(key, (slice, int)):
return self.hits[key]
return super().__getitem__(key)
def __bool__(self):
"""Evaluate the presence of hits in the Elasticsearch response."""
return bool(self.hits)
@property
def hits(self) -> list[Hit]:
"""
This property provides access to the hits (i.e., the results) of the Elasticsearch response.
The hits are represented as an `AttributeList` of `Hit` instances, which allow for easy,
attribute-like access to the hit data.
The hits are lazily loaded, meaning they're not processed until this property is accessed.
Upon first access, the hits data from the response is processed using the `_get_result` method
of the associated `Search` instance (i.e. an instance from ElasticsearchTaskHandler class),
and the results are stored for future accesses.
Each hit also includes all the additional data present in the "hits" field of the response,
accessible as attributes of the hit.
"""
if not hasattr(self, "_hits"):
h = self._d_["hits"]
try:
hits = AttributeList(map(self._search._get_result, h["hits"]))
except AttributeError as e:
raise TypeError("Could not parse hits.", e)
super().__setattr__("_hits", hits)
for k in h:
setattr(self._hits, k, _wrap(h[k]))
return self._hits
| ElasticSearchResponse |
python | aio-libs__aiohttp | docs/code/client_middleware_cookbook.py | {
"start": 4642,
"end": 5072
} | class ____(TCPConnector):
async def _resolve_host(
self, host: str, port: int, traces: Sequence[Trace] | None = None
) -> list[ResolveResult]:
res = await super()._resolve_host(host, port, traces)
# WARNING: This is a simplified example - should also check ::1, private ranges, etc.
if any(r["host"] in {"127.0.0.1"} for r in res):
raise SSRFError()
return res
| SSRFConnector |
python | sphinx-doc__sphinx | sphinx/directives/__init__.py | {
"start": 1196,
"end": 13224
} | class ____(SphinxDirective, Generic[ObjDescT]):
"""Directive to describe a class, function or similar object.
Not used directly, but subclassed (in domain-specific directives)
to add custom behaviour.
"""
has_content = True
required_arguments = 1
optional_arguments = 0
final_argument_whitespace = True
option_spec: ClassVar[OptionSpec] = {
'no-index': directives.flag,
'no-index-entry': directives.flag,
'no-contents-entry': directives.flag,
'no-typesetting': directives.flag,
'noindex': directives.flag,
'noindexentry': directives.flag,
'nocontentsentry': directives.flag,
}
# types of doc fields that this directive handles, see sphinx.util.docfields
doc_field_types: list[Field] = []
domain: str | None = None
objtype: str # set when `run` method is called
indexnode: addnodes.index
# Warning: this might be removed in future version. Don't touch this from extensions.
_doc_field_type_map: dict[str, tuple[Field, bool]] = {}
def get_field_type_map(self) -> dict[str, tuple[Field, bool]]:
if self._doc_field_type_map == {}:
self._doc_field_type_map = {}
for field in self.doc_field_types:
for name in field.names:
self._doc_field_type_map[name] = (field, False)
if field.is_typed:
typed_field = cast('TypedField', field)
for name in typed_field.typenames:
self._doc_field_type_map[name] = (field, True)
return self._doc_field_type_map
def get_signatures(self) -> list[str]:
"""Retrieve the signatures to document from the directive arguments.
By default, signatures are given as arguments, one per line.
"""
lines = nl_escape_re.sub('', self.arguments[0]).split('\n')
if self.config.strip_signature_backslash:
# remove backslashes to support (dummy) escapes; helps Vim highlighting
return [strip_backslash_re.sub(r'\1', line.strip()) for line in lines]
else:
return [line.strip() for line in lines]
def handle_signature(self, sig: str, signode: desc_signature) -> ObjDescT:
"""Parse the signature *sig*.
The individual nodes are then appended to *signode*.
If ValueError is raised, parsing is aborted and the whole
*sig* is put into a single desc_name node.
The return value should be a value that identifies the object. It is
passed to :meth:`add_target_and_index()` unchanged, and otherwise only
used to skip duplicates.
"""
raise ValueError
def add_target_and_index(
self, name: ObjDescT, sig: str, signode: desc_signature
) -> None:
"""Add cross-reference IDs and entries to self.indexnode, if applicable.
*name* is whatever :meth:`handle_signature()` returned.
"""
pass # do nothing by default
def before_content(self) -> None:
"""Called before parsing content.
Used to set information about the current directive context
on the build environment.
"""
pass
def transform_content(self, content_node: addnodes.desc_content) -> None:
"""Can be used to manipulate the content.
Called after creating the content through nested parsing,
but before the ``object-description-transform`` event is emitted,
and before the info-fields are transformed.
"""
pass
def after_content(self) -> None:
"""Called after parsing content.
Used to reset information about the current directive context
on the build environment.
"""
pass
def _object_hierarchy_parts(self, sig_node: desc_signature) -> tuple[str, ...]:
"""Returns a tuple of strings, one entry for each part of the object's
hierarchy (e.g. ``('module', 'submodule', 'Class', 'method')``). The
returned tuple is used to properly nest children within parents in the
table of contents, and can also be used within the
:py:meth:`_toc_entry_name` method.
This method must not be used outwith table of contents generation.
"""
return ()
def _toc_entry_name(self, sig_node: desc_signature) -> str:
"""Returns the text of the table of contents entry for the object.
This function is called once, in :py:meth:`run`, to set the name for the
table of contents entry (a special attribute ``_toc_name`` is set on the
object node, later used in
``environment.collectors.toctree.TocTreeCollector.process_doc().build_toc()``
when the table of contents entries are collected).
To support table of contents entries for their objects, domains must
override this method, also respecting the configuration setting
``toc_object_entries_show_parents``. Domains must also override
:py:meth:`_object_hierarchy_parts`, with one (string) entry for each part of the
object's hierarchy. The result of this method is set on the signature
node, and can be accessed as ``sig_node['_toc_parts']`` for use within
this method. The resulting tuple is also used to properly nest children
within parents in the table of contents.
An example implementations of this method is within the python domain
(:meth:`!PyObject._toc_entry_name`). The python domain sets the
``_toc_parts`` attribute within the :py:meth:`handle_signature()`
method.
"""
return ''
def run(self) -> list[Node]:
"""Main directive entry function, called by docutils upon encountering the
directive.
This directive is meant to be quite easily subclassable, so it delegates
to several additional methods. What it does:
* find out if called as a domain-specific directive, set self.domain
* create a `desc` node to fit all description inside
* parse standard options, currently `no-index`
* create an index node if needed as self.indexnode
* parse all given signatures (as returned by self.get_signatures())
using self.handle_signature(), which should either return a name
or raise ValueError
* add index entries using self.add_target_and_index()
* parse the content and handle doc fields in it
"""
if ':' in self.name:
self.domain, _, self.objtype = self.name.partition(':')
else:
self.domain, self.objtype = '', self.name
self.indexnode = addnodes.index(entries=[])
node = addnodes.desc()
node.document = self.state.document
source, line = self.get_source_info()
# If any options were specified to the directive,
# self.state.document.current_line will at this point be set to
# None. To ensure nodes created as part of the signature have a line
# number set, set the document's line number correctly.
#
# Note that we need to subtract one from the line number since
# note_source uses 0-based line numbers.
if line is not None:
line -= 1
self.state.document.note_source(source, line)
node['domain'] = self.domain
# 'desctype' is a backwards compatible attribute
node['objtype'] = node['desctype'] = self.objtype
# Copy old option names to new ones
# xref RemovedInSphinx90Warning
# deprecate noindex, noindexentry, and nocontentsentry in Sphinx 9.0
if 'no-index' not in self.options and 'noindex' in self.options:
self.options['no-index'] = self.options['noindex']
if 'no-index-entry' not in self.options and 'noindexentry' in self.options:
self.options['no-index-entry'] = self.options['noindexentry']
if (
'no-contents-entry' not in self.options
and 'nocontentsentry' in self.options
):
self.options['no-contents-entry'] = self.options['nocontentsentry']
node['no-index'] = node['noindex'] = no_index = 'no-index' in self.options
node['no-index-entry'] = node['noindexentry'] = 'no-index-entry' in self.options
node['no-contents-entry'] = node['nocontentsentry'] = (
'no-contents-entry' in self.options
)
node['no-typesetting'] = 'no-typesetting' in self.options
if self.domain:
node['classes'].append(self.domain)
node['classes'].append(node['objtype'])
self.names: list[ObjDescT] = []
signatures = self.get_signatures()
for sig in signatures:
# add a signature node for each signature in the current unit
# and add a reference target for it
signode = addnodes.desc_signature(sig, '')
self.set_source_info(signode)
node.append(signode)
try:
# name can also be a tuple, e.g. (classname, objname);
# this is strictly domain-specific (i.e. no assumptions may
# be made in this base class)
name = self.handle_signature(sig, signode)
except ValueError:
# signature parsing failed
signode.clear()
signode += addnodes.desc_name(sig, sig)
continue # we don't want an index entry here
finally:
# Private attributes for ToC generation. Will be modified or removed
# without notice.
if self.config.toc_object_entries:
signode['_toc_parts'] = self._object_hierarchy_parts(signode)
signode['_toc_name'] = self._toc_entry_name(signode)
else:
signode['_toc_parts'] = ()
signode['_toc_name'] = ''
if name not in self.names:
self.names.append(name)
if not no_index:
# only add target and index entry if this is the first
# description of the object with this name in this desc block
self.add_target_and_index(name, sig, signode)
if self.names:
# needed for association of version{added,changed} directives
object_name: ObjDescT = self.names[0]
if isinstance(object_name, tuple):
self.env.current_document.obj_desc_name = str(object_name[0])
else:
self.env.current_document.obj_desc_name = str(object_name)
self.before_content()
content_children = self.parse_content_to_nodes(allow_section_headings=True)
content_node = addnodes.desc_content('', *content_children)
node.append(content_node)
self.transform_content(content_node)
self.env.events.emit(
'object-description-transform', self.domain, self.objtype, content_node
)
DocFieldTransformer(self).transform_all(content_node)
self.env.current_document.obj_desc_name = ''
self.after_content()
if node['no-typesetting']:
# Attempt to return the index node, and a new target node
# containing all the ids of this node and its children.
# If ``:no-index:`` is set, or there are no ids on the node
# or any of its children, then just return the index node,
# as Docutils expects a target node to have at least one id.
if node_ids := [ # type: ignore[var-annotated]
node_id
for el in node.findall(nodes.Element)
for node_id in el.get('ids', ())
]:
target_node = nodes.target(ids=node_ids)
self.set_source_info(target_node)
return [self.indexnode, target_node]
return [self.indexnode]
return [self.indexnode, node]
| ObjectDescription |
python | huggingface__transformers | src/transformers/models/mistral/modeling_mistral.py | {
"start": 9498,
"end": 11290
} | class ____(GradientCheckpointingLayer):
def __init__(self, config: MistralConfig, layer_idx: int):
super().__init__()
self.hidden_size = config.hidden_size
self.self_attn = MistralAttention(config=config, layer_idx=layer_idx)
self.mlp = MistralMLP(config)
self.input_layernorm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
self.post_attention_layernorm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
def forward(
self,
hidden_states: torch.Tensor,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
use_cache: Optional[bool] = False,
cache_position: Optional[torch.LongTensor] = None,
position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None,
**kwargs: Unpack[TransformersKwargs],
) -> torch.Tensor:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
# Self Attention
hidden_states, _ = self.self_attn(
hidden_states=hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
cache_position=cache_position,
position_embeddings=position_embeddings,
**kwargs,
)
hidden_states = residual + hidden_states
# Fully Connected
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
return hidden_states
@auto_docstring
| MistralDecoderLayer |
python | huggingface__transformers | tests/models/flex_olmo/test_modeling_flex_olmo.py | {
"start": 1283,
"end": 1915
} | class ____(CausalLMModelTest, unittest.TestCase):
test_all_params_have_gradient = False
model_tester_class = FlexOlmoModelTester
# Need to use `0.8` instead of `0.9` for `test_cpu_offload`
# This is because we are hitting edge cases with the causal_mask buffer
model_split_percents = [0.5, 0.7, 0.8]
# used in `test_torch_compile_for_training`
_torch_compile_train_cls = FlexOlmoForCausalLM if is_torch_available() else None
@unittest.skip("Dynamic control flow in MoE")
@pytest.mark.torch_compile_test
def test_torch_compile_for_training(self):
pass
@require_torch
| FlexOlmoModelTest |
python | realpython__materials | python-magic-methods/factorial.py | {
"start": 0,
"end": 242
} | class ____:
def __init__(self):
self._cache = {0: 1, 1: 1}
def __call__(self, number):
if number not in self._cache:
self._cache[number] = number * self(number - 1)
return self._cache[number]
| Factorial |
python | joke2k__faker | tests/providers/test_person.py | {
"start": 3396,
"end": 5138
} | class ____(unittest.TestCase):
"""Tests person in the ar locale"""
def setUp(self):
self.fake = Faker("ar")
Faker.seed(0)
def test_first_name(self):
# General first name
name = self.fake.first_name()
assert name
self.assertIsInstance(name, str)
assert name in ArProvider.first_names
# Females first name
name = self.fake.first_name_female()
assert name
self.assertIsInstance(name, str)
assert name in ArProvider.first_names
assert name in ArProvider.first_names_female
# Male first name
name = self.fake.first_name_male()
assert name
self.assertIsInstance(name, str)
assert name in ArProvider.first_names
assert name in ArProvider.first_names_male
def test_last_name(self):
# There's no gender-specific last name in Arabic.
assert not hasattr(ArProvider, "last_names_male")
assert not hasattr(ArProvider, "last_names_female")
# All last names apply for all genders.
assert hasattr(ArProvider, "last_names")
# General last name.
name = self.fake.last_name()
assert name
self.assertIsInstance(name, str)
assert name in ArProvider.last_names
# Females last name.
name = self.fake.last_name_female()
assert name
self.assertIsInstance(name, str)
assert name in ArProvider.last_names
assert name in ArProvider.last_names
# Male last name.
name = self.fake.last_name_male()
assert name
self.assertIsInstance(name, str)
assert name in ArProvider.last_names
assert name in ArProvider.last_names
| TestAr |
python | apache__airflow | airflow-core/tests/unit/api_fastapi/core_api/routes/public/test_assets.py | {
"start": 58405,
"end": 60001
} | class ____(TestQueuedEventEndpoint):
def test_delete_should_respond_204(self, test_client, session, create_dummy_dag):
dag, _ = create_dummy_dag()
dag_id = dag.dag_id
(asset,) = self.create_assets(session=session, num=1)
self._create_asset_dag_run_queues(dag_id, asset.id, session)
adrq = session.query(AssetDagRunQueue).all()
assert len(adrq) == 1
response = test_client.delete(
f"/dags/{dag_id}/assets/{asset.id}/queuedEvents",
)
assert response.status_code == 204
adrq = session.query(AssetDagRunQueue).all()
assert len(adrq) == 0
check_last_log(session, dag_id=dag_id, event="delete_dag_asset_queued_event", logical_date=None)
def test_should_respond_401(self, unauthenticated_test_client):
response = unauthenticated_test_client.delete("/dags/random/assets/random/queuedEvents")
assert response.status_code == 401
def test_should_respond_403(self, unauthorized_test_client):
response = unauthorized_test_client.delete("/dags/random/assets/random/queuedEvents")
assert response.status_code == 403
def test_should_respond_404(self, test_client):
dag_id = "not_exists"
asset_id = 1
response = test_client.delete(
f"/dags/{dag_id}/assets/{asset_id}/queuedEvents",
)
assert response.status_code == 404
assert (
response.json()["detail"]
== "Queued event with dag_id: `not_exists` and asset_id: `1` was not found"
)
| TestDeleteDagAssetQueuedEvent |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/models.py | {
"start": 4482,
"end": 5192
} | class ____(models.Model):
my_id = models.AutoField(primary_key=True)
if django.VERSION >= (5, 0, 0):
import math
class Pizza(models.Model):
AREA = math.pi * models.F("radius") ** 2
radius = models.IntegerField(validators=[MinValueValidator(1)])
slices = models.PositiveIntegerField(validators=[MinValueValidator(2)])
total_area = models.GeneratedField(
expression=AREA,
output_field=models.FloatField(),
db_persist=True,
)
slice_area = models.GeneratedField(
expression=AREA / models.F("slices"),
output_field=models.FloatField(),
db_persist=False,
)
| UserSpecifiedAutoId |
python | getsentry__sentry-python | sentry_sdk/integrations/spark/spark_driver.py | {
"start": 349,
"end": 3844
} | class ____(Integration):
identifier = "spark"
@staticmethod
def setup_once():
# type: () -> None
_setup_sentry_tracing()
def _set_app_properties():
# type: () -> None
"""
Set properties in driver that propagate to worker processes, allowing for workers to have access to those properties.
This allows worker integration to have access to app_name and application_id.
"""
from pyspark import SparkContext
spark_context = SparkContext._active_spark_context
if spark_context:
spark_context.setLocalProperty(
"sentry_app_name",
spark_context.appName,
)
spark_context.setLocalProperty(
"sentry_application_id",
spark_context.applicationId,
)
def _start_sentry_listener(sc):
# type: (SparkContext) -> None
"""
Start java gateway server to add custom `SparkListener`
"""
from pyspark.java_gateway import ensure_callback_server_started
gw = sc._gateway
ensure_callback_server_started(gw)
listener = SentryListener()
sc._jsc.sc().addSparkListener(listener)
def _add_event_processor(sc):
# type: (SparkContext) -> None
scope = sentry_sdk.get_isolation_scope()
@scope.add_event_processor
def process_event(event, hint):
# type: (Event, Hint) -> Optional[Event]
with capture_internal_exceptions():
if sentry_sdk.get_client().get_integration(SparkIntegration) is None:
return event
if sc._active_spark_context is None:
return event
event.setdefault("user", {}).setdefault("id", sc.sparkUser())
event.setdefault("tags", {}).setdefault(
"executor.id", sc._conf.get("spark.executor.id")
)
event["tags"].setdefault(
"spark-submit.deployMode",
sc._conf.get("spark.submit.deployMode"),
)
event["tags"].setdefault("driver.host", sc._conf.get("spark.driver.host"))
event["tags"].setdefault("driver.port", sc._conf.get("spark.driver.port"))
event["tags"].setdefault("spark_version", sc.version)
event["tags"].setdefault("app_name", sc.appName)
event["tags"].setdefault("application_id", sc.applicationId)
event["tags"].setdefault("master", sc.master)
event["tags"].setdefault("spark_home", sc.sparkHome)
event.setdefault("extra", {}).setdefault("web_url", sc.uiWebUrl)
return event
def _activate_integration(sc):
# type: (SparkContext) -> None
_start_sentry_listener(sc)
_set_app_properties()
_add_event_processor(sc)
def _patch_spark_context_init():
# type: () -> None
from pyspark import SparkContext
spark_context_init = SparkContext._do_init
@ensure_integration_enabled(SparkIntegration, spark_context_init)
def _sentry_patched_spark_context_init(self, *args, **kwargs):
# type: (SparkContext, *Any, **Any) -> Optional[Any]
rv = spark_context_init(self, *args, **kwargs)
_activate_integration(self)
return rv
SparkContext._do_init = _sentry_patched_spark_context_init
def _setup_sentry_tracing():
# type: () -> None
from pyspark import SparkContext
if SparkContext._active_spark_context is not None:
_activate_integration(SparkContext._active_spark_context)
return
_patch_spark_context_init()
| SparkIntegration |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 663645,
"end": 664383
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for GistComment."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("GistCommentEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sgqlc.types.Field(sgqlc.types.list_of("GistComment"), graphql_name="nodes")
"""A list of nodes."""
page_info = sgqlc.types.Field(sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo")
"""Information to aid in pagination."""
total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalCount")
"""Identifies the total count of items in the connection."""
| GistCommentConnection |
python | PyCQA__pylint | tests/functional/a/alternative/alternative_union_syntax_error.py | {
"start": 3651,
"end": 3758
} | class ____(metaclass=HorribleMetaclass):
pass
class_list = [WithHorrible | DefaultMetaclass]
| WithHorrible |
python | huggingface__transformers | tests/models/mpnet/test_modeling_mpnet.py | {
"start": 1234,
"end": 7547
} | class ____:
def __init__(
self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_mask=True,
use_token_type_ids=False,
use_labels=True,
vocab_size=99,
hidden_size=64,
num_hidden_layers=2,
num_attention_heads=4,
intermediate_size=64,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
max_position_embeddings=512,
type_vocab_size=16,
type_sequence_label_size=2,
initializer_range=0.02,
num_labels=3,
num_choices=4,
scope=None,
):
self.parent = parent
self.batch_size = batch_size
self.seq_length = seq_length
self.is_training = is_training
self.use_input_mask = use_input_mask
self.use_token_type_ids = use_token_type_ids
self.use_labels = use_labels
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.hidden_act = hidden_act
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.max_position_embeddings = max_position_embeddings
self.type_vocab_size = type_vocab_size
self.type_sequence_label_size = type_sequence_label_size
self.initializer_range = initializer_range
self.num_labels = num_labels
self.num_choices = num_choices
self.scope = scope
def prepare_config_and_inputs(self):
input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
input_mask = None
if self.use_input_mask:
input_mask = random_attention_mask([self.batch_size, self.seq_length])
sequence_labels = None
token_labels = None
choice_labels = None
if self.use_labels:
sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
choice_labels = ids_tensor([self.batch_size], self.num_choices)
config = self.get_config()
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def get_config(self):
return MPNetConfig(
vocab_size=self.vocab_size,
hidden_size=self.hidden_size,
num_hidden_layers=self.num_hidden_layers,
num_attention_heads=self.num_attention_heads,
intermediate_size=self.intermediate_size,
hidden_act=self.hidden_act,
hidden_dropout_prob=self.hidden_dropout_prob,
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
max_position_embeddings=self.max_position_embeddings,
initializer_range=self.initializer_range,
)
def create_and_check_mpnet_model(
self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
):
model = MPNetModel(config=config)
model.to(torch_device)
model.eval()
result = model(input_ids, input_mask)
result = model(input_ids)
self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
def create_and_check_mpnet_for_question_answering(
self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
):
model = MPNetForQuestionAnswering(config=config)
model.to(torch_device)
model.eval()
result = model(
input_ids,
attention_mask=input_mask,
start_positions=sequence_labels,
end_positions=sequence_labels,
)
self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
def create_and_check_mpnet_for_sequence_classification(
self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
):
config.num_labels = self.num_labels
model = MPNetForSequenceClassification(config)
model.to(torch_device)
model.eval()
result = model(input_ids, attention_mask=input_mask, labels=sequence_labels)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
def create_and_check_mpnet_for_multiple_choice(
self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
):
config.num_choices = self.num_choices
model = MPNetForMultipleChoice(config=config)
model.to(torch_device)
model.eval()
multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
result = model(
multiple_choice_inputs_ids,
attention_mask=multiple_choice_input_mask,
labels=choice_labels,
)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
def create_and_check_mpnet_for_token_classification(
self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
):
config.num_labels = self.num_labels
model = MPNetForTokenClassification(config=config)
model.to(torch_device)
model.eval()
result = model(input_ids, attention_mask=input_mask, labels=token_labels)
self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
def prepare_config_and_inputs_for_common(self):
config_and_inputs = self.prepare_config_and_inputs()
(config, input_ids, input_mask, sequence_labels, token_labels, choice_labels) = config_and_inputs
inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
return config, inputs_dict
@require_torch
| MPNetModelTester |
python | huggingface__transformers | tests/models/nystromformer/test_modeling_nystromformer.py | {
"start": 8958,
"end": 11554
} | class ____(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
all_model_classes = (
(
NystromformerModel,
NystromformerForMaskedLM,
NystromformerForMultipleChoice,
NystromformerForQuestionAnswering,
NystromformerForSequenceClassification,
NystromformerForTokenClassification,
)
if is_torch_available()
else ()
)
pipeline_model_mapping = (
{
"feature-extraction": NystromformerModel,
"fill-mask": NystromformerForMaskedLM,
"question-answering": NystromformerForQuestionAnswering,
"text-classification": NystromformerForSequenceClassification,
"token-classification": NystromformerForTokenClassification,
"zero-shot": NystromformerForSequenceClassification,
}
if is_torch_available()
else {}
)
def setUp(self):
self.model_tester = NystromformerModelTester(self)
self.config_tester = ConfigTester(self, config_class=NystromformerConfig, hidden_size=37)
def test_config(self):
self.config_tester.run_common_tests()
def test_model(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*config_and_inputs)
def test_for_masked_lm(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
def test_for_multiple_choice(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
def test_for_question_answering(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
def test_for_sequence_classification(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
def test_for_token_classification(self):
config_and_inputs = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
@slow
def test_model_from_pretrained(self):
model_name = "uw-madison/nystromformer-512"
model = NystromformerModel.from_pretrained(model_name)
self.assertIsNotNone(model)
@require_torch
| NystromformerModelTest |
python | google__pytype | pytype/overlays/special_builtins.py | {
"start": 19014,
"end": 19334
} | class ____(BuiltinFunction):
"""For debugging. reveal_type(x) prints the type of "x"."""
_NAME = "reveal_type"
def call(self, node, func, args, alias_map=None):
for a in args.posargs:
self.ctx.errorlog.reveal_type(self.ctx.vm.frames, node, a)
return node, self.ctx.convert.build_none(node)
| RevealType |
python | apache__airflow | airflow-core/tests/integration/cli/commands/test_celery_command.py | {
"start": 1154,
"end": 3193
} | class ____:
@classmethod
def setup_class(cls):
with conf_vars({("core", "executor"): "CeleryExecutor"}):
# The cli_parser module is loaded during test collection. Reload it here with the
# executor overridden so that we get the expected commands loaded.
reload(executor_loader)
reload(cli_parser)
cls.parser = cli_parser.get_parser()
@conf_vars({("core", "executor"): "CeleryExecutor"})
def test_serve_logs_on_worker_start(self):
with (
mock.patch("airflow.providers.celery.cli.celery_command.Process") as mock_process,
mock.patch("airflow.providers.celery.executors.celery_executor.app"),
):
args = self.parser.parse_args(["celery", "worker", "--concurrency", "1"])
with mock.patch("celery.platforms.check_privileges") as mock_privil:
mock_privil.return_value = 0
celery_command.worker(args)
mock_process.assert_called()
@conf_vars({("core", "executor"): "CeleryExecutor"})
@pytest.mark.parametrize(
("skip", "expected"),
[
(True, ["bundle_cleanup_main"]),
(False, ["serve_logs", "bundle_cleanup_main"]),
],
)
def test_skip_serve_logs_on_worker_start(self, skip, expected):
with (
mock.patch("airflow.providers.celery.cli.celery_command.Process") as mock_popen,
mock.patch("airflow.providers.celery.executors.celery_executor.app"),
):
args = ["celery", "worker", "--concurrency", "1"]
if skip:
args.append("--skip-serve-logs")
args = self.parser.parse_args(args)
with mock.patch("celery.platforms.check_privileges") as mock_privil:
mock_privil.return_value = 0
celery_command.worker(args)
targets = [x.kwargs["target"].__name__ for x in mock_popen.call_args_list]
assert targets == expected
| TestWorkerServeLogs |
python | PrefectHQ__prefect | tests/server/orchestration/api/test_deployments.py | {
"start": 45861,
"end": 51265
} | class ____:
@pytest.fixture
async def deployment_id_1(self):
return uuid4()
@pytest.fixture
async def deployment_id_2(self):
return uuid4()
@pytest.fixture
async def deployments(
self,
session,
deployment_id_1,
deployment_id_2,
flow,
flow_function,
):
await models.deployments.create_deployment(
session=session,
deployment=schemas.core.Deployment(
id=deployment_id_1,
name="My Deployment X",
flow_id=flow.id,
paused=False,
),
)
await models.deployments.create_deployment(
session=session,
deployment=schemas.core.Deployment(
id=deployment_id_2,
name="My Deployment Y",
flow_id=flow.id,
paused=True,
),
)
await session.commit()
async def test_read_deployments(self, deployments, client):
response = await client.post("/deployments/filter")
assert response.status_code == status.HTTP_200_OK
assert len(response.json()) == 2
assert response.json()[0]["status"] == "NOT_READY"
async def test_read_deployments_applies_filter(
self, deployments, deployment_id_1, deployment_id_2, flow, client
):
deployment_filter = dict(
deployments=schemas.filters.DeploymentFilter(
name=schemas.filters.DeploymentFilterName(any_=["My Deployment X"])
).model_dump(mode="json")
)
response = await client.post("/deployments/filter", json=deployment_filter)
assert response.status_code == status.HTTP_200_OK
assert {deployment["id"] for deployment in response.json()} == {
str(deployment_id_1)
}
deployment_filter = dict(
deployments=schemas.filters.DeploymentFilter(
name=schemas.filters.DeploymentFilterName(any_=["My Deployment 123"])
).model_dump(mode="json")
)
response = await client.post("/deployments/filter", json=deployment_filter)
assert response.status_code == status.HTTP_200_OK
assert len(response.json()) == 0
deployment_filter = dict(
flows=schemas.filters.FlowFilter(
name=schemas.filters.FlowFilterName(any_=[flow.name])
).model_dump(mode="json")
)
response = await client.post("/deployments/filter", json=deployment_filter)
assert response.status_code == status.HTTP_200_OK
assert {deployment["id"] for deployment in response.json()} == {
str(deployment_id_1),
str(deployment_id_2),
}
deployment_filter = dict(
deployments=schemas.filters.DeploymentFilter(
name=schemas.filters.DeploymentFilterName(any_=["My Deployment X"])
).model_dump(mode="json"),
flows=schemas.filters.FlowFilter(
name=schemas.filters.FlowFilterName(any_=["not a flow name"])
).model_dump(mode="json"),
)
response = await client.post("/deployments/filter", json=deployment_filter)
assert response.status_code == status.HTTP_200_OK
assert len(response.json()) == 0
deployment_filter = dict(
deployments=schemas.filters.DeploymentFilter(
flow_or_deployment_name=schemas.filters.DeploymentOrFlowNameFilter(
like_=flow.name
)
).model_dump(mode="json")
)
response = await client.post("/deployments/filter", json=deployment_filter)
assert response.status_code == status.HTTP_200_OK
assert {deployment["id"] for deployment in response.json()} == {
str(deployment_id_1),
str(deployment_id_2),
}
async def test_read_deployments_applies_limit(self, deployments, client):
response = await client.post("/deployments/filter", json=dict(limit=1))
assert response.status_code == status.HTTP_200_OK
assert len(response.json()) == 1
async def test_read_deployments_offset(self, deployments, client, session):
response = await client.post("/deployments/filter", json=dict(offset=1))
assert response.status_code == status.HTTP_200_OK
assert len(response.json()) == 1
# sorted by name by default
assert response.json()[0]["name"] == "My Deployment Y"
async def test_read_deployments_sort(self, deployments, client):
response = await client.post(
"/deployments/filter",
json=dict(sort=schemas.sorting.DeploymentSort.NAME_ASC),
)
assert response.status_code == status.HTTP_200_OK
assert response.json()[0]["name"] == "My Deployment X"
response_desc = await client.post(
"/deployments/filter",
json=dict(sort=schemas.sorting.DeploymentSort.NAME_DESC),
)
assert response_desc.status_code == status.HTTP_200_OK
assert response_desc.json()[0]["name"] == "My Deployment Y"
async def test_read_deployments_returns_empty_list(self, client):
response = await client.post("/deployments/filter")
assert response.status_code == status.HTTP_200_OK
assert response.json() == []
| TestReadDeployments |
python | conda__conda | conda/activate.py | {
"start": 1767,
"end": 33505
} | class ____(metaclass=abc.ABCMeta):
# Activate and deactivate have three tasks
# 1. Set and unset environment variables
# 2. Execute/source activate.d/deactivate.d scripts
# 3. Update the command prompt
#
# Shells should also use 'reactivate' following conda's install, update, and
# remove/uninstall commands.
#
# All core logic is in build_activate() or build_deactivate(), and is independent of
# shell type. Each returns a map containing the keys:
# export_vars
# unset_var
# activate_scripts
# deactivate_scripts
#
# The value of the CONDA_PROMPT_MODIFIER environment variable holds conda's contribution
# to the command prompt.
#
# To implement support for a new shell, ideally one would only need to add shell-specific
# information to the __init__ method of this class.
# The following instance variables must be defined by each implementation.
pathsep_join: str
sep: str
path_conversion: Callable[
[str | Iterable[str] | None], str | tuple[str, ...] | None
]
script_extension: str
#: temporary file's extension, None writes to stdout instead
tempfile_extension: str | None
command_join: str
unset_var_tmpl: str
export_var_tmpl: str
path_var_tmpl: str
set_var_tmpl: str
run_script_tmpl: str
hook_source_path: Path | None
inline_hook_source: bool
needs_line_ending_fix: bool
def __init__(self, arguments=None):
self._raw_arguments = arguments
def get_export_unset_vars(self, export_metavars=True, **kwargs):
"""
:param export_metavars: whether to export `conda_exe_vars` meta variables.
:param kwargs: environment variables to export.
.. if you pass and set any other variable to None, then it
emits it to the dict with a value of None.
:return: A dict of env vars to export ordered the same way as kwargs.
And a list of env vars to unset.
"""
unset_vars = []
export_vars = {}
# split provided environment variables into exports vs unsets
for name, value in kwargs.items():
if value is None:
unset_vars.append(name)
else:
export_vars[name] = value
if export_metavars:
# split meta variables into exports vs unsets
for name, value in context.conda_exe_vars_dict.items():
if value is None:
unset_vars.append(name)
elif "/" in value or "\\" in value:
export_vars[name] = self.path_conversion(value)
else:
export_vars[name] = value
else:
# unset all meta variables
unset_vars.extend(context.conda_exe_vars_dict)
# normalize case if requested
if context.envvars_force_uppercase:
export_vars = {name.upper(): value for name, value in export_vars.items()}
unset_vars = [name.upper() for name in unset_vars]
return export_vars, unset_vars
def _finalize(self, commands, ext):
commands = (*commands, "") # add terminating newline
content = self.command_join.join(commands)
# Normalize line endings for Unix shells on Windows
if on_win and self.path_conversion == win_path_to_unix:
content = content.replace("\r\n", "\n")
if ext is None:
return content
elif ext:
with Utf8NamedTemporaryFile("w+", suffix=ext, delete=False) as tf:
# the default mode is 'w+b', and universal new lines don't work in that mode
tf.write(content)
return tf.name
else:
raise NotImplementedError()
def activate(self):
if self.stack:
builder_result = self.build_stack(self.env_name_or_prefix)
else:
builder_result = self.build_activate(self.env_name_or_prefix)
return self._finalize(
self._yield_commands(builder_result), self.tempfile_extension
)
def deactivate(self):
return self._finalize(
self._yield_commands(self.build_deactivate()), self.tempfile_extension
)
def reactivate(self):
return self._finalize(
self._yield_commands(self.build_reactivate()), self.tempfile_extension
)
@deprecated.argument("25.9", "26.3", "auto_activate_base", rename="auto_activate")
def hook(self, auto_activate: bool | None = None) -> str:
builder: list[str] = []
if preamble := self._hook_preamble():
builder.append(preamble)
if self.hook_source_path:
if self.inline_hook_source:
builder.append(self.hook_source_path.read_text())
else:
builder.append(self.run_script_tmpl % self.hook_source_path)
if auto_activate is None and context.auto_activate or auto_activate:
builder.append(f"conda activate '{context.default_activation_env}'\n")
postamble = self._hook_postamble()
if postamble is not None:
builder.append(postamble)
return "\n".join(builder)
def execute(self):
# return value meant to be written to stdout
self._parse_and_set_args()
# invoke pre/post commands, see conda.cli.conda_argparse.do_call
context.plugin_manager.invoke_pre_commands(self.command)
response = getattr(self, self.command)()
context.plugin_manager.invoke_post_commands(self.command)
return response
def template_unset_var(self, key: str) -> str:
return self.unset_var_tmpl % key
def template_export_var(self, key: str, value: str) -> str:
return self.export_var_tmpl % (key, value)
def template_path_var(self, key: str, value: str) -> str:
return self.path_var_tmpl % (key, value)
def _hook_preamble(self) -> str | None:
result = []
for key, value in context.conda_exe_vars_dict.items():
if value is None:
result.append(self.template_unset_var(key))
elif {"/", "\\"}.intersection(value):
result.append(self.template_path_var(key, value))
else:
result.append(self.template_export_var(key, value))
if result:
return self.command_join.join(result) + self.command_join
return None
def _hook_postamble(self) -> str | None:
return None
def _parse_and_set_args(self) -> None:
command, *arguments = self._raw_arguments or [None]
help_flags = ("-h", "--help", "/?")
non_help_args = tuple(arg for arg in arguments if arg not in help_flags)
help_requested = len(arguments) != len(non_help_args)
remainder_args = list(arg for arg in non_help_args if arg and arg != command)
if command not in BUILTIN_COMMANDS:
raise ArgumentError(
"'activate', 'deactivate', 'hook', 'commands', or 'reactivate' "
"command must be given." + (f", not '{command}'." if command else ".")
)
elif help_requested:
raise BUILTIN_COMMANDS[command]
if command.endswith("activate") or command == "hook":
try:
dev_idx = remainder_args.index("--dev")
except ValueError:
context.dev = False
else:
del remainder_args[dev_idx]
context.dev = True
if command == "activate":
self.stack = context.auto_stack and context.shlvl <= context.auto_stack
try:
stack_idx = remainder_args.index("--stack")
except ValueError:
stack_idx = -1
try:
no_stack_idx = remainder_args.index("--no-stack")
except ValueError:
no_stack_idx = -1
if stack_idx >= 0 and no_stack_idx >= 0:
raise ArgumentError(
"cannot specify both --stack and --no-stack to " + command
)
if stack_idx >= 0:
self.stack = True
del remainder_args[stack_idx]
if no_stack_idx >= 0:
self.stack = False
del remainder_args[no_stack_idx]
if len(remainder_args) > 1:
raise ArgumentError(
command
+ " does not accept more than one argument:\n"
+ str(remainder_args)
+ "\n"
)
if remainder_args:
self.env_name_or_prefix = remainder_args[0]
else:
self.env_name_or_prefix = context.default_activation_env
elif remainder_args:
raise ArgumentError(
f"{command} does not accept arguments\nremainder_args: {remainder_args}\n"
)
self.command = command
def _yield_commands(self, cmds_dict):
for key, value in sorted(cmds_dict.get("export_path", {}).items()):
yield self.export_var_tmpl % (key, value)
for script in cmds_dict.get("deactivate_scripts", ()):
yield self.run_script_tmpl % script
for key in cmds_dict.get("unset_vars", ()):
yield self.unset_var_tmpl % key
for key, value in cmds_dict.get("set_vars", {}).items():
yield self.set_var_tmpl % (key, value)
for key, value in cmds_dict.get("export_vars", {}).items():
yield self.export_var_tmpl % (key, value)
for script in cmds_dict.get("activate_scripts", ()):
yield self.run_script_tmpl % script
def build_activate(self, env_name_or_prefix):
return self._build_activate_stack(env_name_or_prefix, False)
def build_stack(self, env_name_or_prefix):
return self._build_activate_stack(env_name_or_prefix, True)
def _build_activate_stack(self, env_name_or_prefix, stack):
# get environment prefix
if re.search(r"\\|/", env_name_or_prefix):
prefix = expand(env_name_or_prefix)
if not isdir(join(prefix, "conda-meta")):
from .exceptions import EnvironmentLocationNotFound
raise EnvironmentLocationNotFound(prefix)
elif env_name_or_prefix in (RESERVED_ENV_NAMES):
prefix = context.root_prefix
else:
prefix = locate_prefix_by_name(env_name_or_prefix)
# get prior shlvl and prefix
old_conda_shlvl = int(os.getenv("CONDA_SHLVL", "").strip() or 0)
old_conda_prefix = os.getenv("CONDA_PREFIX")
# if the prior active prefix is this prefix we are actually doing a reactivate
if old_conda_prefix == prefix and old_conda_shlvl > 0:
return self.build_reactivate()
activate_scripts = self._get_activate_scripts(prefix)
conda_shlvl = old_conda_shlvl + 1
conda_default_env = self._default_env(prefix)
conda_prompt_modifier = self._prompt_modifier(prefix, conda_default_env)
env_vars = {
name: value
for name, value in self._get_environment_env_vars(prefix).items()
if value != CONDA_ENV_VARS_UNSET_VAR
}
# get clobbered environment variables
clobber_vars = set(env_vars).intersection(os.environ)
overwritten_clobber_vars = [
clobber_var
for clobber_var in clobber_vars
if os.getenv(clobber_var) != env_vars[clobber_var]
]
if overwritten_clobber_vars:
print(
"WARNING: overwriting environment variables set in the machine",
file=sys.stderr,
)
print(f"overwriting variable {overwritten_clobber_vars}", file=sys.stderr)
for name in clobber_vars:
env_vars[f"__CONDA_SHLVL_{old_conda_shlvl}_{name}"] = os.getenv(name)
if old_conda_shlvl == 0:
export_vars, unset_vars = self.get_export_unset_vars(
PATH=self.pathsep_join(self._add_prefix_to_path(prefix)),
CONDA_PREFIX=prefix,
CONDA_SHLVL=conda_shlvl,
CONDA_DEFAULT_ENV=conda_default_env,
CONDA_PROMPT_MODIFIER=conda_prompt_modifier,
**env_vars,
)
deactivate_scripts = ()
elif stack:
export_vars, unset_vars = self.get_export_unset_vars(
PATH=self.pathsep_join(self._add_prefix_to_path(prefix)),
CONDA_PREFIX=prefix,
CONDA_SHLVL=conda_shlvl,
CONDA_DEFAULT_ENV=conda_default_env,
CONDA_PROMPT_MODIFIER=conda_prompt_modifier,
**env_vars,
**{
f"CONDA_PREFIX_{old_conda_shlvl}": old_conda_prefix,
f"CONDA_STACKED_{conda_shlvl}": "true",
},
)
deactivate_scripts = ()
else:
export_vars, unset_vars = self.get_export_unset_vars(
PATH=self.pathsep_join(
self._replace_prefix_in_path(old_conda_prefix, prefix)
),
CONDA_PREFIX=prefix,
CONDA_SHLVL=conda_shlvl,
CONDA_DEFAULT_ENV=conda_default_env,
CONDA_PROMPT_MODIFIER=conda_prompt_modifier,
**env_vars,
**{
f"CONDA_PREFIX_{old_conda_shlvl}": old_conda_prefix,
},
)
deactivate_scripts = self._get_deactivate_scripts(old_conda_prefix)
set_vars = {}
if context.changeps1:
self._update_prompt(set_vars, conda_prompt_modifier)
return {
"unset_vars": unset_vars,
"set_vars": set_vars,
"export_vars": export_vars,
"deactivate_scripts": deactivate_scripts,
"activate_scripts": activate_scripts,
}
def build_deactivate(self):
self._deactivate = True
# query environment
old_conda_prefix = os.getenv("CONDA_PREFIX")
old_conda_shlvl = int(os.getenv("CONDA_SHLVL", "").strip() or 0)
if not old_conda_prefix or old_conda_shlvl < 1:
# no active environment, so cannot deactivate; do nothing
return {
"unset_vars": (),
"set_vars": {},
"export_vars": {},
"deactivate_scripts": (),
"activate_scripts": (),
}
deactivate_scripts = self._get_deactivate_scripts(old_conda_prefix)
old_conda_environment_env_vars = self._get_environment_env_vars(
old_conda_prefix
)
new_conda_shlvl = old_conda_shlvl - 1
set_vars = {}
if old_conda_shlvl == 1:
new_path = self.pathsep_join(
self._remove_prefix_from_path(old_conda_prefix)
)
# You might think that you can remove the CONDA_EXE vars with export_metavars=False
# here so that "deactivate means deactivate" but you cannot since the conda shell
# scripts still refer to them and they only set them once at the top. We could change
# that though, the conda() shell function could set them instead of doing it at the
# top. This would be *much* cleaner. I personally cannot abide that I have
# deactivated conda and anything at all in my env still references it (apart from the
# shell script, we need something I suppose!)
export_vars, unset_vars = self.get_export_unset_vars(
CONDA_PREFIX=None,
CONDA_SHLVL=new_conda_shlvl,
CONDA_DEFAULT_ENV=None,
CONDA_PROMPT_MODIFIER=None,
)
conda_prompt_modifier = ""
activate_scripts = ()
export_path = {"PATH": new_path}
else:
if old_conda_shlvl <= 1:
raise ValueError("'old_conda_shlvl' must be 2 or larger")
new_prefix = os.getenv("CONDA_PREFIX_%d" % new_conda_shlvl)
conda_default_env = self._default_env(new_prefix)
conda_prompt_modifier = self._prompt_modifier(new_prefix, conda_default_env)
new_conda_environment_env_vars = self._get_environment_env_vars(new_prefix)
old_prefix_stacked = "CONDA_STACKED_%d" % old_conda_shlvl in os.environ
new_path = ""
unset_vars = ["CONDA_PREFIX_%d" % new_conda_shlvl]
if old_prefix_stacked:
new_path = self.pathsep_join(
self._remove_prefix_from_path(old_conda_prefix)
)
unset_vars.append("CONDA_STACKED_%d" % old_conda_shlvl)
else:
new_path = self.pathsep_join(
self._replace_prefix_in_path(old_conda_prefix, new_prefix)
)
export_vars, unset_vars2 = self.get_export_unset_vars(
CONDA_PREFIX=new_prefix,
CONDA_SHLVL=new_conda_shlvl,
CONDA_DEFAULT_ENV=conda_default_env,
CONDA_PROMPT_MODIFIER=conda_prompt_modifier,
**new_conda_environment_env_vars,
)
unset_vars += unset_vars2
export_path = {"PATH": new_path}
activate_scripts = self._get_activate_scripts(new_prefix)
if context.changeps1:
self._update_prompt(set_vars, conda_prompt_modifier)
# Handle environment variables that need to be unset during deactivation
for env_var in old_conda_environment_env_vars.keys():
if save_value := os.getenv(f"__CONDA_SHLVL_{new_conda_shlvl}_{env_var}"):
export_vars[env_var] = save_value
else:
# Apply case conversion for environment variables that need to be unset
if context.envvars_force_uppercase:
unset_vars.append(env_var.upper())
else:
unset_vars.append(env_var)
return {
"unset_vars": unset_vars,
"set_vars": set_vars,
"export_vars": export_vars,
"export_path": export_path,
"deactivate_scripts": deactivate_scripts,
"activate_scripts": activate_scripts,
}
def build_reactivate(self):
self._reactivate = True
conda_prefix = os.getenv("CONDA_PREFIX")
conda_shlvl = int(os.getenv("CONDA_SHLVL", "").strip() or 0)
if not conda_prefix or conda_shlvl < 1:
# no active environment, so cannot reactivate; do nothing
return {
"unset_vars": [],
"set_vars": {},
"export_vars": {},
"deactivate_scripts": (),
"activate_scripts": (),
}
conda_default_env = os.getenv(
"CONDA_DEFAULT_ENV", self._default_env(conda_prefix)
)
new_path = self.pathsep_join(
self._replace_prefix_in_path(conda_prefix, conda_prefix)
)
set_vars = {}
conda_prompt_modifier = self._prompt_modifier(conda_prefix, conda_default_env)
if context.changeps1:
self._update_prompt(set_vars, conda_prompt_modifier)
export_vars, unset_vars = self.get_export_unset_vars(
PATH=new_path,
CONDA_SHLVL=conda_shlvl,
CONDA_PROMPT_MODIFIER=self._prompt_modifier(
conda_prefix, conda_default_env
),
)
# environment variables are set only to aid transition from conda 4.3 to conda 4.4
return {
"unset_vars": unset_vars,
"set_vars": set_vars,
"export_vars": export_vars,
"deactivate_scripts": self._get_deactivate_scripts(conda_prefix),
"activate_scripts": self._get_activate_scripts(conda_prefix),
}
def _get_starting_path_list(self):
# For isolation, running the conda test suite *without* env. var. inheritance
# every so often is a good idea. We should probably make this a pytest fixture
# along with one that tests both hardlink-only and copy-only, but before that
# conda's testsuite needs to be a lot faster!
clean_paths = {
"darwin": "/usr/bin:/bin:/usr/sbin:/sbin",
# You may think 'let us do something more clever here and interpolate
# `%windir%`' but the point here is the the whole env. is cleaned out
"win32": "C:\\Windows\\system32;"
"C:\\Windows;"
"C:\\Windows\\System32\\Wbem;"
"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\",
}
path = os.getenv(
"PATH",
clean_paths[sys.platform] if sys.platform in clean_paths else "/usr/bin",
)
path_split = path.split(os.pathsep)
return path_split
def _get_path_dirs(self, prefix):
if on_win: # pragma: unix no cover
yield prefix.rstrip(self.sep)
# We need to stat(2) for possible environments because
# tests can't be told where to look!
#
# mingw-w64 is a legacy variant used by m2w64-* packages
#
# We could include clang32 and mingw32 variants
variants = []
for variant in ["ucrt64", "clang64", "mingw64", "clangarm64"]:
path = self.sep.join((prefix, "Library", variant))
# MSYS2 /c/
# cygwin /cygdrive/c/
if re.match("^(/[A-Za-z]/|/cygdrive/[A-Za-z]/).*", prefix):
path = unix_path_to_win(path, prefix)
if isdir(path):
variants.append(variant)
if len(variants) > 1:
print(
f"WARNING: {prefix}: {variants} MSYS2 envs exist: please check your dependencies",
file=sys.stderr,
)
print(
f"WARNING: conda list -n {self._default_env(prefix)}",
file=sys.stderr,
)
if variants:
yield self.sep.join((prefix, "Library", variants[0], "bin"))
yield self.sep.join((prefix, "Library", "mingw-w64", "bin"))
yield self.sep.join((prefix, "Library", "usr", "bin"))
yield self.sep.join((prefix, "Library", "bin"))
yield self.sep.join((prefix, "Scripts"))
yield self.sep.join((prefix, "bin"))
else:
yield self.sep.join((prefix, "bin"))
def _add_prefix_to_path(self, prefix, starting_path_dirs=None):
prefix = self.path_conversion(prefix)
if starting_path_dirs is None:
path_list = list(self.path_conversion(self._get_starting_path_list()))
else:
path_list = list(self.path_conversion(starting_path_dirs))
# If this is the first time we're activating an environment, we need to ensure that
# the condabin directory is included in the path list.
# Under normal conditions, if the shell hook is working correctly, this should
# never trigger.
old_conda_shlvl = int(os.getenv("CONDA_SHLVL", "").strip() or 0)
if not old_conda_shlvl and not any(p.endswith("condabin") for p in path_list):
condabin_dir = self.path_conversion(join(context.conda_prefix, "condabin"))
path_list.insert(0, condabin_dir)
path_list[0:0] = list(self.path_conversion(self._get_path_dirs(prefix)))
return tuple(path_list)
def _remove_prefix_from_path(self, prefix, starting_path_dirs=None):
return self._replace_prefix_in_path(prefix, None, starting_path_dirs)
def _replace_prefix_in_path(self, old_prefix, new_prefix, starting_path_dirs=None):
old_prefix = self.path_conversion(old_prefix)
new_prefix = self.path_conversion(new_prefix)
if starting_path_dirs is None:
path_list = list(self.path_conversion(self._get_starting_path_list()))
else:
path_list = list(self.path_conversion(starting_path_dirs))
def index_of_path(paths, test_path):
for q, path in enumerate(paths):
if paths_equal(path, test_path):
return q
return None
if old_prefix is not None:
prefix_dirs = tuple(self._get_path_dirs(old_prefix))
first_idx = index_of_path(path_list, prefix_dirs[0])
if first_idx is None:
first_idx = 0
else:
prefix_dirs_idx = len(prefix_dirs) - 1
last_idx = None
while last_idx is None and prefix_dirs_idx > -1:
last_idx = index_of_path(path_list, prefix_dirs[prefix_dirs_idx])
if last_idx is None:
print(
f"Did not find path entry {prefix_dirs[prefix_dirs_idx]}",
file=sys.stderr,
)
prefix_dirs_idx = prefix_dirs_idx - 1
# this compensates for an extra Library/bin dir entry from the interpreter on
# windows. If that entry isn't being added, it should have no effect.
library_bin_dir = self.path_conversion(
self.sep.join((sys.prefix, "Library", "bin"))
)
if path_list[last_idx + 1] == library_bin_dir:
last_idx += 1
del path_list[first_idx : last_idx + 1]
else:
first_idx = 0
if new_prefix is not None:
path_list[first_idx:first_idx] = list(self._get_path_dirs(new_prefix))
return tuple(path_list)
def _update_prompt(self, set_vars, conda_prompt_modifier):
pass
def _default_env(self, prefix):
if paths_equal(prefix, context.root_prefix):
return "base"
return basename(prefix) if basename(dirname(prefix)) == "envs" else prefix
def _prompt_modifier(self, prefix, conda_default_env):
if context.changeps1:
# Get current environment and prompt stack
env_stack = []
prompt_stack = []
old_shlvl = int(os.getenv("CONDA_SHLVL", "0").rstrip())
for i in range(1, old_shlvl + 1):
if i == old_shlvl:
env_i = self._default_env(os.getenv("CONDA_PREFIX", ""))
else:
env_i = self._default_env(
os.getenv(f"CONDA_PREFIX_{i}", "").rstrip()
)
stacked_i = bool(os.getenv(f"CONDA_STACKED_{i}", "").rstrip())
env_stack.append(env_i)
if not stacked_i:
prompt_stack = prompt_stack[0:-1]
prompt_stack.append(env_i)
# Modify prompt stack according to pending operation
deactivate = getattr(self, "_deactivate", False)
reactivate = getattr(self, "_reactivate", False)
if deactivate:
prompt_stack = prompt_stack[0:-1]
env_stack = env_stack[0:-1]
stacked = bool(os.getenv(f"CONDA_STACKED_{old_shlvl}", "").rstrip())
if not stacked and env_stack:
prompt_stack.append(env_stack[-1])
elif reactivate:
pass
else:
stack = getattr(self, "stack", False)
if not stack:
prompt_stack = prompt_stack[0:-1]
prompt_stack.append(conda_default_env)
conda_stacked_env = ",".join(prompt_stack[::-1])
return context.env_prompt.format(
default_env=conda_default_env,
stacked_env=conda_stacked_env,
prefix=prefix,
name=basename(prefix),
)
else:
return ""
def _get_activate_scripts(self, prefix):
_script_extension = self.script_extension
se_len = -len(_script_extension)
try:
paths = (
entry.path
for entry in os.scandir(join(prefix, "etc", "conda", "activate.d"))
)
except OSError:
return ()
return self.path_conversion(
sorted(p for p in paths if p[se_len:] == _script_extension)
)
def _get_deactivate_scripts(self, prefix):
_script_extension = self.script_extension
se_len = -len(_script_extension)
try:
paths = (
entry.path
for entry in os.scandir(join(prefix, "etc", "conda", "deactivate.d"))
)
except OSError:
return ()
return self.path_conversion(
sorted((p for p in paths if p[se_len:] == _script_extension), reverse=True)
)
def _get_environment_env_vars(self, prefix):
env_vars_file = join(prefix, PREFIX_STATE_FILE)
pkg_env_var_dir = join(prefix, PACKAGE_ENV_VARS_DIR)
env_vars = {}
# First get env vars from packages
if exists(pkg_env_var_dir):
for pkg_env_var_path in sorted(
entry.path for entry in os.scandir(pkg_env_var_dir)
):
with open(pkg_env_var_path) as f:
env_vars.update(json.loads(f.read()))
# Then get env vars from environment specification
if exists(env_vars_file):
with open(env_vars_file) as f:
prefix_state = json.loads(f.read())
prefix_state_env_vars = prefix_state.get("env_vars", {})
dup_vars = [
ev for ev in env_vars.keys() if ev in prefix_state_env_vars.keys()
]
for dup in dup_vars:
print(
"WARNING: duplicate env vars detected. Vars from the environment "
"will overwrite those from packages",
file=sys.stderr,
)
print(f"variable {dup} duplicated", file=sys.stderr)
env_vars.update(prefix_state_env_vars)
# Remove reserved environment variables and warn if they're being set
collect_reserved_vars = []
for reserved in RESERVED_ENV_VARS:
if reserved in env_vars:
# Only warn if the variable is actually being set (not unset)
if env_vars[reserved] != CONDA_ENV_VARS_UNSET_VAR:
collect_reserved_vars.append(reserved)
# Remove from env_vars regardless
env_vars.pop(reserved)
if collect_reserved_vars:
print_reserved_vars = ", ".join(collect_reserved_vars)
print(
f"WARNING: the configured environment variable(s) for prefix '{prefix}' "
f"are reserved and will be ignored: {print_reserved_vars}.\n\n"
f"Remove the invalid configuration with `conda env config vars unset "
f"-p {prefix} {' '.join(collect_reserved_vars)}`.\n",
file=sys.stderr,
)
return env_vars
def expand(path):
return abspath(expanduser(expandvars(path)))
def backslash_to_forwardslash(
paths: str | Iterable[str] | None,
) -> str | tuple[str, ...] | None:
if paths is None:
return None
elif isinstance(paths, str):
return paths.replace("\\", "/")
else:
return tuple([path.replace("\\", "/") for path in paths])
| _Activator |
python | tensorflow__tensorflow | tensorflow/python/ops/critical_section_ops.py | {
"start": 1432,
"end": 3861
} | class ____(
collections.namedtuple("_ExecutionSignature",
("op", "handle",
"resources", "exclusive_resource_access"))):
"""A class storing an `ExecuteInCriticalResource` op and associated attrs."""
pass
def _identity(x):
"""Identity op that recognizes `TensorArray`, `Operation`, and `Tensor`."""
if isinstance(x, tensor_array_ops.TensorArray):
return x.identity()
elif isinstance(x, ops.Operation):
return control_flow_ops.group(x)
elif context.executing_eagerly() and x is None:
return None
else:
return array_ops.identity(x)
def _get_device_or_colocation(op):
return op.device or _get_colocation(op)
def _get_colocation(op):
"""Get colocation symbol from op, if any."""
try:
return op.get_attr("_class")
except (ValueError, AttributeError):
return None
_CRITICAL_SECTION_STACK = threading.local()
def _get_critical_section_stack():
try:
return _CRITICAL_SECTION_STACK.value
except AttributeError:
_CRITICAL_SECTION_STACK.value = []
return _CRITICAL_SECTION_STACK.value
@contextlib.contextmanager
def _push_critical_section_stack(signature):
"""Push a CriticalSection._signature to the thread-local stack.
If the signature is already on the stack, raise an error because it means
we're trying to execute inside the same locked CriticalSection, which
will create a deadlock.
Args:
signature: Tuple of the type `CriticalSection._signature`. Uniquely
identifies a CriticalSection by its `shared_name`, `container`,
and device.
Yields:
An empty value. The context is guaranteed to run without deadlock.
Raises:
ValueError: If the signature is already on the stack.
RuntimeError: If another thread or function modifies the current stack
entry during the yield.
"""
stack = _get_critical_section_stack()
if signature in stack:
raise ValueError(
f"Attempting to lock a CriticalSection (signature={signature}) in which"
" we are already running. This is illegal and may cause deadlocks.")
stack.append(signature)
try:
yield
finally:
received_signature = stack.pop()
if received_signature != signature:
raise RuntimeError(
"CriticalSection stack inconsistency: expected signature "
f"{signature} but received {received_signature}")
@tf_export("CriticalSection")
| _ExecutionSignature |
python | dagster-io__dagster | python_modules/libraries/create-dagster/create_dagster/version_check.py | {
"start": 502,
"end": 3094
} | class ____:
timestamp: float
raw_versions: list[str]
@property
def datetime(self) -> datetime.datetime:
return datetime.datetime.fromtimestamp(self.timestamp)
@cached_property
def versions(self) -> list[Version]:
return sorted(Version(v) for v in self.raw_versions)
def check_create_dagster_up_to_date(context: DgContext) -> None:
if not _create_dagster_update_check_enabled(context):
return
version_info = _get_create_dagster_pypi_version_info(context)
if version_info is None: # Nothing cached and network error occurred
return None
current_version = Version(__version__)
latest_version = version_info.versions[-1]
if current_version < latest_version:
emit_warning(
"create_dagster_outdated",
f"""
There is a new version of `create-dagster` available:
Latest version: {latest_version}
Current version: {current_version}
Update your create-dagster installation to keep up to date:
[uv tool run] $ uvx -U create-dagster
[uv tool install] $ uv tool upgrade create-dagster
[uv local] $ uv sync --upgrade create-dagster
[pip] $ pip install --upgrade create-dagster
""",
suppress_warnings=[],
)
def _create_dagster_update_check_enabled(context: DgContext) -> bool:
return (
bool(int(os.getenv(CREATE_DAGSTER_UPDATE_CHECK_ENABLED_ENV_VAR, "1")))
and "create_dagster_outdated" not in context.config.cli.suppress_warnings
)
def _get_create_dagster_pypi_version_info(context: DgContext) -> Optional[_PyPiVersionInfo]:
if context.config.cli.verbose:
context.log.info("Checking for the latest version of `create-dagster` on PyPI.")
try:
published_versions = get_published_pypi_versions("create-dagster")
version_info = _PyPiVersionInfo(
raw_versions=[str(v) for v in published_versions],
timestamp=datetime.datetime.now().timestamp(),
)
except DagsterPyPiAccessError as e:
emit_warning(
"create_dagster_outdated",
f"""
There was an error checking for the latest version of `create-dagster` on PyPI. Please check your
internet connection and try again.
Error: {e}
""",
suppress_warnings=[],
)
version_info = None
return version_info
| _PyPiVersionInfo |
python | viewflow__viewflow | tests/workflow/test_lock.py | {
"start": 454,
"end": 3694
} | class ____(TransactionTestCase):
class TestFlow(flow.Flow):
start = flow.StartHandle().Next(this.end)
end = flow.End()
def setUp(self):
self.finished = False
self.locked = False
self.process = Test.TestFlow.process_class.objects.create(flow_class=Test.TestFlow)
self.exception_queue = queue.Queue()
def run_with_lock(self, lock_impl):
try:
with lock_impl(Test.TestFlow, self.process.pk):
while not self.finished:
time.sleep(0.001)
except FlowLockFailed as e:
self.exception_queue.put(e)
finally:
connection.close()
def run_with_lock_and_release(self, lock_impl):
try:
with lock_impl(Test.TestFlow, self.process.pk):
time.sleep(0.5)
except FlowLockFailed as e:
self.exception_queue.put(e)
finally:
connection.close()
@skipUnlessDBFeature('has_select_for_update')
def test_select_for_update_locks(self):
lock_impl = lock.SelectForUpdateLock(attempts=1)
thread1 = threading.Thread(target=self.run_with_lock, args=[lock_impl])
thread2 = threading.Thread(target=self.run_with_lock, args=[lock_impl])
thread1.start()
thread2.start()
try:
self.exception_queue.get(True, 10)
except queue.Empty:
self.fail('No thread was blocked')
finally:
self.finished = True
thread1.join()
thread2.join()
@skipUnlessDBFeature('has_select_for_update')
def test_select_for_update_locks_released(self):
lock_impl = lock.SelectForUpdateLock(attempts=4)
thread1 = threading.Thread(
target=self.run_with_lock_and_release,
args=[lock_impl])
thread2 = threading.Thread(
target=self.run_with_lock_and_release,
args=[lock_impl])
thread1.start()
thread2.start()
thread1.join()
thread2.join()
try:
self.exception_queue.get(True, 1)
self.fail('Thread was blocked')
except queue.Empty:
pass
@skipUnlessDBFeature('has_select_for_update')
def test_select_for_update_lock_ignores_user_exceptions(self):
"""
Check fix for RuntimeError: generator didn't stop after throw().
https://github.com/viewflow/viewflow/pull/164
"""
def test_func():
lock_impl = lock.SelectForUpdateLock(attempts=4)
with lock_impl(Test.TestFlow, self.process.pk):
raise DatabaseError('Test')
with self.assertRaises(DatabaseError):
test_func()
def test_cache_lock(self):
lock_impl = lock.CacheLock(attempts=1)
thread1 = threading.Thread(target=self.run_with_lock, args=[lock_impl])
thread2 = threading.Thread(target=self.run_with_lock, args=[lock_impl])
thread1.start()
thread2.start()
try:
self.exception_queue.get(True, 10)
except queue.Empty:
self.fail('No thread was blocked')
finally:
self.finished = True
thread1.join()
thread2.join()
| Test |
python | kamyu104__LeetCode-Solutions | Python/palindrome-pairs.py | {
"start": 125,
"end": 1459
} | class ____(object):
def palindromePairs(self, words):
"""
:type words: List[str]
:rtype: List[List[int]]
"""
def is_palindrome(s, i, j):
while i < j:
if s[i] != s[j]:
return False
i += 1
j -= 1
return True
res = []
lookup = collections.defaultdict(dict)
for i, word in enumerate(words):
lookup[len(word)][word] = i
for i in xrange(len(words)):
for j in xrange(len(words[i]) + 1):
if j in lookup and is_palindrome(words[i], j, len(words[i])-1):
suffix = words[i][:j][::-1]
bucket = lookup[len(suffix)]
if suffix in bucket and bucket[suffix] != i:
res.append([i, bucket[suffix]])
if j > 0 and len(words[i])-j in lookup and is_palindrome(words[i], 0, j-1):
prefix = words[i][j:][::-1]
bucket = lookup[len(prefix)]
if prefix in bucket and bucket[prefix] != i:
res.append([bucket[prefix], i])
return res
# Time: O(n * k^2), n is the number of the words, k is the max length of the words.
# Space: O(n * k^2)
# Manacher solution.
| Solution |
python | pennersr__django-allauth | allauth/socialaccount/providers/feedly/provider.py | {
"start": 343,
"end": 899
} | class ____(OAuth2Provider):
id = "feedly"
name = "Feedly"
account_class = FeedlyAccount
oauth2_adapter_class = FeedlyOAuth2Adapter
def get_default_scope(self):
return ["https://cloud.feedly.com/subscriptions"]
def extract_uid(self, data):
return str(data["id"])
def extract_common_fields(self, data):
return dict(
email=data.get("email"),
last_name=data.get("familyName"),
first_name=data.get("givenName"),
)
provider_classes = [FeedlyProvider]
| FeedlyProvider |
python | pytorch__pytorch | torch/distributed/tensor/_random.py | {
"start": 4153,
"end": 5302
} | class ____:
"""
Convenience accessor for interpreting the packed bits of (seed: uint64, offset: uint64) in the philox state,
which for some reason is actually exposed as a size-16 uint8 tensor.
The state is always moved to .cpu since it is necessary for it to be on CPU before applying it back to a generator.
"""
def __init__(self, state: torch.Tensor):
self._state = state.to("cpu")
@property
def state(self):
return self._state
@property
def offset(self) -> int:
return int(self._state[8:].view(dtype=torch.int64).item())
@offset.setter
def offset(self, offset: int) -> None:
offset_tensor = torch.tensor([offset], dtype=torch.uint64, device="cpu").view(
torch.uint8
)
self._state[8:] = offset_tensor
@property
def seed(self) -> int:
return int(self._state[:8].view(dtype=torch.uint64).item())
@seed.setter
def seed(self, seed: int) -> None:
seed_tensor = torch.tensor([seed], dtype=torch.uint64, device="cpu").view(
torch.uint8
)
self._state[:8] = seed_tensor
| _PhiloxState |
python | dagster-io__dagster | python_modules/dagster/dagster/_scheduler/scheduler.py | {
"start": 6054,
"end": 32264
} | class ____(NamedTuple):
"""Timestamp information returned by each scheduler iteration that the core scheduler
loop can use to intelligently schedule the next tick.
last_iteration_timestamp is used by subsequent evaluations of this schedule to ensure that we
don't accidentally create incorrect runs after the cronstring changes (it is stored in memory
in these objects and is also periodically persisted on the schedule row in the database -
see _write_and_get_next_checkpoint_timestamp).
next_iteration_timestamp is the timestamp until which the scheduler can wait until running this
schedule again (assuming the cron schedule has not changed) - either because that's the next
time we know the schedule needs to run based on the last time we evaluated its cron string,
or because that's the next time we've determined that we should update the persisted
last_iteration_timestamp value for this schedule described above (this is written on a fixed
interval plus a random jitter value to ensure not every schedule tries to do this at once -
this value is also determined in _write_and_get_next_checkpoint_timestamp.).
"""
cron_schedule: Union[str, Sequence[str]]
next_iteration_timestamp: float
last_iteration_timestamp: float
def should_run_next_iteration(self, schedule: RemoteSchedule, now_timestamp: float):
if schedule.cron_schedule != self.cron_schedule:
# cron schedule has changed - always run next iteration to check
return True
return now_timestamp >= self.next_iteration_timestamp
def execute_scheduler_iteration_loop(
workspace_process_context: IWorkspaceProcessContext,
logger: logging.Logger,
max_catchup_runs: int,
max_tick_retries: int,
shutdown_event: threading.Event,
scheduler_delay_instrumentation: SchedulerDelayInstrumentation = default_scheduler_delay_instrumentation,
) -> "DaemonIterator":
from dagster._daemon.daemon import SpanMarker
scheduler_run_futures: dict[str, Future] = {}
iteration_times: dict[str, ScheduleIterationTimes] = {}
threadpool_executor = None
submit_threadpool_executor = None
with ExitStack() as stack:
settings = workspace_process_context.instance.get_scheduler_settings()
if settings.get("use_threads"):
threadpool_executor = stack.enter_context(
InheritContextThreadPoolExecutor(
max_workers=settings.get("num_workers"),
thread_name_prefix="schedule_daemon_worker",
)
)
num_submit_workers = settings.get("num_submit_workers")
if num_submit_workers:
submit_threadpool_executor = stack.enter_context(
InheritContextThreadPoolExecutor(
max_workers=settings.get("num_submit_workers"),
thread_name_prefix="schedule_submit_worker",
)
)
while True:
start_time = get_current_timestamp()
end_datetime_utc = get_current_datetime()
next_interval_time = _get_next_scheduler_iteration_time(start_time)
yield SpanMarker.START_SPAN
try:
yield from launch_scheduled_runs(
workspace_process_context,
logger,
end_datetime_utc=end_datetime_utc,
iteration_times=iteration_times,
threadpool_executor=threadpool_executor,
submit_threadpool_executor=submit_threadpool_executor,
scheduler_run_futures=scheduler_run_futures,
max_catchup_runs=max_catchup_runs,
max_tick_retries=max_tick_retries,
scheduler_delay_instrumentation=scheduler_delay_instrumentation,
)
except Exception:
error_info = DaemonErrorCapture.process_exception(
exc_info=sys.exc_info(),
logger=logger,
log_message="SchedulerDaemon caught an error",
)
yield error_info
# Wait a few seconds after an error
next_interval_time = min(start_time + ERROR_INTERVAL_TIME, next_interval_time)
yield SpanMarker.END_SPAN
end_time = get_current_timestamp()
if next_interval_time > end_time:
# Sleep until the beginning of the next minute, plus a small epsilon to
# be sure that we're past the start of the minute
shutdown_event.wait(next_interval_time - end_time + 0.001)
yield
def launch_scheduled_runs(
workspace_process_context: IWorkspaceProcessContext,
logger: logging.Logger,
end_datetime_utc: datetime.datetime,
iteration_times: dict[str, ScheduleIterationTimes],
threadpool_executor: Optional[ThreadPoolExecutor] = None,
submit_threadpool_executor: Optional[ThreadPoolExecutor] = None,
scheduler_run_futures: Optional[dict[str, Future]] = None,
max_catchup_runs: int = DEFAULT_MAX_CATCHUP_RUNS,
max_tick_retries: int = 0,
debug_crash_flags: Optional[DebugCrashFlags] = None,
scheduler_delay_instrumentation: SchedulerDelayInstrumentation = default_scheduler_delay_instrumentation,
) -> "DaemonIterator":
instance = workspace_process_context.instance
current_workspace = {
location_entry.origin.location_name: location_entry
for location_entry in workspace_process_context.create_request_context()
.get_code_location_entries()
.values()
}
all_schedule_states = {
schedule_state.selector_id: schedule_state
for schedule_state in instance.all_instigator_state(instigator_type=InstigatorType.SCHEDULE)
}
tick_retention_settings = instance.get_tick_retention_settings(InstigatorType.SCHEDULE)
running_schedules: dict[str, RemoteSchedule] = {}
all_workspace_schedule_selector_ids = set()
error_locations = set()
now_timestamp = end_datetime_utc.timestamp()
for location_entry in current_workspace.values():
code_location = location_entry.code_location
if code_location:
for repo in code_location.get_repositories().values():
for schedule in repo.get_schedules():
selector_id = schedule.selector_id
all_workspace_schedule_selector_ids.add(selector_id)
if schedule.get_current_instigator_state(
all_schedule_states.get(selector_id)
).is_running:
running_schedules[selector_id] = schedule
elif all_schedule_states.get(selector_id):
schedule_state = all_schedule_states[selector_id]
# If there is a DB row to update, see if we should still update the
# last_iteration_timestamp
_write_and_get_next_checkpoint_timestamp(
instance,
all_schedule_states[selector_id],
cast("ScheduleInstigatorData", schedule_state.instigator_data),
now_timestamp,
)
elif location_entry.load_error:
error_locations.add(location_entry.origin.location_name)
# Remove any schedule states that were previously created and can no longer
# be found in the workspace (so that if they are later added back again,
# their timestamps will start at the correct place)
states_to_delete = [
schedule_state
for selector_id, schedule_state in all_schedule_states.items()
if selector_id not in all_workspace_schedule_selector_ids
or (
schedule_state.status == InstigatorStatus.DECLARED_IN_CODE
and not running_schedules.get(selector_id)
)
]
for state in states_to_delete:
location_name = state.origin.repository_origin.code_location_origin.location_name
if location_name in error_locations:
# don't clean up state if its location is an error state
continue
_last_iteration_time = (
state.instigator_data.last_iteration_timestamp or 0.0
if isinstance(state.instigator_data, ScheduleInstigatorData)
else 0.0
)
# Remove all-stopped states declared in code immediately.
# Also remove all other states that are not present in the workspace after a 12-hour grace period.
if state.status == InstigatorStatus.DECLARED_IN_CODE or (
_last_iteration_time
and _last_iteration_time + RETAIN_ORPHANED_STATE_INTERVAL_SECONDS
< end_datetime_utc.timestamp()
):
logger.info(
f"Removing state for schedule {state.instigator_name} that is "
f"no longer present in {location_name}."
)
instance.delete_instigator_state(state.instigator_origin_id, state.selector_id)
if not running_schedules:
yield
return
for schedule in running_schedules.values():
error_info = None
try:
schedule_state = all_schedule_states.get(schedule.selector_id)
if not schedule_state:
assert schedule.default_status == DefaultScheduleStatus.RUNNING
schedule_state = InstigatorState(
schedule.get_remote_origin(),
InstigatorType.SCHEDULE,
InstigatorStatus.DECLARED_IN_CODE,
ScheduleInstigatorData(
schedule.cron_schedule,
end_datetime_utc.timestamp(),
),
)
instance.add_instigator_state(schedule_state)
schedule_debug_crash_flags = (
debug_crash_flags.get(schedule_state.instigator_name) if debug_crash_flags else None
)
if threadpool_executor:
if scheduler_run_futures is None:
check.failed(
"scheduler_run_futures dict must be passed with threadpool_executor"
)
if schedule.selector_id in scheduler_run_futures:
if scheduler_run_futures[schedule.selector_id].done():
try:
result = scheduler_run_futures[schedule.selector_id].result()
iteration_times[schedule.selector_id] = result
except Exception:
# Log exception and continue on rather than erroring the whole scheduler loop
DaemonErrorCapture.process_exception(
exc_info=sys.exc_info(),
logger=logger,
log_message=f"Error getting tick result for schedule {schedule.name}",
)
del scheduler_run_futures[schedule.selector_id]
else:
# only allow one tick per schedule to be in flight
continue
previous_iteration_times = iteration_times.get(schedule.selector_id)
if (
previous_iteration_times
and not previous_iteration_times.should_run_next_iteration(
schedule, end_datetime_utc.timestamp()
)
):
# Not enough time has passed for this schedule, don't bother creating a thread
continue
if previous_iteration_times:
scheduler_delay_instrumentation(
schedule.selector_id,
previous_iteration_times.next_iteration_timestamp,
now_timestamp,
)
future = threadpool_executor.submit(
launch_scheduled_runs_for_schedule,
workspace_process_context,
logger,
schedule,
schedule_state,
end_datetime_utc,
max_catchup_runs,
max_tick_retries,
tick_retention_settings,
schedule_debug_crash_flags,
submit_threadpool_executor=submit_threadpool_executor,
in_memory_last_iteration_timestamp=(
previous_iteration_times.last_iteration_timestamp
if previous_iteration_times
else None
),
)
scheduler_run_futures[schedule.selector_id] = future
yield
else:
previous_iteration_times = iteration_times.get(schedule.selector_id)
if (
previous_iteration_times
and not previous_iteration_times.should_run_next_iteration(
schedule, end_datetime_utc.timestamp()
)
):
# Not enough time has passed for this schedule, don't bother executing
continue
# evaluate the schedules in a loop, synchronously, yielding to allow the schedule daemon to
# heartbeat
found_iteration_times = False
for yielded_value in launch_scheduled_runs_for_schedule_iterator(
workspace_process_context,
logger,
schedule,
schedule_state,
end_datetime_utc,
max_catchup_runs,
max_tick_retries,
tick_retention_settings,
schedule_debug_crash_flags,
submit_threadpool_executor=None,
in_memory_last_iteration_timestamp=(
previous_iteration_times.last_iteration_timestamp
if previous_iteration_times
else None
),
):
if isinstance(yielded_value, ScheduleIterationTimes):
check.invariant(
not found_iteration_times,
"launch_scheduled_runs_for_schedule_iterator yielded more than one ScheduleIterationTimes",
)
found_iteration_times = True
iteration_times[schedule.selector_id] = yielded_value
else:
yield yielded_value
check.invariant(
found_iteration_times,
"launch_scheduled_runs_for_schedule_iterator did not yield a ScheduleIterationTimes",
)
except Exception:
error_info = DaemonErrorCapture.process_exception(
exc_info=sys.exc_info(),
logger=logger,
log_message=f"Scheduler caught an error for schedule {schedule.name}",
)
yield error_info
def launch_scheduled_runs_for_schedule(
workspace_process_context: IWorkspaceProcessContext,
logger: logging.Logger,
remote_schedule: RemoteSchedule,
schedule_state: InstigatorState,
end_datetime_utc: datetime.datetime,
max_catchup_runs: int,
max_tick_retries: int,
tick_retention_settings: Mapping[TickStatus, int],
schedule_debug_crash_flags: Optional[SingleInstigatorDebugCrashFlags],
submit_threadpool_executor: Optional[ThreadPoolExecutor],
in_memory_last_iteration_timestamp: Optional[float],
) -> ScheduleIterationTimes:
# evaluate the tick immediately, but from within a thread. The main thread should be able to
# heartbeat to keep the daemon alive
iteration_times = None
for yielded_value in launch_scheduled_runs_for_schedule_iterator(
workspace_process_context,
logger,
remote_schedule,
schedule_state,
end_datetime_utc,
max_catchup_runs,
max_tick_retries,
tick_retention_settings,
schedule_debug_crash_flags,
submit_threadpool_executor=submit_threadpool_executor,
in_memory_last_iteration_timestamp=in_memory_last_iteration_timestamp,
):
if isinstance(yielded_value, ScheduleIterationTimes):
iteration_times = yielded_value
return check.not_none(iteration_times)
def launch_scheduled_runs_for_schedule_iterator(
workspace_process_context: IWorkspaceProcessContext,
logger: logging.Logger,
remote_schedule: RemoteSchedule,
schedule_state: InstigatorState,
end_datetime_utc: datetime.datetime,
max_catchup_runs: int,
max_tick_retries: int,
tick_retention_settings: Mapping[TickStatus, int],
schedule_debug_crash_flags: Optional[SingleInstigatorDebugCrashFlags],
submit_threadpool_executor: Optional[ThreadPoolExecutor],
in_memory_last_iteration_timestamp: Optional[float],
) -> Generator[Union[None, SerializableErrorInfo, ScheduleIterationTimes], None, None]:
schedule_state = check.inst_param(schedule_state, "schedule_state", InstigatorState)
end_datetime_utc = check.inst_param(end_datetime_utc, "end_datetime_utc", datetime.datetime)
instance = workspace_process_context.instance
instigator_origin_id = remote_schedule.get_remote_origin_id()
ticks = instance.get_ticks(instigator_origin_id, remote_schedule.selector_id, limit=1)
latest_tick: Optional[InstigatorTick] = ticks[0] if ticks else None
instigator_data = cast("ScheduleInstigatorData", schedule_state.instigator_data)
start_timestamp_utc: float = instigator_data.start_timestamp or 0
if latest_tick:
if latest_tick.status == TickStatus.STARTED or (
latest_tick.status == TickStatus.FAILURE
and latest_tick.failure_count <= max_tick_retries
):
# Scheduler was interrupted while performing this tick, re-do it
start_timestamp_utc = max(
start_timestamp_utc,
latest_tick.timestamp,
instigator_data.last_iteration_timestamp or 0.0,
in_memory_last_iteration_timestamp or 0.0,
)
else:
start_timestamp_utc = max(
start_timestamp_utc,
latest_tick.timestamp + 1,
instigator_data.last_iteration_timestamp or 0.0,
in_memory_last_iteration_timestamp or 0.0,
)
else:
start_timestamp_utc = max(
start_timestamp_utc,
instigator_data.last_iteration_timestamp or 0.0,
in_memory_last_iteration_timestamp or 0.0,
)
schedule_name = remote_schedule.name
timezone_str = remote_schedule.execution_timezone
if not timezone_str:
timezone_str = "UTC"
tick_times: list[datetime.datetime] = []
now_timestamp = end_datetime_utc.timestamp()
next_iteration_timestamp = None
for next_time in remote_schedule.execution_time_iterator(start_timestamp_utc):
next_tick_timestamp = next_time.timestamp()
if next_tick_timestamp > now_timestamp:
next_iteration_timestamp = next_tick_timestamp
break
tick_times.append(next_time)
if not tick_times:
next_checkpoint_timestamp = _write_and_get_next_checkpoint_timestamp(
instance,
schedule_state,
instigator_data,
now_timestamp,
)
next_iteration_timestamp = min(
check.not_none(next_iteration_timestamp), next_checkpoint_timestamp
)
yield ScheduleIterationTimes(
cron_schedule=remote_schedule.cron_schedule,
next_iteration_timestamp=next_iteration_timestamp,
last_iteration_timestamp=now_timestamp,
)
return
if not remote_schedule.partition_set_name and len(tick_times) > 1:
logger.warning(f"{schedule_name} has no partition set, so not trying to catch up")
tick_times = tick_times[-1:]
elif len(tick_times) > max_catchup_runs:
logger.warning(f"{schedule_name} has fallen behind, only launching {max_catchup_runs} runs")
tick_times = tick_times[-max_catchup_runs:]
if len(tick_times) == 1:
tick_time = tick_times[0].strftime(default_date_format_string())
logger.info(f"Evaluating schedule `{schedule_name}` at {tick_time}")
else:
times = ", ".join([time.strftime(default_date_format_string()) for time in tick_times])
logger.info(f"Evaluating schedule `{schedule_name}` at the following times: {times}")
for schedule_time in tick_times:
schedule_timestamp = schedule_time.timestamp()
schedule_time_str = schedule_time.strftime(default_date_format_string())
consecutive_failure_count = 0
if latest_tick and latest_tick.status in {TickStatus.FAILURE, TickStatus.STARTED}:
consecutive_failure_count = (
latest_tick.consecutive_failure_count or latest_tick.failure_count
)
if latest_tick and latest_tick.timestamp == schedule_timestamp:
tick = latest_tick
if latest_tick.status == TickStatus.FAILURE:
logger.info(f"Retrying previously failed schedule execution at {schedule_time_str}")
else:
logger.info(
f"Resuming previously interrupted schedule execution at {schedule_time_str}"
)
else:
tick = instance.create_tick(
TickData(
instigator_origin_id=instigator_origin_id,
instigator_name=schedule_name,
instigator_type=InstigatorType.SCHEDULE,
status=TickStatus.STARTED,
timestamp=schedule_timestamp,
selector_id=remote_schedule.selector_id,
consecutive_failure_count=consecutive_failure_count,
)
)
check_for_debug_crash(schedule_debug_crash_flags, "TICK_CREATED")
with _ScheduleLaunchContext(
remote_schedule, tick, instance, logger, tick_retention_settings
) as tick_context:
try:
check_for_debug_crash(schedule_debug_crash_flags, "TICK_HELD")
tick_context.add_log_key(tick_context.log_key)
yield from _schedule_runs_at_time(
workspace_process_context,
logger,
remote_schedule,
schedule_time,
timezone_str,
tick_context,
submit_threadpool_executor,
schedule_debug_crash_flags,
)
except Exception as e:
if isinstance(e, (DagsterUserCodeUnreachableError, DagsterCodeLocationLoadError)):
try:
raise DagsterUserCodeUnreachableError(
f"Unable to reach the user code server for schedule {schedule_name}."
" Schedule will resume execution once the server is available."
) from e
except:
error_data = DaemonErrorCapture.process_exception(
sys.exc_info(),
logger=logger,
log_message=f"Scheduler daemon caught an error for schedule {remote_schedule.name}",
)
tick_context.update_state(
TickStatus.FAILURE,
error=error_data,
# don't increment the failure count - retry forever until the server comes back up
# or the schedule is turned off
failure_count=tick_context.failure_count,
consecutive_failure_count=tick_context.consecutive_failure_count + 1,
)
yield error_data
else:
error_data = DaemonErrorCapture.process_exception(
sys.exc_info(),
logger=logger,
log_message=f"Scheduler daemon caught an error for schedule {remote_schedule.name}",
)
tick_context.update_state(
TickStatus.FAILURE,
error=error_data,
failure_count=tick_context.failure_count + 1,
consecutive_failure_count=tick_context.consecutive_failure_count + 1,
)
yield error_data
# Plan to run the same tick again using the schedule timestamp
# as both the next_iteration_timestamp and the last_iteration_timestmap
# (to ensure that the scheduler doesn't accidentally skip past it)
yield ScheduleIterationTimes(
cron_schedule=remote_schedule.cron_schedule,
next_iteration_timestamp=schedule_time.timestamp(),
last_iteration_timestamp=schedule_time.timestamp(),
)
return
# now log the iteration timestamp
next_checkpoint_timestamp = _write_and_get_next_checkpoint_timestamp(
instance,
schedule_state,
instigator_data,
end_datetime_utc.timestamp(),
)
next_iteration_timestamp = min(
check.not_none(next_iteration_timestamp), next_checkpoint_timestamp
)
yield ScheduleIterationTimes(
cron_schedule=remote_schedule.cron_schedule,
next_iteration_timestamp=next_iteration_timestamp,
last_iteration_timestamp=now_timestamp,
)
return
| ScheduleIterationTimes |
python | kamyu104__LeetCode-Solutions | Python/minimum-operations-to-make-array-values-equal-to-k.py | {
"start": 67,
"end": 309
} | class ____(object):
def minOperations(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: int
"""
mn = min(nums)
return len(set(nums))-int(mn == k) if mn >= k else -1
| Solution |
python | huggingface__transformers | src/transformers/models/seggpt/modeling_seggpt.py | {
"start": 1258,
"end": 2805
} | class ____(ModelOutput):
r"""
last_hidden_state (`torch.FloatTensor` of shape `(batch_size, patch_height, patch_width, hidden_size)`):
Sequence of hidden-states at the output of the last layer of the model.
hidden_states (`tuple[torch.FloatTensor]`, `optional`, returned when `config.output_hidden_states=True`):
Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer)
of shape `(batch_size, patch_height, patch_width, hidden_size)`.
attentions (`tuple[torch.FloatTensor]`, `optional`, returned when `config.output_attentions=True`):
Tuple of *torch.FloatTensor* (one for each layer) of shape
`(batch_size, num_heads, seq_len, seq_len)`.
intermediate_hidden_states (`tuple[torch.FloatTensor]`, *optional*, returned when `config.intermediate_hidden_state_indices` is set):
Tuple of `torch.FloatTensor` of shape `(batch_size, patch_height, patch_width, hidden_size)`.
Each element in the Tuple corresponds to the output of the layer specified in `config.intermediate_hidden_state_indices`.
Additionally, each feature passes through a LayerNorm.
"""
last_hidden_state: torch.FloatTensor
hidden_states: Optional[tuple[torch.FloatTensor]] = None
attentions: Optional[tuple[torch.FloatTensor]] = None
intermediate_hidden_states: Optional[tuple[torch.FloatTensor]] = None
@dataclass
@auto_docstring(
custom_intro="""
Output type of [`SegGptImageSegmentationOutput`].
"""
)
| SegGptEncoderOutput |
python | pypa__hatch | tests/env/plugin/test_interface.py | {
"start": 4424,
"end": 7348
} | class ____:
def test_default(self, isolation, isolated_data_dir, platform, global_application):
config = {"project": {"name": "my_app", "version": "0.0.1"}}
project = Project(isolation, config=config)
environment = MockEnvironment(
isolation,
project.metadata,
"default",
project.config.envs["default"],
{},
isolated_data_dir,
isolated_data_dir,
platform,
0,
global_application,
)
assert environment.env_include == environment.env_include == []
def test_not_array(self, isolation, isolated_data_dir, platform, global_application):
config = {
"project": {"name": "my_app", "version": "0.0.1"},
"tool": {"hatch": {"envs": {"default": {"env-include": 9000}}}},
}
project = Project(isolation, config=config)
environment = MockEnvironment(
isolation,
project.metadata,
"default",
project.config.envs["default"],
{},
isolated_data_dir,
isolated_data_dir,
platform,
0,
global_application,
)
with pytest.raises(TypeError, match="Field `tool.hatch.envs.default.env-include` must be an array"):
_ = environment.env_include
def test_pattern_not_string(self, isolation, isolated_data_dir, platform, global_application):
config = {
"project": {"name": "my_app", "version": "0.0.1"},
"tool": {"hatch": {"envs": {"default": {"env-include": [9000]}}}},
}
project = Project(isolation, config=config)
environment = MockEnvironment(
isolation,
project.metadata,
"default",
project.config.envs["default"],
{},
isolated_data_dir,
isolated_data_dir,
platform,
0,
global_application,
)
with pytest.raises(
TypeError, match="Pattern #1 of field `tool.hatch.envs.default.env-include` must be a string"
):
_ = environment.env_include
def test_correct(self, isolation, isolated_data_dir, platform, global_application):
config = {
"project": {"name": "my_app", "version": "0.0.1"},
"tool": {"hatch": {"envs": {"default": {"env-include": ["FOO*"]}}}},
}
project = Project(isolation, config=config)
environment = MockEnvironment(
isolation,
project.metadata,
"default",
project.config.envs["default"],
{},
isolated_data_dir,
isolated_data_dir,
platform,
0,
global_application,
)
assert environment.env_include == ["HATCH_BUILD_*", "FOO*"]
| TestEnvInclude |
python | huggingface__transformers | src/transformers/models/llava_onevision/modular_llava_onevision.py | {
"start": 9386,
"end": 26480
} | class ____(LlavaNextVideoModel):
def __init__(self, config):
super().__init__(config)
del self.vision_resampler
def pack_image_features(self, image_features, image_sizes, image_newline=None, vision_aspect_ratio="anyres_max_9"):
"""
Reshape, unpad and then pack each image_feature into a single image_features tensor containing all visual vectors.
Args:
image_features (`list[torch.Tensor]` of length num_images, each of shape `(num_patches, image_length, embed_dim)`)
List of image feature tensor, each contains all the visual feature of all patches.
image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
Actual image size of each images (H, W).
image_newline (`torch.Tensor` of shape `(embed_dim)`)
New line embedding vector.
vision_aspect_ratio (`str`, *optional*, "anyres_max_9"):
Aspect ratio used when processong image features. The default value is "anyres_max_9".
Returns:
image_features (`torch.Tensor` of shape `(all_feat_len, embed_dim)`)
feature_lens (`list[int]`)
token length of each image in image_features
"""
new_image_features = []
feature_lens = []
for image_idx, image_feature in enumerate(image_features):
if image_feature.shape[0] > 1:
base_image_feature = image_feature[0]
image_feature = image_feature[1:]
height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
if height * width != base_image_feature.shape[0]:
raise ValueError("The number of patches is not consistent with the image size.")
num_patch_height, num_patch_width = get_anyres_image_grid_shape(
image_sizes[image_idx],
self.config.image_grid_pinpoints,
self.config.vision_config.image_size,
)
image_feature = image_feature.view(num_patch_height, num_patch_width, height, width, -1)
image_feature = image_feature.permute(4, 0, 2, 1, 3).contiguous()
image_feature = image_feature.flatten(1, 2).flatten(2, 3)
image_feature = unpad_image(image_feature, image_sizes[image_idx])
max_num_patches = int(vision_aspect_ratio.strip("anyres_max_"))
channels, curr_height, curr_width = image_feature.shape
ratio = math.sqrt(curr_height * curr_width / (max_num_patches * height**2))
if ratio > 1.1:
image_feature = image_feature[None]
image_feature = nn.functional.interpolate(
image_feature, [int(curr_height // ratio), int(curr_width // ratio)], mode="bilinear"
)[0]
if image_newline is not None:
image_feature = torch.cat(
(
image_feature,
image_newline[:, None, None]
.expand(*image_feature.shape[:-1], 1)
.to(image_feature.device, image_feature.dtype),
),
dim=-1,
)
image_feature = image_feature.flatten(1, 2).transpose(0, 1)
image_feature = torch.cat((base_image_feature, image_feature), dim=0)
else:
image_feature = image_feature[0]
if image_newline is not None:
image_feature = torch.cat((image_feature, image_newline[None].to(image_feature)), dim=0)
new_image_features.append(image_feature)
feature_lens.append(image_feature.size(0))
feature_lens = torch.tensor(feature_lens, dtype=torch.long, device=image_features[0].device)
return new_image_features, feature_lens
def apply_pooling(self, image_features):
height = width = self.config.vision_config.image_size // self.config.vision_config.patch_size
batch_frames, seq_len, dim = image_features.shape
image_features = image_features.view(batch_frames, height, width, -1)
image_features = image_features.permute(0, 3, 1, 2).contiguous()
height, width = image_features.shape[2:]
scaled_shape = [math.ceil(height / 2), math.ceil(width / 2)]
image_features = nn.functional.interpolate(image_features, size=scaled_shape, mode="bilinear")
image_features = image_features.permute(0, 2, 3, 1)
image_features = image_features.view(batch_frames, -1, dim)
return image_features
def get_image_features(
self,
pixel_values: torch.FloatTensor,
image_sizes: torch.Tensor,
vision_feature_layer: Optional[Union[int, list[int]]] = None,
vision_feature_select_strategy: Optional[str] = None,
vision_aspect_ratio: Optional[str] = None,
batch_num_images: Optional[torch.LongTensor] = None,
):
"""
Obtains image last hidden states from the vision tower and apply multimodal projection.
Args:
pixel_values (`torch.FloatTensor]` of shape `(batch_size, num_patches, channels, height, width)`)
The tensors corresponding to the input images.
image_sizes (`torch.Tensor` of shape `(num_images, 2)`)
Actual image size of each images (H, W).
vision_feature_layer (`Union[int, list[int]]`):
The index of the layer to select the vision feature. If multiple indices are provided,
the vision feature of the corresponding indices will be concatenated to form the
vision features.
vision_feature_select_strategy (`str`):
The feature selection strategy used to select the vision feature from the vision backbone.
Can be one of `"default"` or `"full"`
batch_num_images (`torch.LongTensor`, *optional*):
Number of images in each sample.
Returns:
image_features (list[`torch.Tensor`]): List of image feature tensor, each contains all the visual feature of all patches
and are of shape `(num_patches, image_length, embed_dim)`).
"""
vision_feature_layer = (
vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
)
vision_feature_select_strategy = (
vision_feature_select_strategy
if vision_feature_select_strategy is not None
else self.config.vision_feature_select_strategy
)
vision_aspect_ratio = (
vision_aspect_ratio if vision_aspect_ratio is not None else self.config.vision_aspect_ratio
)
# ! infer image_num_patches from image_sizes
if batch_num_images is None:
# treat this as a single-image case for backward compatibility
need_patching = [True] * len(image_sizes)
else:
need_patching = [n == 1 for n in batch_num_images for _ in range(n)]
image_num_patches = [
image_size_to_num_patches(
image_size=imsize,
grid_pinpoints=self.config.image_grid_pinpoints,
patch_size=self.config.vision_config.image_size,
)
if should_patch
else 1
for imsize, should_patch in zip(image_sizes, need_patching)
]
if pixel_values.dim() == 5:
# stacked if input is (batch_size, num_patches, num_channels, height, width)
_pixel_values_list = [pix_val[:num_patch] for pix_val, num_patch in zip(pixel_values, image_num_patches)]
pixel_values = torch.cat(_pixel_values_list, dim=0)
elif pixel_values.dim() != 4:
# otherwise has to be stacked from list of (num_patches, num_channels, height, width)
raise ValueError(f"pixel_values of shape {pixel_values.shape}, expect to be of 4 or 5 dimensions")
image_features = self.vision_tower(pixel_values, output_hidden_states=True)
# If we have one vision feature layer, return the corresponding hidden states,
# otherwise, select the hidden states of each feature layer and concatenate them
if isinstance(vision_feature_layer, int):
selected_image_feature = image_features.hidden_states[vision_feature_layer]
else:
hs_pool = [image_features.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
selected_image_feature = torch.cat(hs_pool, dim=-1)
if vision_feature_select_strategy == "default":
selected_image_feature = selected_image_feature[:, 1:]
image_features = self.multi_modal_projector(selected_image_feature)
image_features = torch.split(image_features, image_num_patches, dim=0)
image_features, feature_lens = self.pack_image_features(
image_features,
image_sizes,
image_newline=self.image_newline,
vision_aspect_ratio=vision_aspect_ratio,
)
return image_features
def get_video_features(
self,
pixel_values: torch.FloatTensor,
vision_feature_layer: Union[int, list[int]],
vision_feature_select_strategy: str,
):
"""
Obtains video last hidden states from the vision tower, apply multimodal projection and pooling.
Args:
pixel_values (`torch.FloatTensor]` of shape `(batch_size, num_frames, channels, height, width)`)
The tensors corresponding to the input video.
vision_feature_layer (`Union[int, list[int]], *optional*, defaults to -2`):
The index of the layer to select the vision feature. If multiple indices are provided,
the vision feature of the corresponding indices will be concatenated to form the
vision features.
vision_feature_select_strategy (`str`):
The feature selection strategy used to select the vision feature from the vision backbone.
Can be one of `"default"` or `"full"`
Returns:
video_features (list[`torch.Tensor`]): List of video feature tensor, each contains all the visual feature of all patches
and are of shape `(num_videos, video_length, embed_dim)`).
"""
batch_size, frames, channels, height, width = pixel_values.shape
pixel_values = pixel_values.view(batch_size * frames, channels, height, width)
video_features = self.vision_tower(pixel_values, output_hidden_states=True)
# If we have one vision feature layer, return the corresponding hidden states,
# otherwise, select the hidden states of each feature layer and concatenate them
if isinstance(vision_feature_layer, int):
selected_video_feature = video_features.hidden_states[vision_feature_layer]
else:
hs_pool = [video_features.hidden_states[layer_idx] for layer_idx in vision_feature_layer]
selected_video_feature = torch.cat(hs_pool, dim=-1)
if vision_feature_select_strategy == "default":
selected_video_feature = selected_video_feature[:, 1:]
video_features = self.multi_modal_projector(selected_video_feature)
video_features = self.apply_pooling(video_features)
video_features = video_features.reshape(batch_size, frames * video_features.shape[1], -1)
return video_features
def forward(
self,
input_ids: Optional[torch.LongTensor] = None,
pixel_values: Optional[torch.FloatTensor] = None,
image_sizes: Optional[torch.LongTensor] = None,
pixel_values_videos: Optional[torch.FloatTensor] = None,
image_sizes_videos: Optional[torch.LongTensor] = None,
attention_mask: Optional[torch.Tensor] = None,
position_ids: Optional[torch.LongTensor] = None,
past_key_values: Optional[Cache] = None,
inputs_embeds: Optional[torch.FloatTensor] = None,
vision_feature_layer: Optional[Union[int, list[int]]] = None,
vision_feature_select_strategy: Optional[str] = None,
vision_aspect_ratio: Optional[str] = None,
batch_num_images: Optional[torch.LongTensor] = None,
use_cache: Optional[bool] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
cache_position: Optional[torch.LongTensor] = None,
**kwargs: Unpack[FlashAttentionKwargs],
) -> Union[tuple, LlavaOnevisionModelOutputWithPast]:
r"""
image_sizes_videos (`torch.LongTensor` of shape `(batch_size, frames, 2)`, *optional*):
The sizes of the videos in the batch, being (height, width) for each frame in the video.
vision_aspect_ratio (`str`, *optional*, defaults to `"anyres_max_9"`):
Aspect ratio used when processong image features. The default value is "anyres_max_9".
batch_num_images (`torch.LongTensor`, *optional*):
Number of images in each sample.
"""
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
vision_feature_layer = (
vision_feature_layer if vision_feature_layer is not None else self.config.vision_feature_layer
)
vision_feature_select_strategy = (
vision_feature_select_strategy
if vision_feature_select_strategy is not None
else self.config.vision_feature_select_strategy
)
vision_aspect_ratio = (
vision_aspect_ratio if vision_aspect_ratio is not None else self.config.vision_aspect_ratio
)
if (input_ids is None) ^ (inputs_embeds is not None):
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
if inputs_embeds is None:
inputs_embeds = self.get_input_embeddings()(input_ids)
# Images are processed with Anyres
if pixel_values is not None:
image_features = self.get_image_features(
pixel_values,
image_sizes,
vision_feature_layer=vision_feature_layer,
vision_feature_select_strategy=vision_feature_select_strategy,
batch_num_images=batch_num_images,
)
image_features = torch.cat(image_features, dim=0)
image_features = image_features.to(inputs_embeds.device, inputs_embeds.dtype)
special_image_mask, _ = self.get_placeholder_mask(
input_ids, inputs_embeds=inputs_embeds, image_features=image_features
)
inputs_embeds = inputs_embeds.masked_scatter(special_image_mask, image_features)
# Video are simply embedded and further pooled to decrease seq len
if pixel_values_videos is not None:
video_features = self.get_video_features(
pixel_values_videos,
vision_feature_layer=vision_feature_layer,
vision_feature_select_strategy=vision_feature_select_strategy,
)
image_newline = (
self.image_newline[None, None, :].repeat(video_features.shape[0], 1, 1).to(video_features.device)
)
video_features = torch.cat((video_features, image_newline), dim=1)
video_features = video_features.flatten(0, 1).to(inputs_embeds.device, inputs_embeds.dtype)
_, special_video_mask = self.get_placeholder_mask(
input_ids, inputs_embeds=inputs_embeds, video_features=video_features
)
inputs_embeds = inputs_embeds.masked_scatter(special_video_mask, video_features)
outputs = self.language_model(
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
inputs_embeds=inputs_embeds,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=True,
cache_position=cache_position,
**kwargs,
)
return LlavaOnevisionModelOutputWithPast(
last_hidden_state=outputs.last_hidden_state,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
image_hidden_states=image_features if pixel_values is not None else None,
video_hidden_states=video_features if pixel_values_videos is not None else None,
)
| LlavaOnevisionModel |
python | facebook__pyre-check | tools/upgrade/errors.py | {
"start": 768,
"end": 7498
} | class ____(libcst.CSTTransformer):
def leave_SimpleWhitespace(
self,
original_node: libcst.SimpleWhitespace,
updated_node: libcst.SimpleWhitespace,
) -> Union[libcst.SimpleWhitespace, libcst.ParenthesizedWhitespace]:
whitespace = original_node.value.replace("\\", "")
if "\n" in whitespace:
first_line = libcst.TrailingWhitespace(
whitespace=libcst.SimpleWhitespace(
value=whitespace.split("\n")[0].rstrip()
),
comment=None,
newline=libcst.Newline(),
)
last_line = libcst.SimpleWhitespace(value=whitespace.split("\n")[1])
return libcst.ParenthesizedWhitespace(
first_line=first_line, empty_lines=[], indent=True, last_line=last_line
)
return updated_node
@staticmethod
def basic_parenthesize(
node: libcst.CSTNode,
whitespace: Optional[libcst.BaseParenthesizableWhitespace] = None,
) -> libcst.CSTNode:
if not hasattr(node, "lpar"):
return node
if whitespace:
return node.with_changes(
lpar=[libcst.LeftParen(whitespace_after=whitespace)],
rpar=[libcst.RightParen()],
)
return node.with_changes(lpar=[libcst.LeftParen()], rpar=[libcst.RightParen()])
def leave_Assert(
self, original_node: libcst.Assert, updated_node: libcst.Assert
) -> libcst.Assert:
test = updated_node.test
message = updated_node.msg
comma = updated_node.comma
if not test:
return updated_node
if message and isinstance(comma, libcst.Comma):
message = LineBreakTransformer.basic_parenthesize(
message, comma.whitespace_after
)
comma = comma.with_changes(
whitespace_after=libcst.SimpleWhitespace(
value=" ",
)
)
assert_whitespace = updated_node.whitespace_after_assert
if isinstance(assert_whitespace, libcst.ParenthesizedWhitespace):
return updated_node.with_changes(
test=LineBreakTransformer.basic_parenthesize(test, assert_whitespace),
msg=message,
comma=comma,
whitespace_after_assert=libcst.SimpleWhitespace(value=" "),
)
return updated_node.with_changes(
test=LineBreakTransformer.basic_parenthesize(test),
msg=message,
comma=comma,
)
def leave_Assign(
self, original_node: libcst.Assign, updated_node: libcst.Assign
) -> libcst.Assign:
assign_value = updated_node.value
assign_whitespace = updated_node.targets[-1].whitespace_after_equal
if libcst_matchers.matches(
assign_whitespace, libcst_matchers.ParenthesizedWhitespace()
):
adjusted_target = updated_node.targets[-1].with_changes(
whitespace_after_equal=libcst.SimpleWhitespace(value=" ")
)
updated_targets = list(updated_node.targets[:-1])
updated_targets.append(adjusted_target)
return updated_node.with_changes(
targets=tuple(updated_targets),
value=LineBreakTransformer.basic_parenthesize(
assign_value, assign_whitespace
),
)
return updated_node.with_changes(
value=LineBreakTransformer.basic_parenthesize(assign_value)
)
def leave_AnnAssign(
self, original_node: libcst.AnnAssign, updated_node: libcst.AnnAssign
) -> libcst.AnnAssign:
assign_value = updated_node.value
equal = updated_node.equal
if not isinstance(equal, libcst.AssignEqual):
return updated_node
assign_whitespace = equal.whitespace_after
updated_value = (
LineBreakTransformer.basic_parenthesize(assign_value, assign_whitespace)
if assign_value
else None
)
if libcst_matchers.matches(
assign_whitespace, libcst_matchers.ParenthesizedWhitespace()
):
updated_equal = equal.with_changes(
whitespace_after=libcst.SimpleWhitespace(value=" ")
)
return updated_node.with_changes(
equal=updated_equal,
value=updated_value,
)
return updated_node.with_changes(value=updated_value)
def leave_Del(
self, original_node: libcst.Del, updated_node: libcst.Del
) -> libcst.Del:
delete_target = updated_node.target
delete_whitespace = updated_node.whitespace_after_del
if isinstance(delete_whitespace, libcst.ParenthesizedWhitespace):
return updated_node.with_changes(
target=LineBreakTransformer.basic_parenthesize(
delete_target, delete_whitespace
),
whitespace_after_del=libcst.SimpleWhitespace(value=" "),
)
return updated_node.with_changes(
target=LineBreakTransformer.basic_parenthesize(delete_target)
)
def leave_Raise(
self, original_node: libcst.Raise, updated_node: libcst.Raise
) -> libcst.Raise:
exception = updated_node.exc
if not exception:
return updated_node
raise_whitespace = updated_node.whitespace_after_raise
if isinstance(raise_whitespace, libcst.ParenthesizedWhitespace):
return updated_node.with_changes(
exc=LineBreakTransformer.basic_parenthesize(
exception, raise_whitespace
),
whitespace_after_raise=libcst.SimpleWhitespace(value=" "),
)
return updated_node.with_changes(
exc=LineBreakTransformer.basic_parenthesize(exception)
)
def leave_Return(
self, original_node: libcst.Return, updated_node: libcst.Return
) -> libcst.Return:
return_value = updated_node.value
if not return_value:
return updated_node
return_whitespace = updated_node.whitespace_after_return
if isinstance(return_whitespace, libcst.ParenthesizedWhitespace):
return updated_node.with_changes(
value=LineBreakTransformer.basic_parenthesize(
return_value, return_whitespace
),
whitespace_after_return=libcst.SimpleWhitespace(value=" "),
)
return updated_node.with_changes(
value=LineBreakTransformer.basic_parenthesize(return_value)
)
| LineBreakTransformer |
python | euske__pdfminer | pdfminer/pdffont.py | {
"start": 20869,
"end": 22215
} | class ____(PDFSimpleFont):
def __init__(self, rsrcmgr, spec):
try:
self.basefont = literal_name(spec['BaseFont'])
except KeyError:
if STRICT:
raise PDFFontError('BaseFont is missing')
self.basefont = 'unknown'
try:
(descriptor, widths) = FontMetricsDB.get_metrics(self.basefont)
except KeyError:
descriptor = dict_value(spec.get('FontDescriptor', {}))
firstchar = int_value(spec.get('FirstChar', 0))
#lastchar = int_value(spec.get('LastChar', 255))
widths = list_value(spec.get('Widths', [0]*256))
widths = dict((i+firstchar, w) for (i, w) in enumerate(widths))
PDFSimpleFont.__init__(self, descriptor, widths, spec)
if 'Encoding' not in spec and 'FontFile' in descriptor:
# try to recover the missing encoding info from the font file.
self.fontfile = stream_value(descriptor.get('FontFile'))
length1 = int_value(self.fontfile['Length1'])
data = self.fontfile.get_data()[:length1]
parser = Type1FontHeaderParser(BytesIO(data))
self.cid2unicode = parser.get_encoding()
return
def __repr__(self):
return '<PDFType1Font: basefont=%r>' % self.basefont
# PDFTrueTypeFont
| PDFType1Font |
python | numba__numba | numba/tests/test_func_lifetime.py | {
"start": 3931,
"end": 4908
} | class ____(TestCase):
def test_double_free(self):
from numba import njit
import numpy as np
# This is the function that causes the crash
@njit
def is_point_in_polygons(point, polygons):
num_polygons = polygons.shape[0]
if num_polygons != 0:
# An extra decref is inserted in this block
intentionally_unused_variable = polygons[0]
return 0
# This function creates some NRT objects for the previous function
# to corrupt.
@njit
def dummy():
return np.empty(10, dtype=np.int64)
polygons = np.array([[[0, 1]]])
points = np.array([[-1.5, 0.5]])
a = dummy()
is_point_in_polygons(points[0], polygons)
b = dummy()
# Crash happens at second call
is_point_in_polygons(points[0], polygons)
c = dummy()
if __name__ == '__main__':
unittest.main()
| TestLifeTimeIssue |
python | HypothesisWorks__hypothesis | hypothesis-python/tests/django/toystore/models.py | {
"start": 1163,
"end": 1229
} | class ____(models.Model):
customish = CustomishField()
| Customish |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-github/source_github/github_schema.py | {
"start": 827963,
"end": 828685
} | class ____(sgqlc.types.relay.Connection):
"""The connection type for Package."""
__schema__ = github_schema
__field_names__ = ("edges", "nodes", "page_info", "total_count")
edges = sgqlc.types.Field(sgqlc.types.list_of("PackageEdge"), graphql_name="edges")
"""A list of edges."""
nodes = sgqlc.types.Field(sgqlc.types.list_of("Package"), graphql_name="nodes")
"""A list of nodes."""
page_info = sgqlc.types.Field(sgqlc.types.non_null("PageInfo"), graphql_name="pageInfo")
"""Information to aid in pagination."""
total_count = sgqlc.types.Field(sgqlc.types.non_null(Int), graphql_name="totalCount")
"""Identifies the total count of items in the connection."""
| PackageConnection |
python | airbytehq__airbyte | airbyte-integrations/connectors/source-braintree/source_braintree/schemas/transaction.py | {
"start": 923,
"end": 1053
} | class ____(BaseModel):
billing_period_end_date: Optional[date]
billing_period_start_date: Optional[date]
| SubscriptionDetails |
python | getsentry__sentry | src/sentry/integrations/github/webhook.py | {
"start": 12387,
"end": 20811
} | class ____(GitHubWebhook):
"""https://developer.github.com/v3/activity/events/types/#pushevent"""
@property
def event_type(self) -> IntegrationWebhookEventType:
return IntegrationWebhookEventType.PUSH
def should_ignore_commit(self, commit: Mapping[str, Any]) -> bool:
return GitHubRepositoryProvider.should_ignore_commit(commit["message"])
def _handle(
self,
integration: RpcIntegration,
event: Mapping[str, Any],
**kwargs,
) -> None:
authors = {}
if not ((organization := kwargs.get("organization")) and (repo := kwargs.get("repo"))):
raise ValueError("Missing organization and repo")
client = integration.get_installation(organization_id=organization.id).get_client()
gh_username_cache: MutableMapping[str, str | None] = {}
languages = set()
for commit in event["commits"]:
if not commit["distinct"]:
continue
if self.should_ignore_commit(commit):
continue
author_email = commit["author"]["email"]
if "@" not in author_email:
author_email = f"{author_email[:65]}@localhost"
# try to figure out who anonymous emails are
elif self.is_anonymous_email(author_email):
gh_username: str | None = commit["author"].get("username")
# bot users don't have usernames
if gh_username:
external_id = self.get_external_id(gh_username)
if gh_username in gh_username_cache:
author_email = gh_username_cache[gh_username] or author_email
else:
try:
commit_author = CommitAuthor.objects.get(
external_id=external_id, organization_id=organization.id
)
except CommitAuthor.DoesNotExist:
commit_author = None
if commit_author is not None and not self.is_anonymous_email(
commit_author.email
):
author_email = commit_author.email
gh_username_cache[gh_username] = author_email
else:
try:
gh_user = client.get_user(gh_username)
except ApiError:
logger.warning("Github user is missing.")
else:
# even if we can't find a user, set to none so we
# don't re-query
gh_username_cache[gh_username] = None
identity_user = None
# TODO(hybrid-cloud): Combine into a single RPC call if possible
identity = identity_service.get_identity(
filter={
"identity_ext_id": gh_user["id"],
"provider_type": self.provider,
"provider_ext_id": self.get_idp_external_id(
integration, kwargs.get("host")
),
}
)
if identity is not None:
identity_user = user_service.get_user(user_id=identity.user_id)
if identity_user is not None:
author_email = identity_user.email
gh_username_cache[gh_username] = author_email
if commit_author is not None:
try:
with transaction.atomic(
router.db_for_write(CommitAuthor)
):
commit_author.update(
email=author_email, external_id=external_id
)
except IntegrityError:
pass
if commit_author is not None:
authors[author_email] = commit_author
# TODO(dcramer): we need to deal with bad values here, but since
# its optional, lets just throw it out for now
if len(author_email) > 75:
author = None
elif author_email not in authors:
authors[author_email] = author = CommitAuthor.objects.get_or_create(
organization_id=organization.id,
email=author_email,
defaults={"name": commit["author"]["name"][:128]},
)[0]
update_kwargs = {}
if author.name != commit["author"]["name"][:128]:
update_kwargs["name"] = commit["author"]["name"][:128]
gh_username = commit["author"].get("username")
if gh_username:
external_id = self.get_external_id(gh_username)
if author.external_id != external_id and not self.is_anonymous_email(
author.email
):
update_kwargs["external_id"] = external_id
if update_kwargs:
try:
with transaction.atomic(router.db_for_write(CommitAuthor)):
author.update(**update_kwargs)
except IntegrityError:
pass
else:
author = authors[author_email]
if author:
author.preload_users()
try:
with transaction.atomic(router.db_for_write(Commit)):
c = Commit.objects.create(
organization_id=organization.id,
repository_id=repo.id,
key=commit["id"],
message=commit["message"],
author=author,
date_added=parse_date(commit["timestamp"]).astimezone(timezone.utc),
)
file_changes = []
for fname in commit["added"]:
languages.add(get_file_language(fname))
file_changes.append(
CommitFileChange(
organization_id=organization.id,
commit_id=c.id,
filename=fname,
type="A",
)
)
for fname in commit["removed"]:
languages.add(get_file_language(fname))
file_changes.append(
CommitFileChange(
organization_id=organization.id,
commit_id=c.id,
filename=fname,
type="D",
)
)
for fname in commit["modified"]:
languages.add(get_file_language(fname))
file_changes.append(
CommitFileChange(
organization_id=organization.id,
commit_id=c.id,
filename=fname,
type="M",
)
)
if file_changes:
CommitFileChange.objects.bulk_create(file_changes)
post_bulk_create(file_changes)
except IntegrityError:
pass
languages.discard(None)
repo.languages = list(set(repo.languages or []).union(languages))
repo.save()
| PushEventWebhook |
python | getsentry__sentry | src/sentry/conduit/endpoints/organization_conduit_demo.py | {
"start": 608,
"end": 780
} | class ____(serializers.Serializer):
token = serializers.CharField()
channel_id = serializers.UUIDField()
url = serializers.URLField()
| ConduitCredentialsSerializer |
python | huggingface__transformers | src/transformers/models/janus/configuration_janus.py | {
"start": 1333,
"end": 5678
} | class ____(PreTrainedConfig):
r"""
This is the configuration class to store the configuration of a [`JanusVisionModel`]. It is used to instantiate a
`JanusVisionModel` according to the specified arguments, defining the model architecture.
Configuration objects inherit from [`PreTrainedConfig`] and can be used to control the model outputs. Read the
documentation from [`PreTrainedConfig`] for more information.
Args:
hidden_size (`int`, *optional*, defaults to 1024):
Dimensionality of the encoder layers and the pooler layer.
num_hidden_layers (`int`, *optional*, defaults to 24):
Number of hidden layers in the Transformer encoder.
num_attention_heads (`int`, *optional*, defaults to 16):
Number of attention heads for each attention layer in the Transformer encoder.
num_channels (`int`, *optional*, defaults to 3):
The number of input channels.
patch_size (`int`, *optional*, defaults to 16):
The size (resolution) of each patch.
image_size (`int`, *optional*, defaults to 384):
The size (resolution) of each image.
attention_dropout (`float`, *optional*, defaults to 0.0):
Dropout probability for attention weights.
layer_norm_eps (`float`, *optional*, defaults to 1e-06):
The epsilon used by the layer normalization layers.
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
`"relu"`, `"selu"`, and `"gelu_new"` are supported.
mlp_ratio (`float`, *optional*, defaults to 4.0):
Ratio of MLP hidden dimensionality to embedding dimensionality.
attention_bias (`bool`, *optional*, defaults to `True`):
Whether to add a bias to the queries, keys, and values in the attention layers.
hidden_dropout_rate (`float`, *optional*, defaults to 0.0):
The dropout probability for fully connected layers in the encoder.
projection_dim (`int`, *optional*, defaults to 2048):
Dimensionality of the MLP projection head.
projection_dropout (`float`, *optional*, defaults to 0.0):
Dropout probability for the projection layer.
use_qk_norm (`bool`, *optional*, defaults to `False`):
Whether to normalize the query and key matrices.
initializer_range (`float`, *optional*, defaults to 0.02):
The standard deviation of the truncated normal initializer for initializing all weight matrices.
depth (`int`, *optional*, defaults to 2):
Number of hidden layers in the aligner module.
num_image_tokens (`int`, *optional*, defaults to 576):
Number of image tokens.
"""
model_type = "janus_vision_model"
base_config_key = "vision_config"
def __init__(
self,
hidden_size=1024,
num_hidden_layers=24,
num_attention_heads=16,
num_channels=3,
patch_size=16,
image_size=384,
attention_dropout=0.0,
layer_norm_eps=1e-6,
hidden_act="gelu",
mlp_ratio=4.0,
attention_bias=True,
hidden_dropout_rate=0.0,
projection_dim=2048,
projection_dropout=0.0,
use_qk_norm=False,
initializer_range=0.02,
depth=2,
num_image_tokens=576,
**kwargs,
):
super().__init__(**kwargs)
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.num_channels = num_channels
self.patch_size = patch_size
self.image_size = image_size
self.attention_dropout = attention_dropout
self.layer_norm_eps = layer_norm_eps
self.hidden_act = hidden_act
self.mlp_ratio = mlp_ratio
self.attention_bias = attention_bias
self.hidden_dropout_rate = hidden_dropout_rate
self.projection_dim = projection_dim
self.projection_dropout = projection_dropout
self.use_qk_norm = use_qk_norm
self.initializer_range = initializer_range
self.depth = depth
self.num_image_tokens = num_image_tokens
| JanusVisionConfig |
python | tornadoweb__tornado | tornado/test/web_test.py | {
"start": 40018,
"end": 56879
} | class ____(WebTestCase):
# The expected SHA-512 hash of robots.txt, used in tests that call
# StaticFileHandler.get_version
robots_txt_hash = (
b"63a36e950e134b5217e33c763e88840c10a07d80e6057d92b9ac97508de7fb1f"
b"a6f0e9b7531e169657165ea764e8963399cb6d921ffe6078425aaafe54c04563"
)
static_dir = os.path.join(os.path.dirname(__file__), "static")
def get_handlers(self):
class StaticUrlHandler(RequestHandler):
def get(self, path):
with_v = int(self.get_argument("include_version", "1"))
self.write(self.static_url(path, include_version=with_v))
class AbsoluteStaticUrlHandler(StaticUrlHandler):
include_host = True
class OverrideStaticUrlHandler(RequestHandler):
def get(self, path):
do_include = bool(self.get_argument("include_host"))
self.include_host = not do_include
regular_url = self.static_url(path)
override_url = self.static_url(path, include_host=do_include)
if override_url == regular_url:
return self.write(str(False))
protocol = self.request.protocol + "://"
protocol_length = len(protocol)
check_regular = regular_url.find(protocol, 0, protocol_length)
check_override = override_url.find(protocol, 0, protocol_length)
if do_include:
result = check_override == 0 and check_regular == -1
else:
result = check_override == -1 and check_regular == 0
self.write(str(result))
return [
("/static_url/(.*)", StaticUrlHandler),
("/abs_static_url/(.*)", AbsoluteStaticUrlHandler),
("/override_static_url/(.*)", OverrideStaticUrlHandler),
("/root_static/(.*)", StaticFileHandler, dict(path="/")),
]
def get_app_kwargs(self):
return dict(static_path=relpath("static"))
def test_static_files(self):
response = self.fetch("/robots.txt")
self.assertIn(b"Disallow: /", response.body)
response = self.fetch("/static/robots.txt")
self.assertIn(b"Disallow: /", response.body)
self.assertEqual(response.headers.get("Content-Type"), "text/plain")
def test_static_files_cacheable(self):
# Test that the version parameter triggers cache-control headers. This
# test is pretty weak but it gives us coverage of the code path which
# was important for detecting the deprecation of datetime.utcnow.
response = self.fetch("/robots.txt?v=12345")
self.assertIn(b"Disallow: /", response.body)
self.assertIn("Cache-Control", response.headers)
self.assertIn("Expires", response.headers)
def test_static_compressed_files(self):
response = self.fetch("/static/sample.xml.gz")
self.assertEqual(response.headers.get("Content-Type"), "application/gzip")
response = self.fetch("/static/sample.xml.bz2")
self.assertEqual(
response.headers.get("Content-Type"), "application/octet-stream"
)
# make sure the uncompressed file still has the correct type
response = self.fetch("/static/sample.xml")
self.assertIn(
response.headers.get("Content-Type"), {"text/xml", "application/xml"}
)
def test_static_windows_special_filenames(self):
# Windows has some magic filenames that are special and (in some ways) "exist"
# in every directory. These filenames are used to access stdio and hardware
# devices and so should not be served as static files.
filenames = [
"CON",
"PRN",
"AUX",
"NUL",
"COM1",
"LPT1",
]
for filename in filenames:
with self.subTest(filename=filename):
response = self.fetch(f"/static/{filename}")
# The exact behavior of these filenames differs across versions of
# Windows and Python.
# https://github.com/python/cpython/issues/90520#issuecomment-1093942179
# This sometimes hits the "file not in static root directory" check (which
# returns 403) and sometimes the "file does not exist" check (which returns 404).
# Either outcome is fine as long as we don't actually try to serve the file.
self.assertIn(response.code, (404, 403))
def test_static_url(self):
response = self.fetch("/static_url/robots.txt")
self.assertEqual(response.body, b"/static/robots.txt?v=" + self.robots_txt_hash)
def test_absolute_static_url(self):
response = self.fetch("/abs_static_url/robots.txt")
self.assertEqual(
response.body,
(utf8(self.get_url("/")) + b"static/robots.txt?v=" + self.robots_txt_hash),
)
def test_relative_version_exclusion(self):
response = self.fetch("/static_url/robots.txt?include_version=0")
self.assertEqual(response.body, b"/static/robots.txt")
def test_absolute_version_exclusion(self):
response = self.fetch("/abs_static_url/robots.txt?include_version=0")
self.assertEqual(response.body, utf8(self.get_url("/") + "static/robots.txt"))
def test_include_host_override(self):
self._trigger_include_host_check(False)
self._trigger_include_host_check(True)
def _trigger_include_host_check(self, include_host):
path = "/override_static_url/robots.txt?include_host=%s"
response = self.fetch(path % int(include_host))
self.assertEqual(response.body, utf8(str(True)))
def get_and_head(self, *args, **kwargs):
"""Performs a GET and HEAD request and returns the GET response.
Fails if any ``Content-*`` headers returned by the two requests
differ.
"""
head_response = self.fetch(*args, method="HEAD", **kwargs)
get_response = self.fetch(*args, method="GET", **kwargs)
content_headers = set()
for h in itertools.chain(head_response.headers, get_response.headers):
if h.startswith("Content-"):
content_headers.add(h)
for h in content_headers:
self.assertEqual(
head_response.headers.get(h),
get_response.headers.get(h),
"%s differs between GET (%s) and HEAD (%s)"
% (h, head_response.headers.get(h), get_response.headers.get(h)),
)
return get_response
def test_static_304_if_modified_since(self):
response1 = self.get_and_head("/static/robots.txt")
response2 = self.get_and_head(
"/static/robots.txt",
headers={"If-Modified-Since": response1.headers["Last-Modified"]},
)
self.assertEqual(response2.code, 304)
self.assertNotIn("Content-Length", response2.headers)
def test_static_304_if_none_match(self):
response1 = self.get_and_head("/static/robots.txt")
response2 = self.get_and_head(
"/static/robots.txt", headers={"If-None-Match": response1.headers["Etag"]}
)
self.assertEqual(response2.code, 304)
def test_static_304_etag_modified_bug(self):
response1 = self.get_and_head("/static/robots.txt")
response2 = self.get_and_head(
"/static/robots.txt",
headers={
"If-None-Match": '"MISMATCH"',
"If-Modified-Since": response1.headers["Last-Modified"],
},
)
self.assertEqual(response2.code, 200)
def test_static_304_if_modified_since_invalid(self):
response = self.get_and_head(
"/static/robots.txt",
headers={"If-Modified-Since": "!nv@l!d"},
)
self.assertEqual(response.code, 200)
def test_static_if_modified_since_pre_epoch(self):
# On windows, the functions that work with time_t do not accept
# negative values, and at least one client (processing.js) seems
# to use if-modified-since 1/1/1960 as a cache-busting technique.
response = self.get_and_head(
"/static/robots.txt",
headers={"If-Modified-Since": "Fri, 01 Jan 1960 00:00:00 GMT"},
)
self.assertEqual(response.code, 200)
def test_static_if_modified_since_time_zone(self):
# Instead of the value from Last-Modified, make requests with times
# chosen just before and after the known modification time
# of the file to ensure that the right time zone is being used
# when parsing If-Modified-Since.
stat = os.stat(relpath("static/robots.txt"))
response = self.get_and_head(
"/static/robots.txt",
headers={"If-Modified-Since": format_timestamp(stat.st_mtime - 1)},
)
self.assertEqual(response.code, 200)
response = self.get_and_head(
"/static/robots.txt",
headers={"If-Modified-Since": format_timestamp(stat.st_mtime + 1)},
)
self.assertEqual(response.code, 304)
def test_static_etag(self):
response = self.get_and_head("/static/robots.txt")
self.assertEqual(
utf8(response.headers.get("Etag")), b'"' + self.robots_txt_hash + b'"'
)
def test_static_with_range(self):
response = self.get_and_head(
"/static/robots.txt", headers={"Range": "bytes=0-9"}
)
self.assertEqual(response.code, 206)
self.assertEqual(response.body, b"User-agent")
self.assertEqual(
utf8(response.headers.get("Etag")), b'"' + self.robots_txt_hash + b'"'
)
self.assertEqual(response.headers.get("Content-Length"), "10")
self.assertEqual(response.headers.get("Content-Range"), "bytes 0-9/26")
def test_static_with_range_full_file(self):
response = self.get_and_head(
"/static/robots.txt", headers={"Range": "bytes=0-"}
)
# Note: Chrome refuses to play audio if it gets an HTTP 206 in response
# to ``Range: bytes=0-`` :(
self.assertEqual(response.code, 200)
robots_file_path = os.path.join(self.static_dir, "robots.txt")
with open(robots_file_path, encoding="utf-8") as f:
self.assertEqual(response.body, utf8(f.read()))
self.assertEqual(response.headers.get("Content-Length"), "26")
self.assertIsNone(response.headers.get("Content-Range"))
def test_static_with_range_full_past_end(self):
response = self.get_and_head(
"/static/robots.txt", headers={"Range": "bytes=0-10000000"}
)
self.assertEqual(response.code, 200)
robots_file_path = os.path.join(self.static_dir, "robots.txt")
with open(robots_file_path, encoding="utf-8") as f:
self.assertEqual(response.body, utf8(f.read()))
self.assertEqual(response.headers.get("Content-Length"), "26")
self.assertIsNone(response.headers.get("Content-Range"))
def test_static_with_range_partial_past_end(self):
response = self.get_and_head(
"/static/robots.txt", headers={"Range": "bytes=1-10000000"}
)
self.assertEqual(response.code, 206)
robots_file_path = os.path.join(self.static_dir, "robots.txt")
with open(robots_file_path, encoding="utf-8") as f:
self.assertEqual(response.body, utf8(f.read()[1:]))
self.assertEqual(response.headers.get("Content-Length"), "25")
self.assertEqual(response.headers.get("Content-Range"), "bytes 1-25/26")
def test_static_with_range_end_edge(self):
response = self.get_and_head(
"/static/robots.txt", headers={"Range": "bytes=22-"}
)
self.assertEqual(response.body, b": /\n")
self.assertEqual(response.headers.get("Content-Length"), "4")
self.assertEqual(response.headers.get("Content-Range"), "bytes 22-25/26")
def test_static_with_range_neg_end(self):
response = self.get_and_head(
"/static/robots.txt", headers={"Range": "bytes=-4"}
)
self.assertEqual(response.body, b": /\n")
self.assertEqual(response.headers.get("Content-Length"), "4")
self.assertEqual(response.headers.get("Content-Range"), "bytes 22-25/26")
def test_static_with_range_neg_past_start(self):
response = self.get_and_head(
"/static/robots.txt", headers={"Range": "bytes=-1000000"}
)
self.assertEqual(response.code, 200)
robots_file_path = os.path.join(self.static_dir, "robots.txt")
with open(robots_file_path, encoding="utf-8") as f:
self.assertEqual(response.body, utf8(f.read()))
self.assertEqual(response.headers.get("Content-Length"), "26")
self.assertIsNone(response.headers.get("Content-Range"))
def test_static_invalid_range(self):
response = self.get_and_head("/static/robots.txt", headers={"Range": "asdf"})
self.assertEqual(response.code, 200)
def test_static_unsatisfiable_range_zero_suffix(self):
response = self.get_and_head(
"/static/robots.txt", headers={"Range": "bytes=-0"}
)
self.assertEqual(response.headers.get("Content-Range"), "bytes */26")
self.assertEqual(response.code, 416)
def test_static_unsatisfiable_range_invalid_start(self):
response = self.get_and_head(
"/static/robots.txt", headers={"Range": "bytes=26"}
)
self.assertEqual(response.code, 416)
self.assertEqual(response.headers.get("Content-Range"), "bytes */26")
def test_static_unsatisfiable_range_end_less_than_start(self):
response = self.get_and_head(
"/static/robots.txt", headers={"Range": "bytes=10-3"}
)
self.assertEqual(response.code, 416)
self.assertEqual(response.headers.get("Content-Range"), "bytes */26")
def test_static_head(self):
response = self.fetch("/static/robots.txt", method="HEAD")
self.assertEqual(response.code, 200)
# No body was returned, but we did get the right content length.
self.assertEqual(response.body, b"")
self.assertEqual(response.headers["Content-Length"], "26")
self.assertEqual(
utf8(response.headers["Etag"]), b'"' + self.robots_txt_hash + b'"'
)
def test_static_head_range(self):
response = self.fetch(
"/static/robots.txt", method="HEAD", headers={"Range": "bytes=1-4"}
)
self.assertEqual(response.code, 206)
self.assertEqual(response.body, b"")
self.assertEqual(response.headers["Content-Length"], "4")
self.assertEqual(
utf8(response.headers["Etag"]), b'"' + self.robots_txt_hash + b'"'
)
def test_static_range_if_none_match(self):
response = self.get_and_head(
"/static/robots.txt",
headers={
"Range": "bytes=1-4",
"If-None-Match": b'"' + self.robots_txt_hash + b'"',
},
)
self.assertEqual(response.code, 304)
self.assertEqual(response.body, b"")
self.assertNotIn("Content-Length", response.headers)
self.assertEqual(
utf8(response.headers["Etag"]), b'"' + self.robots_txt_hash + b'"'
)
def test_static_404(self):
response = self.get_and_head("/static/blarg")
self.assertEqual(response.code, 404)
def test_path_traversal_protection(self):
# curl_httpclient processes ".." on the client side, so we
# must test this with simple_httpclient.
self.http_client.close()
self.http_client = SimpleAsyncHTTPClient()
with ExpectLog(gen_log, ".*not in root static directory"):
response = self.get_and_head("/static/../static_foo.txt")
# Attempted path traversal should result in 403, not 200
# (which means the check failed and the file was served)
# or 404 (which means that the file didn't exist and
# is probably a packaging error).
self.assertEqual(response.code, 403)
@unittest.skipIf(os.name != "posix", "non-posix OS")
def test_root_static_path(self):
# Sometimes people set the StaticFileHandler's path to '/'
# to disable Tornado's path validation (in conjunction with
# their own validation in get_absolute_path). Make sure
# that the stricter validation in 4.2.1 doesn't break them.
path = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "static/robots.txt"
)
response = self.get_and_head("/root_static" + urllib.parse.quote(path))
self.assertEqual(response.code, 200)
| StaticFileTest |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/paramType1.py | {
"start": 1227,
"end": 1295
} | class ____(type):
def m1(self: type[_T]) -> Iterator[_T]: ...
| MyMeta |
python | kubernetes-client__python | kubernetes/base/config/kube_config.py | {
"start": 23659,
"end": 25970
} | class ____(object):
"""Remembers each config key's path and construct a relevant exception
message in case of missing keys. The assumption is all access keys are
present in a well-formed kube-config."""
def __init__(self, name, value, path=None):
self.name = name
self.value = value
self.path = path
def __contains__(self, key):
return key in self.value
def __len__(self):
return len(self.value)
def safe_get(self, key):
if (isinstance(self.value, list) and isinstance(key, int) or
key in self.value):
return self.value[key]
def __getitem__(self, key):
v = self.safe_get(key)
if v is None:
raise ConfigException(
'Invalid kube-config file. Expected key %s in %s'
% (key, self.name))
if isinstance(v, dict) or isinstance(v, list):
return ConfigNode('%s/%s' % (self.name, key), v, self.path)
else:
return v
def get_with_name(self, name, safe=False):
if not isinstance(self.value, list):
raise ConfigException(
'Invalid kube-config file. Expected %s to be a list'
% self.name)
result = None
for v in self.value:
if 'name' not in v:
raise ConfigException(
'Invalid kube-config file. '
'Expected all values in %s list to have \'name\' key'
% self.name)
if v['name'] == name:
if result is None:
result = v
else:
raise ConfigException(
'Invalid kube-config file. '
'Expected only one object with name %s in %s list'
% (name, self.name))
if result is not None:
if isinstance(result, ConfigNode):
return result
else:
return ConfigNode(
'%s[name=%s]' %
(self.name, name), result, self.path)
if safe:
return None
raise ConfigException(
'Invalid kube-config file. '
'Expected object with name %s in %s list' % (name, self.name))
| ConfigNode |
python | jina-ai__jina | tests/unit/orchestrate/flow/flow-construct/test_flow_except.py | {
"start": 399,
"end": 1383
} | class ____(Executor):
@requests
def foo(self, **kwargs):
raise NotImplementedError
@pytest.mark.parametrize('protocol', ['http', 'grpc', 'websocket'])
def test_bad_flow(mocker, protocol):
def validate(req):
bad_routes = [
r for r in req.routes if r.status.code == jina_pb2.StatusProto.ERROR
]
assert req.status.code == jina_pb2.StatusProto.ERROR
assert bad_routes[0].executor == 'r1'
f = (
Flow(protocol=protocol)
.add(name='r1', uses=BadExecutor)
.add(name='r2')
.add(name='r3')
)
on_error_mock = mocker.Mock()
# always test two times, make sure the flow test_bad_flow_customizedstill works after it fails on the first
with f:
f.index([Document(text='abbcs'), Document(text='efgh')], on_error=on_error_mock)
f.index([Document(text='abbcs'), Document(text='efgh')], on_error=on_error_mock)
validate_callback(on_error_mock, validate)
| BadExecutor |
python | microsoft__pyright | packages/pyright-internal/src/tests/samples/with1.py | {
"start": 141,
"end": 345
} | class ____(object):
def __exit__(
self,
t: Optional[type] = None,
exc: Optional[BaseException] = None,
tb: Optional[Any] = None,
) -> bool:
return True
| Class1 |
python | pytorch__pytorch | test/distributed/fsdp/test_fsdp_use_orig_params.py | {
"start": 47344,
"end": 54739
} | class ____(FSDPTest):
@property
def world_size(self) -> int:
return 2
@skip_if_lt_x_gpu(2)
def test_no_sync_correctness(self):
"""
Tests a basic ``no_sync()`` setup by comparing ``use_orig_params=True``
against ``use_orig_params=False``.
"""
self.run_subtests(
{
"sharding_strategy": [
ShardingStrategy.FULL_SHARD,
ShardingStrategy.SHARD_GRAD_OP,
ShardingStrategy.NO_SHARD,
],
},
self._test_no_sync_correctness,
)
def _test_no_sync_correctness(self, sharding_strategy: ShardingStrategy):
model = nn.Linear(7, 1, bias=False, device=device_type)
fsdp_kwargs = {
"sharding_strategy": sharding_strategy,
}
model_use_flat_params = FSDP(
copy.deepcopy(model), use_orig_params=False, **fsdp_kwargs
)
model_use_orig_params = FSDP(model, use_orig_params=True, **fsdp_kwargs)
optim_use_flat_params = torch.optim.AdamW(
model_use_flat_params.parameters(), foreach=True
)
optim_use_orig_params = torch.optim.AdamW(
model_use_orig_params.parameters(), foreach=True
)
def _check_param_grad_parity(
_baseline_model: nn.Module,
_test_model: nn.Module,
):
"""
This assumes that the model is ``nn.Linear(7, 1, bias=False)``
(i.e. with a single 1D weight parameter) to be able to directly
compare the baseline and test models. On rank 1, the baseline
includes 1 element of padding.
"""
self.assertEqual(len(list(_baseline_model.parameters())), 1)
self.assertEqual(len(list(_test_model.parameters())), 1)
for flat_param, orig_param in zip(
_baseline_model.parameters(), _test_model.parameters()
):
# Baseline is permitted to have padding
self.assertGreaterEqual(flat_param.numel(), orig_param.numel())
unpadded_param_numel = orig_param.numel()
# For `NO_SHARD`, `use_orig_params=True` presents unflattened
# parameters, while `False` presents flattened ones
torch.testing.assert_close(
flat_param[:unpadded_param_numel], orig_param.flatten()
)
# Gradient numel is different if right after `no_sync()` since
# the gradient is unsharded, while the parameter is sharded
unpadded_grad_numel = orig_param.grad.numel()
# For `use_orig_params=False`, the unsharded gradient is
# flattened, while for `True`, it is unflattened
torch.testing.assert_close(
flat_param.grad[:unpadded_grad_numel].reshape(
orig_param.grad.shape
),
orig_param.grad,
)
inp = torch.randn((2, 7), device=device_type)
grad = torch.randn((2, 1), device=device_type)
# Compute some reference gradients using one forward/backward
out_use_flat_params = model_use_flat_params(inp)
out_use_orig_params = model_use_orig_params(inp)
torch.testing.assert_close(out_use_flat_params, out_use_orig_params)
out_use_flat_params.backward(grad)
out_use_orig_params.backward(grad)
_check_param_grad_parity(model_use_flat_params, model_use_orig_params)
ref_grads_use_flat_params = [
param.grad.detach().clone() for param in model_use_flat_params.parameters()
]
ref_grads_use_orig_params = [
param.grad.detach().clone()
for param in model_use_orig_params.parameters()
if param.grad is not None
]
# Run a forward/backward in `no_sync()`
optim_use_flat_params.zero_grad(set_to_none=True)
optim_use_orig_params.zero_grad(set_to_none=True)
for model in (model_use_flat_params, model_use_orig_params):
with model.no_sync():
out = model(inp)
out.backward(grad)
_check_param_grad_parity(model_use_flat_params, model_use_orig_params)
# Run a forward/backward outside `no_sync()`
for model in (model_use_flat_params, model_use_orig_params):
out = model(inp)
out.backward(grad)
_check_param_grad_parity(model_use_flat_params, model_use_orig_params)
# Check that, since we accumulated gradients across 2 iterations, that
# the new gradients are 2x the reference gradients
grads_use_flat_params = [
param.grad.detach().clone() for param in model_use_flat_params.parameters()
]
grads_use_orig_params = [
param.grad.detach().clone()
for param in model_use_orig_params.parameters()
if param.grad is not None
]
for grad, ref_grad in zip(grads_use_flat_params, ref_grads_use_flat_params):
torch.testing.assert_close(grad, 2 * ref_grad)
for grad, ref_grad in zip(grads_use_orig_params, ref_grads_use_orig_params):
torch.testing.assert_close(grad, 2 * ref_grad)
@skip_if_lt_x_gpu(2)
def test_no_sync_mixed_precision(self):
"""
Tests that dtypes are as expected when using ``no_sync()`` with
``use_orig_params=True`` and parameter mixed precision.
"""
self.run_subtests(
{
"sharding_strategy": [
ShardingStrategy.FULL_SHARD,
ShardingStrategy.SHARD_GRAD_OP,
ShardingStrategy.NO_SHARD,
]
},
self._test_no_sync_mixed_precision,
)
def _test_no_sync_mixed_precision(self, sharding_strategy: ShardingStrategy):
model = nn.Linear(3, 3, device=device_type)
mixed_precision = MixedPrecision(
param_dtype=torch.float16,
reduce_dtype=torch.float32,
)
fsdp_kwargs = {
"sharding_strategy": sharding_strategy,
"mixed_precision": mixed_precision,
"use_orig_params": True,
}
fsdp_model = FSDP(model, **fsdp_kwargs)
inp = torch.randn((2, 3), device=device_type)
with fsdp_model.no_sync():
# For each of these `no_sync()` backward passes, check that the
# gradients are in the low precision parameter dtype (FP16)
fsdp_model(inp).sum().backward()
for param in fsdp_model.parameters():
if param.grad is not None:
self.assertEqual(param.grad.dtype, torch.float16)
fsdp_model(inp).sum().backward()
for param in fsdp_model.parameters():
if param.grad is not None:
self.assertEqual(param.grad.dtype, torch.float16)
# For the backward pass outside `no_sync()`, check that the gradients
# are cast to the full precision in preparation for the optimizer step
fsdp_model(inp).sum().backward()
for param in fsdp_model.parameters():
if param.grad is not None:
self.assertEqual(param.grad.dtype, torch.float32)
| TestFSDPUseOrigParamsNoSync |
python | spack__spack | lib/spack/spack/build_environment.py | {
"start": 5268,
"end": 9197
} | class ____(Executable):
"""Special callable executable object for make so the user can specify parallelism options
on a per-invocation basis.
"""
def __init__(self, name: str, *, jobs: int, supports_jobserver: bool = True) -> None:
super().__init__(name)
self.supports_jobserver = supports_jobserver
self.jobs = jobs
@overload
def __call__(
self,
*args: str,
parallel: bool = ...,
jobs_env: Optional[str] = ...,
jobs_env_supports_jobserver: bool = ...,
fail_on_error: bool = ...,
ignore_errors: Union[int, Sequence[int]] = ...,
ignore_quotes: Optional[bool] = ...,
timeout: Optional[int] = ...,
env: Optional[Union[Dict[str, str], EnvironmentModifications]] = ...,
extra_env: Optional[Union[Dict[str, str], EnvironmentModifications]] = ...,
input: Optional[TextIO] = ...,
output: Union[Optional[TextIO], str] = ...,
error: Union[Optional[TextIO], str] = ...,
_dump_env: Optional[Dict[str, str]] = ...,
) -> None: ...
@overload
def __call__(
self,
*args: str,
parallel: bool = ...,
jobs_env: Optional[str] = ...,
jobs_env_supports_jobserver: bool = ...,
fail_on_error: bool = ...,
ignore_errors: Union[int, Sequence[int]] = ...,
ignore_quotes: Optional[bool] = ...,
timeout: Optional[int] = ...,
env: Optional[Union[Dict[str, str], EnvironmentModifications]] = ...,
extra_env: Optional[Union[Dict[str, str], EnvironmentModifications]] = ...,
input: Optional[TextIO] = ...,
output: Union[Type[str], Callable] = ...,
error: Union[Optional[TextIO], str, Type[str], Callable] = ...,
_dump_env: Optional[Dict[str, str]] = ...,
) -> str: ...
@overload
def __call__(
self,
*args: str,
parallel: bool = ...,
jobs_env: Optional[str] = ...,
jobs_env_supports_jobserver: bool = ...,
fail_on_error: bool = ...,
ignore_errors: Union[int, Sequence[int]] = ...,
ignore_quotes: Optional[bool] = ...,
timeout: Optional[int] = ...,
env: Optional[Union[Dict[str, str], EnvironmentModifications]] = ...,
extra_env: Optional[Union[Dict[str, str], EnvironmentModifications]] = ...,
input: Optional[TextIO] = ...,
output: Union[Optional[TextIO], str, Type[str], Callable] = ...,
error: Union[Type[str], Callable] = ...,
_dump_env: Optional[Dict[str, str]] = ...,
) -> str: ...
def __call__(
self,
*args: str,
parallel: bool = True,
jobs_env: Optional[str] = None,
jobs_env_supports_jobserver: bool = False,
**kwargs,
) -> Optional[str]:
"""Runs this ``make`` executable in a subprocess.
Args:
parallel: if False, parallelism is disabled
jobs_env: environment variable that will be set to the current level of parallelism
jobs_env_supports_jobserver: whether the jobs env supports a job server
For all the other ``**kwargs``, refer to :func:`spack.util.executable.Executable.__call__`.
"""
jobs = get_effective_jobs(
self.jobs, parallel=parallel, supports_jobserver=self.supports_jobserver
)
if jobs is not None:
args = (f"-j{jobs}",) + args
if jobs_env:
# Caller wants us to set an environment variable to control the parallelism
jobs_env_jobs = get_effective_jobs(
self.jobs, parallel=parallel, supports_jobserver=jobs_env_supports_jobserver
)
if jobs_env_jobs is not None:
extra_env = kwargs.setdefault("extra_env", {})
extra_env.update({jobs_env: str(jobs_env_jobs)})
return super().__call__(*args, **kwargs)
| MakeExecutable |
python | ansible__ansible | test/integration/targets/module_defaults/collections/ansible_collections/testns/testcoll/plugins/action/vyos.py | {
"start": 240,
"end": 446
} | class ____(ActionBase):
def run(self, tmp=None, task_vars=None):
result = super(ActionModule, self).run(tmp, task_vars)
result['action_plugin'] = 'vyos'
return result
| ActionModule |
python | PrefectHQ__prefect | tests/test_task_engine.py | {
"start": 99276,
"end": 103936
} | class ____:
async def test_task_transitions_to_rolled_back_on_transaction_rollback(
self,
events_pipeline,
prefect_client,
):
task_run_state = None
@task
def foo():
pass
@foo.on_rollback
def rollback(txn):
pass
@flow
def txn_flow():
with transaction():
nonlocal task_run_state
task_run_state = foo(return_state=True)
raise ValueError("txn failed")
txn_flow(return_state=True)
task_run_id = task_run_state.state_details.task_run_id
await events_pipeline.process_events()
task_run_states = await prefect_client.read_task_run_states(task_run_id)
state_names = [state.name for state in task_run_states]
assert state_names == [
"Pending",
"Running",
"Completed",
"RolledBack",
]
async def test_task_transitions_to_rolled_back_on_transaction_rollback_async(
self,
events_pipeline,
prefect_client,
):
task_run_state = None
@task
async def foo():
pass
@foo.on_rollback
def rollback(txn):
pass
@flow
async def txn_flow():
with transaction():
nonlocal task_run_state
task_run_state = await foo(return_state=True)
raise ValueError("txn failed")
await txn_flow(return_state=True)
task_run_id = task_run_state.state_details.task_run_id
await events_pipeline.process_events()
task_run_states = await prefect_client.read_task_run_states(task_run_id)
state_names = [state.name for state in task_run_states]
assert state_names == [
"Pending",
"Running",
"Completed",
"RolledBack",
]
def test_rollback_errors_are_logged(self, caplog):
@task
def foo():
pass
@foo.on_rollback
def rollback(txn):
raise RuntimeError("whoops!")
@flow
def txn_flow():
with transaction():
foo()
raise ValueError("txn failed")
txn_flow(return_state=True)
assert "An error was encountered while running rollback hook" in caplog.text
assert "RuntimeError" in caplog.text
assert "whoops!" in caplog.text
def test_rollback_hook_execution_and_completion_are_logged(self, caplog):
@task
def foo():
pass
@foo.on_rollback
def rollback(txn):
pass
@flow
def txn_flow():
with transaction():
foo()
raise ValueError("txn failed")
txn_flow(return_state=True)
assert "Running rollback hook 'rollback'" in caplog.text
assert "Rollback hook 'rollback' finished running successfully" in caplog.text
def test_commit_errors_are_logged(self, caplog):
@task
def foo():
pass
@foo.on_commit
def rollback(txn):
raise RuntimeError("whoops!")
@flow
def txn_flow():
with transaction():
foo()
txn_flow(return_state=True)
assert "An error was encountered while running commit hook" in caplog.text
assert "RuntimeError" in caplog.text
assert "whoops!" in caplog.text
def test_commit_hook_execution_and_completion_are_logged(self, caplog):
@task
def foo():
pass
@foo.on_commit
def commit(txn):
pass
@flow
def txn_flow():
with transaction():
foo()
txn_flow(return_state=True)
assert "Running commit hook 'commit'" in caplog.text
assert "Commit hook 'commit' finished running successfully" in caplog.text
async def test_async_rollback_hooks(self):
spy = AsyncMock()
@task
def foo():
pass
@foo.on_rollback
async def rollback(txn):
await spy()
with pytest.raises(RuntimeError):
with transaction():
foo()
raise RuntimeError("Zut alors!")
spy.assert_called_once()
async def test_async_commit_hooks(self):
spy = AsyncMock()
@task
def foo():
pass
@foo.on_commit
async def commit(txn):
await spy()
with transaction():
foo()
spy.assert_called_once()
| TestTransactionHooks |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.