Coverage for /home/runner/work/bijux-cli/bijux-cli/src/bijux_cli/contracts/serializer.py: 100%

10 statements  

« prev     ^ index     » next       coverage.py v7.10.4, created at 2025-08-19 23:36 +0000

1# SPDX-License-Identifier: MIT 

2# Copyright © 2025 Bijan Mousavi 

3 

4"""Defines the contract for the object serialization service. 

5 

6This module specifies the `SerializerProtocol`, a formal interface that any 

7service responsible for serializing objects to strings or bytes (e.g., in 

8JSON or YAML format) and deserializing them back must implement. 

9""" 

10 

11from __future__ import annotations 

12 

13from typing import Protocol, TypeVar, runtime_checkable 

14 

15from bijux_cli.core.enums import OutputFormat 

16 

17T = TypeVar("T") 

18 

19 

20@runtime_checkable 

21class SerializerProtocol(Protocol[T]): 

22 """Defines the contract for stateless, thread-safe object serialization. 

23 

24 This interface specifies methods for serializing and deserializing objects 

25 to and from strings or bytes in various formats, such as JSON or YAML. 

26 """ 

27 

28 def dumps( 

29 self, 

30 obj: T, 

31 *, 

32 fmt: OutputFormat = OutputFormat.JSON, 

33 pretty: bool = False, 

34 ) -> str: 

35 """Serializes an object to a string. 

36 

37 Args: 

38 obj (T): The object to serialize. 

39 fmt (OutputFormat): The output format. Defaults to `OutputFormat.JSON`. 

40 pretty (bool): If True, formats the output for human readability. 

41 

42 Returns: 

43 str: The serialized object as a string. 

44 """ 

45 ... 

46 

47 def dumps_bytes( 

48 self, 

49 obj: T, 

50 *, 

51 fmt: OutputFormat = OutputFormat.JSON, 

52 pretty: bool = False, 

53 ) -> bytes: 

54 """Serializes an object to bytes. 

55 

56 Args: 

57 obj (T): The object to serialize. 

58 fmt (OutputFormat): The output format. Defaults to `OutputFormat.JSON`. 

59 pretty (bool): If True, formats the output for human readability. 

60 

61 Returns: 

62 bytes: The serialized object as bytes. 

63 """ 

64 ... 

65 

66 def loads( 

67 self, 

68 data: str | bytes, 

69 *, 

70 fmt: OutputFormat = OutputFormat.JSON, 

71 pretty: bool = False, 

72 ) -> T: 

73 """Deserializes data from a string or bytes into an object. 

74 

75 Args: 

76 data (str | bytes): The string or bytes to deserialize. 

77 fmt (OutputFormat): The format of the input data. Defaults to 

78 `OutputFormat.JSON`. 

79 pretty (bool): A hint that may affect parsing, though often unused 

80 during deserialization. 

81 

82 Returns: 

83 T: The deserialized object. 

84 """ 

85 ... 

86 

87 def emit( 

88 self, payload: T, *, fmt: OutputFormat = OutputFormat.JSON, pretty: bool = False 

89 ) -> None: 

90 """Serializes and emits a payload to standard output. 

91 

92 Args: 

93 payload (T): The object to serialize and emit. 

94 fmt (OutputFormat): The output format. 

95 pretty (bool): If True, formats the output for human readability. 

96 

97 Returns: 

98 None: 

99 """ 

100 ...