|
17 | 17 |
|
18 | 18 | import signal |
19 | 19 | import unittest |
| 20 | +import unittest.mock |
20 | 21 | from contextlib import contextmanager |
21 | 22 |
|
22 | 23 | import numpy as np |
@@ -197,6 +198,41 @@ def test_samecomponent(self): |
197 | 198 | self.assertFalse(g.samecomponent(g[1], g[2])) |
198 | 199 |
|
199 | 200 |
|
| 201 | +class TestNotRecomputed(unittest.TestCase): |
| 202 | + """The traversal runs once, and again only after the graph has changed""" |
| 203 | + |
| 204 | + def traversals(self, g, ask): |
| 205 | + calls = [] |
| 206 | + original = type(g[0]).adjacent |
| 207 | + |
| 208 | + def spy(vertex, *args, **kwargs): |
| 209 | + calls.append(vertex) |
| 210 | + return original(vertex, *args, **kwargs) |
| 211 | + |
| 212 | + with unittest.mock.patch.object(type(g[0]), "adjacent", spy): |
| 213 | + ask() |
| 214 | + return len(calls) |
| 215 | + |
| 216 | + def check(self, cls): |
| 217 | + g = build(cls, 4, [(0, 1), (2, 3)]) |
| 218 | + ask = lambda: (g.nc, g.component(g[0]), g.samecomponent(g[0], g[1]), g[2].label) |
| 219 | + |
| 220 | + self.assertGreater(self.traversals(g, ask), 0) # first time: does the work |
| 221 | + self.assertEqual(self.traversals(g, ask), 0) # nothing changed: none |
| 222 | + self.assertEqual(self.traversals(g, ask), 0) |
| 223 | + |
| 224 | + g.add_edge(g[1], g[2]) # a change: once more, and the answer is new |
| 225 | + self.assertGreater(self.traversals(g, ask), 0) |
| 226 | + self.assertEqual(g.nc, 1) |
| 227 | + self.assertEqual(self.traversals(g, ask), 0) |
| 228 | + |
| 229 | + def test_undirected(self): |
| 230 | + self.check(UGraph) |
| 231 | + |
| 232 | + def test_directed(self): |
| 233 | + self.check(DGraph) |
| 234 | + |
| 235 | + |
200 | 236 | class TestUndirectedComponents(_Components, unittest.TestCase): |
201 | 237 | cls = UGraph |
202 | 238 |
|
|
0 commit comments