| 24 | 24 | |
| 25 | 25 | class Graph: |
| 26 | 26 | def __init__(self, data: list | None = None): |
| 27 | | pass |
| 27 | # Edge Case: Graph data is None |
| 28 | if data is None: |
| 29 | data = [] |
| 30 | |
| 31 | # Edge Case: Graph data is not a list |
| 32 | if not isinstance(data, list): |
| 33 | raise TypeError("Graph data malformed") |
| 34 | |
| 35 | self.nodes = [] |
| 36 | self.edges = [] |
| 37 | self.attrs = {} |
| 38 | |
| 39 | # Process each item in the data list |
| 40 | for item in data: |
| 41 | # Edge Case: Item is not a tuple |
| 42 | if not isinstance(item, tuple): |
| 43 | raise TypeError("Graph item malformed") |
| 44 | |
| 45 | # Edge Case: Item is an empty tuple |
| 46 | if len(item) == 0: |
| 47 | raise TypeError("Graph item malformed") |
| 48 | |
| 49 | item_type = item[0] |
| 50 | |
| 51 | # Process ATTR item |
| 52 | if item_type == ATTR: |
| 53 | # Edge Case: ATTR item doesn't have exactly 3 elements |
| 54 | if len(item) != 3: |
| 55 | raise TypeError("Graph item malformed") |
| 56 | |
| 57 | _, key, value = item |
| 58 | self.attrs[key] = value |
| 59 | |
| 60 | # Process NODE item |
| 61 | elif item_type == NODE: |
| 62 | # Edge Case: NODE item doesn't have exactly 3 elements |
| 63 | if len(item) != 3: |
| 64 | raise TypeError("Graph item malformed") |
| 65 | |
| 66 | _, name, attrs = item |
| 67 | # Edge Case: Node name is not a string |
| 68 | if not isinstance(name, str): |
| 69 | raise TypeError("Graph item malformed") |
| 70 | # Edge Case: Node attrs is not a dict |
| 71 | if not isinstance(attrs, dict): |
| 72 | raise TypeError("Graph item malformed") |
| 73 | |
| 74 | self.nodes.append(Node(name, attrs)) |
| 75 | |
| 76 | # Process EDGE item |
| 77 | elif item_type == EDGE: |
| 78 | # Edge Case: EDGE item doesn't have exactly 4 elements |
| 79 | if len(item) != 4: |
| 80 | raise TypeError("Graph item malformed") |
| 81 | |
| 82 | _, src, dst, attrs = item |
| 83 | # Edge Case: Edge src is not a string |
| 84 | if not isinstance(src, str): |
| 85 | raise TypeError("Graph item malformed") |
| 86 | # Edge Case: Edge dst is not a string |
| 87 | if not isinstance(dst, str): |
| 88 | raise TypeError("Graph item malformed") |
| 89 | # Edge Case: Edge attrs is not a dict |
| 90 | if not isinstance(attrs, dict): |
| 91 | raise TypeError("Graph item malformed") |
| 92 | |
| 93 | self.edges.append(Edge(src, dst, attrs)) |
| 94 | |
| 95 | # Edge Case: Unknown item type |
| 96 | else: |
| 97 | raise ValueError("Unknown item") |
| 98 | # Handled Edge Cases: Graph data is None; Graph data is not a list; Item is not a tuple; Item is an empty tuple; ATTR item doesn't have exactly 3 elements; NODE item doesn't have exactly 3 elements; Node name is not a string; Node attrs is not a dict; EDGE item doesn't have exactly 4 elements; Edge src is not a string; Edge dst is not a string; Edge attrs is not a dict; Unknown item type |