Skip to content
This repository has been archived by the owner on May 4, 2024. It is now read-only.

Commit

Permalink
Add spec for Graph#to_dot implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
floriandejonckheere committed Apr 1, 2024
1 parent 2b2668f commit 189ac01
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 13 deletions.
4 changes: 0 additions & 4 deletions lib/mosaik/graph/edge.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,6 @@ def initialize(attributes = {})
@attributes = attributes
end

def to_dot
attributes.map { |k, v| "#{k}=#{v}" }.join(", ")
end

def inspect
"#<#{self.class.name} attributes=#{attributes.map { |k, v| "#{k}: #{v}" }.join(',')}>"
end
Expand Down
11 changes: 10 additions & 1 deletion lib/mosaik/graph/graph.rb
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,16 @@ def tsort_each_child(vertex, &)
def to_dot
<<~DOT
digraph {
#{vertices.values.map(&:to_dot).join("\n ")}
#{
vertices
.values
.flat_map do |vertex|
vertex
.edges
.filter_map { |k, e| "\"#{vertex.id}\" -#{directed? ? '>' : '-'} \"#{k}\" [#{e.attributes.map { |ek, ev| "#{ek}=#{ev}" }.join(',')}]" }
end
.join("\n ")
}
}
DOT
end
Expand Down
8 changes: 0 additions & 8 deletions lib/mosaik/graph/vertex.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,6 @@ def remove_edge(id)
edges.delete(id)
end

def to_dot
edges.map do |to, edges|
edges.map do |edge|
"\"#{id}\" -> \"#{to}\" [#{edge.to_dot}]"
end
end.flatten.join("\n ")
end

def inspect
"#<#{self.class.name} id=#{id} attributes=#{attributes.map { |k, v| "#{k}: #{v}" }.join(',')} edges=#{edges.count}>"
end
Expand Down
21 changes: 21 additions & 0 deletions spec/mosaik/graph/graph_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,27 @@
end
end

describe "#to_dot" do
context "when the graph is directed" do
subject(:graph) { build(:graph, directed: true) }

it "returns the graph in DOT format" do
graph.add_vertex("vertex1")
graph.add_vertex("vertex2")
graph.add_vertex("vertex3")
graph.add_edge("vertex1", "vertex2")
graph.add_edge("vertex2", "vertex3", foo: "bar", baz: "bat")

expect(graph.to_dot).to eq <<~DOT
digraph {
"vertex1" -> "vertex2" []
"vertex2" -> "vertex3" [foo=bar,baz=bat]
}
DOT
end
end
end

describe "#tsort" do
it "topologically sorts the vertices" do
graph.add_vertex("vertex1")
Expand Down

0 comments on commit 189ac01

Please sign in to comment.