|
| 1 | +""" |
| 2 | +``graph[x]`` resolves an index, a name or a vertex, and says so clearly when it |
| 3 | +cannot -- it must never quietly hand back ``None``. |
| 4 | +""" |
| 5 | + |
| 6 | +import unittest |
| 7 | + |
| 8 | +import numpy as np |
| 9 | + |
| 10 | +from pgraph import DGraph, UGraph |
| 11 | + |
| 12 | + |
| 13 | +class _GetItem: |
| 14 | + Graph: type |
| 15 | + |
| 16 | + def setUp(self): |
| 17 | + self.g = self.Graph() |
| 18 | + self.a = self.g.add_vertex([0, 0], name="a") |
| 19 | + self.b = self.g.add_vertex([1, 0], name="b") |
| 20 | + self.c = self.g.add_vertex([2, 0], name="c") |
| 21 | + |
| 22 | + def test_int(self): |
| 23 | + self.assertIs(self.g[0], self.a) |
| 24 | + self.assertIs(self.g[2], self.c) |
| 25 | + self.assertIs(self.g[-1], self.c) |
| 26 | + |
| 27 | + def test_numpy_integer(self): |
| 28 | + # e.g. the result of np.argmin(), a very common way to get an index |
| 29 | + self.assertIs(self.g[np.int64(1)], self.b) |
| 30 | + self.assertIs(self.g[np.argmin([3.0, 1.0, 2.0])], self.b) |
| 31 | + |
| 32 | + def test_name(self): |
| 33 | + self.assertIs(self.g["b"], self.b) |
| 34 | + |
| 35 | + def test_vertex(self): |
| 36 | + self.assertIs(self.g[self.c], self.c) |
| 37 | + |
| 38 | + def test_unknown_name(self): |
| 39 | + with self.assertRaises(KeyError): |
| 40 | + self.g["zz"] |
| 41 | + |
| 42 | + def test_index_out_of_range(self): |
| 43 | + with self.assertRaises(IndexError): |
| 44 | + self.g[3] |
| 45 | + with self.assertRaises(IndexError): |
| 46 | + self.g[-4] |
| 47 | + |
| 48 | + def test_wrong_type(self): |
| 49 | + for bad in (1.5, None, [0], (0,), slice(0, 2), 1 + 2j): |
| 50 | + with self.subTest(bad=bad): |
| 51 | + with self.assertRaises(TypeError): |
| 52 | + self.g[bad] |
| 53 | + |
| 54 | + def test_membership_and_iteration_unaffected(self): |
| 55 | + self.assertIn("a", self.g) |
| 56 | + self.assertEqual([v.name for v in self.g], ["a", "b", "c"]) |
| 57 | + |
| 58 | + |
| 59 | +class TestUGraphGetItem(_GetItem, unittest.TestCase): |
| 60 | + Graph = UGraph |
| 61 | + |
| 62 | + |
| 63 | +class TestDGraphGetItem(_GetItem, unittest.TestCase): |
| 64 | + Graph = DGraph |
| 65 | + |
| 66 | + |
| 67 | +if __name__ == "__main__": |
| 68 | + unittest.main() |
0 commit comments