| 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 | raise TypeError("Graph data malformed") |
| 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 | for item in data: |
| 40 | # Edge Case: Graph item is not a tuple or is empty |
| 41 | if not isinstance(item, tuple) or len(item) == 0: |
| 42 | raise TypeError("Graph item malformed") |
| 43 | |
| 44 | item_type = item[0] |
| 45 | |
| 46 | # Edge Case: Node item with incorrect number of elements or wrong data types |
| 47 | if item_type == NODE: |
| 48 | if len(item) != 3: |
| 49 | raise TypeError("Graph item malformed") |
| 50 | _, name, attrs = item |
| 51 | # Check if name is not a string or attrs is not a dict |
| 52 | if not isinstance(name, str) or not isinstance(attrs, dict): |
| 53 | raise TypeError("Graph item malformed") |
| 54 | self.nodes.append(Node(name, attrs)) |
| 55 | |
| 56 | # Edge Case: Edge item with incorrect number of elements or wrong data types |
| 57 | elif item_type == EDGE: |
| 58 | if len(item) != 4: |
| 59 | raise TypeError("Graph item malformed") |
| 60 | _, src, dst, attrs = item |
| 61 | # Check if src or dst is not a string or attrs is not a dict |
| 62 | if not isinstance(src, str) or not isinstance(dst, str) or not isinstance(attrs, dict): |
| 63 | raise TypeError("Graph item malformed") |
| 64 | self.edges.append(Edge(src, dst, attrs)) |
| 65 | |
| 66 | # Edge Case: Attribute item with incorrect number of elements or wrong data types |
| 67 | elif item_type == ATTR: |
| 68 | if len(item) != 3: |
| 69 | raise TypeError("Graph item malformed") |
| 70 | _, key, value = item |
| 71 | # Check if key or value is not a string |
| 72 | if not isinstance(key, str) or not isinstance(value, str): |
| 73 | raise TypeError("Graph item malformed") |
| 74 | self.attrs[key] = value |
| 75 | |
| 76 | # Edge Case: Unknown item type |
| 77 | else: |
| 78 | raise ValueError("Unknown item") |
| 79 | |
| 80 | # Handled Edge Cases: Graph data is None; Graph data is not a list; Graph item is not a tuple; Graph item is empty; Node item with incorrect number of elements; Node name is not a string; Node attributes is not a dict; Edge item with incorrect number of elements; Edge source is not a string; Edge destination is not a string; Edge attributes is not a dict; Attribute item with incorrect number of elements; Attribute key is not a string; Attribute value is not a string; Unknown item type |