Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
phuoc.tran committed Nov 24, 2024
1 parent 718f641 commit 415c2b1
Show file tree
Hide file tree
Showing 6 changed files with 149 additions and 42 deletions.
30 changes: 23 additions & 7 deletions diagrams/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,8 @@ def __init__(
if isinstance(outformat, list):
for one_format in outformat:
if not self._validate_outformat(one_format):
raise ValueError(f'"{one_format}" is not a valid output format')
raise ValueError(
f'"{one_format}" is not a valid output format')
else:
if not self._validate_outformat(outformat):
raise ValueError(f'"{outformat}" is not a valid output format')
Expand Down Expand Up @@ -478,7 +479,8 @@ def __init__(

if label:
# Graphviz complaining about using label for edges, so replace it with xlabel.
# Update: xlabel option causes the misaligned label position: https://github.com/mingrammer/diagrams/issues/83
# Update: xlabel option causes the misaligned label position:
# https://github.com/mingrammer/diagrams/issues/83
self._attrs["label"] = label
if color:
self._attrs["color"] = color
Expand All @@ -490,7 +492,8 @@ def __sub__(self, other: Union["Node", "Edge", List["Node"]]):
"""Implement Self - Node or Edge and Self - [Nodes]"""
return self.connect(other)

def __rsub__(self, other: Union[List["Node"], List["Edge"]]) -> List["Edge"]:
def __rsub__(self, other: Union[List["Node"],
List["Edge"]]) -> List["Edge"]:
"""Called for [Nodes] or [Edges] - Self because list don't have __sub__ operators."""
return self.append(other)

Expand All @@ -504,15 +507,23 @@ def __lshift__(self, other: Union["Node", "Edge", List["Node"]]):
self.reverse = True
return self.connect(other)

def __rrshift__(self, other: Union[List["Node"], List["Edge"]]) -> List["Edge"]:
def __rrshift__(self,
other: Union[List["Node"],
List["Edge"]]) -> List["Edge"]:
"""Called for [Nodes] or [Edges] >> Self because list of Edges don't have __rshift__ operators."""
return self.append(other, forward=True)

def __rlshift__(self, other: Union[List["Node"], List["Edge"]]) -> List["Edge"]:
def __rlshift__(self,
other: Union[List["Node"],
List["Edge"]]) -> List["Edge"]:
"""Called for [Nodes] or [Edges] << Self because list of Edges don't have __lshift__ operators."""
return self.append(other, reverse=True)

def append(self, other: Union[List["Node"], List["Edge"]], forward=None, reverse=None) -> List["Edge"]:
def append(self,
other: Union[List["Node"],
List["Edge"]],
forward=None,
reverse=None) -> List["Edge"]:
result = []
for o in other:
if isinstance(o, Edge):
Expand All @@ -521,7 +532,12 @@ def append(self, other: Union[List["Node"], List["Edge"]], forward=None, reverse
self._attrs = o.attrs.copy()
result.append(o)
else:
result.append(Edge(o, forward=forward, reverse=reverse, **self._attrs))
result.append(
Edge(
o,
forward=forward,
reverse=reverse,
**self._attrs))
return result

def connect(self, other: Union["Node", "Edge", List["Node"]]):
Expand Down
3 changes: 2 additions & 1 deletion diagrams/c4/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ def _format_description(description):
"""
wrapper = textwrap.TextWrapper(width=40, max_lines=3)
lines = [html.escape(line) for line in wrapper.wrap(description)]
lines += [""] * (3 - len(lines)) # fill up with empty lines so it is always three
# fill up with empty lines so it is always three
lines += [""] * (3 - len(lines))
return "<br/>".join(lines)


Expand Down
3 changes: 2 additions & 1 deletion scripts/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ def _gen_class_name(path: str) -> str:
name = _gen_class_name(path)
resource_path = os.path.join(resource_root, path)
alias = cfg.ALIASES[pvd].get(typ, {}).get(name)
typ_classes[typ].append({"name": name, "alias": alias, "resource_path": resource_path})
typ_classes[typ].append(
{"name": name, "alias": alias, "resource_path": resource_path})
return tmpl.render(pvd=pvd, typ_classes=typ_classes)


Expand Down
21 changes: 11 additions & 10 deletions scripts/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def cleaner_aws(f):
f = f.replace("-light-bg", "")
for p in cfg.FILE_PREFIXES["aws"]:
if f.startswith(p):
f = f[len(p) :]
f = f[len(p):]
break
return f.lower()

Expand All @@ -42,7 +42,7 @@ def cleaner_azure(f):
f = "-".join(f.split())
for p in cfg.FILE_PREFIXES["azure"]:
if f.startswith(p):
f = f[len(p) :]
f = f[len(p):]
break
return f.lower()

Expand All @@ -52,7 +52,7 @@ def cleaner_gcp(f):
f = "-".join(f.split())
for p in cfg.FILE_PREFIXES["gcp"]:
if f.startswith(p):
f = f[len(p) :]
f = f[len(p):]
break
return f.lower()

Expand All @@ -62,7 +62,7 @@ def cleaner_ibm(f):
f = "-".join(f.split())
for p in cfg.FILE_PREFIXES["ibm"]:
if f.startswith(p):
f = f[len(p) :]
f = f[len(p):]
break
return f.lower()

Expand All @@ -72,7 +72,7 @@ def cleaner_firebase(f):
f = "-".join(f.split())
for p in cfg.FILE_PREFIXES["firebase"]:
if f.startswith(p):
f = f[len(p) :]
f = f[len(p):]
break
return f.lower()

Expand All @@ -81,7 +81,7 @@ def cleaner_k8s(f):
f = f.replace("-256", "")
for p in cfg.FILE_PREFIXES["k8s"]:
if f.startswith(p):
f = f[len(p) :]
f = f[len(p):]
break
return f.lower()

Expand All @@ -90,15 +90,15 @@ def cleaner_digitalocean(f):
f = f.replace("-32", "")
for p in cfg.FILE_PREFIXES["digitalocean"]:
if f.startswith(p):
f = f[len(p) :]
f = f[len(p):]
break
return f.lower()


def cleaner_alibabacloud(f):
for p in cfg.FILE_PREFIXES["alibabacloud"]:
if f.startswith(p):
f = f[len(p) :]
f = f[len(p):]
break
return f.lower()

Expand All @@ -108,7 +108,7 @@ def cleaner_oci(f):
f = f.replace("_", "-")
for p in cfg.FILE_PREFIXES["oci"]:
if f.startswith(p):
f = f[len(p) :]
f = f[len(p):]
break
return f.lower()

Expand Down Expand Up @@ -203,7 +203,8 @@ def svg2png2(pvd: str) -> None:
def _convert(base: str, path: str):
path_src = os.path.join(base, path)
path_dest = path_src.replace(".svg", ".png")
subprocess.run([cfg.CMD_SVG2PNG_IM, *cfg.CMD_SVG2PNG_IM_OPTS, path_src, path_dest])
subprocess.run([cfg.CMD_SVG2PNG_IM, *
cfg.CMD_SVG2PNG_IM_OPTS, path_src, path_dest])
subprocess.run(["rm", path_src])

for root, _, files in os.walk(resource_dir(pvd)):
Expand Down
13 changes: 10 additions & 3 deletions tests/test_c4.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@

class C4Test(unittest.TestCase):
def setUp(self):
self.name = "diagram-" + "".join([random.choice(string.hexdigits) for n in range(7)]).lower()
self.name = "diagram-" + \
"".join([random.choice(string.hexdigits) for n in range(7)]).lower()

def tearDown(self):
setdiagram(None)
Expand All @@ -29,8 +30,14 @@ def tearDown(self):
def test_nodes(self):
with Diagram(name=self.name, show=False):
person = Person("person", "A person.")
container = Container("container", "Java application", "The application.")
database = Database("database", "Oracle database", "Stores information.")
container = Container(
"container",
"Java application",
"The application.")
database = Database(
"database",
"Oracle database",
"Stores information.")

def test_external_nodes(self):
with Diagram(name=self.name, show=False):
Expand Down
121 changes: 101 additions & 20 deletions tests/test_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,68 +247,142 @@ def test_nodes_to_node_with_additional_attributes(self):
with Cluster():
node1 = Node("node1")
nodes = [Node("node2"), Node("node3")]
self.assertEqual(nodes - Edge(color="red") - Edge(color="green") - node1, node1)
self.assertEqual(
nodes -
Edge(
color="red") -
Edge(
color="green") -
node1,
node1)

def test_node_to_node_with_attributes(self):
with Diagram(name=os.path.join(self.name, "node_to_node_with_attributes"), show=False):
with Cluster():
node1 = Node("node1")
node2 = Node("node2")
self.assertEqual(node1 << Edge(color="red", label="1.1") << node2, node2)
self.assertEqual(node1 >> Edge(color="green", label="1.2") >> node2, node2)
self.assertEqual(node1 << Edge(color="blue", label="1.3") >> node2, node2)
self.assertEqual(
node1 << Edge(
color="red",
label="1.1") << node2,
node2)
self.assertEqual(
node1 >> Edge(
color="green",
label="1.2") >> node2,
node2)
self.assertEqual(
node1 << Edge(
color="blue",
label="1.3") >> node2,
node2)

def test_node_to_node_with_additional_attributes(self):
with Diagram(name=os.path.join(self.name, "node_to_node_with_additional_attributes"), show=False):
with Cluster():
node1 = Node("node1")
node2 = Node("node2")
self.assertEqual(node1 << Edge(color="red", label="2.1") << Edge(color="blue") << node2, node2)
self.assertEqual(node1 >> Edge(color="green", label="2.2") >> Edge(color="red") >> node2, node2)
self.assertEqual(node1 << Edge(color="blue", label="2.3") >> Edge(color="black") >> node2, node2)
self.assertEqual(
node1 << Edge(
color="red",
label="2.1") << Edge(
color="blue") << node2,
node2)
self.assertEqual(
node1 >> Edge(
color="green",
label="2.2") >> Edge(
color="red") >> node2,
node2)
self.assertEqual(
node1 << Edge(
color="blue",
label="2.3") >> Edge(
color="black") >> node2,
node2)

def test_nodes_to_node_with_attributes_loop(self):
with Diagram(name=os.path.join(self.name, "nodes_to_node_with_attributes_loop"), show=False):
with Cluster():
node = Node("node")
self.assertEqual(node >> Edge(color="red", label="3.1") >> node, node)
self.assertEqual(node << Edge(color="green", label="3.2") << node, node)
self.assertEqual(node >> Edge(color="blue", label="3.3") << node, node)
self.assertEqual(node << Edge(color="pink", label="3.4") >> node, node)
self.assertEqual(
node >> Edge(
color="red",
label="3.1") >> node,
node)
self.assertEqual(
node << Edge(
color="green",
label="3.2") << node,
node)
self.assertEqual(
node >> Edge(
color="blue",
label="3.3") << node,
node)
self.assertEqual(
node << Edge(
color="pink",
label="3.4") >> node,
node)

def test_nodes_to_node_with_attributes_bothdirectional(self):
with Diagram(name=os.path.join(self.name, "nodes_to_node_with_attributes_bothdirectional"), show=False):
with Cluster():
node1 = Node("node1")
nodes = [Node("node2"), Node("node3")]
self.assertEqual(nodes << Edge(color="green", label="4") >> node1, node1)
self.assertEqual(
nodes << Edge(
color="green",
label="4") >> node1,
node1)

def test_nodes_to_node_with_attributes_bidirectional(self):
with Diagram(name=os.path.join(self.name, "nodes_to_node_with_attributes_bidirectional"), show=False):
with Cluster():
node1 = Node("node1")
nodes = [Node("node2"), Node("node3")]
self.assertEqual(nodes << Edge(color="blue", label="5") >> node1, node1)
self.assertEqual(
nodes << Edge(
color="blue",
label="5") >> node1,
node1)

def test_nodes_to_node_with_attributes_onedirectional(self):
with Diagram(name=os.path.join(self.name, "nodes_to_node_with_attributes_onedirectional"), show=False):
with Cluster():
node1 = Node("node1")
nodes = [Node("node2"), Node("node3")]
self.assertEqual(nodes >> Edge(color="red", label="6.1") >> node1, node1)
self.assertEqual(nodes << Edge(color="green", label="6.2") << node1, node1)
self.assertEqual(
nodes >> Edge(
color="red",
label="6.1") >> node1,
node1)
self.assertEqual(
nodes << Edge(
color="green",
label="6.2") << node1,
node1)

def test_nodes_to_node_with_additional_attributes_directional(self):
with Diagram(name=os.path.join(self.name, "nodes_to_node_with_additional_attributes_directional"), show=False):
with Cluster():
node1 = Node("node1")
nodes = [Node("node2"), Node("node3")]
self.assertEqual(
nodes >> Edge(color="red", label="6.1") >> Edge(color="blue", label="6.2") >> node1, node1
)
nodes >> Edge(
color="red",
label="6.1") >> Edge(
color="blue",
label="6.2") >> node1,
node1)
self.assertEqual(
nodes << Edge(color="green", label="6.3") << Edge(color="pink", label="6.4") << node1, node1
)
nodes << Edge(
color="green",
label="6.3") << Edge(
color="pink",
label="6.4") << node1,
node1)


class ResourcesTest(unittest.TestCase):
Expand All @@ -319,5 +393,12 @@ def test_folder_depth(self):
exceeded.
"""
resources_dir = pathlib.Path(__file__).parent.parent / "resources"
max_depth = max(os.path.relpath(d, resources_dir).count(os.sep) + 1 for d, _, _ in os.walk(resources_dir))
max_depth = max(
os.path.relpath(
d,
resources_dir).count(
os.sep) +
1 for d,
_,
_ in os.walk(resources_dir))
self.assertLessEqual(max_depth, 2)

0 comments on commit 415c2b1

Please sign in to comment.