| 24 | 24 | |
| 25 | 25 | class Graph: |
| 26 | 26 | def __init__(self, data=None): |
| 27 | | pass |
| 27 | # Edge Case: Handle None data input |
| 28 | if data is None: |
| 29 | data = [] |
| 30 | |
| 31 | # Edge Case: Handle non-list data input |
| 32 | if not isinstance(data, list): |
| 33 | raise TypeError("Graph data malformed") |
| 34 | |
| 35 | self.nodes = [] |
| 36 | self.edges = [] |
| 37 | self.attrs = {} |
| 38 | |
| 39 | # Edge Case: Handle malformed data elements |
| 40 | for item in data: |
| 41 | # Edge Case: Handle items that are not tuples |
| 42 | if not isinstance(item, tuple): |
| 43 | raise TypeError("Graph data malformed") |
| 44 | |
| 45 | # Edge Case: Handle tuples with insufficient elements |
| 46 | if len(item) < 2: |
| 47 | raise TypeError("Graph item incomplete") |
| 48 | |
| 49 | item_type = item[0] |
| 50 | |
| 51 | if item_type == NODE: |
| 52 | # Edge Case: Handle incorrect number of arguments for Node |
| 53 | if len(item) != 3: |
| 54 | raise ValueError("Node is malformed") |
| 55 | # Edge Case: Handle non-string node name |
| 56 | if not isinstance(item[1], str): |
| 57 | raise ValueError("Node is malformed") |
| 58 | # Edge Case: Handle non-dict node attributes |
| 59 | if not isinstance(item[2], dict): |
| 60 | raise ValueError("Node is malformed") |
| 61 | self.nodes.append(Node(item[1], item[2])) |
| 62 | |
| 63 | elif item_type == EDGE: |
| 64 | # Edge Case: Handle incorrect number of arguments for Edge |
| 65 | if len(item) != 4: |
| 66 | raise ValueError("Edge is malformed") |
| 67 | # Edge Case: Handle non-string source or destination |
| 68 | if not isinstance(item[1], str) or not isinstance(item[2], str): |
| 69 | raise ValueError("Edge is malformed") |
| 70 | # Edge Case: Handle non-dict edge attributes |
| 71 | if not isinstance(item[3], dict): |
| 72 | raise ValueError("Edge is malformed") |
| 73 | self.edges.append(Edge(item[1], item[2], item[3])) |
| 74 | |
| 75 | elif item_type == ATTR: |
| 76 | # Edge Case: Handle incorrect number of arguments for Attribute |
| 77 | if len(item) != 3: |
| 78 | raise ValueError("Attribute is malformed") |
| 79 | # Edge Case: Handle non-string attribute key or value |
| 80 | if not isinstance(item[1], str) or not isinstance(item[2], str): |
| 81 | raise ValueError("Attribute is malformed") |
| 82 | self.attrs[item[1]] = item[2] |
| 83 | |
| 84 | else: |
| 85 | # Edge Case: Handle unknown item types |
| 86 | raise ValueError("Unknown item") |
| 87 | |
| 88 | # Handled Edge Cases: None data input, non-list data input, non-tuple items, tuples with insufficient elements, incorrect number of arguments for Node/Edge/Attribute, non-string node names, non-dict node/edge attributes, non-string source/destination nodes, non-string attribute keys/values, unknown item types |