Coverage for value_object_pattern/usables/internet/media_type_value_object.py: 46.88%
114 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-11-21 14:31 +0000
« prev ^ index » next coverage.py v7.15.4, created at 2026-11-21 14:31 +0000
1# ruff: noqa: N802
2"""
3Provide a value object for HTTP media types.
4"""
6from __future__ import annotations 1abcdefghij
8from re import Pattern, compile as re_compile, sub as re_sub 1abcdefghij
9from typing import NoReturn, cast 1abcdefghij
11from value_object_pattern.decorators import process, validation 1abcdefghij
12from value_object_pattern.usables import NotEmptyStringValueObject, TrimmedStringValueObject 1abcdefghij
15class MediaTypeValueObject(NotEmptyStringValueObject, TrimmedStringValueObject): 1abcdefghij
16 """
17 Validate and normalize an HTTP media type.
19 Media types contain a type and subtype followed by optional parameters. The type, subtype, and parameter names are
20 case-insensitive and are normalized to lowercase. Parameter values retain their original case. Instances can be
21 created directly with `value` or through a named constructor such as `JSON()` or `MULTIPART_FORM_DATA()`.
23 References:
24 RFC 9110 media types: https://www.rfc-editor.org/rfc/rfc9110.html#name-media-type
25 IANA Media Types Registry: https://www.iana.org/assignments/media-types/media-types.xhtml
27 Example:
28 ```python
29 from value_object_pattern.usables.internet import MediaTypeValueObject
31 media_type = MediaTypeValueObject(value='Application/JSON; Charset="UTF-8"')
32 print(repr(media_type))
33 # >>> MediaTypeValueObject(value='application/json; charset="UTF-8"')
34 ```
35 """
37 _HTTP_TCHAR_PATTERN = r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+" 1abcdefghij
38 _QUOTED_STRING_PATTERN = r'"(?:[\t !#-\[\]-~\x80-\xff]|\\[\t -~\x80-\xff])*"' 1abcdefghij
39 _MEDIA_TYPE_REGEX: Pattern[str] = re_compile(pattern=rf'^(?P<type>{_HTTP_TCHAR_PATTERN})/(?P<subtype>{_HTTP_TCHAR_PATTERN})(?P<parameters>(?:[ \t]*;[ \t]*{_HTTP_TCHAR_PATTERN}=(?:{_HTTP_TCHAR_PATTERN}|{_QUOTED_STRING_PATTERN}))*)$') # noqa: E501 # fmt: skip 1abcdefghij
40 _PARAMETER_REGEX: Pattern[str] = re_compile(pattern=rf'[ \t]*;[ \t]*(?P<name>{_HTTP_TCHAR_PATTERN})=(?P<value>{_HTTP_TCHAR_PATTERN}|{_QUOTED_STRING_PATTERN})') # noqa: E501 # fmt: skip 1abcdefghij
42 @staticmethod 1abcdefghij
43 def _unquote_parameter_value(value: str) -> str: 1abcdefghij
44 """
45 Return the semantic value of a token or quoted parameter value.
47 Args:
48 value (str): The serialized parameter value.
50 Returns:
51 str: The token value or unquoted and unescaped quoted-string value.
52 """
53 if not value.startswith('"'):
54 return value
56 return re_sub(pattern=r'\\([\t -~\x80-\xff])', repl=r'\1', string=value[1:-1])
58 @classmethod 1abcdefghij
59 def _parse_media_type(cls, value: str) -> tuple[str, str, tuple[tuple[str, str, str], ...]] | None: 1abcdefghij
60 """
61 Parse a media type into normalized components.
63 Args:
64 value (str): The media type to parse.
66 Returns:
67 tuple[str, str, tuple[tuple[str, str, str], ...]] | None: Parsed components, or `None` when the value is
68 invalid or repeats a parameter.
69 """
70 media_type_match = cls._MEDIA_TYPE_REGEX.fullmatch(string=value)
71 if media_type_match is None:
72 return None
74 parameters: list[tuple[str, str, str]] = []
75 parameter_names: set[str] = set()
76 for parameter_match in cls._PARAMETER_REGEX.finditer(media_type_match.group('parameters')):
77 parameter_name = cast(str, parameter_match.group('name'))
78 serialized_value = cast(str, parameter_match.group('value'))
79 parameter_name = parameter_name.lower()
80 if parameter_name in parameter_names:
81 return None
83 parameter_names.add(parameter_name)
84 parameters.append(
85 (
86 parameter_name,
87 cls._unquote_parameter_value(value=serialized_value),
88 serialized_value,
89 ),
90 )
92 top_level_type = cast(str, media_type_match.group('type'))
93 subtype = cast(str, media_type_match.group('subtype'))
95 return top_level_type.lower(), subtype.lower(), tuple(parameters)
97 @process(order=0) 1abcdefghij
98 def _normalize_media_type(self, value: str) -> str: 1abcdefghij
99 """
100 Normalize case-insensitive media type components.
102 Args:
103 value (str): The validated media type.
105 Returns:
106 str: The normalized media type.
107 """
108 parsed_media_type = self._parse_media_type(value=value)
109 if parsed_media_type is None:
110 self._raise_value_is_not_media_type(value=value)
112 media_type, subtype, parameters = parsed_media_type
114 return f'{media_type}/{subtype}{"".join(f"; {name}={serialized_value}" for name, _, serialized_value in parameters)}' # noqa: E501
116 def _parsed_media_type(self) -> tuple[str, str, tuple[tuple[str, str, str], ...]]: 1abcdefghij
117 """
118 Return the parsed components of the stored media type.
120 Returns:
121 tuple[str, str, tuple[tuple[str, str, str], ...]]: The normalized type, subtype, and parameters.
123 Raises:
124 ValueError: If the immutable stored value is not a valid media type.
125 """
126 parsed_media_type = self._parse_media_type(value=self.value)
127 if parsed_media_type is None:
128 self._raise_value_is_not_media_type(value=self.value)
130 return parsed_media_type
132 @property 1abcdefghij
133 def top_level_type(self) -> str: 1abcdefghij
134 """
135 Return the normalized top-level media type.
137 Returns:
138 str: The lowercase top-level type, such as `application` or `text`.
139 """
140 top_level_type, _, _ = self._parsed_media_type()
142 return top_level_type
144 @property 1abcdefghij
145 def subtype(self) -> str: 1abcdefghij
146 """
147 Return the normalized media-type subtype.
149 Returns:
150 str: The lowercase subtype, such as `json` or `vnd.example+json`.
151 """
152 _, subtype, _ = self._parsed_media_type()
154 return subtype
156 @property 1abcdefghij
157 def parameters(self) -> dict[str, str]: 1abcdefghij
158 """
159 Return the media-type parameters by name.
161 Returns:
162 dict[str, str]: Parameter names mapped to unquoted and unescaped semantic values.
163 """
164 _, _, parameters = self._parsed_media_type()
166 return {name: value for name, value, _ in parameters}
168 @validation(order=1) 1abcdefghij
169 def _ensure_value_is_media_type(self, value: str) -> None: 1abcdefghij
170 """
171 Ensure the value uses the HTTP media-type grammar.
173 Args:
174 value (str): The media type to validate.
176 Raises:
177 ValueError: If the value is not a valid media type.
178 """
179 if self._parse_media_type(value=value) is None:
180 self._raise_value_is_not_media_type(value=value)
182 def _raise_value_is_not_media_type(self, value: str) -> NoReturn: 1abcdefghij
183 """
184 Raise an error for an invalid media type.
186 Args:
187 value (str): The invalid media type.
189 Raises:
190 ValueError: Always raised with the invalid value.
191 """
192 raise ValueError(f'MediaTypeValueObject value <<<{value}>>> is not a valid HTTP media type.')
194 @classmethod 1abcdefghij
195 def APPLICATION_OCTET_STREAM(cls) -> MediaTypeValueObject: 1abcdefghij
196 """
197 Create a value object for the application/octet-stream media type.
199 Returns:
200 MediaTypeValueObject: A value object containing `application/octet-stream`.
202 Example:
203 ```python
204 from value_object_pattern.usables.internet import MediaTypeValueObject
206 octet_stream = MediaTypeValueObject.APPLICATION_OCTET_STREAM()
207 print(repr(octet_stream))
208 # >>> MediaTypeValueObject(value='application/octet-stream')
209 ```
210 """
211 return cls(value='application/octet-stream')
213 @classmethod 1abcdefghij
214 def APPLICATION_PDF(cls) -> MediaTypeValueObject: 1abcdefghij
215 """
216 Create a value object for the application/pdf media type.
218 Returns:
219 MediaTypeValueObject: A value object containing `application/pdf`.
221 Example:
222 ```python
223 from value_object_pattern.usables.internet import MediaTypeValueObject
225 pdf = MediaTypeValueObject.APPLICATION_PDF()
226 print(repr(pdf))
227 # >>> MediaTypeValueObject(value='application/pdf')
228 ```
229 """
230 return cls(value='application/pdf')
232 @classmethod 1abcdefghij
233 def APPLICATION_XML(cls) -> MediaTypeValueObject: 1abcdefghij
234 """
235 Create a value object for the application/xml media type.
237 Returns:
238 MediaTypeValueObject: A value object containing `application/xml`.
240 Example:
241 ```python
242 from value_object_pattern.usables.internet import MediaTypeValueObject
244 xml = MediaTypeValueObject.APPLICATION_XML()
245 print(repr(xml))
246 # >>> MediaTypeValueObject(value='application/xml')
247 ```
248 """
249 return cls(value='application/xml')
251 @classmethod 1abcdefghij
252 def APPLICATION_ZIP(cls) -> MediaTypeValueObject: 1abcdefghij
253 """
254 Create a value object for the application/zip media type.
256 Returns:
257 MediaTypeValueObject: A value object containing `application/zip`.
259 Example:
260 ```python
261 from value_object_pattern.usables.internet import MediaTypeValueObject
263 zip_archive = MediaTypeValueObject.APPLICATION_ZIP()
264 print(repr(zip_archive))
265 # >>> MediaTypeValueObject(value='application/zip')
266 ```
267 """
268 return cls(value='application/zip')
270 @classmethod 1abcdefghij
271 def AUDIO_MPEG(cls) -> MediaTypeValueObject: 1abcdefghij
272 """
273 Create a value object for the audio/mpeg media type.
275 Returns:
276 MediaTypeValueObject: A value object containing `audio/mpeg`.
278 Example:
279 ```python
280 from value_object_pattern.usables.internet import MediaTypeValueObject
282 audio = MediaTypeValueObject.AUDIO_MPEG()
283 print(repr(audio))
284 # >>> MediaTypeValueObject(value='audio/mpeg')
285 ```
286 """
287 return cls(value='audio/mpeg')
289 @classmethod 1abcdefghij
290 def FORM_URLENCODED(cls) -> MediaTypeValueObject: 1abcdefghij
291 """
292 Create a value object for the application/x-www-form-urlencoded media type.
294 Returns:
295 MediaTypeValueObject: A value object containing `application/x-www-form-urlencoded`.
297 Example:
298 ```python
299 from value_object_pattern.usables.internet import MediaTypeValueObject
301 form = MediaTypeValueObject.FORM_URLENCODED()
302 print(repr(form))
303 # >>> MediaTypeValueObject(value='application/x-www-form-urlencoded')
304 ```
305 """
306 return cls(value='application/x-www-form-urlencoded')
308 @classmethod 1abcdefghij
309 def IMAGE_GIF(cls) -> MediaTypeValueObject: 1abcdefghij
310 """
311 Create a value object for the image/gif media type.
313 Returns:
314 MediaTypeValueObject: A value object containing `image/gif`.
316 Example:
317 ```python
318 from value_object_pattern.usables.internet import MediaTypeValueObject
320 gif = MediaTypeValueObject.IMAGE_GIF()
321 print(repr(gif))
322 # >>> MediaTypeValueObject(value='image/gif')
323 ```
324 """
325 return cls(value='image/gif')
327 @classmethod 1abcdefghij
328 def IMAGE_JPEG(cls) -> MediaTypeValueObject: 1abcdefghij
329 """
330 Create a value object for the image/jpeg media type.
332 Returns:
333 MediaTypeValueObject: A value object containing `image/jpeg`.
335 Example:
336 ```python
337 from value_object_pattern.usables.internet import MediaTypeValueObject
339 jpeg = MediaTypeValueObject.IMAGE_JPEG()
340 print(repr(jpeg))
341 # >>> MediaTypeValueObject(value='image/jpeg')
342 ```
343 """
344 return cls(value='image/jpeg')
346 @classmethod 1abcdefghij
347 def IMAGE_PNG(cls) -> MediaTypeValueObject: 1abcdefghij
348 """
349 Create a value object for the image/png media type.
351 Returns:
352 MediaTypeValueObject: A value object containing `image/png`.
354 Example:
355 ```python
356 from value_object_pattern.usables.internet import MediaTypeValueObject
358 png = MediaTypeValueObject.IMAGE_PNG()
359 print(repr(png))
360 # >>> MediaTypeValueObject(value='image/png')
361 ```
362 """
363 return cls(value='image/png')
365 @classmethod 1abcdefghij
366 def IMAGE_SVG_XML(cls) -> MediaTypeValueObject: 1abcdefghij
367 """
368 Create a value object for the image/svg+xml media type.
370 Returns:
371 MediaTypeValueObject: A value object containing `image/svg+xml`.
373 Example:
374 ```python
375 from value_object_pattern.usables.internet import MediaTypeValueObject
377 svg = MediaTypeValueObject.IMAGE_SVG_XML()
378 print(repr(svg))
379 # >>> MediaTypeValueObject(value='image/svg+xml')
380 ```
381 """
382 return cls(value='image/svg+xml')
384 @classmethod 1abcdefghij
385 def MULTIPART_FORM_DATA(cls) -> MediaTypeValueObject: 1abcdefghij
386 """
387 Create a value object for the multipart/form-data media type.
389 Returns:
390 MediaTypeValueObject: A value object containing `multipart/form-data`.
392 Example:
393 ```python
394 from value_object_pattern.usables.internet import MediaTypeValueObject
396 multipart = MediaTypeValueObject.MULTIPART_FORM_DATA()
397 print(repr(multipart))
398 # >>> MediaTypeValueObject(value='multipart/form-data')
399 ```
400 """
401 return cls(value='multipart/form-data')
403 @classmethod 1abcdefghij
404 def JSON(cls) -> MediaTypeValueObject: 1abcdefghij
405 """
406 Create a value object for the application/json media type.
408 Returns:
409 MediaTypeValueObject: A value object containing `application/json`.
411 Example:
412 ```python
413 from value_object_pattern.usables.internet import MediaTypeValueObject
415 json = MediaTypeValueObject.JSON()
416 print(repr(json))
417 # >>> MediaTypeValueObject(value='application/json')
418 ```
419 """
420 return cls(value='application/json')
422 @classmethod 1abcdefghij
423 def TEXT_CSS(cls) -> MediaTypeValueObject: 1abcdefghij
424 """
425 Create a value object for the text/css media type.
427 Returns:
428 MediaTypeValueObject: A value object containing `text/css`.
430 Example:
431 ```python
432 from value_object_pattern.usables.internet import MediaTypeValueObject
434 css = MediaTypeValueObject.TEXT_CSS()
435 print(repr(css))
436 # >>> MediaTypeValueObject(value='text/css')
437 ```
438 """
439 return cls(value='text/css')
441 @classmethod 1abcdefghij
442 def TEXT_HTML(cls) -> MediaTypeValueObject: 1abcdefghij
443 """
444 Create a value object for the text/html media type.
446 Returns:
447 MediaTypeValueObject: A value object containing `text/html`.
449 Example:
450 ```python
451 from value_object_pattern.usables.internet import MediaTypeValueObject
453 text_html = MediaTypeValueObject.TEXT_HTML()
454 print(repr(text_html))
455 # >>> MediaTypeValueObject(value='text/html')
456 ```
457 """
458 return cls(value='text/html')
460 @classmethod 1abcdefghij
461 def TEXT_JAVASCRIPT(cls) -> MediaTypeValueObject: 1abcdefghij
462 """
463 Create a value object for the text/javascript media type.
465 Returns:
466 MediaTypeValueObject: A value object containing `text/javascript`.
468 Example:
469 ```python
470 from value_object_pattern.usables.internet import MediaTypeValueObject
472 javascript = MediaTypeValueObject.TEXT_JAVASCRIPT()
473 print(repr(javascript))
474 # >>> MediaTypeValueObject(value='text/javascript')
475 ```
476 """
477 return cls(value='text/javascript')
479 @classmethod 1abcdefghij
480 def TEXT_PLAIN(cls) -> MediaTypeValueObject: 1abcdefghij
481 """
482 Create a value object for the text/plain media type.
484 Returns:
485 MediaTypeValueObject: A value object containing `text/plain`.
487 Example:
488 ```python
489 from value_object_pattern.usables.internet import MediaTypeValueObject
491 plain_text = MediaTypeValueObject.TEXT_PLAIN()
492 print(repr(plain_text))
493 # >>> MediaTypeValueObject(value='text/plain')
494 ```
495 """
496 return cls(value='text/plain')
498 @classmethod 1abcdefghij
499 def VIDEO_MP4(cls) -> MediaTypeValueObject: 1abcdefghij
500 """
501 Create a value object for the video/mp4 media type.
503 Returns:
504 MediaTypeValueObject: A value object containing `video/mp4`.
506 Example:
507 ```python
508 from value_object_pattern.usables.internet import MediaTypeValueObject
510 video = MediaTypeValueObject.VIDEO_MP4()
511 print(repr(video))
512 # >>> MediaTypeValueObject(value='video/mp4')
513 ```
514 """
515 return cls(value='video/mp4')