Coverage for tests/test_utils.py : 30%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
22from collections import Counter, namedtuple
23from glob import glob
24import os
25import unittest
27from lsst.daf.butler.core.utils import findFileResources, iterable, getFullTypeName, Singleton
28from lsst.daf.butler import Formatter, Registry
29from lsst.daf.butler import NamedKeyDict, StorageClass
32TESTDIR = os.path.dirname(__file__)
35class IterableTestCase(unittest.TestCase):
36 """Tests for `iterable` helper.
37 """
39 def testNonIterable(self):
40 self.assertEqual(list(iterable(0)), [0, ])
42 def testString(self):
43 self.assertEqual(list(iterable("hello")), ["hello", ])
45 def testIterableNoString(self):
46 self.assertEqual(list(iterable([0, 1, 2])), [0, 1, 2])
47 self.assertEqual(list(iterable(["hello", "world"])), ["hello", "world"])
50class SingletonTestCase(unittest.TestCase):
51 """Tests of the Singleton metaclass"""
53 class IsSingleton(metaclass=Singleton):
54 def __init__(self):
55 self.data = {}
56 self.id = 0
58 class IsBadSingleton(IsSingleton):
59 def __init__(self, arg):
60 """A singleton can not accept any arguments."""
61 self.arg = arg
63 class IsSingletonSubclass(IsSingleton):
64 def __init__(self):
65 super().__init__()
67 def testSingleton(self):
68 one = SingletonTestCase.IsSingleton()
69 two = SingletonTestCase.IsSingleton()
71 # Now update the first one and check the second
72 one.data["test"] = 52
73 self.assertEqual(one.data, two.data)
74 two.id += 1
75 self.assertEqual(one.id, two.id)
77 three = SingletonTestCase.IsSingletonSubclass()
78 self.assertNotEqual(one.id, three.id)
80 with self.assertRaises(TypeError):
81 SingletonTestCase.IsBadSingleton(52)
84class NamedKeyDictTest(unittest.TestCase):
86 def setUp(self):
87 self.TestTuple = namedtuple("TestTuple", ("name", "id"))
88 self.a = self.TestTuple(name="a", id=1)
89 self.b = self.TestTuple(name="b", id=2)
90 self.dictionary = {self.a: 10, self.b: 20}
91 self.names = {self.a.name, self.b.name}
93 def check(self, nkd):
94 self.assertEqual(len(nkd), 2)
95 self.assertEqual(nkd.names, self.names)
96 self.assertEqual(nkd.keys(), self.dictionary.keys())
97 self.assertEqual(list(nkd.values()), list(self.dictionary.values()))
98 self.assertEqual(list(nkd.items()), list(self.dictionary.items()))
99 self.assertEqual(list(nkd.byName().values()), list(self.dictionary.values()))
100 self.assertEqual(list(nkd.byName().keys()), list(nkd.names))
102 def testConstruction(self):
103 self.check(NamedKeyDict(self.dictionary))
104 self.check(NamedKeyDict(iter(self.dictionary.items())))
106 def testDuplicateNameConstruction(self):
107 self.dictionary[self.TestTuple(name="a", id=3)] = 30
108 with self.assertRaises(AssertionError):
109 NamedKeyDict(self.dictionary)
110 with self.assertRaises(AssertionError):
111 NamedKeyDict(iter(self.dictionary.items()))
113 def testNoNameConstruction(self):
114 self.dictionary["a"] = 30
115 with self.assertRaises(AttributeError):
116 NamedKeyDict(self.dictionary)
117 with self.assertRaises(AttributeError):
118 NamedKeyDict(iter(self.dictionary.items()))
120 def testGetItem(self):
121 nkd = NamedKeyDict(self.dictionary)
122 self.assertEqual(nkd["a"], 10)
123 self.assertEqual(nkd[self.a], 10)
124 self.assertEqual(nkd["b"], 20)
125 self.assertEqual(nkd[self.b], 20)
126 self.assertIn("a", nkd)
127 self.assertIn(self.b, nkd)
129 def testSetItem(self):
130 nkd = NamedKeyDict(self.dictionary)
131 nkd[self.a] = 30
132 self.assertEqual(nkd["a"], 30)
133 nkd["b"] = 40
134 self.assertEqual(nkd[self.b], 40)
135 with self.assertRaises(KeyError):
136 nkd["c"] = 50
137 with self.assertRaises(AssertionError):
138 nkd[self.TestTuple("a", 3)] = 60
140 def testDelItem(self):
141 nkd = NamedKeyDict(self.dictionary)
142 del nkd[self.a]
143 self.assertNotIn("a", nkd)
144 del nkd["b"]
145 self.assertNotIn(self.b, nkd)
146 self.assertEqual(len(nkd), 0)
148 def testIter(self):
149 self.assertEqual(set(iter(NamedKeyDict(self.dictionary))), set(self.dictionary))
151 def testEquality(self):
152 nkd = NamedKeyDict(self.dictionary)
153 self.assertEqual(nkd, self.dictionary)
154 self.assertEqual(self.dictionary, nkd)
157class TestButlerUtils(unittest.TestCase):
158 """Tests of the simple utilities."""
160 def testTypeNames(self):
161 # Check types and also an object
162 tests = [(Formatter, "lsst.daf.butler.core.formatter.Formatter"),
163 (int, "int"),
164 (StorageClass, "lsst.daf.butler.core.storageClass.StorageClass"),
165 (StorageClass(None), "lsst.daf.butler.core.storageClass.StorageClass"),
166 (Registry, "lsst.daf.butler.registry.Registry")]
168 for item, typeName in tests:
169 self.assertEqual(getFullTypeName(item), typeName)
172class FindFileResourcesTestCase(unittest.TestCase):
174 def test_getSingleFile(self):
175 """Test getting a file by its file name."""
176 filename = os.path.join(TESTDIR, "config/basic/butler.yaml")
177 self.assertEqual([filename], findFileResources([filename]))
179 def test_getAllFiles(self):
180 """Test getting all the files by not passing a regex."""
181 expected = Counter([p for p in glob(os.path.join(TESTDIR, "config", "**"), recursive=True)
182 if os.path.isfile(p)])
183 self.assertNotEqual(len(expected), 0) # verify some files were found
184 files = Counter(findFileResources([os.path.join(TESTDIR, "config")]))
185 self.assertEqual(expected, files)
187 def test_getAllFilesRegex(self):
188 """Test getting all the files with a regex-specified file ending."""
189 expected = Counter(glob(os.path.join(TESTDIR, "config", "**", "*.yaml"), recursive=True))
190 self.assertNotEqual(len(expected), 0) # verify some files were found
191 files = Counter(findFileResources([os.path.join(TESTDIR, "config")], r"\.yaml\b"))
192 self.assertEqual(expected, files)
194 def test_multipleInputs(self):
195 """Test specifying more than one location to find a files."""
196 expected = Counter(glob(os.path.join(TESTDIR, "config", "basic", "**", "*.yaml"), recursive=True))
197 expected.update(glob(os.path.join(TESTDIR, "config", "templates", "**", "*.yaml"), recursive=True))
198 self.assertNotEqual(len(expected), 0) # verify some files were found
199 files = Counter(findFileResources([os.path.join(TESTDIR, "config", "basic"),
200 os.path.join(TESTDIR, "config", "templates")],
201 r"\.yaml\b"))
202 self.assertEqual(expected, files)
205if __name__ == "__main__": 205 ↛ 206line 205 didn't jump to line 206, because the condition on line 205 was never true
206 unittest.main()