Hide keyboard shortcuts

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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

# This file is part of daf_butler. 

# 

# Developed for the LSST Data Management System. 

# This product includes software developed by the LSST Project 

# (http://www.lsst.org). 

# See the COPYRIGHT file at the top-level directory of this distribution 

# for details of code ownership. 

# 

# This program is free software: you can redistribute it and/or modify 

# it under the terms of the GNU General Public License as published by 

# the Free Software Foundation, either version 3 of the License, or 

# (at your option) any later version. 

# 

# This program is distributed in the hope that it will be useful, 

# but WITHOUT ANY WARRANTY; without even the implied warranty of 

# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

# GNU General Public License for more details. 

# 

# You should have received a copy of the GNU General Public License 

# along with this program. If not, see <http://www.gnu.org/licenses/>. 

 

from contextlib import contextmanager 

import itertools 

import os 

import os.path 

import shutil 

import stat 

import tempfile 

import unittest 

 

import sqlalchemy 

 

from lsst.sphgeom import ConvexPolygon, UnitVector3d 

 

from lsst.daf.butler import ddl 

from lsst.daf.butler.registry import RegistryConfig 

from lsst.daf.butler.registry.databases.sqlite import SqliteDatabase 

from lsst.daf.butler.registry.tests import DatabaseTests, RegistryTests 

from lsst.daf.butler.registry import Registry 

 

TESTDIR = os.path.abspath(os.path.dirname(__file__)) 

 

 

@contextmanager 

def removeWritePermission(filename): 

mode = os.stat(filename).st_mode 

try: 

os.chmod(filename, stat.S_IREAD) 

yield 

finally: 

os.chmod(filename, mode) 

 

 

def isEmptyDatabaseActuallyWriteable(database: SqliteDatabase) -> bool: 

"""Check whether we really can modify a database. 

 

This intentionally allows any exception to be raised (not just 

`ReadOnlyDatabaseError`) to deal with cases where the file is read-only 

but the Database was initialized (incorrectly) with writeable=True. 

""" 

try: 

with database.declareStaticTables(create=True) as context: 

context.addTable( 

"a", 

ddl.TableSpec(fields=[ddl.FieldSpec("b", dtype=sqlalchemy.Integer, primaryKey=True)]) 

) 

return True 

except Exception: 

return False 

 

 

class SqliteFileDatabaseTestCase(unittest.TestCase, DatabaseTests): 

"""Tests for `SqliteDatabase` using a standard file-based database. 

""" 

 

def setUp(self): 

self.root = tempfile.mkdtemp(dir=TESTDIR) 

 

def tearDown(self): 

if self.root is not None and os.path.exists(self.root): 

shutil.rmtree(self.root, ignore_errors=True) 

 

def makeEmptyDatabase(self, origin: int = 0) -> SqliteDatabase: 

_, filename = tempfile.mkstemp(dir=self.root, suffix=".sqlite3") 

connection = SqliteDatabase.connect(filename=filename) 

return SqliteDatabase.fromConnection(connection=connection, origin=origin) 

 

def getNewConnection(self, database: SqliteDatabase, *, writeable: bool) -> SqliteDatabase: 

connection = SqliteDatabase.connect(filename=database.filename, writeable=writeable) 

return SqliteDatabase.fromConnection(origin=database.origin, connection=connection, 

writeable=writeable) 

 

@contextmanager 

def asReadOnly(self, database: SqliteDatabase) -> SqliteDatabase: 

with removeWritePermission(database.filename): 

yield self.getNewConnection(database, writeable=False) 

 

def testConnection(self): 

"""Test that different ways of connecting to a SQLite database 

are equivalent. 

""" 

_, filename = tempfile.mkstemp(dir=self.root, suffix=".sqlite3") 

# Create a read-write database by passing in the filename. 

rwFromFilename = SqliteDatabase.fromConnection(SqliteDatabase.connect(filename=filename), origin=0) 

self.assertEqual(rwFromFilename.filename, filename) 

self.assertEqual(rwFromFilename.origin, 0) 

self.assertTrue(rwFromFilename.isWriteable()) 

self.assertTrue(isEmptyDatabaseActuallyWriteable(rwFromFilename)) 

# Create a read-write database via a URI. 

rwFromUri = SqliteDatabase.fromUri(f"sqlite:///{filename}", origin=0) 

self.assertEqual(rwFromUri.filename, filename) 

self.assertEqual(rwFromUri.origin, 0) 

self.assertTrue(rwFromUri.isWriteable()) 

self.assertTrue(isEmptyDatabaseActuallyWriteable(rwFromUri)) 

# We don't support SQLite URIs inside SQLAlchemy URIs. 

with self.assertRaises(NotImplementedError): 

SqliteDatabase.connect(uri=f"sqlite:///file:{filename}?uri=true") 

 

# Test read-only connections against a read-only file. 

with removeWritePermission(filename): 

# Create a read-only database by passing in the filename. 

roFromFilename = SqliteDatabase.fromConnection(SqliteDatabase.connect(filename=filename), 

origin=0, writeable=False) 

self.assertEqual(roFromFilename.filename, filename) 

self.assertEqual(roFromFilename.origin, 0) 

self.assertFalse(roFromFilename.isWriteable()) 

self.assertFalse(isEmptyDatabaseActuallyWriteable(roFromFilename)) 

# Create a read-write database via a URI. 

roFromUri = SqliteDatabase.fromUri(f"sqlite:///{filename}", origin=0, writeable=False) 

self.assertEqual(roFromUri.filename, filename) 

self.assertEqual(roFromUri.origin, 0) 

self.assertFalse(roFromUri.isWriteable()) 

self.assertFalse(isEmptyDatabaseActuallyWriteable(roFromUri)) 

 

 

class SqliteMemoryDatabaseTestCase(unittest.TestCase, DatabaseTests): 

"""Tests for `SqliteDatabase` using an in-memory database. 

""" 

 

def makeEmptyDatabase(self, origin: int = 0) -> SqliteDatabase: 

connection = SqliteDatabase.connect(filename=None) 

return SqliteDatabase.fromConnection(connection=connection, origin=origin) 

 

def getNewConnection(self, database: SqliteDatabase, *, writeable: bool) -> SqliteDatabase: 

return SqliteDatabase.fromConnection(origin=database.origin, connection=database._connection, 

writeable=writeable) 

 

@contextmanager 

def asReadOnly(self, database: SqliteDatabase) -> SqliteDatabase: 

yield self.getNewConnection(database, writeable=False) 

 

def testConnection(self): 

"""Test that different ways of connecting to a SQLite database 

are equivalent. 

""" 

# Create an in-memory database by passing filename=None. 

memFromFilename = SqliteDatabase.fromConnection(SqliteDatabase.connect(filename=None), origin=0) 

self.assertIsNone(memFromFilename.filename) 

self.assertEqual(memFromFilename.origin, 0) 

self.assertTrue(memFromFilename.isWriteable()) 

self.assertTrue(isEmptyDatabaseActuallyWriteable(memFromFilename)) 

# Create an in-memory database via a URI. 

memFromUri = SqliteDatabase.fromUri("sqlite://", origin=0) 

self.assertIsNone(memFromUri.filename) 

self.assertEqual(memFromUri.origin, 0) 

self.assertTrue(memFromUri.isWriteable()) 

self.assertTrue(isEmptyDatabaseActuallyWriteable(memFromUri)) 

# We don't support SQLite URIs inside SQLAlchemy URIs. 

with self.assertRaises(NotImplementedError): 

SqliteDatabase.connect(uri="sqlite:///:memory:?uri=true") 

# We don't support read-only in-memory databases. 

with self.assertRaises(NotImplementedError): 

SqliteDatabase.connect(filename=None, writeable=False) 

 

 

class SqliteFileRegistryTestCase(unittest.TestCase, RegistryTests): 

"""Tests for `Registry` backed by a SQLite file-based database. 

""" 

 

def setUp(self): 

self.root = tempfile.mkdtemp(dir=TESTDIR) 

 

def tearDown(self): 

if self.root is not None and os.path.exists(self.root): 

shutil.rmtree(self.root, ignore_errors=True) 

 

def makeRegistry(self) -> Registry: 

_, filename = tempfile.mkstemp(dir=self.root, suffix=".sqlite3") 

config = RegistryConfig() 

config["db"] = f"sqlite:///{filename}" 

return Registry.fromConfig(config, create=True, butlerRoot=self.root) 

 

 

class SqliteMemoryRegistryTestCase(unittest.TestCase, RegistryTests): 

"""Tests for `Registry` backed by a SQLite in-memory database. 

""" 

 

def makeRegistry(self) -> Registry: 

config = RegistryConfig() 

config["db"] = f"sqlite://" 

return Registry.fromConfig(config, create=True) 

 

def testRegions(self): 

"""Tests for using region fields in `Registry` dimensions. 

""" 

# TODO: the test regions used here are enormous (significant fractions 

# of the sphere), and that makes this test prohibitively slow on 

# most real databases. These should be made more realistic, and the 

# test moved to daf/butler/registry/tests/registry.py. 

registry = self.makeRegistry() 

regionTract = ConvexPolygon((UnitVector3d(1, 0, 0), 

UnitVector3d(0, 1, 0), 

UnitVector3d(0, 0, 1))) 

regionPatch = ConvexPolygon((UnitVector3d(1, 1, 0), 

UnitVector3d(0, 1, 0), 

UnitVector3d(0, 0, 1))) 

regionVisit = ConvexPolygon((UnitVector3d(1, 0, 0), 

UnitVector3d(0, 1, 1), 

UnitVector3d(0, 0, 1))) 

regionVisitDetector = ConvexPolygon((UnitVector3d(1, 0, 0), 

UnitVector3d(0, 1, 0), 

UnitVector3d(0, 1, 1))) 

for a, b in itertools.combinations((regionTract, regionPatch, regionVisit, regionVisitDetector), 2): 

self.assertNotEqual(a, b) 

 

# This depends on current dimensions.yaml definitions 

self.assertEqual(len(list(registry.queryDimensions(["patch", "htm7"]))), 0) 

 

# Add some dimension entries 

registry.insertDimensionData("instrument", {"name": "DummyCam"}) 

registry.insertDimensionData("physical_filter", 

{"instrument": "DummyCam", "name": "dummy_r", "abstract_filter": "r"}, 

{"instrument": "DummyCam", "name": "dummy_i", "abstract_filter": "i"}) 

for detector in (1, 2, 3, 4, 5): 

registry.insertDimensionData("detector", {"instrument": "DummyCam", "id": detector, 

"full_name": str(detector)}) 

registry.insertDimensionData("visit", 

{"instrument": "DummyCam", "id": 0, "name": "zero", 

"physical_filter": "dummy_r", "region": regionVisit}, 

{"instrument": "DummyCam", "id": 1, "name": "one", 

"physical_filter": "dummy_i"}) 

registry.insertDimensionData("skymap", {"skymap": "DummySkyMap", "hash": bytes()}) 

registry.insertDimensionData("tract", {"skymap": "DummySkyMap", "tract": 0, "region": regionTract}) 

registry.insertDimensionData("patch", 

{"skymap": "DummySkyMap", "tract": 0, "patch": 0, 

"cell_x": 0, "cell_y": 0, "region": regionPatch}) 

registry.insertDimensionData("visit_detector_region", 

{"instrument": "DummyCam", "visit": 0, "detector": 2, 

"region": regionVisitDetector}) 

 

def getRegion(dataId): 

return registry.expandDataId(dataId).region 

 

# Get region for a tract 

self.assertEqual(regionTract, getRegion({"skymap": "DummySkyMap", "tract": 0})) 

# Attempt to get region for a non-existent tract 

with self.assertRaises(LookupError): 

getRegion({"skymap": "DummySkyMap", "tract": 1}) 

# Get region for a (tract, patch) combination 

self.assertEqual(regionPatch, getRegion({"skymap": "DummySkyMap", "tract": 0, "patch": 0})) 

# Get region for a non-existent (tract, patch) combination 

with self.assertRaises(LookupError): 

getRegion({"skymap": "DummySkyMap", "tract": 0, "patch": 1}) 

# Get region for a visit 

self.assertEqual(regionVisit, getRegion({"instrument": "DummyCam", "visit": 0})) 

# Attempt to get region for a non-existent visit 

with self.assertRaises(LookupError): 

getRegion({"instrument": "DummyCam", "visit": 10}) 

# Get region for a (visit, detector) combination 

self.assertEqual(regionVisitDetector, 

getRegion({"instrument": "DummyCam", "visit": 0, "detector": 2})) 

# Attempt to get region for a non-existent (visit, detector) 

# combination. This returns None rather than raising because we don't 

# want to require the region record to be present. 

self.assertIsNone(getRegion({"instrument": "DummyCam", "visit": 0, "detector": 3})) 

# getRegion for a dataId containing no spatial dimensions should 

# return None 

self.assertIsNone(getRegion({"instrument": "DummyCam"})) 

# getRegion for a mix of spatial dimensions should return 

# NotImplemented, at least until we get it implemented. 

self.assertIs(getRegion({"instrument": "DummyCam", "visit": 0, "detector": 2, 

"skymap": "DummySkyMap", "tract": 0}), 

NotImplemented) 

# Check if we can get the region for a skypix 

self.assertIsInstance(getRegion({"htm9": 1000}), ConvexPolygon) 

# patch_htm7_overlap should not be empty 

self.assertNotEqual(len(list(registry.queryDimensions(["patch", "htm7"]))), 0) 

 

 

290 ↛ 291line 290 didn't jump to line 291, because the condition on line 290 was never trueif __name__ == "__main__": 

unittest.main()