| 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: Graph item is not a tuple |
| 42 | if not isinstance(item, tuple): |
| 43 | raise TypeError("Graph item malformed") |
| 44 | |
| 45 | # Edge Case: Graph item is empty |
| 46 | if len(item) == 0: |
| 47 | raise TypeError("Graph item malformed") |
| 48 | |
| 49 | item_type = item[0] |
| 50 | |
| 51 | # Edge Case: Unknown item type |
| 52 | if item_type not in [NODE, EDGE, ATTR]: |
| 53 | raise ValueError("Unknown item") |
| 54 | |
| 55 | # Process based on item type |
| 56 | if item_type == NODE: |
| 57 | # Edge Case: Node tuple has incorrect number of elements |
| 58 | if len(item) != 3: |
| 59 | raise TypeError("Graph item malformed") |
| 60 | |
| 61 | name, attrs = item[1], item[2] |
| 62 | # Edge Case: Node attributes is not a dict |
| 63 | if not isinstance(attrs, dict): |
| 64 | raise TypeError("Node attributes must be a dict") |
| 65 | |
| 66 | self.nodes.append(Node(name, attrs)) |
| 67 | |
| 68 | elif item_type == EDGE: |
| 69 | # Edge Case: Edge tuple has incorrect number of elements |
| 70 | if len(item) != 4: |
| 71 | raise TypeError("Graph item malformed") |
| 72 | |
| 73 | src, dst, attrs = item[1], item[2], item[3] |
| 74 | # Edge Case: Edge attributes is not a dict |
| 75 | if not isinstance(attrs, dict): |
| 76 | raise TypeError("Edge attributes must be a dict") |
| 77 | |
| 78 | self.edges.append(Edge(src, dst, attrs)) |
| 79 | |
| 80 | elif item_type == ATTR: |
| 81 | # Edge Case: ATTR tuple has incorrect number of elements |
| 82 | if len(item) != 3: |
| 83 | raise TypeError("Graph item malformed") |
| 84 | |
| 85 | key, value = item[1], item[2] |
| 86 | self.attrs[key] = value |
| 87 | |
| 88 | # Handled Edge Cases: Graph data is None; Graph data is not a list; Graph item is not a tuple; Graph item is empty; Unknown item type; Node tuple has incorrect number of elements; Node attributes is not a dict; Edge tuple has incorrect number of elements; Edge attributes is not a dict; ATTR tuple has incorrect number of elements |