id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,200 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/src/bananas/admin/api/views.py
|
bananas.admin.api.views.TranslationAPI.Admin
|
class Admin:
exclude_tags: ClassVar[List[str]] = ["navigation"]
|
class Admin:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
1,201 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/src/bananas/models.py
|
bananas.models.UUIDModel.Meta
|
class Meta:
abstract = True
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
1,202 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/example/example/api.py
|
example.api.AppleViewSet
|
class AppleViewSet(BananasAPI, viewsets.ModelViewSet):
name = lazy_title(_("apple"))
@tags(exclude=["navigation"])
def list(self, request):
return Response()
@tags(["navigation"])
@action(detail=False)
def red_delicious(self, request):
return Response()
@tags(include=["navigation"])
@action(detail=False)
def granny_smith(self, request):
return Response()
class Admin:
app_label = "fruit"
|
class AppleViewSet(BananasAPI, viewsets.ModelViewSet):
@tags(exclude=["navigation"])
def list(self, request):
pass
@tags(["navigation"])
@action(detail=False)
def red_delicious(self, request):
pass
@tags(include=["navigation"])
@action(detail=False)
def granny_smith(self, request):
pass
class Admin:
| 10 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 2 | 0 | 0 | 0 | 3 | 0 | 3 | 7 | 20 | 5 | 15 | 10 | 5 | 0 | 10 | 7 | 5 | 1 | 1 | 0 | 3 |
1,203 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/example/example/api.py
|
example.api.PearViewSet.Admin
|
class Admin:
app_label = "fruit"
|
class Admin:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
1,204 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/example/example/api.py
|
example.api.UserDetailsSerializer
|
class UserDetailsSerializer(serializers.HyperlinkedModelSerializer):
full_name = serializers.SerializerMethodField()
@schema_serializer_method(serializer_or_field=serializers.CharField)
def get_full_name(self, obj):
return obj.get_full_name()
class Meta:
model = User
fields = ("id", "url", "username", "full_name", "email", "is_staff")
def build_url_field(self, field_name, model_class):
"""
This is needed due to DRF's model serializer uses the queryset to build url name
# TODO: Move this to own serializer mixin or fix problem elsewhere?
"""
field, kwargs = super().build_url_field(field_name, model_class)
view = self.root.context["view"]
kwargs["view_name"] = view.get_url_name("detail")
return field, kwargs
|
class UserDetailsSerializer(serializers.HyperlinkedModelSerializer):
@schema_serializer_method(serializer_or_field=serializers.CharField)
def get_full_name(self, obj):
pass
class Meta:
def build_url_field(self, field_name, model_class):
'''
This is needed due to DRF's model serializer uses the queryset to build url name
# TODO: Move this to own serializer mixin or fix problem elsewhere?
'''
pass
| 5 | 1 | 7 | 2 | 4 | 2 | 1 | 0.31 | 1 | 1 | 0 | 0 | 2 | 0 | 2 | 2 | 23 | 6 | 13 | 10 | 8 | 4 | 12 | 9 | 8 | 1 | 1 | 0 | 2 |
1,205 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/example/example/api.py
|
example.api.UserDetailsSerializer.Meta
|
class Meta:
model = User
fields = ("id", "url", "username", "full_name", "email", "is_staff")
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 0 | 0 | 0 |
1,206 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/example/example/api.py
|
example.api.UserSerializer.Meta
|
class Meta:
model = User
fields = ("username", "first_name", "last_name", "email")
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 0 | 0 | 0 |
1,207 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/src/bananas/admin/api/views.py
|
bananas.admin.api.views.LoginAPI
|
class LoginAPI(BananasAdminAPI):
name = _("Log in") # type: ignore[assignment]
basename = "login"
permission_classes = (IsAnonymous,)
serializer_class = AuthenticationSerializer # Placeholder for schema
class Admin:
verbose_name_plural = None
@schema(responses={200: UserSerializer})
def create(self, request: Request) -> Response:
"""
Log in django staff user
"""
# TODO: Decorate api with sensitive post parameters as Django admin do?
# from django.utils.decorators import method_decorator
# from django.views.decorators.debug import sensitive_post_parameters
# sensitive_post_parameters_m = method_decorator(sensitive_post_parameters())
login_form = AuthenticationForm(request, data=request.data)
if not login_form.is_valid():
raise serializers.ValidationError(
login_form.errors) # type: ignore[arg-type]
auth_login(request, login_form.get_user())
serializer = UserSerializer(request.user)
return Response(serializer.data, status=status.HTTP_200_OK)
|
class LoginAPI(BananasAdminAPI):
class Admin:
@schema(responses={200: UserSerializer})
def create(self, request: Request) -> Response:
'''
Log in django staff user
'''
pass
| 4 | 1 | 18 | 4 | 7 | 8 | 2 | 0.67 | 1 | 1 | 1 | 0 | 1 | 0 | 1 | 5 | 28 | 6 | 15 | 11 | 11 | 10 | 14 | 10 | 11 | 2 | 2 | 1 | 2 |
1,208 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/example/example/api.py
|
example.api.UserViewSet
|
class UserViewSet(BananasAPI, viewsets.ModelViewSet):
name = lazy_title(_("users"))
permission_classes = (DjangoModelPermissions,)
queryset = User.objects.all()
class Admin:
verbose_name = lazy_title(_("user"))
@schema(query_serializer=UserFilterSerializer)
def list(self, request):
return super().list(request)
def get_queryset(self):
queryset = super().get_queryset()
serializer = UserFilterSerializer(data=self.request.query_params)
serializer.is_valid(raise_exception=True)
username = serializer.validated_data.get("username")
if username:
queryset = queryset.filter(username__contains=username)
return queryset
def get_serializer_class(self):
if self.action in ("retrieve", "list"):
return UserDetailsSerializer
elif self.action == "form":
return FormSerializer
else:
return UserSerializer
@action(detail=False)
def foo(self, request):
return Response("Just a simple extra list action")
@action(detail=True)
def bar(self, request, pk):
url = reverse("bananas:v1.0:example.user-bar", kwargs={"pk": pk})
return Response(
"Just a simple extra detail action, url = {url}".format(url=url)
)
@action(detail=True, methods=["post"], name=_("Send activation e-mail"))
def send_activation_email(self, request, pk):
return Response("Just another simple extra detail action")
@action(detail=True, url_path="baz/(?P<x>.+)/ham/(?P<y>.+)")
def baz(self, request, pk, x, y):
return Response(
"Just a simple extra detail action, {pk}, {x}, {y}".format(
pk=pk, x=x, y=y)
)
@action(detail=False, methods=["get", "post"])
def form(self, request):
if request.method == "GET":
return Response({})
serializer = FormSerializer(data=self.request.data)
serializer.is_valid(raise_exception=True)
return Response(serializer.validated_data)
|
class UserViewSet(BananasAPI, viewsets.ModelViewSet):
class Admin:
@schema(query_serializer=UserFilterSerializer)
def list(self, request):
pass
def get_queryset(self):
pass
def get_serializer_class(self):
pass
@action(detail=False)
def foo(self, request):
pass
@action(detail=True)
def bar(self, request, pk):
pass
@action(detail=True, methods=["post"], name=_("Send activation e-mail"))
def send_activation_email(self, request, pk):
pass
@action(detail=True, url_path="baz/(?P<x>.+)/ham/(?P<y>.+)")
def baz(self, request, pk, x, y):
pass
@action(detail=False, methods=["get", "post"])
def form(self, request):
pass
| 16 | 0 | 5 | 0 | 5 | 0 | 2 | 0 | 2 | 5 | 4 | 0 | 8 | 1 | 8 | 12 | 60 | 12 | 48 | 26 | 32 | 0 | 36 | 19 | 26 | 3 | 1 | 1 | 12 |
1,209 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/tests/drf/admin_api.py
|
tests.drf.admin_api.FooAPI
|
class FooAPI(BananasAdminAPI):
name = lazy_title(_("foo"))
serializer_class = HamSerializer
def list(self, request: Request) -> Response:
serializer = self.serializer_class({"spam": "Skinka"})
return Response(serializer.data)
@action(detail=False)
def bar(self, request: Request) -> Response:
return Response({"bar": True})
@tags(include=["navigation"])
@action(detail=False, methods=["get", "post"])
def baz(self, request: Request) -> Response:
return Response({"baz": True})
|
class FooAPI(BananasAdminAPI):
def list(self, request: Request) -> Response:
pass
@action(detail=False)
def bar(self, request: Request) -> Response:
pass
@tags(include=["navigation"])
@action(detail=False, methods=["get", "post"])
def baz(self, request: Request) -> Response:
pass
| 7 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 7 | 16 | 3 | 13 | 9 | 6 | 0 | 10 | 7 | 6 | 1 | 2 | 0 | 3 |
1,210 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/tests/drf/admin_api.py
|
tests.drf.admin_api.HamAPI
|
class HamAPI(BananasAPI, viewsets.ModelViewSet):
name = lazy_capitalize(_("ham"))
serializer_class = HamSerializer
def get_queryset(self) -> QuerySet:
return None # type: ignore
@tags(exclude=["navigation"])
def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
return Response()
|
class HamAPI(BananasAPI, viewsets.ModelViewSet):
def get_queryset(self) -> QuerySet:
pass
@tags(exclude=["navigation"])
def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:
pass
| 4 | 0 | 2 | 0 | 2 | 1 | 1 | 0.13 | 2 | 1 | 0 | 0 | 2 | 0 | 2 | 6 | 10 | 2 | 8 | 6 | 4 | 1 | 7 | 5 | 4 | 1 | 1 | 0 | 2 |
1,211 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/tests/drf/fenced_api.py
|
tests.drf.fenced_api.SimpleSerializer.Meta
|
class Meta:
model = Parent
fields = ("name",)
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 0 | 0 | 0 |
1,212 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/tests/drf/test_fencing.py
|
tests.drf.test_fencing.TestAllowIfUnmodifiedSince
|
class TestAllowIfUnmodifiedSince(TestCase):
@override_settings(USE_TZ=False)
def test_raises_improperly_configured_for_naive_django_config(self):
with self.assertRaises(ImproperlyConfigured):
allow_if_unmodified_since()
|
class TestAllowIfUnmodifiedSince(TestCase):
@override_settings(USE_TZ=False)
def test_raises_improperly_configured_for_naive_django_config(self):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 73 | 5 | 0 | 5 | 3 | 2 | 0 | 4 | 2 | 2 | 1 | 2 | 1 | 1 |
1,213 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/tests/drf/test_fencing.py
|
tests.drf.test_fencing.TestParseDateModified.test_can_get_none.A
|
class A(TimeStampedModel):
date_modified = None
|
class A(TimeStampedModel):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 2 | 0 | 2 | 2 | 1 | 1 | 2 | 2 | 1 | 0 | 2 | 0 | 0 |
1,214 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/tests/drf/test_fencing.py
|
tests.drf.test_fencing.TestParseDateModified.test_replaces_microsecond.A
|
class A(TimeStampedModel):
date_modified = datetime.datetime( # type: ignore[assignment]
2021, 1, 14, 17, 30, 1, 1, tzinfo=datetime.timezone.utc
)
|
class A(TimeStampedModel):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 4 | 0 | 4 | 2 | 3 | 1 | 2 | 2 | 1 | 0 | 2 | 0 | 0 |
1,215 |
5monkeys/django-bananas
|
5monkeys_django-bananas/example/example/api.py
|
example.api.FormSerializer
|
class FormSerializer(serializers.Serializer):
text = serializers.CharField()
integer = serializers.IntegerField()
date = serializers.DateField()
datetime = serializers.DateTimeField()
boolean = serializers.BooleanField(required=True)
choices = serializers.ChoiceField(
choices=(
("se", "Sweden"),
("no", "Norway"),
("fi", "Finland"),
("dk", "Denmark"),
)
)
multiple_choices = serializers.MultipleChoiceField(
choices=(
("se", "Sweden"),
("no", "Norway"),
("fi", "Finland"),
("dk", "Denmark"),
)
)
|
class FormSerializer(serializers.Serializer):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 22 | 0 | 22 | 8 | 21 | 0 | 8 | 8 | 7 | 0 | 1 | 0 | 0 |
1,216 |
5monkeys/django-bananas
|
5monkeys_django-bananas/example/example/api.py
|
example.api.PeachViewSet
|
class PeachViewSet(BananasAPI, viewsets.ModelViewSet):
name = lazy_title(_("peach"))
def list(self, request):
return Response()
class Admin:
app_label = "fruit"
|
class PeachViewSet(BananasAPI, viewsets.ModelViewSet):
def list(self, request):
pass
class Admin:
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 2 | 0 | 0 | 0 | 1 | 0 | 1 | 5 | 9 | 3 | 6 | 5 | 3 | 0 | 6 | 5 | 3 | 1 | 1 | 0 | 1 |
1,217 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/tests/models.py
|
tests.models.BananasModel.Meta
|
class Meta:
app_label = "tests"
abstract = True
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 0 | 0 | 0 |
1,218 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/tests/test_admin.py
|
tests.test_admin.AdminTest
|
class AdminTest(TestCase):
staff_user: ClassVar[User]
@classmethod
def setUpTestData(cls):
call_command("syncpermissions")
cls.staff_user = User.objects.create_user(
username="user", password="test", is_staff=True
)
def setUp(self):
self.detail_url = reverse("admin:tests_simple")
self.custom_url = reverse("admin:tests_simple_custom")
self.special_url = reverse("admin:tests_simple_special")
@reset_admin_registry
def test_admin(self):
@admin.register
class AnAdminView(admin.AdminView):
__module__ = "tests.admin"
class FakeRequest:
META = {"SCRIPT_NAME": ""}
user = AnonymousUser()
ctx = admin.site.each_context(FakeRequest()) # type: ignore[arg-type]
self.assertTrue("settings" in ctx)
self.assertIsInstance(admin.site.urls, tuple)
@reset_admin_registry
def test_register_without_args(self):
# As decorator without arguments
@admin.register
class MyAdminViewRegisteredWithoutArgs(admin.AdminView):
__module__ = "tests.admin"
model_admin = get_model_admin_from_registry(
MyAdminViewRegisteredWithoutArgs)
self.assertIsNotNone(model_admin)
self.assertIsInstance(model_admin, admin.ModelAdminView)
@reset_admin_registry
def test_register_with_args(self):
# As decorator with arguments
@admin.register(admin_class=SpecialModelAdmin)
class MyAdminViewRegisteredWithArgs(admin.AdminView):
__module__ = "tests.admin"
model_admin = get_model_admin_from_registry(
MyAdminViewRegisteredWithArgs)
self.assertIsNotNone(model_admin)
self.assertIsInstance(model_admin, SpecialModelAdmin)
@reset_admin_registry
def test_register_normally(self):
# Just registered
class MyAdminViewRegisteredNormally(admin.AdminView):
__module__ = "tests.admin"
admin.register(MyAdminViewRegisteredNormally,
admin_class=SpecialModelAdmin)
model_admin = get_model_admin_from_registry(
MyAdminViewRegisteredNormally)
self.assertIsNotNone(model_admin)
self.assertIsInstance(model_admin, SpecialModelAdmin)
@reset_admin_registry
def test_register_app_nested_in_package(self):
@admin.register
class MyAdminViewRegisteredInNestedApp(admin.AdminView):
__module__ = "somepackage.tests.admin"
model_admin = get_model_admin_from_registry(
MyAdminViewRegisteredInNestedApp)
self.assertIsNotNone(model_admin)
self.assertIsInstance(model_admin, admin.ModelAdminView)
def assert_unauthorized(self, url):
response = self.client.get(url)
self.assertEqual(response.status_code, 302)
self.assertRedirects(
response,
"{}?next={}".format(reverse("admin:login"), url),
fetch_redirect_response=False,
)
def test_admin_view_non_staff(self):
user = self.staff_user
user.is_staff = False
user.save(update_fields=["is_staff"])
self.client.login(username=user.username, password="test")
self.assert_unauthorized(self.custom_url)
self.assert_unauthorized(self.detail_url)
def test_admin_view_staff(self):
staff_user = self.staff_user
self.client.force_login(staff_user)
# We need the correct permission
self.assert_unauthorized(self.custom_url)
self.assert_unauthorized(self.detail_url)
perm = Permission.objects.filter(codename="can_access_simple").first()
assert perm is not None
staff_user.user_permissions.add(perm)
expected_view_tools = {"Even more special action"}
response = self.client.get(self.custom_url)
self.assertEqual(response.status_code, 200)
context = response.context
self.assertEqual(context["context"], "custom")
self.assertEqual(len(context["view_tools"]), 1)
self.assertEqual(
{t.text for t in context["view_tools"]},
expected_view_tools,
)
response = self.client.get(self.detail_url)
context = response.context
self.assertEqual(response.status_code, 200)
self.assertEqual(context["context"], "get")
self.assertEqual(len(context["view_tools"]), 1)
self.assertEqual(
{t.text for t in context["view_tools"]},
expected_view_tools,
)
def test_admin_view_with_permission(self):
staff_user = self.staff_user
self.client.force_login(staff_user)
self.assert_unauthorized(self.special_url)
perm = Permission.objects.filter(
codename="can_do_special_stuff").first()
assert perm is not None
staff_user.user_permissions.add(perm)
expected_view_tools = {"Special Action", "Even more special action"}
response = self.client.get(self.special_url)
context = response.context
self.assertEqual(response.status_code, 200)
self.assertEqual(context["context"], "special")
self.assertEqual(len(context["view_tools"]), 2)
self.assertEqual(
{t.text for t in context["view_tools"]},
expected_view_tools,
)
# No access to other views
self.assert_unauthorized(self.custom_url)
self.assert_unauthorized(self.detail_url)
|
class AdminTest(TestCase):
@classmethod
def setUpTestData(cls):
pass
def setUpTestData(cls):
pass
@reset_admin_registry
def test_admin(self):
pass
@admin.register
class AnAdminView(admin.AdminView):
class FakeRequest:
@reset_admin_registry
def test_register_without_args(self):
pass
@admin.register
class MyAdminViewRegisteredWithoutArgs(admin.AdminView):
@reset_admin_registry
def test_register_with_args(self):
pass
@admin.register(admin_class=SpecialModelAdmin)
class MyAdminViewRegisteredWithArgs(admin.AdminView):
@reset_admin_registry
def test_register_normally(self):
pass
class MyAdminViewRegisteredNormally(admin.AdminView):
@reset_admin_registry
def test_register_app_nested_in_package(self):
pass
@admin.register
class MyAdminViewRegisteredInNestedApp(admin.AdminView):
def assert_unauthorized(self, url):
pass
def test_admin_view_non_staff(self):
pass
def test_admin_view_staff(self):
pass
def test_admin_view_with_permission(self):
pass
| 28 | 0 | 12 | 1 | 10 | 1 | 1 | 0.05 | 1 | 8 | 7 | 0 | 10 | 3 | 11 | 11 | 147 | 26 | 116 | 55 | 88 | 6 | 91 | 45 | 73 | 1 | 1 | 0 | 11 |
1,219 |
5monkeys/django-bananas
|
5monkeys_django-bananas/example/example/migrations/0001_initial.py
|
example.migrations.0001_initial.Migration
|
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Monkey',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_created', models.DateTimeField(auto_now_add=True, null=True, verbose_name='date created')),
('date_modified', models.DateTimeField(auto_now=True, null=True, verbose_name='date modified')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'abstract': False,
},
),
]
|
class Migration(migrations.Migration):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 22 | 3 | 19 | 4 | 18 | 0 | 4 | 4 | 3 | 0 | 1 | 0 | 0 |
1,220 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/example/example/api.py
|
example.api.UserViewSet.Admin
|
class Admin:
verbose_name = lazy_title(_("user"))
|
class Admin:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
1,221 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/src/bananas/admin/api/views.py
|
bananas.admin.api.views.ChangePasswordAPI
|
class ChangePasswordAPI(BananasAdminAPI):
name = _("Change password") # type: ignore[assignment]
basename = "change_password"
serializer_class = PasswordChangeSerializer # Placeholder for schema
class Admin:
verbose_name_plural = None
@schema(responses={204: ""})
def create(self, request: Request) -> Response:
"""
Change password for logged in django staff user
"""
# TODO: Decorate api with sensitive post parameters as Django admin do?
assert isinstance(request.user, AbstractBaseUser)
password_form = PasswordChangeForm(request.user, data=request.data)
if not password_form.is_valid():
raise serializers.ValidationError(
password_form.errors) # type: ignore[arg-type]
password_form.save()
# type: ignore[arg-type]
update_session_auth_hash(request, password_form.user)
return Response(status=status.HTTP_204_NO_CONTENT)
|
class ChangePasswordAPI(BananasAdminAPI):
class Admin:
@schema(responses={204: ""})
def create(self, request: Request) -> Response:
'''
Change password for logged in django staff user
'''
pass
| 4 | 1 | 16 | 4 | 8 | 6 | 2 | 0.53 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 5 | 25 | 6 | 15 | 9 | 11 | 8 | 14 | 8 | 11 | 2 | 2 | 1 | 2 |
1,222 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/src/bananas/admin/api/serializers.py
|
bananas.admin.api.serializers.UserSerializer.Meta
|
class Meta:
model = get_user_model()
ref_name = "Me"
fields = (
"id",
"username",
"full_name",
"email",
"is_superuser",
"permissions",
"groups",
)
read_only_fields = fields
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 13 | 0 | 13 | 5 | 12 | 0 | 5 | 5 | 4 | 0 | 0 | 0 | 0 |
1,223 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/src/bananas/admin/api/serializers.py
|
bananas.admin.api.serializers.UserSerializer
|
class UserSerializer(serializers.ModelSerializer):
username = serializers.CharField(source="get_username", read_only=True)
full_name = serializers.SerializerMethodField()
email = serializers.SerializerMethodField()
is_superuser = serializers.BooleanField(read_only=True)
permissions = serializers.SerializerMethodField()
groups = serializers.SerializerMethodField()
class Meta:
model = get_user_model()
ref_name = "Me"
fields = (
"id",
"username",
"full_name",
"email",
"is_superuser",
"permissions",
"groups",
)
read_only_fields = fields
@schema_serializer_method(
serializer_or_field=serializers.CharField(
help_text=_("Falls back to username, if not implemented or empty")
)
)
def get_full_name(self, obj: User) -> str:
getter: Optional[Callable[[], str]] = getattr(
obj, "get_full_name", None)
if getter is not None:
full_name = getter()
if not full_name:
full_name = obj.get_username()
return full_name
@schema_serializer_method(serializer_or_field=serializers.CharField())
def get_email(self, obj: User) -> Optional[str]:
return getattr(obj, obj.get_email_field_name(), None)
@schema_serializer_method(
serializer_or_field=serializers.ListField(
help_text=_(
"Permissions that the user has, both through group and user permissions."
)
)
)
def get_permissions(self, obj: User) -> List[str]:
return sorted(obj.get_all_permissions())
@schema_serializer_method(serializer_or_field=serializers.ListField)
def get_groups(self, obj: User) -> Iterable[str]:
return obj.groups.order_by("name").values_list("name", flat=True)
|
class UserSerializer(serializers.ModelSerializer):
class Meta:
@schema_serializer_method(
serializer_or_field=serializers.CharField(
help_text=_("Falls back to username, if not implemented or empty")
)
)
def get_full_name(self, obj: User) -> str:
pass
@schema_serializer_method(serializer_or_field=serializers.CharField())
def get_email(self, obj: User) -> Optional[str]:
pass
@schema_serializer_method(
serializer_or_field=serializers.ListField(
help_text=_(
"Permissions that the user has, both through group and user permissions."
)
)
)
def get_permissions(self, obj: User) -> List[str]:
pass
@schema_serializer_method(serializer_or_field=serializers.ListField)
def get_groups(self, obj: User) -> Iterable[str]:
pass
| 10 | 0 | 4 | 1 | 3 | 0 | 2 | 0 | 1 | 1 | 0 | 0 | 4 | 0 | 4 | 4 | 54 | 7 | 47 | 32 | 27 | 0 | 25 | 18 | 19 | 3 | 1 | 1 | 6 |
1,224 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/drf/fencing.py
|
bananas.drf.fencing.UsesQuerySet
|
class UsesQuerySet(Protocol[_MT_co]):
def get_queryset(self) -> "QuerySet[_MT_co]":
...
|
class UsesQuerySet(Protocol[_MT_co]):
def get_queryset(self) -> "QuerySet[_MT_co]":
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 23 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 4 | 0 | 1 |
1,225 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/drf/utils.py
|
bananas.drf.utils.HeaderError
|
class HeaderError(ValueError):
code = "invalid_header"
def as_api_error(self) -> BadRequest:
return BadRequest(detail=str(self), code=self.code)
|
class HeaderError(ValueError):
def as_api_error(self) -> BadRequest:
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 2 | 1 | 2 | 1 | 0 | 1 | 12 | 5 | 1 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 4 | 0 | 1 |
1,226 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/drf/utils.py
|
bananas.drf.utils.InvalidHeader
|
class InvalidHeader(HeaderError):
def __init__(self, header: str) -> None:
self.header = header
super().__init__(f"Malformed header in request: {header}")
|
class InvalidHeader(HeaderError):
def __init__(self, header: str) -> None:
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 1 | 1 | 1 | 13 | 4 | 0 | 4 | 3 | 2 | 0 | 4 | 3 | 2 | 1 | 5 | 0 | 1 |
1,227 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/drf/utils.py
|
bananas.drf.utils.MissingHeader
|
class MissingHeader(HeaderError):
code = "missing_header"
def __init__(self, header: str) -> None:
self.header = header
super().__init__(f"Header missing in request: {header}")
|
class MissingHeader(HeaderError):
def __init__(self, header: str) -> None:
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 2 | 0 | 0 | 1 | 1 | 1 | 13 | 6 | 1 | 5 | 4 | 3 | 0 | 5 | 4 | 3 | 1 | 5 | 0 | 1 |
1,228 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/environment.py
|
bananas.environment.EnvironWrapper
|
class EnvironWrapper:
"""
Wrapper around os environ with type conversion support.
"""
def __delitem__(self, key: str) -> None:
environ.__delitem__(key)
def __getitem__(self, key: str) -> str:
return environ.__getitem__(key)
def __setitem__(self, key: str, value: str) -> None:
environ.__setitem__(key, value)
def __contains__(self, key: object) -> bool:
return environ.__contains__(key)
def __getattr__(self, item: str) -> object:
return getattr(environ, item)
get: Callable[..., str]
@overload
def parse(self, parser: Callable[[str], S], key: str, default: None) -> Optional[S]:
...
@overload
def parse(self, parser: Callable[[str], S], key: str, default: S) -> S:
...
def parse(
self, parser: Callable[[str], S], key: str, default: Optional[S] = None
) -> Optional[S]:
value: Union[str, Undefined] = environ.get(key, UNDEFINED)
if isinstance(value, Undefined):
return default
try:
return parser(value)
except ValueError:
log.warning(f"Unable to parse environment variable {key}={value}")
return default
@overload
def get_bool(self, key: str, default: U) -> Union[bool, U]:
...
@overload
def get_bool(self, key: str, default: None = None) -> Optional[bool]:
...
def get_bool(self, key: str, default: object = None) -> object:
return self.parse(parse_bool, key, default=default)
@overload
def get_int(self, key: str, default: U) -> Union[int, U]:
...
@overload
def get_int(self, key: str, default: None = None) -> Optional[int]:
...
def get_int(self, key: str, default: object = None) -> object:
return self.parse(parse_int, key, default=default)
@overload
def get_tuple(self, key: str, default: U) -> Union[Tuple[str, ...], U]:
...
@overload
def get_tuple(self, key: str, default: None = None) -> Optional[Tuple[str, ...]]:
...
def get_tuple(self, key: str, default: object = None) -> object:
return self.parse(parse_tuple, key, default=default)
@overload
def get_list(self, key: str, default: U) -> Union[List[str], U]:
...
@overload
def get_list(self, key: str, default: None = None) -> Optional[List[str]]:
...
def get_list(self, key: str, default: object = None) -> object:
return self.parse(parse_list, key, default=default)
@overload
def get_set(self, key: str, default: U) -> Union[Set[str], U]:
...
@overload
def get_set(self, key: str, default: None = None) -> Optional[Set[str]]:
...
def get_set(self, key: str, default: object = None) -> object:
return self.parse(parse_set, key, default=default)
|
class EnvironWrapper:
'''
Wrapper around os environ with type conversion support.
'''
def __delitem__(self, key: str) -> None:
pass
def __getitem__(self, key: str) -> str:
pass
def __setitem__(self, key: str, value: str) -> None:
pass
def __contains__(self, key: object) -> bool:
pass
def __getattr__(self, item: str) -> object:
pass
@overload
def parse(self, parser: Callable[[str], S], key: str, default: None) -> Optional[S]:
pass
@overload
def parse(self, parser: Callable[[str], S], key: str, default: None) -> Optional[S]:
pass
def parse(self, parser: Callable[[str], S], key: str, default: None) -> Optional[S]:
pass
@overload
def get_bool(self, key: str, default: U) -> Union[bool, U]:
pass
@overload
def get_bool(self, key: str, default: U) -> Union[bool, U]:
pass
def get_bool(self, key: str, default: U) -> Union[bool, U]:
pass
@overload
def get_int(self, key: str, default: U) -> Union[int, U]:
pass
@overload
def get_int(self, key: str, default: U) -> Union[int, U]:
pass
def get_int(self, key: str, default: U) -> Union[int, U]:
pass
@overload
def get_tuple(self, key: str, default: U) -> Union[Tuple[str, ...], U]:
pass
@overload
def get_tuple(self, key: str, default: U) -> Union[Tuple[str, ...], U]:
pass
def get_tuple(self, key: str, default: U) -> Union[Tuple[str, ...], U]:
pass
@overload
def get_list(self, key: str, default: U) -> Union[List[str], U]:
pass
@overload
def get_list(self, key: str, default: U) -> Union[List[str], U]:
pass
def get_list(self, key: str, default: U) -> Union[List[str], U]:
pass
@overload
def get_set(self, key: str, default: U) -> Union[Set[str], U]:
pass
@overload
def get_set(self, key: str, default: U) -> Union[Set[str], U]:
pass
def get_set(self, key: str, default: U) -> Union[Set[str], U]:
pass
| 36 | 1 | 2 | 0 | 2 | 0 | 1 | 0.04 | 0 | 6 | 1 | 0 | 23 | 0 | 23 | 23 | 96 | 24 | 69 | 39 | 31 | 3 | 55 | 25 | 31 | 3 | 0 | 1 | 25 |
1,229 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/environment.py
|
bananas.environment.Undefined
|
class Undefined:
...
|
class Undefined:
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 0 | 0 | 0 |
1,230 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/environment.py
|
bananas.environment._Instantiable
|
class _Instantiable(Protocol[Q]):
def __init__(self, value: Iterable[Q]) -> None:
...
|
class _Instantiable(Protocol[Q]):
def __init__(self, value: Iterable[Q]) -> None:
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 1 | 0 | 1 | 23 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 4 | 0 | 1 |
1,231 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/environment.py
|
bananas.environment._InstantiableIterable
|
class _InstantiableIterable(Iterable[Q], _Instantiable[Q], Generic[Q]):
...
|
class _InstantiableIterable(Iterable[Q], _Instantiable[Q], Generic[Q]):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 23 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 5 | 0 | 0 |
1,232 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/management/commands/show_urls.py
|
bananas.management.commands.show_urls.Command
|
class Command(BaseCommand):
def handle(self, *args: object, **kwargs: object) -> None:
show_urls()
|
class Command(BaseCommand):
def handle(self, *args: object, **kwargs: object) -> None:
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 3 | 0 | 3 | 2 | 1 | 0 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
1,233 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/management/commands/syncpermissions.py
|
bananas.management.commands.syncpermissions.Command
|
class Command(BaseCommand):
help = "Create admin permissions"
def handle(self, *args: object, **options: object) -> None:
if args: # pragma: no cover
raise CommandError("Command doesn't accept any arguments")
return self.handle_noargs(**options)
def handle_noargs(self, *args: object, **options: object) -> None:
from django.contrib import admin as django_admin
from django.contrib.contenttypes.models import ContentType
from bananas import admin
django_admin.autodiscover()
for model, _ in admin.site._registry.items():
if issubclass(getattr(model, "View", object), admin.AdminView):
meta = model._meta
assert isinstance(meta.object_name, str)
ct, created = ContentType.objects.get_or_create(
app_label=meta.app_label, model=meta.object_name.lower()
)
if created:
self.stdout.write(
f"Found new admin view: {ct.name} [{ct.app_label}]"
)
for codename, name in model._meta.permissions:
p, created = Permission.objects.update_or_create(
codename=codename, content_type=ct, defaults={"name": name}
)
if created:
self.stdout.write(f"Created permission: {name}")
|
class Command(BaseCommand):
def handle(self, *args: object, **options: object) -> None:
pass
def handle_noargs(self, *args: object, **options: object) -> None:
pass
| 3 | 0 | 16 | 3 | 13 | 1 | 4 | 0.04 | 1 | 2 | 0 | 0 | 2 | 0 | 2 | 2 | 36 | 8 | 28 | 12 | 22 | 1 | 22 | 12 | 16 | 6 | 1 | 4 | 8 |
1,234 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/models.py
|
bananas.models.Missing
|
class Missing:
...
|
class Missing:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 0 | 0 | 0 |
1,235 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/models.py
|
bananas.models.ModelDict
|
class ModelDict(Dict[str, Any]):
_nested: Optional[Dict[str, "ModelDict"]] = None
def __getattr__(self, item: str) -> Any:
"""
Try to to get attribute as key item.
Fallback on prefixed nested keys.
Finally fallback on real attribute lookup.
"""
try:
return self.__getitem__(item)
except KeyError:
try:
return self.__getnested__(item)
except KeyError:
return self.__getattribute__(item)
def __getnested__(self, item: str) -> "ModelDict":
"""
Find existing items prefixed with given item
and return a new ModelDict containing matched keys,
stripped from prefix.
:param str item: Item prefix key to find
:return ModelDict:
"""
# Ensure _nested cache
if self._nested is None:
self._nested: Dict[str, ModelDict] = {}
# Try to get previously accessed/cached nested item
value = self._nested.get(item, MISSING)
if not isinstance(value, Missing):
# Return previously accessed nested item
return value
else:
# Find any keys matching nested prefix
prefix = item + "__"
keys = [key for key in self.keys() if key.startswith(prefix)]
if keys:
# Construct nested dict of matched keys, stripped from prefix
n = ModelDict({key[len(item) + 2 :]: self[key] for key in keys})
# Cache and return
self._nested[item] = n
return n
# Item not a nested key, raise
raise KeyError(item)
def expand(self) -> "ModelDict":
keys = list(self)
for key in keys:
field, __, nested_key = key.partition("__")
if nested_key:
if field not in keys:
nested = self.__getnested__(field)
if isinstance(nested, self.__class__):
nested = nested.expand()
self[field] = nested
del self[key]
return ModelDict(self)
@classmethod
# Ignore types until no longer work-in-progress.
def from_model(cls, model, *fields, **named_fields): # type: ignore[no-untyped-def]
"""
Work-in-progress constructor,
consuming fields and values from django model instance.
"""
d = ModelDict()
if not (fields or named_fields):
# Default to all fields
fields = [ # type: ignore[assignment]
f.attname for f in model._meta.concrete_fields
]
not_found = object()
for name, field in chain(zip(fields, fields), named_fields.items()):
_fields = field.split("__")
value = model
for i, _field in enumerate(_fields, start=1):
# NOTE: we don't want to rely on hasattr here
previous_value = value
value = getattr(previous_value, _field, not_found)
if value is not_found:
if _field in dir(previous_value):
raise ValueError(
"{!r}.{} had an AttributeError exception".format(
previous_value, _field
)
)
else:
raise AttributeError(
f"{previous_value!r} does not have {_field!r} attribute"
)
elif value is None:
if name not in named_fields:
name = "__".join(_fields[:i])
break
d[name] = value
return d
|
class ModelDict(Dict[str, Any]):
def __getattr__(self, item: str) -> Any:
'''
Try to to get attribute as key item.
Fallback on prefixed nested keys.
Finally fallback on real attribute lookup.
'''
pass
def __getnested__(self, item: str) -> "ModelDict":
'''
Find existing items prefixed with given item
and return a new ModelDict containing matched keys,
stripped from prefix.
:param str item: Item prefix key to find
:return ModelDict:
'''
pass
def expand(self) -> "ModelDict":
pass
@classmethod
def from_model(cls, model, *fields, **named_fields):
'''
Work-in-progress constructor,
consuming fields and values from django model instance.
'''
pass
| 6 | 3 | 26 | 4 | 16 | 7 | 5 | 0.42 | 1 | 11 | 1 | 0 | 3 | 0 | 4 | 4 | 111 | 18 | 67 | 22 | 61 | 28 | 55 | 21 | 50 | 8 | 1 | 4 | 20 |
1,236 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/models.py
|
bananas.models.SecretField
|
class SecretField(models.CharField):
description = _("Generates and stores a random key.")
default_error_messages = { # noqa: RUF012
"random-is-none": _("%(cls)s.get_random_bytes returned None"),
"random-too-short": _(
"Too few random bytes received from "
"get_random_bytes. Number of"
" bytes=%(num_bytes)s,"
" min_length=%(min_length)s"
),
}
def __init__(
self,
verbose_name: Optional[str] = None,
num_bytes: int = 32,
min_bytes: int = 32,
auto: bool = True,
**kwargs: Any,
):
self.num_bytes, self.auto, self.min_length = num_bytes, auto, min_bytes
field_length = self.get_field_length(self.num_bytes)
defaults: Mapping[str, Any] = {
"max_length": field_length,
**kwargs,
**(
{
"editable": False,
"blank": True,
}
if self.auto
else {}
),
}
super().__init__(verbose_name, **defaults)
@staticmethod
def get_field_length(num_bytes: int) -> int:
"""
Return the length of hexadecimal byte representation of ``n`` bytes.
:param num_bytes:
:return: The field length required to store the byte representation.
"""
return num_bytes * 2
def pre_save(self, model_instance: models.Model, add: bool) -> Any:
if self.auto and add:
value = self.get_random_str()
setattr(model_instance, self.attname, value)
return value
else:
return super().pre_save(model_instance, add)
def get_random_str(self) -> str:
random = self.get_random_bytes()
self._check_random_bytes(random)
return binascii.hexlify(random).decode("utf8")
def _check_random_bytes(self, random: Optional[Sized]) -> None:
if random is None:
raise ValidationError(
self.error_messages["random-is-none"],
code="invalid",
params={"cls": self.__class__.__name__},
)
if len(random) < self.min_length:
raise ValidationError(
self.error_messages["random-too-short"],
code="invalid",
params={"num_bytes": len(random), "min_length": self.min_length},
)
def get_random_bytes(self) -> bytes:
return os.urandom(self.num_bytes)
|
class SecretField(models.CharField):
def __init__(
self,
verbose_name: Optional[str] = None,
num_bytes: int = 32,
min_bytes: int = 32,
auto: bool = True,
**kwargs: Any,
):
pass
@staticmethod
def get_field_length(num_bytes: int) -> int:
'''
Return the length of hexadecimal byte representation of ``n`` bytes.
:param num_bytes:
:return: The field length required to store the byte representation.
'''
pass
def pre_save(self, model_instance: models.Model, add: bool) -> Any:
pass
def get_random_str(self) -> str:
pass
def _check_random_bytes(self, random: Optional[Sized]) -> None:
pass
def get_random_bytes(self) -> bytes:
pass
| 8 | 1 | 10 | 1 | 9 | 1 | 2 | 0.1 | 1 | 6 | 0 | 1 | 5 | 3 | 6 | 6 | 80 | 12 | 63 | 22 | 48 | 6 | 27 | 14 | 20 | 3 | 1 | 1 | 10 |
1,237 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/models.py
|
bananas.models.TimeStampedModel
|
class TimeStampedModel(models.Model):
"""
Provides automatic date_created and date_modified fields.
"""
date_created = models.DateTimeField(
blank=True,
null=True,
editable=False,
auto_now_add=True,
verbose_name=_("date created"),
)
date_modified = models.DateTimeField(
blank=True,
null=True,
editable=False,
auto_now=True,
verbose_name=_("date modified"),
)
class Meta:
abstract = True
def save(self, *args: Any, **kwargs: Any) -> None:
if "update_fields" in kwargs and "date_modified" not in kwargs["update_fields"]:
update_fields = list(kwargs["update_fields"])
update_fields.append("date_modified")
kwargs["update_fields"] = update_fields
super().save(*args, **kwargs)
|
class TimeStampedModel(models.Model):
'''
Provides automatic date_created and date_modified fields.
'''
class Meta:
def save(self, *args: Any, **kwargs: Any) -> None:
pass
| 3 | 1 | 6 | 0 | 6 | 0 | 2 | 0.13 | 1 | 3 | 0 | 6 | 1 | 0 | 1 | 1 | 29 | 3 | 23 | 7 | 20 | 3 | 11 | 7 | 8 | 2 | 1 | 1 | 2 |
1,238 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/models.py
|
bananas.models.URLSecretField
|
class URLSecretField(SecretField):
@staticmethod
def get_field_length(num_bytes: int) -> int:
"""
Get the maximum possible length of a base64 encoded bytearray of
length ``length``.
:param num_bytes: The length of the bytearray
:return: The worst case length of the base64 result.
"""
return math.ceil(num_bytes / 3.0) * 4
@staticmethod
def y64_encode(s: bytes) -> bytes:
"""
Implementation of Y64 non-standard URL-safe base64 variant.
See http://en.wikipedia.org/wiki/Base64#Variants_summary_table
:return: base64-encoded result with substituted
``{"+", "/", "="} => {".", "_", "-"}``.
"""
first_pass = base64.urlsafe_b64encode(s)
return first_pass.translate(bytes.maketrans(b"+/=", b"._-"))
def get_random_str(self) -> str:
random = self.get_random_bytes()
self._check_random_bytes(random)
return self.y64_encode(random).decode("utf-8")
|
class URLSecretField(SecretField):
@staticmethod
def get_field_length(num_bytes: int) -> int:
'''
Get the maximum possible length of a base64 encoded bytearray of
length ``length``.
:param num_bytes: The length of the bytearray
:return: The worst case length of the base64 result.
'''
pass
@staticmethod
def y64_encode(s: bytes) -> bytes:
'''
Implementation of Y64 non-standard URL-safe base64 variant.
See http://en.wikipedia.org/wiki/Base64#Variants_summary_table
:return: base64-encoded result with substituted
``{"+", "/", "="} => {".", "_", "-"}``.
'''
pass
def get_random_str(self) -> str:
pass
| 6 | 2 | 8 | 1 | 3 | 4 | 1 | 1 | 1 | 3 | 0 | 0 | 1 | 0 | 3 | 9 | 29 | 5 | 12 | 8 | 6 | 12 | 10 | 6 | 6 | 1 | 2 | 0 | 3 |
1,239 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/query.py
|
bananas.query.IsManager
|
class IsManager(Protocol[_MT]):
model: Type[_MT]
_db: Optional[str]
|
class IsManager(Protocol[_MT]):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 22 | 3 | 0 | 3 | 1 | 2 | 0 | 3 | 1 | 2 | 0 | 4 | 0 | 0 |
1,240 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/query.py
|
bananas.query.IsQuerySet
|
class IsQuerySet(Protocol[_MT_co]):
def values(
self, *fields: Union[str, Combinable], **expressions: Any
) -> "_QuerySet[_MT_co, ModelDict]":
...
|
class IsQuerySet(Protocol[_MT_co]):
def values(
self, *fields: Union[str, Combinable], **expressions: Any
) -> "_QuerySet[_MT_co, ModelDict]":
pass
| 2 | 0 | 4 | 0 | 4 | 0 | 1 | 0 | 1 | 2 | 0 | 1 | 1 | 0 | 1 | 23 | 5 | 0 | 5 | 4 | 1 | 0 | 3 | 2 | 1 | 1 | 4 | 0 | 1 |
1,241 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/query.py
|
bananas.query.ModelDictIterable
|
class ModelDictIterable:
def __init__(self, queryset: T) -> None:
self.queryset = queryset
self.named_fields: Mapping[str, str] = self.queryset._hints.get("_named_fields") # type: ignore[attr-defined]
def __iter__(self) -> Iterator[ModelDict]:
queryset = self.queryset
query = queryset.query
compiler = query.get_compiler(queryset.db)
field_names: List[str] = list(query.values_select)
extra_names: List[str] = list(query.extra_select)
annotation_names: List[str] = list(query.annotation_select)
# Modified super(); rename fields given in queryset.values() kwargs
names = extra_names + field_names + annotation_names
if self.named_fields:
names = self.rename_fields(names)
for row in compiler.results_iter():
yield ModelDict(zip(names, row))
def rename_fields(self, names: Iterable[str]) -> List[str]:
named_fields = {value: key for key, value in self.named_fields.items()}
names = [named_fields.get(name, name) for name in names]
return names
|
class ModelDictIterable:
def __init__(self, queryset: T) -> None:
pass
def __iter__(self) -> Iterator[ModelDict]:
pass
def rename_fields(self, names: Iterable[str]) -> List[str]:
pass
| 4 | 0 | 8 | 1 | 6 | 1 | 2 | 0.1 | 0 | 4 | 1 | 0 | 3 | 2 | 3 | 3 | 26 | 5 | 20 | 15 | 16 | 2 | 20 | 15 | 16 | 3 | 0 | 1 | 5 |
1,242 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/query.py
|
bananas.query.ModelDictManagerMixin
|
class ModelDictManagerMixin:
def dicts(
self, *fields: str, **named_fields: str
) -> "_QuerySet[_MT_co, ModelDict]":
# Mypy: `self` types don't add up
queryset = self.get_queryset() # type: ignore[misc]
return queryset.dicts(*fields, **named_fields)
def get_queryset(self: IsManager[_MT]) -> ModelDictQuerySet:
return ModelDictQuerySet(self.model, using=self._db)
|
class ModelDictManagerMixin:
def dicts(
self, *fields: str, **named_fields: str
) -> "_QuerySet[_MT_co, ModelDict]":
pass
def get_queryset(self: IsManager[_MT]) -> ModelDictQuerySet:
pass
| 3 | 0 | 4 | 0 | 4 | 1 | 1 | 0.25 | 0 | 3 | 2 | 1 | 2 | 1 | 2 | 2 | 10 | 1 | 8 | 7 | 3 | 2 | 6 | 4 | 3 | 1 | 0 | 0 | 2 |
1,243 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/query.py
|
bananas.query.ModelDictQuerySetMixin
|
class ModelDictQuerySetMixin:
def dicts(
self: IsQuerySet[_MT_co], *fields: str, **named_fields: str
) -> "_QuerySet[_MT_co, ModelDict]":
if named_fields:
fields += tuple(named_fields.values())
clone = self.values(*fields)
clone._iterable_class = ModelDictIterable # type: ignore[assignment]
# QuerySet._hints is a dict object used by db router
# to aid deciding which db should get a request. Currently
# django only supports `instance`, so it's probably
# fine to set a custom key on this dict as it's a guaranteed
# way that it'll be returned with the QuerySet instance
# while leaving the queryset intact
clone._add_hints(**{"_named_fields": named_fields}) # type: ignore[attr-defined]
return clone
|
class ModelDictQuerySetMixin:
def dicts(
self: IsQuerySet[_MT_co], *fields: str, **named_fields: str
) -> "_QuerySet[_MT_co, ModelDict]":
pass
| 2 | 0 | 18 | 3 | 9 | 8 | 2 | 0.8 | 0 | 4 | 2 | 2 | 1 | 0 | 1 | 1 | 19 | 3 | 10 | 5 | 6 | 8 | 8 | 3 | 6 | 2 | 0 | 1 | 2 |
1,244 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/admin/api/versioning.py
|
bananas.admin.api.versioning.BananasVersioning
|
class BananasVersioning(NamespaceVersioning):
default_version: str = v1_0.__version__
allowed_versions: Sequence[str] = tuple(
version.__version__ for version in __versions__
)
version_map: ClassVar[Dict[str, ModuleType]] = {
version.__version__: version for version in __versions__
}
def get_versioned_viewname(self, viewname: str, request: Request) -> str:
"""
Prefix viewname with full namespace bananas:vX.Y:
"""
assert request.resolver_match is not None
namespace = request.resolver_match.namespace
if namespace:
viewname = f"{namespace}:{viewname}"
return viewname
|
class BananasVersioning(NamespaceVersioning):
def get_versioned_viewname(self, viewname: str, request: Request) -> str:
'''
Prefix viewname with full namespace bananas:vX.Y:
'''
pass
| 2 | 1 | 10 | 1 | 6 | 3 | 2 | 0.21 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 19 | 2 | 14 | 6 | 12 | 3 | 10 | 6 | 8 | 2 | 1 | 1 | 2 |
1,245 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/url.py
|
bananas.url.DatabaseInfo
|
class DatabaseInfo(NamedTuple):
engine: str
name: Optional[str]
schema: Optional[str]
user: Optional[str]
password: Optional[str]
host: Optional[str]
port: Optional[int]
params: Dict[str, str]
|
class DatabaseInfo(NamedTuple):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 9 | 0 | 9 | 1 | 8 | 0 | 9 | 1 | 8 | 0 | 1 | 0 | 0 |
1,246 |
5monkeys/django-bananas
|
5monkeys_django-bananas/example/example/admin.py
|
example.admin.BananasAdmin
|
class BananasAdmin(AdminView):
verbose_name = _('Bananas')
permissions = (('foobar_permission', 'Can foo bars'),)
tools = (
(_('home'), 'admin:index', 'has_access'),
('superadmin only', 'https://foo.bar/', 'foobar_permission'),
)
def get(self, request):
return self.render('bananas.html')
|
class BananasAdmin(AdminView):
def get(self, request):
pass
| 2 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 11 | 10 | 1 | 9 | 5 | 7 | 0 | 6 | 5 | 4 | 1 | 2 | 0 | 1 |
1,247 |
5monkeys/django-bananas
|
5monkeys_django-bananas/example/example/admin.py
|
example.admin.MonkeyAdmin
|
class MonkeyAdmin(admin.ModelAdmin):
list_display = ('id',)
list_filter = ('user__username',)
raw_id_fields = ('user',)
date_hierarchy = 'date_created'
actions_on_top = True
actions_on_bottom = True
actions_selection_counter = False
|
class MonkeyAdmin(admin.ModelAdmin):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 | 0 | 8 | 8 | 7 | 0 | 8 | 8 | 7 | 0 | 1 | 0 | 0 |
1,248 |
5monkeys/django-bananas
|
5monkeys_django-bananas/example/example/api.py
|
example.api.BananaViewSet
|
class BananaViewSet(BananasAPI, viewsets.ModelViewSet):
name = lazy_title(_("banana"))
def list(self, request):
return Response()
class Admin:
app_label = "fruit"
|
class BananaViewSet(BananasAPI, viewsets.ModelViewSet):
def list(self, request):
pass
class Admin:
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 2 | 0 | 0 | 0 | 1 | 0 | 1 | 5 | 9 | 3 | 6 | 5 | 3 | 0 | 6 | 5 | 3 | 1 | 1 | 0 | 1 |
1,249 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/drf/errors.py
|
bananas.drf.errors.PreconditionFailed
|
class PreconditionFailed(APIException):
status_code = status.HTTP_412_PRECONDITION_FAILED
default_detail = "An HTTP precondition failed"
default_code = "precondition_failed"
|
class PreconditionFailed(APIException):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 1 | 0 | 0 |
1,250 |
5monkeys/django-bananas
|
5monkeys_django-bananas/example/example/api.py
|
example.api.UserFilterSerializer
|
class UserFilterSerializer(serializers.Serializer):
username = serializers.CharField(required=False)
|
class UserFilterSerializer(serializers.Serializer):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
1,251 |
5monkeys/django-bananas
|
5monkeys_django-bananas/example/example/api.py
|
example.api.PearViewSet
|
class PearViewSet(BananasAPI, viewsets.ModelViewSet):
name = lazy_title(_("pear"))
def list(self, request):
return Response()
class Admin:
app_label = "fruit"
|
class PearViewSet(BananasAPI, viewsets.ModelViewSet):
def list(self, request):
pass
class Admin:
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 2 | 0 | 0 | 0 | 1 | 0 | 1 | 5 | 9 | 3 | 6 | 5 | 3 | 0 | 6 | 5 | 3 | 1 | 1 | 0 | 1 |
1,252 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/tests/test_admin.py
|
tests.test_admin.AdminTest.test_register_with_args.MyAdminViewRegisteredWithArgs
|
class MyAdminViewRegisteredWithArgs(admin.AdminView):
__module__ = "tests.admin"
|
class MyAdminViewRegisteredWithArgs(admin.AdminView):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 2 | 0 | 0 |
1,253 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/tests/test_admin.py
|
tests.test_admin.AdminTest.test_admin.FakeRequest
|
class FakeRequest:
META = {"SCRIPT_NAME": ""}
user = AnonymousUser()
|
class FakeRequest:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 0 | 0 | 0 |
1,254 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/tests/test_admin.py
|
tests.test_admin.AdminTest.test_admin.AnAdminView
|
class AnAdminView(admin.AdminView):
__module__ = "tests.admin"
|
class AnAdminView(admin.AdminView):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 2 | 0 | 0 |
1,255 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/admin/api/mixins.py
|
bananas.admin.api.mixins.SchemaSerializerMixin
|
class SchemaSerializerMixin:
def get_serializer_class(self) -> Type["BaseSerializer[_MT_co]"]:
serializer_class = cast(GenericViewSet, super()).get_serializer_class()
action = getattr(self, cast(GenericViewSet, self).action, None)
schema = getattr(action, "_swagger_auto_schema", None)
if schema:
responses = schema.get("responses")
if responses:
status_code = sorted(responses.keys())[0]
if status_code < 300:
serializer_class = responses[status_code]
return serializer_class
|
class SchemaSerializerMixin:
def get_serializer_class(self) -> Type["BaseSerializer[_MT_co]"]:
pass
| 2 | 0 | 13 | 2 | 11 | 0 | 4 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 14 | 2 | 12 | 7 | 10 | 0 | 12 | 7 | 10 | 4 | 0 | 3 | 4 |
1,256 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/admin/api/permissions.py
|
bananas.admin.api.permissions.IsAnonymous
|
class IsAnonymous(BasePermission):
"""
Allows access only to non-authenticated users.
"""
def has_permission(self, request: Request, view: APIView) -> bool:
return not request.user or request.user.is_anonymous
|
class IsAnonymous(BasePermission):
'''
Allows access only to non-authenticated users.
'''
def has_permission(self, request: Request, view: APIView) -> bool:
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 7 | 1 | 3 | 2 | 1 | 3 | 3 | 2 | 1 | 1 | 1 | 0 | 1 |
1,257 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/admin/api/schemas/yasg.py
|
bananas.admin.api.schemas.yasg.BananasEndpointEnumerator
|
class BananasEndpointEnumerator(EndpointEnumerator):
def should_include_endpoint(
self,
path: str,
callback: Callable,
app_name: str = "",
namespace: str = "",
url_name: Optional[str] = None,
) -> bool:
# Fall back to check namespace on the resolver match
request = self.request
if (
not namespace
and getattr(request, "version", None)
and getattr(request, "resolver_match", None)
):
namespace = request.resolver_match.namespace or ""
return cast(
bool,
super().should_include_endpoint(
path, callback, app_name, namespace, url_name
),
)
|
class BananasEndpointEnumerator(EndpointEnumerator):
def should_include_endpoint(
self,
path: str,
callback: Callable,
app_name: str = "",
namespace: str = "",
url_name: Optional[str] = None,
) -> bool:
pass
| 2 | 0 | 22 | 0 | 21 | 1 | 2 | 0.05 | 1 | 3 | 0 | 0 | 1 | 0 | 1 | 1 | 23 | 0 | 22 | 10 | 13 | 1 | 6 | 3 | 4 | 2 | 1 | 1 | 2 |
1,258 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/admin/api/schemas/yasg.py
|
bananas.admin.api.schemas.yasg.BananasOpenAPISchemaGenerator
|
class BananasOpenAPISchemaGenerator(OpenAPISchemaGenerator):
endpoint_enumerator_class = BananasEndpointEnumerator
def get_schema(
self, request: Optional[Request] = None, public: bool = False
) -> Dict[str, Any]:
schema: Dict[str, Any] = super().get_schema(request, public)
api_settings = getattr(settings, "ADMIN", {}).get("API", {})
schema["schemes"] = api_settings.get("SCHEMES", schema["schemes"])
return schema
def get_paths(
self, endpoints: Dict[str, Any], components: Any, request: Request, public: bool
) -> Tuple[Any, str]:
paths, prefix = super().get_paths(endpoints, components, request, public)
path = request._request.path
return paths, path[: path.rfind("/")] + prefix
|
class BananasOpenAPISchemaGenerator(OpenAPISchemaGenerator):
def get_schema(
self, request: Optional[Request] = None, public: bool = False
) -> Dict[str, Any]:
pass
def get_paths(
self, endpoints: Dict[str, Any], components: Any, request: Request, public: bool
) -> Tuple[Any, str]:
pass
| 3 | 0 | 7 | 0 | 7 | 0 | 1 | 0 | 1 | 4 | 0 | 0 | 2 | 0 | 2 | 2 | 17 | 2 | 15 | 12 | 8 | 0 | 11 | 8 | 8 | 1 | 1 | 0 | 2 |
1,259 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/admin/api/schemas/yasg.py
|
bananas.admin.api.schemas.yasg.BananasSimpleRouter
|
class BananasSimpleRouter(BananasBaseRouter, SimpleRouter):
def get_schema_view(self) -> Any:
view = get_schema_view(
openapi.Info(
title="Django Bananas Admin API Schema",
default_version=BananasVersioning.default_version,
description="API for django-bananas.js",
# terms_of_service="https://www.google.com/policies/terms/",
# license=openapi.License(name="BSD License"),
),
# validators=["flex", "ssv"],
public=False,
generator_class=BananasOpenAPISchemaGenerator,
authentication_classes=(SessionAuthentication,),
permission_classes=(permissions.AllowAny,),
patterns=self.urls,
)
view.versioning_class = BananasVersioning
return view
|
class BananasSimpleRouter(BananasBaseRouter, SimpleRouter):
def get_schema_view(self) -> Any:
pass
| 2 | 0 | 19 | 1 | 15 | 3 | 1 | 0.19 | 2 | 3 | 2 | 0 | 1 | 0 | 1 | 3 | 20 | 1 | 16 | 3 | 14 | 3 | 5 | 3 | 3 | 1 | 1 | 0 | 1 |
1,260 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/tests/test_admin.py
|
tests.test_admin.AdminTest.test_register_app_nested_in_package.MyAdminViewRegisteredInNestedApp
|
class MyAdminViewRegisteredInNestedApp(admin.AdminView):
__module__ = "somepackage.tests.admin"
|
class MyAdminViewRegisteredInNestedApp(admin.AdminView):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 2 | 0 | 0 |
1,261 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/admin/api/schemas/yasg.py
|
bananas.admin.api.schemas.yasg.BananasSwaggerSchema
|
class BananasSwaggerSchema(SwaggerAutoSchema):
def get_operation_id(self, operation_keys: Sequence[str]) -> str:
name = ".".join(operation_keys[2:])
basename: str = self.view.get_admin_meta().basename
return basename + ":" + name
def get_summary_and_description(self) -> Tuple[Optional[str], str]:
"""
Compat: drf-yasg 1.12+
"""
summary = self.get_summary()
_, description = super().get_summary_and_description()
return summary, description
def get_summary(self) -> str:
"""
Compat: drf-yasg 1.11
"""
title = None
method_name = getattr(self.view, "action", self.method.lower())
action = getattr(self.view, method_name, None)
action_kwargs = getattr(action, "kwargs", None)
if action_kwargs:
title = action_kwargs.get("name")
if not title and is_custom_action(self.view.action):
title = _(self.view.action.replace("_", " ")).capitalize()
if not title:
meta = self.view.get_admin_meta()
if self.view.action in ["retrieve", "update", "partial_update"]:
title = str(meta.get("verbose_name") or meta.name)
elif self.view.action == "create":
title = meta.get("verbose_name")
if title:
title = str(_("Add")) + " " + str(title).lower()
else:
title = meta.name
elif self.view.action == "list":
title = str(meta.get("verbose_name_plural") or meta.name)
else:
title = str(meta.name)
return title
def get_tags(self, operation_keys: Tuple[str, ...]) -> List[str]:
view = self.view
meta = self.view.get_admin_meta()
tags = {f"app:{meta.app_label}"}
if self.is_navigation():
tags.add("navigation")
if issubclass(view.__class__, viewsets.ModelViewSet):
tags.add("crud")
view_method = getattr(view, view.action, None)
if view_method:
include_tags = set(getattr(view_method, "include_tags", None) or [])
exclude_tags = set(getattr(view_method, "exclude_tags", None) or [])
tags |= include_tags
tags -= exclude_tags
return [tag for tag in tags if tag not in meta.exclude_tags]
def is_navigation(self) -> bool:
if not hasattr(self, "_is_navigation"):
self._is_navigation = False
try:
if self.method == "GET" and (
self.view.action == "list" or not hasattr(self.view, "list")
):
self.view.reverse_action("list")
self._is_navigation = True
except NoReverseMatch:
pass
return self._is_navigation
|
class BananasSwaggerSchema(SwaggerAutoSchema):
def get_operation_id(self, operation_keys: Sequence[str]) -> str:
pass
def get_summary_and_description(self) -> Tuple[Optional[str], str]:
'''
Compat: drf-yasg 1.12+
'''
pass
def get_summary_and_description(self) -> Tuple[Optional[str], str]:
'''
Compat: drf-yasg 1.11
'''
pass
def get_tags(self, operation_keys: Tuple[str, ...]) -> List[str]:
pass
def is_navigation(self) -> bool:
pass
| 6 | 2 | 15 | 2 | 12 | 1 | 4 | 0.1 | 1 | 4 | 0 | 1 | 5 | 1 | 5 | 5 | 80 | 14 | 60 | 22 | 54 | 6 | 54 | 22 | 48 | 8 | 1 | 3 | 18 |
1,262 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/tests/test_commands.py
|
tests.test_commands.CommandTests
|
class CommandTests(TestCase):
@pytest.mark.skipif(
not drf_installed(), reason="Django rest framework not installed"
)
def test_show_urls(self):
urls = show_urls.collect_urls()
admin_api_url_count = 50
self.assertEqual(len(urls), admin_api_url_count)
# type: ignore[attr-defined]
with mock.patch.object(show_urls.sys, "stdout", autospec=True) as stdout:
show_urls.show_urls()
self.assertEqual(stdout.write.call_count, admin_api_url_count)
call_command("show_urls")
|
class CommandTests(TestCase):
@pytest.mark.skipif(
not drf_installed(), reason="Django rest framework not installed"
)
def test_show_urls(self):
pass
| 3 | 0 | 12 | 4 | 8 | 1 | 1 | 0.08 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 1 | 16 | 4 | 12 | 8 | 7 | 1 | 9 | 4 | 7 | 1 | 1 | 1 | 1 |
1,263 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/admin/api/serializers.py
|
bananas.admin.api.serializers.AuthenticationSerializer
|
class AuthenticationSerializer(serializers.Serializer):
username = serializers.CharField(label=_("Username"), write_only=True)
password = serializers.CharField(label=_("Password"), write_only=True)
|
class AuthenticationSerializer(serializers.Serializer):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 1 | 0 | 0 |
1,264 |
5monkeys/django-bananas
|
5monkeys_django-bananas/src/bananas/admin/api/serializers.py
|
bananas.admin.api.serializers.PasswordChangeSerializer
|
class PasswordChangeSerializer(serializers.Serializer):
old_password = serializers.CharField(label=_("Old password"), write_only=True)
new_password1 = serializers.CharField(
label=_("New password"),
help_text="\n".join(password_validators_help_texts()),
write_only=True,
)
new_password2 = serializers.CharField(
label=_("New password confirmation"), write_only=True
)
|
class PasswordChangeSerializer(serializers.Serializer):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 0 | 10 | 4 | 9 | 0 | 4 | 4 | 3 | 0 | 1 | 0 | 0 |
1,265 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/tests/test_admin.py
|
tests.test_admin.AdminTest.test_register_without_args.MyAdminViewRegisteredWithoutArgs
|
class MyAdminViewRegisteredWithoutArgs(admin.AdminView):
__module__ = "tests.admin"
|
class MyAdminViewRegisteredWithoutArgs(admin.AdminView):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 2 | 0 | 0 |
1,266 |
5monkeys/django-bananas
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-bananas/tests/test_admin.py
|
tests.test_admin.AdminTest.test_register_normally.MyAdminViewRegisteredNormally
|
class MyAdminViewRegisteredNormally(admin.AdminView):
__module__ = "tests.admin"
|
class MyAdminViewRegisteredNormally(admin.AdminView):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 2 | 0 | 0 |
1,267 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/tests/models.py
|
django_enumfield.tests.models.PersonStatus
|
class PersonStatus(Enum):
UNBORN = 0
ALIVE = 1
DEAD = 2
REANIMATED = 3
VOID = 4
__transitions__ = {
UNBORN: (VOID,),
ALIVE: (UNBORN,),
DEAD: (UNBORN, ALIVE),
REANIMATED: (DEAD,),
}
|
class PersonStatus(Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 70 | 13 | 1 | 12 | 7 | 11 | 0 | 7 | 7 | 6 | 0 | 4 | 0 | 0 |
1,268 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/tests/models.py
|
django_enumfield.tests.models.PersonStatusDefault
|
class PersonStatusDefault(Enum):
UNBORN = 0
ALIVE = 1
DEAD = 2
REANIMATED = 3
VOID = 4
__default__ = UNBORN
|
class PersonStatusDefault(Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 70 | 8 | 1 | 7 | 7 | 6 | 0 | 7 | 7 | 6 | 0 | 4 | 0 | 0 |
1,269 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/tests/test_contrib.py
|
django_enumfield.tests.test_contrib.DRFTestCase
|
class DRFTestCase(TestCase):
def test_enum_field(self):
field = EnumField(BeerState)
self.assertEqual(field.to_internal_value("0"), BeerState.FIZZY)
self.assertEqual(
field.to_internal_value(BeerState.EMPTY.value), BeerState.EMPTY
)
self.assertEqual(
field.to_representation(BeerState.FIZZY), BeerState.FIZZY.value
)
def test_enum_field__validation_fail(self):
field = EnumField(BeerState)
with self.assertRaises(ValidationError):
field.to_internal_value("3")
nonrequired_field = EnumField(LampState, required=False)
with self.assertRaises(SkipField):
self.assertEqual(nonrequired_field.to_internal_value("3"), 1)
def test_named_enum_field(self):
field = NamedEnumField(LampState)
self.assertEqual(field.to_internal_value("1"), LampState.ON)
self.assertEqual(field.to_representation(LampState.OFF), "OFF")
|
class DRFTestCase(TestCase):
def test_enum_field(self):
pass
def test_enum_field__validation_fail(self):
pass
def test_named_enum_field(self):
pass
| 4 | 0 | 7 | 0 | 7 | 0 | 1 | 0 | 1 | 4 | 4 | 0 | 3 | 0 | 3 | 3 | 24 | 3 | 21 | 8 | 17 | 0 | 17 | 8 | 13 | 1 | 1 | 1 | 3 |
1,270 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/tests/test_enum.py
|
django_enumfield.tests.test_enum.EnumFieldTest
|
class EnumFieldTest(TestCase):
def test_enum_field_init(self):
for enum, default in {
PersonStatus: NOT_PROVIDED,
PersonStatusDefault: PersonStatusDefault.UNBORN,
}.items():
field = EnumField(enum)
self.assertEqual(field.default, default)
self.assertEqual(len(enum.choices()), len(field.choices))
field = EnumField(enum, default=enum.ALIVE)
self.assertEqual(field.default, enum.ALIVE)
field = EnumField(enum, default=None)
self.assertEqual(field.default, None)
def test_enum_field_save(self):
# Test model with EnumField WITHOUT __transitions__
lamp = Lamp.objects.create()
self.assertEqual(lamp.state, LampState.OFF)
lamp.state = LampState.ON
lamp.save()
self.assertEqual(lamp.state, LampState.ON)
self.assertEqual(lamp.state, 1)
self.assertRaises(InvalidStatusOperationError, setattr, lamp, "state", 99)
# Test model with EnumField WITH __transitions__
person = Person.objects.create()
pk = person.pk
self.assertEqual(person.status, PersonStatus.ALIVE)
person.status = PersonStatus.DEAD
person.save()
self.assertTrue(isinstance(person.status, PersonStatus))
self.assertEqual(person.status, PersonStatus.DEAD)
person = Person.objects.get(pk=pk)
self.assertEqual(person.status, PersonStatus.DEAD)
self.assertTrue(isinstance(person.status, int))
self.assertTrue(isinstance(person.status, PersonStatus))
self.assertRaises(InvalidStatusOperationError, setattr, person, "status", 99)
person = Person.objects.create(status=PersonStatus.ALIVE)
self.assertRaises(
InvalidStatusOperationError, setattr, person, "status", PersonStatus.UNBORN
)
person.status = PersonStatus.DEAD
self.assertEqual(person.save(), "Person.save")
with self.assertRaises(InvalidStatusOperationError):
person.status = PersonStatus.VOID
person.save()
self.assertTrue(Person.objects.filter(status=PersonStatus.DEAD).exists())
beer = Beer.objects.create()
beer.style = BeerStyle.LAGER
self.assertEqual(beer.state, BeerState.FIZZY)
beer.save()
def test_enum_field_refresh_from_db(self):
lamp = Lamp.objects.create(state=LampState.OFF)
lamp2 = Lamp.objects.get(pk=lamp.id)
lamp.state = LampState.ON
lamp.save()
self.assertEqual(lamp.state, LampState.ON)
self.assertEqual(lamp2.state, LampState.OFF)
lamp2.refresh_from_db()
self.assertEqual(lamp2.state, LampState.ON)
def test_magic_model_properties(self):
beer = Beer.objects.create(style=BeerStyle.WEISSBIER)
self.assertEqual(getattr(beer, "get_style_display")(), "WEISSBIER")
def test_enum_field_del(self):
lamp = Lamp.objects.create()
del lamp.state
self.assertEqual(lamp.state, None)
self.assertRaises(IntegrityError, lamp.save)
def test_enum_field_del_save(self):
beer = Beer.objects.create()
beer.style = BeerStyle.STOUT
beer.state = None
beer.save()
self.assertEqual(beer.state, None)
self.assertEqual(beer.style, BeerStyle.STOUT)
def test_enum_field_modelform_create(self):
request_factory = RequestFactory()
request = request_factory.post("", data={"status": "2"})
form = PersonForm(request.POST)
self.assertTrue(isinstance(form.fields["status"], forms.TypedChoiceField))
self.assertTrue(form.is_valid())
person = form.save()
self.assertTrue(person.status, PersonStatus.DEAD)
request = request_factory.post("", data={"status": "99"})
form = PersonForm(request.POST, instance=person)
self.assertFalse(form.is_valid())
def test_enum_field_modelform(self):
person = Person.objects.create()
request_factory = RequestFactory()
request = request_factory.post("", data={"status": "2"})
form = PersonForm(request.POST, instance=person)
self.assertTrue(isinstance(form.fields["status"], forms.TypedChoiceField))
self.assertTrue(form.is_valid())
form.save()
self.assertTrue(person.status, PersonStatus.DEAD)
request = request_factory.post("", data={"status": "99"})
form = PersonForm(request.POST, instance=person)
self.assertFalse(form.is_valid())
def test_enum_field_modelform_initial(self):
person = Person.objects.create()
form = PersonForm(instance=person)
self.assertEqual(form.fields["status"].initial, PersonStatus.ALIVE.value)
self.assertIn(
'<option value="{}" selected'.format(PersonStatus.ALIVE.value),
str(form["status"]),
)
def test_enum_field_nullable_field(self):
class BeerForm(forms.ModelForm):
class Meta:
model = Beer
fields = ("style", "state")
form = BeerForm()
self.assertEqual(len(form.fields["style"].choices), 3)
self.assertEqual(form.fields["style"].choices[0][1].label, "LAGER")
self.assertEqual(form.fields["style"].choices[1][1].label, "STOUT")
self.assertEqual(form.fields["style"].choices[2][1].label, "WEISSBIER")
self.assertEqual(len(form.fields["state"].choices), 4)
self.assertEqual(form.fields["state"].choices[0][1].label, "")
self.assertEqual(form.fields["state"].choices[1][1].label, "FIZZY")
self.assertEqual(form.fields["state"].choices[2][1].label, "STALE")
self.assertEqual(form.fields["state"].choices[3][1].label, "EMPTY")
def test_migration(self):
app_dir = dirname(abspath(__file__))
self.assertTrue(exists(join(app_dir, "models.py")))
migrations_dir = join(app_dir, "migrations")
self.assertTrue(not exists(migrations_dir))
call_command("makemigrations", "tests")
with patch_sqlite_connection():
call_command("sqlmigrate", "tests", "0001")
def test_enum_form_field(self):
class CustomPersonForm(forms.Form):
status = EnumChoiceField(PersonStatus)
form = CustomPersonForm(initial={"status": PersonStatus.DEAD})
self.assertEqual(form["status"].initial, PersonStatus.DEAD.value)
self.assertIn(
'<option value="{}" selected'.format(PersonStatus.DEAD.value),
str(form["status"]),
)
self.assertEqual(form.fields["status"].choices, PersonStatus.choices())
# Test validation
form = CustomPersonForm(
data={"status": str(PersonStatus.ALIVE.value)},
initial={"status": PersonStatus.DEAD.value},
)
self.assertTrue(form.is_valid(), form.errors)
self.assertEqual(form.cleaned_data["status"], PersonStatus.ALIVE)
def test_enum_form_field_not_required(self):
class CustomPersonForm(forms.Form):
status = EnumChoiceField(PersonStatus, required=False)
form = CustomPersonForm(
data={"status": None}, initial={"status": PersonStatus.DEAD.value}
)
self.assertEqual(
form.fields["status"].choices, PersonStatus.choices(blank=True)
)
self.assertIn('<option value="" selected', str(form["status"]))
self.assertTrue(form.is_valid(), form.errors)
self.assertEqual(form.cleaned_data["status"], "")
def test_enum_display_none(self):
beer = Beer(state=None)
self.assertIsNone(beer.get_state_display())
|
class EnumFieldTest(TestCase):
def test_enum_field_init(self):
pass
def test_enum_field_save(self):
pass
def test_enum_field_refresh_from_db(self):
pass
def test_magic_model_properties(self):
pass
def test_enum_field_del(self):
pass
def test_enum_field_del_save(self):
pass
def test_enum_field_modelform_create(self):
pass
def test_enum_field_modelform_create(self):
pass
def test_enum_field_modelform_initial(self):
pass
def test_enum_field_nullable_field(self):
pass
class BeerForm(forms.ModelForm):
class Meta:
def test_migration(self):
pass
def test_enum_form_field(self):
pass
class CustomPersonForm(forms.Form):
def test_enum_form_field_not_required(self):
pass
class CustomPersonForm(forms.Form):
def test_enum_display_none(self):
pass
| 19 | 0 | 13 | 2 | 11 | 0 | 1 | 0.02 | 1 | 16 | 14 | 0 | 14 | 0 | 14 | 14 | 196 | 37 | 156 | 50 | 137 | 3 | 138 | 50 | 119 | 2 | 1 | 1 | 15 |
1,271 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/tests/test_enum.py
|
django_enumfield.tests.test_enum.EnumTest
|
class EnumTest(TestCase):
def test_label(self):
self.assertEqual(PersonStatus.ALIVE.label, "ALIVE")
self.assertEqual(LabelBeer.STELLA.label, "Stella Artois")
self.assertEqual(LabelBeer.label(LabelBeer.STELLA), "Stella Artois")
# Same as when coercing to string
self.assertEqual(str(PersonStatus.ALIVE), "ALIVE")
self.assertEqual(str(LabelBeer.STELLA), "Stella Artois")
def test_name(self):
self.assertEqual(PersonStatus.ALIVE.name, "ALIVE")
self.assertEqual(LabelBeer.STELLA.name, "STELLA")
# Check that the old classmethod still works. Kept for backward compatibility.
self.assertEqual(LabelBeer.name(LabelBeer.STELLA.value), "STELLA")
self.assertEqual(PersonStatus.name("ALIVE"), "ALIVE")
self.assertEqual(PersonStatus.name(PersonStatus.ALIVE), "ALIVE")
def test_get(self):
self.assertTrue(isinstance(PersonStatus.get(PersonStatus.ALIVE), Enum))
self.assertTrue(isinstance(PersonStatus.get("ALIVE"), Enum))
self.assertEqual(
PersonStatus.get(PersonStatus.ALIVE),
PersonStatus.get("ALIVE"),
)
# Returns `default` if not found
self.assertEqual(PersonStatus.get("ALIVEISH", "?"), "?")
self.assertEqual(PersonStatus.get(99, "??"), "??")
def test_get_name(self):
self.assertEqual(PersonStatus.get_name(PersonStatus.ALIVE), "ALIVE")
self.assertEqual(PersonStatus.get_name(PersonStatus.ALIVE.value), "ALIVE")
self.assertEqual(PersonStatus.get_name(PersonStatus.ALIVE.name), "ALIVE")
self.assertIsNone(PersonStatus.get_name(89))
def test_get_label(self):
self.assertEqual(LabelBeer.get_label(LabelBeer.STELLA), "Stella Artois")
self.assertEqual(LabelBeer.get_label(LabelBeer.STELLA.value), "Stella Artois")
self.assertEqual(LabelBeer.get_label(LabelBeer.STELLA.name), "Stella Artois")
self.assertIsNone(LabelBeer.get_label(89))
def test_choices(self):
self.assertEqual(len(PersonStatus.choices()), len(PersonStatus))
for value, member in PersonStatus.choices():
self.assertTrue(isinstance(value, int))
self.assertTrue(isinstance(member, PersonStatus))
self.assertTrue(PersonStatus.get(value) == member)
blank = PersonStatus.choices(blank=True)[0]
self.assertEqual(blank, (BlankEnum.BLANK.value, BlankEnum.BLANK))
def test_items(self):
self.assertEqual(len(PersonStatus.items()), len(PersonStatus))
for name, value in PersonStatus.items():
self.assertTrue(isinstance(value, int))
self.assertTrue(isinstance(name, str))
self.assertEqual(PersonStatus.get(value), PersonStatus.get(name))
def test_default(self):
for enum, default in {
PersonStatus: None,
PersonStatusDefault: PersonStatusDefault.UNBORN,
}.items():
self.assertEqual(enum.default(), default)
def test_field(self):
self.assertTrue(isinstance(PersonStatus.field(), EnumField))
def test_equal(self):
self.assertTrue(PersonStatus.ALIVE == PersonStatus.ALIVE)
self.assertFalse(PersonStatus.ALIVE == PersonStatus.DEAD)
self.assertEqual(
PersonStatus.get(PersonStatus.ALIVE), PersonStatus.get(PersonStatus.ALIVE)
)
def test_labels(self):
self.assertEqual(LabelBeer.JUPILER.name, LabelBeer.JUPILER.label)
self.assertNotEqual(LabelBeer.STELLA.name, LabelBeer.STELLA.label)
self.assertTrue(isinstance(LabelBeer.STELLA.label, str))
self.assertEqual(LabelBeer.STELLA.label, "Stella Artois")
# Check that the old classmethod still works. Kept for backward compatibility.
self.assertEqual(LabelBeer.label(LabelBeer.STELLA.value), "Stella Artois")
self.assertEqual(LabelBeer.label("STELLA"), "Stella Artois")
def test_hash(self):
self.assertTrue({LabelBeer.JUPILER: True}[LabelBeer.JUPILER])
def test_comparison(self):
self.assertGreater(PersonStatus.ALIVE, PersonStatus.UNBORN.value)
self.assertLess(PersonStatus.REANIMATED, PersonStatus.VOID)
self.assertGreater(PersonStatus.ALIVE, PersonStatus.UNBORN.value)
def test_values(self):
self.assertEqual(
PersonStatus.values,
{
PersonStatus.UNBORN.value: PersonStatus.UNBORN,
PersonStatus.ALIVE.value: PersonStatus.ALIVE,
PersonStatus.DEAD.value: PersonStatus.DEAD,
PersonStatus.REANIMATED.value: PersonStatus.REANIMATED,
PersonStatus.VOID.value: PersonStatus.VOID,
},
)
|
class EnumTest(TestCase):
def test_label(self):
pass
def test_name(self):
pass
def test_get(self):
pass
def test_get_name(self):
pass
def test_get_label(self):
pass
def test_choices(self):
pass
def test_items(self):
pass
def test_default(self):
pass
def test_field(self):
pass
def test_equal(self):
pass
def test_labels(self):
pass
def test_hash(self):
pass
def test_comparison(self):
pass
def test_values(self):
pass
| 15 | 0 | 7 | 0 | 6 | 0 | 1 | 0.05 | 1 | 8 | 6 | 0 | 14 | 0 | 14 | 14 | 105 | 17 | 84 | 19 | 69 | 4 | 67 | 19 | 52 | 2 | 1 | 1 | 17 |
1,272 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/tests/models.py
|
django_enumfield.tests.models.Person
|
class Person(models.Model):
example = models.CharField(max_length=100, default="foo")
status = EnumField(PersonStatus, default=PersonStatus.ALIVE)
def save(self, *args, **kwargs):
super(Person, self).save(*args, **kwargs)
return "Person.save"
|
class Person(models.Model):
def save(self, *args, **kwargs):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 1 | 7 | 1 | 6 | 4 | 4 | 0 | 6 | 4 | 4 | 1 | 1 | 0 | 1 |
1,273 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/tests/models.py
|
django_enumfield.tests.models.LampState
|
class LampState(Enum):
OFF = 0
ON = 1
__default__ = OFF
|
class LampState(Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 70 | 5 | 1 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 4 | 0 | 0 |
1,274 |
5monkeys/django-enumfield
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-enumfield/django_enumfield/tests/test_enum.py
|
django_enumfield.tests.test_enum.EnumFieldTest.test_enum_form_field.CustomPersonForm
|
class CustomPersonForm(forms.Form):
status = EnumChoiceField(PersonStatus)
|
class CustomPersonForm(forms.Form):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
1,275 |
5monkeys/django-enumfield
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-enumfield/django_enumfield/tests/test_enum.py
|
django_enumfield.tests.test_enum.EnumFieldTest.test_enum_field_nullable_field.BeerForm.Meta
|
class Meta:
model = Beer
fields = ("style", "state")
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 0 | 0 | 0 |
1,276 |
5monkeys/django-enumfield
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-enumfield/django_enumfield/enum.py
|
django_enumfield.enum.classdispatcher._classdispatcher
|
class _classdispatcher(object):
def __init__(self, method=None):
self.fget = method
def __get__(self, instance, cls=None):
if instance is None:
return getattr(cls, class_method)
return self.fget(instance)
|
class _classdispatcher(object):
def __init__(self, method=None):
pass
def __get__(self, instance, cls=None):
pass
| 3 | 0 | 3 | 0 | 3 | 0 | 2 | 0 | 1 | 0 | 0 | 0 | 2 | 1 | 2 | 2 | 8 | 1 | 7 | 4 | 4 | 0 | 7 | 4 | 4 | 2 | 1 | 1 | 3 |
1,277 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/contrib/drf.py
|
django_enumfield.contrib.drf.EnumField
|
class EnumField(serializers.ChoiceField):
default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')}
def __init__(self, enum, **kwargs):
self.enum = enum
choices = (
(self.get_choice_value(enum_value), enum_value.label)
for _, enum_value in enum.choices()
)
super(EnumField, self).__init__(choices, **kwargs)
def get_choice_value(self, enum_value):
return enum_value.value
def to_internal_value(self, data):
if isinstance(data, str) and data.isdigit():
data = int(data)
try:
value = self.enum.get(data).value
except AttributeError: # .get() returned None
if not self.required:
raise serializers.SkipField()
self.fail("invalid_choice", input=data)
return value
def to_representation(self, value):
enum_value = self.enum.get(value)
if enum_value is not None:
return self.get_choice_value(enum_value)
|
class EnumField(serializers.ChoiceField):
def __init__(self, enum, **kwargs):
pass
def get_choice_value(self, enum_value):
pass
def to_internal_value(self, data):
pass
def to_representation(self, value):
pass
| 5 | 0 | 6 | 1 | 6 | 0 | 2 | 0.04 | 1 | 4 | 0 | 1 | 4 | 1 | 4 | 4 | 31 | 6 | 25 | 11 | 20 | 1 | 22 | 10 | 17 | 4 | 1 | 2 | 8 |
1,278 |
5monkeys/django-enumfield
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-enumfield/django_enumfield/enum.py
|
django_enumfield.enum.Enum
|
class Enum(enum.IntEnum):
"""A container for holding and restoring enum values"""
__labels__ = {} # type: Mapping[int, StrOrPromise]
__default__ = None # type: Optional[int]
__transitions__ = {} # type: Mapping[int, Sequence[int]]
def __str__(self):
return self.label
@classdispatcher("get_name")
def name(self):
# type: () -> str
return self._name_
@classdispatcher("get_label")
def label(self):
# type: () -> str
"""Get human readable label for the matching Enum.Value.
:return: label for value
:rtype: str
"""
labels = self.__class__.__labels__
return force_str(labels.get(self.value, self.name))
@classproperty # type: ignore[arg-type]
def do_not_call_in_templates(cls):
# type: () -> bool
# Fix for Django templates so that any lookups of enums won't fail
# More info: https://stackoverflow.com/questions/35953132/how-to-access-enum-types-in-django-templates # noqa: E501
return True
@classproperty # type: ignore[arg-type]
def values(cls):
# type: () -> Mapping[int, Enum]
# type: ignore[attr-defined]
return {member.value: member for member in cls}
def deconstruct(self):
"""
See "Adding a deconstruct() method" in
https://docs.djangoproject.com/en/1.8/topics/migrations/
"""
c = self.__class__
path = "{}.{}".format(c.__module__, c.__name__)
return path, [self.value], {}
@classmethod
def items(cls):
# type: () -> List[Tuple[str, int]]
"""
:return: List of tuples consisting of every enum value in the form
[('NAME', value), ...]
"""
items = [(member.name, member.value) for member in cls]
return sorted(items, key=lambda x: x[1])
@classmethod
def choices(cls, blank=False):
# type: (bool) -> List[Tuple[Union[int, str], enum.Enum]]
"""Choices for Enum
:return: List of tuples (<value>, <member>)
"""
choices = sorted(
[(member.value, member) for member in cls], key=lambda x: x[0]
) # type: List[Tuple[Union[str, int], enum.Enum]]
if blank:
choices.insert(0, (BlankEnum.BLANK.value, BlankEnum.BLANK))
return choices
@classmethod
def default(cls):
# type: () -> Optional[Enum]
"""Default Enum value. Set default value to `__default__` attribute
of your enum class or override this method if you need another
default value.
Usage:
IntegerField(choices=my_enum.choices(), default=my_enum.default(), ...
:return Default value, if set.
"""
if cls.__default__ is not None:
return cast(Enum, cls(cls.__default__))
return None
@classmethod
def field(cls, **kwargs):
# type: (Any) -> EnumField
"""A shortcut for field declaration
Usage:
class MyModelStatuses(Enum):
UNKNOWN = 0
class MyModel(Model):
status = MyModelStatuses.field()
:param kwargs: Arguments passed in EnumField.__init__()
:rtype: EnumField
"""
return EnumField(cls, **kwargs)
@classmethod
def get(
cls,
name_or_numeric, # type: Union[str, int, T]
default=None, # type: Optional[Default]
):
# type: (...) -> Union[Enum, Optional[Default]]
"""Get Enum.Value object matching the value argument.
:param name_or_numeric: Integer value or attribute name
:param default: The default to return if the value passed is not
a valid enum value
"""
if isinstance(name_or_numeric, cls):
return name_or_numeric
if isinstance(name_or_numeric, int):
try:
return cls(name_or_numeric)
except ValueError:
pass
elif isinstance(name_or_numeric, str):
try:
return cls[name_or_numeric]
except KeyError:
pass
return default
@classmethod
def get_name(cls, name_or_numeric):
# type: (Union[str, int, T]) -> Optional[str]
"""Get Enum.Value name matching the value argument.
:param name_or_numeric: Integer value or attribute name
:return: The name or None if not found
"""
value = cls.get(name_or_numeric)
if value is not None:
return value.name
return None
@classmethod
def get_label(cls, name_or_numeric):
# type: (Union[str, int, Enum]) -> Optional[str]
"""Get Enum.Value label matching the value argument.
:param name_or_numeric: Integer value or attribute name
:return: The label or None if not found
"""
value = cls.get(name_or_numeric)
if value is not None:
return value.label
return None
@classmethod
def is_valid_transition(cls, from_value, to_value):
# type: (Union[int, Enum], Union[int, Enum]) -> bool
"""Will check if to_value is a valid transition from from_value.
Returns true if it is a valid transition.
:param from_value: Start transition point
:param to_value: End transition point
:return: Success flag
"""
if isinstance(from_value, cls):
from_value = from_value.value
if isinstance(to_value, cls):
to_value = to_value.value
return (
from_value == to_value
or not cls.__transitions__
or (from_value in cls.transition_origins(to_value))
)
@classmethod
def transition_origins(cls, to_value):
# type: (Union[int, T]) -> Sequence[int]
"""Returns all values the to_value can make a transition from.
:param to_value End transition point
"""
if isinstance(to_value, cls):
to_value = to_value.value
return cls.__transitions__.get(to_value, [])
|
class Enum(enum.IntEnum):
'''A container for holding and restoring enum values'''
def __str__(self):
pass
@classdispatcher("get_name")
def name(self):
pass
@classdispatcher("get_label")
def label(self):
'''Get human readable label for the matching Enum.Value.
:return: label for value
:rtype: str
'''
pass
@classproperty
def do_not_call_in_templates(cls):
pass
@classproperty
def values(cls):
pass
def deconstruct(self):
'''
See "Adding a deconstruct() method" in
https://docs.djangoproject.com/en/1.8/topics/migrations/
'''
pass
@classmethod
def items(cls):
'''
:return: List of tuples consisting of every enum value in the form
[('NAME', value), ...]
'''
pass
@classmethod
def choices(cls, blank=False):
'''Choices for Enum
:return: List of tuples (<value>, <member>)
'''
pass
@classmethod
def default(cls):
'''Default Enum value. Set default value to `__default__` attribute
of your enum class or override this method if you need another
default value.
Usage:
IntegerField(choices=my_enum.choices(), default=my_enum.default(), ...
:return Default value, if set.
'''
pass
@classmethod
def field(cls, **kwargs):
'''A shortcut for field declaration
Usage:
class MyModelStatuses(Enum):
UNKNOWN = 0
class MyModel(Model):
status = MyModelStatuses.field()
:param kwargs: Arguments passed in EnumField.__init__()
:rtype: EnumField
'''
pass
@classmethod
def get(
cls,
name_or_numeric, # type: Union[str, int, T]
default=None, # type: Optional[Default]
):
'''Get Enum.Value object matching the value argument.
:param name_or_numeric: Integer value or attribute name
:param default: The default to return if the value passed is not
a valid enum value
'''
pass
@classmethod
def get_name(cls, name_or_numeric):
'''Get Enum.Value name matching the value argument.
:param name_or_numeric: Integer value or attribute name
:return: The name or None if not found
'''
pass
@classmethod
def get_label(cls, name_or_numeric):
'''Get Enum.Value label matching the value argument.
:param name_or_numeric: Integer value or attribute name
:return: The label or None if not found
'''
pass
@classmethod
def is_valid_transition(cls, from_value, to_value):
'''Will check if to_value is a valid transition from from_value.
Returns true if it is a valid transition.
:param from_value: Start transition point
:param to_value: End transition point
:return: Success flag
'''
pass
@classmethod
def transition_origins(cls, to_value):
'''Returns all values the to_value can make a transition from.
:param to_value End transition point
'''
pass
| 29 | 12 | 10 | 0 | 5 | 5 | 2 | 0.87 | 1 | 5 | 2 | 6 | 6 | 0 | 15 | 70 | 182 | 23 | 90 | 43 | 57 | 78 | 66 | 26 | 50 | 6 | 3 | 2 | 27 |
1,279 |
5monkeys/django-enumfield
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-enumfield/django_enumfield/db/fields.py
|
django_enumfield.db.fields.partialishmethod
|
class partialishmethod(_partialmethod):
"""Workaround for https://github.com/python/cpython/issues/99152"""
def __get__(self, obj, cls=None):
return self._make_unbound_method().__get__(obj, cls)
|
class partialishmethod(_partialmethod):
'''Workaround for https://github.com/python/cpython/issues/99152'''
def __get__(self, obj, cls=None):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.33 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 6 | 5 | 1 | 3 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 2 | 0 | 1 |
1,280 |
5monkeys/django-enumfield
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-enumfield/django_enumfield/contrib/drf.py
|
django_enumfield.contrib.drf.NamedEnumField.Meta
|
class Meta:
swagger_schema_fields = {"type": "string"}
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 0 | 0 | 0 |
1,281 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/tests/test_validators.py
|
django_enumfield.tests.test_validators.ValidatorTest
|
class ValidatorTest(unittest.TestCase):
def test_validate_available_choice_1(self):
"""Test passing a value non convertible to an int raises an
InvalidStatusOperationError
"""
self.assertRaises(
InvalidStatusOperationError,
validate_available_choice,
*(BeerStyle, "Not an int")
)
def test_validate_available_choice_2(self):
"""Test passing an int as a string validation"""
self.assertRaises(
InvalidStatusOperationError,
validate_available_choice,
BeerStyle,
str(BeerStyle.LAGER.value),
)
def test_validate_available_choice_3(self):
"""Test passing an int validation"""
self.assertIsNone(validate_available_choice(BeerStyle, BeerStyle.LAGER))
def test_validate_by_setting(self):
person = Person()
with self.assertRaises(InvalidStatusOperationError):
person.status = PersonStatus.UNBORN
with self.assertRaises(InvalidStatusOperationError):
person.status = models.NOT_PROVIDED
|
class ValidatorTest(unittest.TestCase):
def test_validate_available_choice_1(self):
'''Test passing a value non convertible to an int raises an
InvalidStatusOperationError
'''
pass
def test_validate_available_choice_2(self):
'''Test passing an int as a string validation'''
pass
def test_validate_available_choice_3(self):
'''Test passing an int validation'''
pass
def test_validate_by_setting(self):
pass
| 5 | 3 | 7 | 0 | 5 | 1 | 1 | 0.23 | 1 | 5 | 4 | 0 | 4 | 0 | 4 | 76 | 31 | 4 | 22 | 6 | 17 | 5 | 13 | 6 | 8 | 1 | 2 | 1 | 4 |
1,282 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/db/fields.py
|
django_enumfield.db.fields.EnumField
|
class EnumField(models.IntegerField):
"""EnumField is a convenience field to automatically handle validation of transition
between Enum values and set field choices from the enum.
EnumField(MyEnum, default=MyEnum.INITIAL)
"""
default_error_messages = models.IntegerField.default_error_messages # type: ignore
def __init__(self, enum, *args, **kwargs):
kwargs.setdefault("choices", enum.choices())
if enum.default() is not None:
kwargs.setdefault("default", enum.default())
self.enum = enum
super(EnumField, self).__init__(*args, **kwargs)
def get_default(self):
if self.has_default() and callable(self.default):
return self.default()
return self.default
def get_internal_type(self):
return "IntegerField"
def contribute_to_class(
self, cls, name, private_only=False, virtual_only=models.NOT_PROVIDED
):
super(EnumField, self).contribute_to_class(cls, name)
if self.choices:
setattr(
cls,
"get_%s_display" % self.name,
partialishmethod(self._get_FIELD_display),
)
models.signals.class_prepared.connect(self._setup_validation, sender=cls)
def _get_FIELD_display(self, cls):
value = getattr(cls, self.attname)
if value is None:
return value
return force_str(value.label, strings_only=True)
def get_prep_value(self, value):
value = super(EnumField, self).get_prep_value(value)
if value is None:
return value
if isinstance(value, Enum):
return value.value
return int(value)
def from_db_value(self, value, *_):
if value is not None:
return self.enum.get(value)
return value
def to_python(self, value):
if value is not None:
if isinstance(value, str) and value.isdigit():
value = int(value)
return self.enum.get(value)
def _setup_validation(self, sender, **kwargs):
"""
User a customer setter for the field to validate new value against the old one.
The current value is set as '_enum_[att_name]' on the model instance.
"""
att_name = self.get_attname()
private_att_name = "_enum_%s" % att_name
enum = self.enum
def set_enum(self, new_value):
if new_value is models.NOT_PROVIDED:
new_value = None
if hasattr(self, private_att_name):
# Fetch previous value from private enum attribute.
old_value = getattr(self, private_att_name)
else:
# First setattr no previous value on instance.
old_value = new_value
# Update private enum attribute with new value
if new_value is not None and not isinstance(new_value, enum):
if isinstance(new_value, Enum):
raise TypeError(
"Invalid Enum class passed. Passed {}, expected {}".format(
new_value.__class__.__name__, enum.__name__
)
)
try:
new_value = enum(new_value)
except ValueError:
raise InvalidStatusOperationError(
gettext(
"{value!r} is not one of the available choices "
"for enum {enum}."
).format(value=new_value, enum=enum)
)
setattr(self, private_att_name, new_value)
self.__dict__[att_name] = new_value
# Run validation for new value.
validators.validate_valid_transition(enum, old_value, new_value)
def get_enum(self):
return getattr(self, private_att_name)
def delete_enum(self):
self.__dict__[att_name] = None
return setattr(self, private_att_name, None)
if not sender._meta.abstract:
setattr(sender, att_name, property(get_enum, set_enum, delete_enum))
def validate(self, value, model_instance):
super(EnumField, self).validate(value, model_instance)
validators.validate_valid_transition(
self.enum, self.value_from_object(model_instance), value
)
def formfield(self, **kwargs):
enum_form_class = partial(EnumChoiceField, enum=self.enum)
defaults = {
"widget": forms.Select,
"form_class": enum_form_class,
"choices_form_class": enum_form_class,
"choices": self.enum.choices(blank=self.blank),
}
defaults.update(kwargs)
return super(EnumField, self).formfield(**defaults)
def deconstruct(self):
name, path, args, kwargs = super(EnumField, self).deconstruct()
kwargs["enum"] = self.enum
if "choices" in kwargs:
del kwargs["choices"]
if "verbose_name" in kwargs:
del kwargs["verbose_name"]
if "default" in kwargs and isinstance(kwargs["default"], self.enum):
# The enum value cannot be deconstructed properly
# for migrations (on django <= 1.8).
# So we send the int value instead.
kwargs["default"] = kwargs["default"].value
return name, path, args, kwargs
|
class EnumField(models.IntegerField):
'''EnumField is a convenience field to automatically handle validation of transition
between Enum values and set field choices from the enum.
EnumField(MyEnum, default=MyEnum.INITIAL)
'''
def __init__(self, enum, *args, **kwargs):
pass
def get_default(self):
pass
def get_internal_type(self):
pass
def contribute_to_class(
self, cls, name, private_only=False, virtual_only=models.NOT_PROVIDED
):
pass
def _get_FIELD_display(self, cls):
pass
def get_prep_value(self, value):
pass
def from_db_value(self, value, *_):
pass
def to_python(self, value):
pass
def _setup_validation(self, sender, **kwargs):
'''
User a customer setter for the field to validate new value against the old one.
The current value is set as '_enum_[att_name]' on the model instance.
'''
pass
def set_enum(self, new_value):
pass
def get_enum(self):
pass
def delete_enum(self):
pass
def validate(self, value, model_instance):
pass
def formfield(self, **kwargs):
pass
def deconstruct(self):
pass
| 16 | 2 | 11 | 0 | 9 | 1 | 2 | 0.15 | 1 | 11 | 3 | 0 | 12 | 1 | 12 | 12 | 143 | 20 | 108 | 28 | 90 | 16 | 85 | 26 | 69 | 6 | 1 | 2 | 33 |
1,283 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/exceptions.py
|
django_enumfield.exceptions.InvalidStatusOperationError
|
class InvalidStatusOperationError(ValidationError):
pass
|
class InvalidStatusOperationError(ValidationError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 1 | 0 | 0 |
1,284 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/forms/fields.py
|
django_enumfield.forms.fields.EnumChoiceField
|
class EnumChoiceField(forms.TypedChoiceField):
def __init__(self, enum, **kwargs):
kwargs.setdefault(
"choices", enum.choices(blank=not kwargs.get("required", True))
)
kwargs.setdefault("coerce", int)
super(EnumChoiceField, self).__init__(**kwargs)
self.enum = enum
def prepare_value(self, value):
if isinstance(value, NativeEnum):
return value.value
return value
def clean(self, value):
value = super(EnumChoiceField, self).clean(value)
if value == self.empty_value:
return value
return self.enum(value)
|
class EnumChoiceField(forms.TypedChoiceField):
def __init__(self, enum, **kwargs):
pass
def prepare_value(self, value):
pass
def clean(self, value):
pass
| 4 | 0 | 5 | 0 | 5 | 0 | 2 | 0 | 1 | 2 | 0 | 0 | 3 | 1 | 3 | 3 | 19 | 2 | 17 | 5 | 13 | 0 | 15 | 5 | 11 | 2 | 1 | 1 | 5 |
1,285 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/tests/models.py
|
django_enumfield.tests.models.Beer
|
class Beer(models.Model):
style = EnumField(BeerStyle)
state = EnumField(BeerState, null=True, blank=True)
label = EnumField(LabelBeer, default=get_default_beer_label)
|
class Beer(models.Model):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 0 | 4 | 4 | 3 | 0 | 4 | 4 | 3 | 0 | 1 | 0 | 0 |
1,286 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/tests/models.py
|
django_enumfield.tests.models.BeerState
|
class BeerState(Enum):
FIZZY = 0
STALE = 1
EMPTY = 2
__default__ = FIZZY
|
class BeerState(Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 70 | 6 | 1 | 5 | 5 | 4 | 0 | 5 | 5 | 4 | 0 | 4 | 0 | 0 |
1,287 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/tests/models.py
|
django_enumfield.tests.models.BeerStyle
|
class BeerStyle(Enum):
LAGER = 0
STOUT = 1
WEISSBIER = 2
__default__ = LAGER
|
class BeerStyle(Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 70 | 6 | 1 | 5 | 5 | 4 | 0 | 5 | 5 | 4 | 0 | 4 | 0 | 0 |
1,288 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/tests/models.py
|
django_enumfield.tests.models.LabelBeer
|
class LabelBeer(Enum):
STELLA = 0
JUPILER = 1
TYSKIE = 2
__labels__ = {STELLA: _("Stella Artois"), TYSKIE: _("Browar Tyskie")}
|
class LabelBeer(Enum):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 70 | 6 | 1 | 5 | 5 | 4 | 0 | 5 | 5 | 4 | 0 | 4 | 0 | 0 |
1,289 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/tests/models.py
|
django_enumfield.tests.models.Lamp
|
class Lamp(models.Model):
state = EnumField(LampState, verbose_name="stately_state")
|
class Lamp(models.Model):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
1,290 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/enum.py
|
django_enumfield.enum.BlankEnum
|
class BlankEnum(enum.Enum):
BLANK = ""
@property
def label(self):
return ""
|
class BlankEnum(enum.Enum):
@property
def label(self):
pass
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 50 | 6 | 1 | 5 | 4 | 2 | 0 | 4 | 3 | 2 | 1 | 4 | 0 | 1 |
1,291 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/setup.py
|
setup.osx_install_data
|
class osx_install_data(install_data):
def finalize_options(self):
self.set_undefined_options("install", ("install_lib", "install_dir"))
install_data.finalize_options(self)
|
class osx_install_data(install_data):
def finalize_options(self):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 36 | 4 | 0 | 4 | 2 | 2 | 0 | 4 | 2 | 2 | 1 | 2 | 0 | 1 |
1,292 |
5monkeys/django-enumfield
|
5monkeys_django-enumfield/django_enumfield/contrib/drf.py
|
django_enumfield.contrib.drf.NamedEnumField
|
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
return enum_value.name
class Meta:
swagger_schema_fields = {"type": "string"}
|
class NamedEnumField(EnumField):
def get_choice_value(self, enum_value):
pass
class Meta:
| 3 | 0 | 2 | 0 | 2 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 5 | 6 | 1 | 5 | 4 | 2 | 0 | 5 | 4 | 2 | 1 | 2 | 0 | 1 |
1,293 |
5monkeys/django-enumfield
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-enumfield/django_enumfield/tests/test_enum.py
|
django_enumfield.tests.test_enum.PersonForm.Meta
|
class Meta:
model = Person
fields = ("status",)
|
class Meta:
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 3 | 0 | 3 | 3 | 2 | 0 | 3 | 3 | 2 | 0 | 0 | 0 | 0 |
1,294 |
5monkeys/django-enumfield
|
/Users/umroot/Documents/PhD_works/PhD-Core-Contents/Class-level-dataset-curation/data/git_repos_for_analysis/5monkeys_django-enumfield/django_enumfield/tests/test_enum.py
|
django_enumfield.tests.test_enum.EnumFieldTest.test_enum_form_field_not_required.CustomPersonForm
|
class CustomPersonForm(forms.Form):
status = EnumChoiceField(PersonStatus, required=False)
|
class CustomPersonForm(forms.Form):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 2 | 2 | 1 | 0 | 2 | 2 | 1 | 0 | 1 | 0 | 0 |
1,295 |
5monkeys/djedi-cms
|
5monkeys_djedi-cms/djedi/plugins/img.py
|
djedi.plugins.img.DataForm
|
class DataForm(BaseEditorForm):
data__id = forms.CharField(
label="ID",
max_length=255,
required=False,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
data__alt = forms.CharField(
label="Alt text",
max_length=255,
required=False,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
data__class = forms.CharField(
label="Class",
max_length=255,
required=False,
widget=forms.TextInput(attrs={"class": "form-control"}),
)
|
class DataForm(BaseEditorForm):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 21 | 2 | 19 | 4 | 18 | 0 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
1,296 |
5monkeys/djedi-cms
|
5monkeys_djedi-cms/djedi/middleware/mixins.py
|
djedi.middleware.mixins.TranslationMixin
|
class TranslationMixin:
def activate_language(self):
# Activate current django translation
language = translation.get_language()
cio.env.push_state(i18n=language)
|
class TranslationMixin:
def activate_language(self):
pass
| 2 | 0 | 4 | 0 | 3 | 1 | 1 | 0.25 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | 1 | 5 | 0 | 4 | 3 | 2 | 1 | 4 | 3 | 2 | 1 | 0 | 0 | 1 |
1,297 |
5monkeys/djedi-cms
|
5monkeys_djedi-cms/djedi/middleware/mixins.py
|
djedi.middleware.mixins.AdminPanelMixin
|
class AdminPanelMixin:
def inject_admin_panel(self, request, response):
# Do not inject admin panel on gzipped responses
if "gzip" in response.get("Content-Encoding", ""):
_log.debug("gzip detected, not injecting panel.")
return
# Only inject admin panel in html pages
content_type = response.get("Content-Type", "").split(";")[0]
if content_type not in ("text/html", "application/xhtml+xml"):
_log.debug("Non-HTML Content-Type detected, not injecting")
return
# Do not inject admin panel in admin
try:
admin_prefix = reverse("admin:index")
except NoReverseMatch:
_log.debug(
'No reverse match for "admin:index", can\'t detect '
"django-admin pages"
)
else:
if request.path.startswith(admin_prefix):
_log.debug(
"admin page detected, not injecting panel. admin_prefix=%r",
admin_prefix,
)
return
try:
djedi_cms_url = reverse("admin:djedi:cms")
except NoReverseMatch:
raise ImproperlyConfigured(
"Could not find djedi in your url conf, "
"enable django admin or include "
"djedi.urls within the admin namespace."
)
else:
if request.path.startswith(djedi_cms_url):
_log.debug("djedi page detected, not injecting panel")
return
# Validate user permissions
if not has_permission(request):
_log.debug("insufficient permissions, not injecting.")
return
embed = self.render_cms()
self.body_append(response, embed)
def render_cms(self):
def get_requested_uri(node):
# Get first namespace URI, remove any version and ensures extension.
# TODO: Default extension fallback should be handled in content-io
uri = node.namespace_uri
uri = uri.clone(
ext=uri.ext or settings.URI_DEFAULT_EXT,
version=None,
)
return uri
defaults = {
get_requested_uri(node): node.initial
for node in pipeline.history.list("get")
}
return render_embed(nodes=defaults)
def body_append(self, response, html):
idx = response.content.lower().rfind(b"</body>")
if idx >= 0:
response.content = b"".join(
(response.content[:idx], html.encode("utf8"), response.content[idx:])
)
if response.get("Content-Length", None):
response["Content-Length"] = len(response.content)
|
class AdminPanelMixin:
def inject_admin_panel(self, request, response):
pass
def render_cms(self):
pass
def get_requested_uri(node):
pass
def body_append(self, response, html):
pass
| 5 | 0 | 21 | 2 | 17 | 2 | 3 | 0.1 | 0 | 0 | 0 | 1 | 3 | 0 | 3 | 3 | 78 | 11 | 61 | 12 | 56 | 6 | 43 | 12 | 38 | 8 | 0 | 2 | 13 |
1,298 |
5monkeys/djedi-cms
|
5monkeys_djedi-cms/djedi/middleware/admin.py
|
djedi.middleware.admin.DjediAdminMiddleware
|
class DjediAdminMiddleware(DjediMiddleware, AdminPanelMixin):
def process_response(self, request, response):
self.inject_admin_panel(request, response)
return super().process_response(request, response)
|
class DjediAdminMiddleware(DjediMiddleware, AdminPanelMixin):
def process_response(self, request, response):
pass
| 2 | 0 | 3 | 0 | 3 | 0 | 1 | 0 | 2 | 1 | 0 | 1 | 1 | 0 | 1 | 9 | 4 | 0 | 4 | 2 | 2 | 0 | 4 | 2 | 2 | 1 | 1 | 0 | 1 |
1,299 |
5monkeys/djedi-cms
|
5monkeys_djedi-cms/djedi/middleware/__init__.py
|
djedi.middleware.DjediMiddleware
|
class DjediMiddleware:
def __init__(self, get_response=None):
self.get_response = get_response
def __call__(self, request):
response = self.process_request(request)
if not response:
try:
response = self.get_response(request)
response = self.process_response(request=request, response=response)
except Exception as e:
self.process_exception(request=request, exception=e)
raise
return response
def process_request(self, request):
# Bootstrap content-io
pipeline.clear()
cio.env.reset()
def process_response(self, request, response):
pipeline.clear()
return response
def process_exception(self, request, exception):
pipeline.clear()
|
class DjediMiddleware:
def __init__(self, get_response=None):
pass
def __call__(self, request):
pass
def process_request(self, request):
pass
def process_response(self, request, response):
pass
def process_exception(self, request, exception):
pass
| 6 | 0 | 4 | 0 | 4 | 0 | 1 | 0.05 | 0 | 1 | 0 | 1 | 5 | 1 | 5 | 5 | 26 | 4 | 21 | 9 | 15 | 1 | 21 | 8 | 15 | 3 | 0 | 2 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.