Skip to content

Commit

Permalink
style: format code
Browse files Browse the repository at this point in the history
  • Loading branch information
kyrylo-kh committed May 27, 2024
1 parent 3366597 commit 8613e01
Show file tree
Hide file tree
Showing 11 changed files with 100 additions and 85 deletions.
56 changes: 32 additions & 24 deletions credentials/apps/badges/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,23 +50,27 @@ class BadgeRequirementInline(admin.TabularInline):
"group",
)
readonly_fields = ("rules",)
ordering = ("group",)
ordering = ("group",)
form = BadgeRequirementForm
formset = BadgeRequirementFormSet

def rules(self, obj):
"""
Display all data rules for the requirement.
"""
return format_html(
"<ul>{}</ul>",
mark_safe(
"".join(
f"<li>{rule.data_path} {rule.OPERATORS[rule.operator]} {rule.value}</li>"
for rule in obj.rules.all()
)
),
) if obj.rules.exists() else _("No rules specified.")
return (
format_html(
"<ul>{}</ul>",
mark_safe(
"".join(
f"<li>{rule.data_path} {rule.OPERATORS[rule.operator]} {rule.value}</li>"
for rule in obj.rules.all()
)
),
)
if obj.rules.exists()
else _("No rules specified.")
)


class BadgePenaltyInline(admin.TabularInline):
Expand Down Expand Up @@ -94,20 +98,24 @@ def formfield_for_manytomany(self, db_field, request, **kwargs):
if template_id:
kwargs["queryset"] = BadgeRequirement.objects.filter(template_id=template_id)
return super().formfield_for_manytomany(db_field, request, **kwargs)

def rules(self, obj):
"""
Display all data rules for the penalty.
"""
return format_html(
"<ul>{}</ul>",
mark_safe(
"".join(
f"<li>{rule.data_path} {rule.OPERATORS[rule.operator]} {rule.value}</li>"
for rule in obj.rules.all()
)
),
) if obj.rules.exists() else _("No rules specified.")
return (
format_html(
"<ul>{}</ul>",
mark_safe(
"".join(
f"<li>{rule.data_path} {rule.OPERATORS[rule.operator]} {rule.value}</li>"
for rule in obj.rules.all()
)
),
)
if obj.rules.exists()
else _("No rules specified.")
)


class FulfillmentInline(admin.TabularInline):
Expand Down Expand Up @@ -168,23 +176,23 @@ def sync_organization_badge_templates(self, request, queryset):
)

messages.success(request, _("Badge templates were successfully updated."))

@admin.display(description=_("API key"))
def api_key_hidden(self, obj):
"""
Hide API key and display text.
"""

return _("Pre-configured from the environment.") if obj.is_preconfigured else obj.api_key

def get_fields(self, request, obj=None):
fields = super().get_fields(request, obj)

if not (obj and obj.is_preconfigured):
fields = [field for field in fields if field != "api_key_hidden"]
fields.append("api_key")
return fields

def get_readonly_fields(self, request, obj=None):
readonly_fields = super().get_readonly_fields(request, obj)

Expand Down
18 changes: 12 additions & 6 deletions credentials/apps/badges/admin_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def clean(self):
if str(uuid) in CredlyOrganization.get_preconfigured_organizations().keys():
if api_key:
raise forms.ValidationError(_("You can't provide an API key for a configured organization."))

Check warning on line 48 in credentials/apps/badges/admin_forms.py

View check run for this annotation

Codecov / codecov/patch

credentials/apps/badges/admin_forms.py#L48

Added line #L48 was not covered by tests

api_key = settings.BADGES_CONFIG["credly"]["ORGANIZATIONS"][str(uuid)]

Check warning on line 50 in credentials/apps/badges/admin_forms.py

View check run for this annotation

Codecov / codecov/patch

credentials/apps/badges/admin_forms.py#L50

Added line #L50 was not covered by tests

credly_api_client = CredlyAPIClient(uuid, api_key)
Expand Down Expand Up @@ -80,6 +80,7 @@ class BadgePenaltyForm(forms.ModelForm):
"""
Form for BadgePenalty model.
"""

class Meta:
model = BadgePenalty
fields = "__all__"
Expand Down Expand Up @@ -138,23 +139,28 @@ def clean(self):

if data_path_type == bool and cleaned_data.get("value") not in AbstractDataRule.BOOL_VALUES:
raise forms.ValidationError(_("Value must be a boolean."))

Check warning on line 141 in credentials/apps/badges/admin_forms.py

View check run for this annotation

Codecov / codecov/patch

credentials/apps/badges/admin_forms.py#L141

Added line #L141 was not covered by tests

return cleaned_data

Check warning on line 143 in credentials/apps/badges/admin_forms.py

View check run for this annotation

Codecov / codecov/patch

credentials/apps/badges/admin_forms.py#L143

Added line #L143 was not covered by tests


class DataRuleFormSet(ParentMixin, forms.BaseInlineFormSet): ...


class DataRuleForm(DataRuleExtensionsMixin, forms.ModelForm):
"""
Form for DataRule model.
"""

class Meta:
model = DataRule
fields = "__all__"

data_path = forms.ChoiceField()


class BadgeRequirementFormSet(ParentMixin, forms.BaseInlineFormSet): ...


class BadgeRequirementForm(forms.ModelForm):
class Meta:
model = BadgeRequirement
Expand All @@ -166,13 +172,13 @@ def __init__(self, *args, parent_instance=None, **kwargs):
self.template = parent_instance
super().__init__(*args, **kwargs)

Check warning on line 173 in credentials/apps/badges/admin_forms.py

View check run for this annotation

Codecov / codecov/patch

credentials/apps/badges/admin_forms.py#L172-L173

Added lines #L172 - L173 were not covered by tests

self.fields["group"].choices = Choices(
*[(chr(i), chr(i)) for i in range(65, 91)]
)
self.fields["group"].choices = Choices(*[(chr(i), chr(i)) for i in range(65, 91)])
self.fields["group"].initial = chr(65 + self.template.requirements.count())

Check warning on line 176 in credentials/apps/badges/admin_forms.py

View check run for this annotation

Codecov / codecov/patch

credentials/apps/badges/admin_forms.py#L176

Added line #L176 was not covered by tests


class PenaltyDataRuleFormSet(ParentMixin, forms.BaseInlineFormSet): ...


class PenaltyDataRuleForm(DataRuleExtensionsMixin, forms.ModelForm):
"""
Form for PenaltyDataRule model.
Expand Down
24 changes: 13 additions & 11 deletions credentials/apps/badges/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ class CredlyOrganization(TimeStampedModel):
"""

uuid = models.UUIDField(unique=True, help_text=_("Put your Credly Organization ID here."))
api_key = models.CharField(max_length=255, help_text=_("Credly API shared secret for Credly Organization."), blank=True)
api_key = models.CharField(
max_length=255, help_text=_("Credly API shared secret for Credly Organization."), blank=True
)
name = models.CharField(
max_length=255,
null=True,
Expand All @@ -52,14 +54,14 @@ def get_all_organization_ids(cls):
Get all organization IDs.
"""
return list(cls.objects.values_list("uuid", flat=True))

Check warning on line 56 in credentials/apps/badges/models.py

View check run for this annotation

Codecov / codecov/patch

credentials/apps/badges/models.py#L56

Added line #L56 was not covered by tests

@classmethod
def get_preconfigured_organizations(cls):
"""
Get preconfigured organizations.
"""
return settings.BADGES_CONFIG["credly"].get("ORGANIZATIONS", {})

Check warning on line 63 in credentials/apps/badges/models.py

View check run for this annotation

Codecov / codecov/patch

credentials/apps/badges/models.py#L63

Added line #L63 was not covered by tests

@property
def is_preconfigured(self):
"""
Expand Down Expand Up @@ -99,7 +101,7 @@ def save(self, *args, **kwargs):
if not self.origin:
self.origin = self.ORIGIN
self.save(*args, **kwargs)

@property
def groups(self):
return self.requirements.values_list("group", flat=True).distinct()
Expand Down Expand Up @@ -327,12 +329,12 @@ def apply(self, data: dict) -> bool:
"""

comparison_func = getattr(operator, self.operator, None)

if comparison_func:
data_value = str(keypath(data, self.data_path))
return comparison_func(data_value, self._value_to_bool())
return False

Check warning on line 336 in credentials/apps/badges/models.py

View check run for this annotation

Codecov / codecov/patch

credentials/apps/badges/models.py#L336

Added line #L336 was not covered by tests

def _value_to_bool(self):
"""
Converts the value to a boolean or returns the original value if it is not a boolean string.
Expand Down Expand Up @@ -410,7 +412,7 @@ def reset_requirements(self, username: str):
"""
Resets all related requirements for the user.
"""

for requirement in self.requirements.all():
requirement.reset(username)

Expand Down Expand Up @@ -482,7 +484,7 @@ def ratio(self) -> float:

if not self.groups:
return 0.00

true_values = len(list(filter(lambda x: x, self.groups.values())))
return round(true_values / len(self.groups.keys()), 2)

Expand All @@ -506,7 +508,7 @@ def progress(self):
Notify about the progress.
"""
notify_progress_complete(self, self.username, self.template.id)

def regress(self):
"""
Notify about the regression.
Expand All @@ -530,7 +532,7 @@ class Fulfillment(models.Model):
null=True,
related_name="fulfillments",
)
group = models.CharField( max_length=255, null=True, blank=True, help_text=_("Group ID for the requirement."))
group = models.CharField(max_length=255, null=True, blank=True, help_text=_("Group ID for the requirement."))


class CredlyBadge(UserCredential):
Expand Down Expand Up @@ -604,5 +606,5 @@ def propagated(self):
"""
Checks if this user credential already has issued (external) Credly badge.
"""

return self.external_uuid and (self.state in self.ISSUING_STATES)
2 changes: 2 additions & 0 deletions credentials/apps/badges/signals/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,15 @@ def handle_badging_event(sender, signal, **kwargs):

process_event(signal, **kwargs)

Check warning on line 46 in credentials/apps/badges/signals/handlers.py

View check run for this annotation

Codecov / codecov/patch

credentials/apps/badges/signals/handlers.py#L46

Added line #L46 was not covered by tests


@receiver(BADGE_REQUIREMENT_FULFILLED)
def handle_requirement_fulfilled(sender, username, **kwargs): # pylint: disable=unused-argument
"""
On user's Badge progression (completion).
"""
BadgeProgress.for_user(username=username, template_id=sender.template.id).progress()


@receiver(BADGE_REQUIREMENT_REGRESSED)
def handle_requirement_regressed(sender, username, **kwargs): # pylint: disable=unused-argument
"""
Expand Down
19 changes: 11 additions & 8 deletions credentials/apps/badges/tests/test_admin_forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,13 +46,16 @@ def test_clean_requirements_same_template(self):
self.requirement3,
],
}
self.assertEqual(form.clean(), {
"template": self.badge_template2,
"requirements": [
self.requirement2,
self.requirement3,
],
})
self.assertEqual(
form.clean(),
{
"template": self.badge_template2,
"requirements": [
self.requirement2,
self.requirement3,
],
},
)

def test_clean_requirements_different_template(self):
form = BadgePenaltyForm()
Expand All @@ -67,4 +70,4 @@ def test_clean_requirements_different_template(self):
with self.assertRaises(forms.ValidationError) as cm:
form.clean()

self.assertEqual(str(cm.exception), "['All requirements must belong to the same template.']")
self.assertEqual(str(cm.exception), "['All requirements must belong to the same template.']")
10 changes: 5 additions & 5 deletions credentials/apps/badges/tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,19 +217,19 @@ def setUp(self):
template=self.badge_template,
event_type="org.openedx.learning.course.passing.status.updated.v1",
description="Test description",
group="A"
group="A",
)
self.requirement2 = BadgeRequirement.objects.create(
template=self.badge_template,
event_type="org.openedx.learning.course.passing.status.updated.v1",
description="Test description",
group="B"
group="B",
)
self.requirement3 = BadgeRequirement.objects.create(
template=self.badge_template,
event_type="org.openedx.learning.ccx.course.passing.status.updated.v1",
description="Test description",
group="C"
group="C",
)

def test_user_progress_success(self):
Expand Down Expand Up @@ -297,13 +297,13 @@ def setUp(self):
template=self.badge_template,
event_type="org.openedx.learning.course.passing.status.updated.v1",
description="Test description",
group="A"
group="A",
)
self.requirement2 = BadgeRequirement.objects.create(
template=self.badge_template,
event_type="org.openedx.learning.course.passing.status.updated.v1",
description="Test description",
group="B"
group="B",
)

self.group_requirement1 = BadgeRequirement.objects.create(
Expand Down
Loading

0 comments on commit 8613e01

Please sign in to comment.