learning-credentials 0.4.0rc1__tar.gz → 0.4.0rc3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/CHANGELOG.rst +2 -0
  2. {learning_credentials-0.4.0rc1/learning_credentials.egg-info → learning_credentials-0.4.0rc3}/PKG-INFO +3 -1
  3. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/compat.py +6 -3
  4. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/generators.py +66 -30
  5. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3/learning_credentials.egg-info}/PKG-INFO +3 -1
  6. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/pyproject.toml +2 -1
  7. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/tests/test_generators.py +133 -22
  8. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/LICENSE.txt +0 -0
  9. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/MANIFEST.in +0 -0
  10. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/README.rst +0 -0
  11. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/__init__.py +0 -0
  12. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/admin.py +0 -0
  13. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/api/__init__.py +0 -0
  14. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/api/urls.py +0 -0
  15. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/api/v1/__init__.py +0 -0
  16. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/api/v1/permissions.py +0 -0
  17. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/api/v1/serializers.py +0 -0
  18. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/api/v1/urls.py +0 -0
  19. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/api/v1/views.py +0 -0
  20. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/apps.py +0 -0
  21. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/conf/locale/config.yaml +0 -0
  22. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/exceptions.py +0 -0
  23. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/migrations/0001_initial.py +0 -0
  24. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/migrations/0002_migrate_to_learning_credentials.py +0 -0
  25. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/migrations/0003_rename_certificates_to_credentials.py +0 -0
  26. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/migrations/0004_replace_course_keys_with_learning_context_keys.py +0 -0
  27. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/migrations/0005_rename_processors_and_generators.py +0 -0
  28. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/migrations/0006_cleanup_openedx_certificates_tables.py +0 -0
  29. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/migrations/0007_validation.py +0 -0
  30. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/migrations/__init__.py +0 -0
  31. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/models.py +0 -0
  32. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/processors.py +0 -0
  33. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/settings/__init__.py +0 -0
  34. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/settings/common.py +0 -0
  35. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/settings/production.py +0 -0
  36. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/tasks.py +0 -0
  37. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/templates/learning_credentials/base.html +0 -0
  38. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/templates/learning_credentials/edx_ace/certificate_generated/email/body.html +0 -0
  39. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/templates/learning_credentials/edx_ace/certificate_generated/email/body.txt +0 -0
  40. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/templates/learning_credentials/edx_ace/certificate_generated/email/from_name.txt +0 -0
  41. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/templates/learning_credentials/edx_ace/certificate_generated/email/head.html +0 -0
  42. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/templates/learning_credentials/edx_ace/certificate_generated/email/subject.txt +0 -0
  43. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/templates/learning_credentials/verify.html +0 -0
  44. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials/urls.py +0 -0
  45. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials.egg-info/SOURCES.txt +0 -0
  46. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials.egg-info/dependency_links.txt +0 -0
  47. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials.egg-info/entry_points.txt +0 -0
  48. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials.egg-info/requires.txt +0 -0
  49. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/learning_credentials.egg-info/top_level.txt +0 -0
  50. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/setup.cfg +0 -0
  51. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/tests/test_models.py +0 -0
  52. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/tests/test_processors.py +0 -0
  53. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/tests/test_tasks.py +0 -0
  54. {learning_credentials-0.4.0rc1 → learning_credentials-0.4.0rc3}/tests/test_views.py +0 -0
@@ -24,6 +24,8 @@ Added
24
24
 
25
25
  * Frontend form and backend API endpoint for verifying credentials.
26
26
  * Option to invalidate issued credentials.
27
+ * Support for defining the course name using the `cert_name_long` field (in Studio's Advanced Settings).
28
+ * Support for specifying individual fonts for PDF text elements.
27
29
 
28
30
  0.3.0 - 2025-09-17
29
31
  ******************
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: learning-credentials
3
- Version: 0.4.0rc1
3
+ Version: 0.4.0rc3
4
4
  Summary: A pluggable service for preparing Open edX credentials.
5
5
  Author-email: OpenCraft <help@opencraft.com>
6
6
  License-Expression: AGPL-3.0-or-later
@@ -184,6 +184,8 @@ Added
184
184
 
185
185
  * Frontend form and backend API endpoint for verifying credentials.
186
186
  * Option to invalidate issued credentials.
187
+ * Support for defining the course name using the `cert_name_long` field (in Studio's Advanced Settings).
188
+ * Support for specifying individual fonts for PDF text elements.
187
189
 
188
190
  0.3.0 - 2025-09-17
189
191
  ******************
@@ -52,10 +52,13 @@ def get_course_grading_policy(course_id: CourseKey) -> dict:
52
52
  def _get_course_name(course_id: CourseKey) -> str:
53
53
  """Get the course name from Open edX."""
54
54
  # noinspection PyUnresolvedReferences,PyPackageRequirements
55
- from openedx.core.djangoapps.content.learning_sequences.api import get_course_outline
55
+ from openedx.core.djangoapps.content.course_overviews.api import get_course_overview_or_none
56
56
 
57
- course_outline = get_course_outline(course_id)
58
- return (course_outline and course_outline.title) or str(course_id)
57
+ name = str(course_id)
58
+ if course_overview := get_course_overview_or_none(course_id):
59
+ name = course_overview.cert_name_long or course_overview.display_name or name
60
+
61
+ return name
59
62
 
60
63
 
61
64
  def _get_learning_path_name(learning_path_key: LearningPathKey) -> str:
@@ -19,9 +19,9 @@ from django.core.files.base import ContentFile
19
19
  from django.core.files.storage import FileSystemStorage, default_storage
20
20
  from pypdf import PdfReader, PdfWriter
21
21
  from pypdf.constants import UserAccessPermissions
22
- from reportlab.pdfbase import pdfmetrics
23
- from reportlab.pdfbase.ttfonts import TTFont
24
- from reportlab.pdfgen import canvas
22
+ from reportlab.pdfbase.pdfmetrics import FontError, FontNotFoundError, registerFont
23
+ from reportlab.pdfbase.ttfonts import TTFError, TTFont
24
+ from reportlab.pdfgen.canvas import Canvas
25
25
 
26
26
  from .compat import get_default_storage_url, get_learning_context_name, get_localized_credential_date
27
27
  from .models import CredentialAsset
@@ -33,6 +33,7 @@ if TYPE_CHECKING: # pragma: no cover
33
33
 
34
34
  from django.contrib.auth.models import User
35
35
  from opaque_keys.edx.keys import CourseKey
36
+ from pypdf import PageObject
36
37
 
37
38
 
38
39
  def _get_user_name(user: User) -> str:
@@ -45,25 +46,29 @@ def _get_user_name(user: User) -> str:
45
46
  return user.profile.name or f"{user.first_name} {user.last_name}"
46
47
 
47
48
 
48
- def _register_font(options: dict[str, Any]) -> str:
49
+ def _register_font(font_name: Any) -> str | None: # noqa: ANN401
49
50
  """
50
51
  Register a custom font if specified in options. If not specified, use the default font (Helvetica).
51
52
 
52
- :param options: A dictionary containing the font.
53
- :returns: The font name.
53
+ :param font_name: The name of the font to register.
54
+ :returns: The font name if registered successfully, otherwise None.
54
55
  """
55
- if font := options.get('font'):
56
- pdfmetrics.registerFont(TTFont(font, CredentialAsset.get_asset_by_slug(font)))
56
+ if not font_name:
57
+ return None
57
58
 
58
- return font or 'Helvetica'
59
+ try:
60
+ registerFont(TTFont(font_name, CredentialAsset.get_asset_by_slug(font_name)))
61
+ except (FontError, FontNotFoundError, TTFError):
62
+ log.exception("Error registering font %s", font_name)
63
+ else:
64
+ return font_name
59
65
 
60
66
 
61
- def _write_text_on_template(template: any, font: str, username: str, context_name: str, options: dict[str, Any]) -> any:
67
+ def _write_text_on_template(template: PageObject, username: str, context_name: str, options: dict[str, Any]) -> Canvas:
62
68
  """
63
69
  Prepare a new canvas and write the user and course name onto it.
64
70
 
65
71
  :param template: Pdf template.
66
- :param font: Font name.
67
72
  :param username: The name of the user to generate the credential for.
68
73
  :param context_name: The name of the learning context.
69
74
  :param options: A dictionary documented in the `generate_pdf_credential` function.
@@ -86,19 +91,26 @@ def _write_text_on_template(template: any, font: str, username: str, context_nam
86
91
  return tuple(int(hex_color[i : i + 2], 16) / 255 for i in range(0, 6, 2))
87
92
 
88
93
  template_width, template_height = template.mediabox[2:]
89
- pdf_canvas = canvas.Canvas(io.BytesIO(), pagesize=(template_width, template_height))
94
+ pdf_canvas = Canvas(io.BytesIO(), pagesize=(template_width, template_height))
95
+ font = _register_font(options.get('font')) or 'Helvetica'
90
96
 
91
97
  # Write the learner name.
92
- pdf_canvas.setFont(font, options.get('name_size', 32))
98
+ if options.get('name_uppercase', getattr(settings, 'LEARNING_CREDENTIALS_NAME_UPPERCASE', False)):
99
+ username = username.upper()
100
+
101
+ name_font = _register_font(options.get('name_font')) or font
102
+ pdf_canvas.setFont(name_font, options.get('name_size', 32))
93
103
  name_color = options.get('name_color', '#000')
94
104
  pdf_canvas.setFillColorRGB(*hex_to_rgb(name_color))
95
105
 
96
106
  name_x = (template_width - pdf_canvas.stringWidth(username)) / 2
97
107
  name_y = options.get('name_y', 290)
108
+
98
109
  pdf_canvas.drawString(name_x, name_y, username)
99
110
 
100
111
  # Write the learning context name.
101
- pdf_canvas.setFont(font, options.get('context_name_size', 28))
112
+ context_name_font = _register_font(options.get('context_name_font')) or font
113
+ pdf_canvas.setFont(context_name_font, options.get('context_name_size', 28))
102
114
  context_name_color = options.get('context_name_color', '#000')
103
115
  pdf_canvas.setFillColorRGB(*hex_to_rgb(context_name_color))
104
116
 
@@ -113,13 +125,22 @@ def _write_text_on_template(template: any, font: str, username: str, context_nam
113
125
 
114
126
  # Write the issue date.
115
127
  issue_date = get_localized_credential_date()
116
- pdf_canvas.setFont(font, 12)
128
+ if options.get('issue_date_uppercase', getattr(settings, 'LEARNING_CREDENTIALS_ISSUE_DATE_UPPERCASE', False)):
129
+ issue_date = issue_date.upper()
130
+
131
+ issue_date_font = _register_font(options.get('issue_date_font')) or font
132
+ pdf_canvas.setFont(issue_date_font, options.get('issue_date_size', 12))
117
133
  issue_date_color = options.get('issue_date_color', '#000')
118
134
  pdf_canvas.setFillColorRGB(*hex_to_rgb(issue_date_color))
119
135
 
120
136
  issue_date_x = (template_width - pdf_canvas.stringWidth(issue_date)) / 2
121
137
  issue_date_y = options.get('issue_date_y', 120)
122
- pdf_canvas.drawString(issue_date_x, issue_date_y, issue_date)
138
+
139
+ issue_date_char_space = options.get(
140
+ 'issue_date_char_space', getattr(settings, 'LEARNING_CREDENTIALS_ISSUE_DATE_CHAR_SPACE', 0)
141
+ )
142
+
143
+ pdf_canvas.drawString(issue_date_x, issue_date_y, issue_date, charSpace=issue_date_char_space)
123
144
 
124
145
  return pdf_canvas
125
146
 
@@ -168,7 +189,7 @@ def generate_pdf_credential(
168
189
  credential_uuid: UUID,
169
190
  options: dict[str, Any],
170
191
  ) -> str:
171
- """
192
+ r"""
172
193
  Generate a PDF credential.
173
194
 
174
195
  :param learning_context_key: The ID of the course or learning path the credential is for.
@@ -179,33 +200,48 @@ def generate_pdf_credential(
179
200
 
180
201
  Options:
181
202
  - template: The path to the PDF template file.
182
- - template_two_lines: The path to the PDF template file for two-line context names.
183
- A two-line context name is specified by using a semicolon as a separator.
184
- - font: The name of the font to use.
203
+ - template_multiline: The path to the PDF template file for multiline context names.
204
+ A multiline context name is specified by using '\n' or ';' as a separator.
205
+ - font: The name of the font to use. The default font is Helvetica.
185
206
  - name_y: The Y coordinate of the name on the credential (vertical position on the template).
186
207
  - name_color: The color of the name on the credential (hexadecimal color code).
187
208
  - name_size: The font size of the name on the credential. The default value is 32.
188
- - context_name: Specify the custom course or Learning Path name.
209
+ - name_font: The font of the name on the credential. It overrides the `font` option.
210
+ - name_uppercase: If set to true (without quotes), the name will be converted to uppercase.
211
+ The default value is False, unless specified otherwise in the instance settings.
212
+ - context_name: Specify the custom course or Learning Path name. If not provided, it will be retrieved
213
+ automatically from the "cert_name_long" or "display_name" fields for courses, or from the Learning Path model.
189
214
  - context_name_y: The Y coordinate of the context name on the credential (vertical position on the template).
190
215
  - context_name_color: The color of the context name on the credential (hexadecimal color code).
191
216
  - context_name_size: The font size of the context name on the credential. The default value is 28.
217
+ - context_name_font: The font of the context name on the credential. It overrides the `font` option.
192
218
  - issue_date_y: The Y coordinate of the issue date on the credential (vertical position on the template).
193
219
  - issue_date_color: The color of the issue date on the credential (hexadecimal color code).
220
+ - issue_date_size: The font size of the issue date on the credential. The default value is 12.
221
+ - issue_date_font: The font of the issue date on the credential. It overrides the `font` option.
222
+ - issue_date_char_space: The character spacing of the issue date on the credential
223
+ (default is 0.0, unless specified otherwise in the instance settings).
224
+ - issue_date_uppercase: If set to true (without quotes), the issue date will be converted to uppercase.
225
+ The default value is False, unless specified otherwise in the instance settings.
194
226
  """
195
227
  log.info("Starting credential generation for user %s", user.id)
196
228
 
197
229
  username = _get_user_name(user)
198
230
  context_name = options.get('context_name') or get_learning_context_name(learning_context_key)
231
+ template_path = options.get('template')
199
232
 
200
- # Get template from the CredentialAsset.
201
- # HACK: We support two-line strings by using a semicolon as a separator.
202
- if ';' in context_name and (template_path := options.get('template_two_lines')):
203
- template_file = CredentialAsset.get_asset_by_slug(template_path)
204
- context_name = context_name.replace(';', '\n')
205
- else:
206
- template_file = CredentialAsset.get_asset_by_slug(options['template'])
233
+ # Handle multiline context name (we support semicolon as a separator to preserve backward compatibility).
234
+ context_name = context_name.replace(';', '\n').replace(r'\n', '\n')
235
+ if '\n' in context_name:
236
+ # `template_two_lines` is kept for backward compatibility.
237
+ template_path = options.get('template_multiline', options.get('template_two_lines', template_path))
238
+
239
+ if not template_path:
240
+ msg = "Template path must be specified in options."
241
+ raise ValueError(msg)
207
242
 
208
- font = _register_font(options)
243
+ # Get template from the CredentialAsset.
244
+ template_file = CredentialAsset.get_asset_by_slug(template_path)
209
245
 
210
246
  # Load the PDF template.
211
247
  with template_file.open('rb') as template_file:
@@ -214,7 +250,7 @@ def generate_pdf_credential(
214
250
  credential = PdfWriter()
215
251
 
216
252
  # Create a new canvas, prepare the page and write the data
217
- pdf_canvas = _write_text_on_template(template, font, username, context_name, options)
253
+ pdf_canvas = _write_text_on_template(template, username, context_name, options)
218
254
 
219
255
  overlay_pdf = PdfReader(io.BytesIO(pdf_canvas.getpdfdata()))
220
256
  template.merge_page(overlay_pdf.pages[0])
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: learning-credentials
3
- Version: 0.4.0rc1
3
+ Version: 0.4.0rc3
4
4
  Summary: A pluggable service for preparing Open edX credentials.
5
5
  Author-email: OpenCraft <help@opencraft.com>
6
6
  License-Expression: AGPL-3.0-or-later
@@ -184,6 +184,8 @@ Added
184
184
 
185
185
  * Frontend form and backend API endpoint for verifying credentials.
186
186
  * Option to invalidate issued credentials.
187
+ * Support for defining the course name using the `cert_name_long` field (in Studio's Advanced Settings).
188
+ * Support for specifying individual fonts for PDF text elements.
187
189
 
188
190
  0.3.0 - 2025-09-17
189
191
  ******************
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "learning-credentials"
3
- version = "0.4.0-rc1"
3
+ version = "0.4.0-rc3"
4
4
  description = "A pluggable service for preparing Open edX credentials."
5
5
  dynamic = ["readme"]
6
6
  requires-python = ">=3.11"
@@ -188,6 +188,7 @@ ignore = [
188
188
  'RUF018', # assignment-in-assert
189
189
  'ARG002', # unused-method-argument
190
190
  'PLR0913', # too-many-arguments
191
+ 'FBT001', # flake8-boolean-trap
191
192
  ]
192
193
 
193
194
  [tool.ruff.lint.flake8-annotations]
@@ -17,6 +17,7 @@ from pypdf import PdfWriter
17
17
  from pypdf.constants import UserAccessPermissions
18
18
 
19
19
  from learning_credentials.generators import (
20
+ FontError,
20
21
  _get_user_name,
21
22
  _register_font,
22
23
  _save_credential,
@@ -42,25 +43,38 @@ def test_get_user_name():
42
43
  def test_register_font_without_custom_font(mock_get_asset_by_slug: Mock):
43
44
  """Test the _register_font falls back to the default font when no custom font is specified."""
44
45
  options = {}
45
- assert _register_font(options) == "Helvetica"
46
+ assert _register_font(options) is None
46
47
  mock_get_asset_by_slug.assert_not_called()
47
48
 
48
49
 
49
50
  @patch("learning_credentials.generators.CredentialAsset.get_asset_by_slug")
50
51
  @patch('learning_credentials.generators.TTFont')
51
- @patch("learning_credentials.generators.pdfmetrics.registerFont")
52
+ @patch("learning_credentials.generators.registerFont")
52
53
  def test_register_font_with_custom_font(mock_register_font: Mock, mock_font_class: Mock, mock_get_asset_by_slug: Mock):
53
54
  """Test the _register_font registers the custom font when specified."""
54
55
  custom_font = "MyFont"
55
- options = {"font": custom_font}
56
-
57
56
  mock_get_asset_by_slug.return_value = "font_path"
58
57
 
59
- assert _register_font(options) == custom_font
58
+ assert _register_font(custom_font) == custom_font
60
59
  mock_get_asset_by_slug.assert_called_once_with(custom_font)
61
60
  mock_font_class.assert_called_once_with(custom_font, mock_get_asset_by_slug.return_value)
62
61
  mock_register_font.assert_called_once_with(mock_font_class.return_value)
63
62
 
63
+ @patch("learning_credentials.generators.CredentialAsset.get_asset_by_slug")
64
+ @patch('learning_credentials.generators.TTFont', side_effect=FontError("Font registration failed"))
65
+ @patch("learning_credentials.generators.registerFont")
66
+ def test_register_font_with_registration_failure(
67
+ mock_register_font: Mock, mock_font_class: Mock, mock_get_asset_by_slug: Mock
68
+ ):
69
+ """Test the _register_font returns None when font registration fails."""
70
+ custom_font = "MyFont"
71
+ mock_get_asset_by_slug.return_value = "font_path"
72
+
73
+ assert _register_font(custom_font) is None
74
+ mock_get_asset_by_slug.assert_called_once_with(custom_font)
75
+ mock_font_class.assert_called_once_with(custom_font, mock_get_asset_by_slug.return_value)
76
+ mock_register_font.assert_not_called()
77
+
64
78
 
65
79
  @pytest.mark.parametrize(
66
80
  ("context_name", "options", "expected"),
@@ -87,7 +101,7 @@ def test_register_font_with_custom_font(mock_register_font: Mock, mock_font_clas
87
101
  ('Programming\n101\nAdvanced Programming', {}, {}), # Multiline course name.
88
102
  ],
89
103
  )
90
- @patch('learning_credentials.generators.canvas.Canvas', return_value=Mock(stringWidth=Mock(return_value=10)))
104
+ @patch('learning_credentials.generators.Canvas', return_value=Mock(stringWidth=Mock(return_value=10)))
91
105
  def test_write_text_on_template(mock_canvas_class: Mock, context_name: str, options: dict[str, int], expected: dict):
92
106
  """Test the _write_text_on_template function."""
93
107
  username = 'John Doe'
@@ -106,7 +120,7 @@ def test_write_text_on_template(mock_canvas_class: Mock, context_name: str, opti
106
120
 
107
121
  # Call the function with test parameters and mocks
108
122
  with patch('learning_credentials.generators.get_localized_credential_date', return_value=test_date):
109
- _write_text_on_template(template_mock, font, username, context_name, options)
123
+ _write_text_on_template(template_mock, username, context_name, options)
110
124
 
111
125
  # Verifying that Canvas was the correct pagesize.
112
126
  # Use `call_args_list` to ignore the first argument, which is an instance of io.BytesIO.
@@ -155,6 +169,90 @@ def test_write_text_on_template(mock_canvas_class: Mock, context_name: str, opti
155
169
  assert canvas_object.drawString.mock_calls[-1][1] == (expected_issue_date_x, expected_issue_date_y, test_date)
156
170
 
157
171
 
172
+ @pytest.mark.parametrize(
173
+ ("option_value", "setting_value", "expected_uppercase"),
174
+ [
175
+ (None, False, False), # No option set, setting is False - use default (lowercase)
176
+ (None, True, True), # No option set, setting is True - use setting (uppercase)
177
+ (False, False, False), # Explicitly disabled, setting is False
178
+ (False, True, False), # Explicitly disabled, setting is True - option overrides
179
+ (True, False, True), # Explicitly enabled, setting is False - option overrides
180
+ (True, True, True), # Explicitly enabled, setting is True
181
+ ],
182
+ )
183
+ @patch('learning_credentials.generators.get_localized_credential_date', return_value='April 1, 2021')
184
+ @patch('learning_credentials.generators.Canvas', return_value=Mock(stringWidth=Mock(return_value=10)))
185
+ def test_write_text_on_template_uppercase(
186
+ mock_canvas_class: Mock,
187
+ mock_get_date: Mock,
188
+ option_value: bool | None,
189
+ setting_value: bool,
190
+ expected_uppercase: bool,
191
+ ):
192
+ """Test the _write_text_on_template function with uppercase option and settings."""
193
+ username = "John Doe"
194
+ context_name = "Programming 101"
195
+ template_mock = Mock(mediabox=[0, 0, 300, 200])
196
+ options = {}
197
+
198
+ if expected_uppercase:
199
+ expected_name = "JOHN DOE"
200
+ expected_date = "APRIL 1, 2021"
201
+ else:
202
+ expected_name = username
203
+ expected_date = mock_get_date.return_value
204
+
205
+ if option_value is not None:
206
+ options['name_uppercase'] = option_value
207
+ options['issue_date_uppercase'] = option_value
208
+
209
+ with override_settings(
210
+ LEARNING_CREDENTIALS_NAME_UPPERCASE=setting_value,
211
+ LEARNING_CREDENTIALS_ISSUE_DATE_UPPERCASE=setting_value,
212
+ ):
213
+ _write_text_on_template(template_mock, username, context_name, options)
214
+
215
+ assert mock_canvas_class.return_value.drawString.mock_calls[-3][1][2] == expected_name
216
+ assert mock_canvas_class.return_value.drawString.mock_calls[-1][1][2] == expected_date
217
+
218
+
219
+ @pytest.mark.parametrize(
220
+ ("option_value", "setting_value", "expected_char_space"),
221
+ [
222
+ (None, 0, 0), # No option set, setting is 0 - use default
223
+ (None, 2, 2), # No option set, setting has value - use setting
224
+ (0, 0, 0), # Explicitly set to 0, setting is 0
225
+ (0, 2, 0), # Explicitly set to 0, setting has value - option overrides
226
+ (3, 0, 3), # Explicitly set to 3, setting is 0 - option overrides
227
+ (3, 2, 3), # Explicitly set to 3, setting has value - option overrides
228
+ ],
229
+ )
230
+ @patch('learning_credentials.generators.get_localized_credential_date', return_value='April 1, 2021')
231
+ @patch('learning_credentials.generators.Canvas', return_value=Mock(stringWidth=Mock(return_value=10)))
232
+ def test_write_text_on_template_issue_date_char_space(
233
+ mock_canvas_class: Mock,
234
+ _mock_get_date: Mock, # noqa: PT019
235
+ option_value: int | None,
236
+ setting_value: int,
237
+ expected_char_space: int,
238
+ ):
239
+ """Test the _write_text_on_template function with issue_date_char_space option and settings."""
240
+ username = "John Doe"
241
+ context_name = "Programming 101"
242
+ template_mock = Mock(mediabox=[0, 0, 300, 200])
243
+ options = {}
244
+
245
+ if option_value is not None:
246
+ options['issue_date_char_space'] = option_value
247
+
248
+ with override_settings(LEARNING_CREDENTIALS_ISSUE_DATE_CHAR_SPACE=setting_value):
249
+ _write_text_on_template(template_mock, username, context_name, options)
250
+
251
+ # Check that the last drawString call (for issue date) has the correct charSpace parameter
252
+ last_draw_call = mock_canvas_class.return_value.drawString.mock_calls[-1]
253
+ assert last_draw_call[2]['charSpace'] == expected_char_space
254
+
255
+
158
256
  @override_settings(LMS_ROOT_URL="https://example.com", MEDIA_URL="media/")
159
257
  @pytest.mark.parametrize(
160
258
  "storage",
@@ -222,20 +320,22 @@ def test_save_credential(mock_contentfile: Mock, mock_token_hex: Mock, storage:
222
320
  ("context_name", "options", "expected_template_slug", "expected_context_name"),
223
321
  [
224
322
  # Default.
225
- ('Test Course', {'template': 'template_slug'}, 'template_slug', 'Test Course'),
226
- # Specify a different template for two-line course names and replace semicolon with newline in course name.
227
- (
228
- 'Test Course; Test Course',
229
- {'template': 'template_slug', 'template_two_lines': 'template_two_lines_slug'},
230
- 'template_two_lines_slug',
231
- 'Test Course\n Test Course',
232
- ),
233
- # Do not replace semicolon with newline when the `template_two_lines` option is not specified.
234
- ('Test Course; Test Course', {'template': 'template_slug'}, 'template_slug', 'Test Course; Test Course'),
323
+ ('Test Course', {'template': 'default'}, 'default', 'Test Course'),
235
324
  # Override course name.
236
- ('Test Course', {'template': 'template_slug', 'context_name': 'Override'}, 'template_slug', 'Override'),
325
+ ('Test Course', {'template': 'default', 'context_name': 'Override'}, 'default', 'Override'),
237
326
  # Ignore empty course name override.
238
- ('Test Course', {'template': 'template_slug', 'context_name': ''}, 'template_slug', 'Test Course'),
327
+ ('Test Course', {'template': 'default', 'context_name': ''}, 'default', 'Test Course'),
328
+ # Specify a different template for multiline course names and replace \n with newline.
329
+ ('Test\nCourse', {'template': 'default', 'template_multiline': 'multiline'}, 'multiline', 'Test\nCourse'),
330
+ ('Test\\nCourse', {'template_multiline': 'multiline'}, 'multiline', 'Test\nCourse'),
331
+ # Backward compatibility with semicolon separator.
332
+ ('Test;Course', {'template_multiline': 'multiline'}, 'multiline', 'Test\nCourse'),
333
+ # Mixed semicolon and newline separators.
334
+ ('Te\nst\\nCourse;', {'template_multiline': 'multiline'}, 'multiline', 'Te\nst\nCourse\n'),
335
+ # Check backward compatibility with `template_two_lines` option.
336
+ ('Test\\nCourse', {'template': 'default', 'template_two_lines': 'two_lines'}, 'two_lines', 'Test\nCourse'),
337
+ # Ensure that the default template is used when no multiline template is specified.
338
+ ('Test\\nCourse', {'template': 'default'}, 'default', 'Test\nCourse'),
239
339
  ],
240
340
  )
241
341
  @patch(
@@ -251,7 +351,6 @@ def test_save_credential(mock_contentfile: Mock, mock_token_hex: Mock, storage:
251
351
  )
252
352
  @patch('learning_credentials.generators._get_user_name')
253
353
  @patch('learning_credentials.generators.get_learning_context_name')
254
- @patch('learning_credentials.generators._register_font')
255
354
  @patch('learning_credentials.generators.PdfReader')
256
355
  @patch('learning_credentials.generators.PdfWriter')
257
356
  @patch(
@@ -264,7 +363,6 @@ def test_generate_pdf_credential(
264
363
  mock_write_text_on_template: Mock,
265
364
  mock_pdf_writer: Mock,
266
365
  mock_pdf_reader: Mock,
267
- mock_register_font: Mock,
268
366
  mock_get_learning_context_name: Mock,
269
367
  mock_get_user_name: Mock,
270
368
  mock_get_asset_by_slug: Mock,
@@ -287,7 +385,6 @@ def test_generate_pdf_credential(
287
385
  mock_get_learning_context_name.assert_not_called()
288
386
  else:
289
387
  mock_get_learning_context_name.assert_called_once_with(course_id)
290
- mock_register_font.assert_called_once_with(options)
291
388
  assert mock_pdf_reader.call_count == 2
292
389
  mock_pdf_writer.assert_called_once_with()
293
390
 
@@ -297,3 +394,17 @@ def test_generate_pdf_credential(
297
394
  assert args[-1] == options
298
395
 
299
396
  mock_save_credential.assert_called_once()
397
+
398
+ @patch('learning_credentials.generators.get_learning_context_name')
399
+ @patch('learning_credentials.generators._get_user_name')
400
+ def test_generate_pdf_credential_no_template(mock_get_user_name: Mock, mock_get_learning_context_name: Mock):
401
+ """Test that generate_pdf_credential raises ValueError when no template is specified."""
402
+ course_id = CourseKey.from_string('course-v1:edX+DemoX+Demo_Course')
403
+ user = Mock()
404
+ options = {} # No template specified.
405
+
406
+ with pytest.raises(ValueError, match=r"Template path must be specified in options."):
407
+ generate_pdf_credential(course_id, user, Mock(), options)
408
+
409
+ mock_get_user_name.assert_called_once_with(user)
410
+ mock_get_learning_context_name.assert_called_once_with(course_id)