Coverage for tests/test_remote_butler.py: 53%

71 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2024-03-26 02:48 -0700

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 software is dual licensed under the GNU General Public License and also 

10# under a 3-clause BSD license. Recipients may choose which of these licenses 

11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt, 

12# respectively. If you choose the GPL option then the following text applies 

13# (but note that there is still no warranty even if you opt for BSD instead): 

14# 

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

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

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

18# (at your option) any later version. 

19# 

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

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

22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

23# GNU General Public License for more details. 

24# 

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

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

27 

28import os 

29import unittest 

30from unittest.mock import patch 

31 

32from lsst.daf.butler import Butler, Registry 

33from lsst.daf.butler._exceptions import UnknownButlerUserError 

34from lsst.daf.butler.datastores.file_datastore.retrieve_artifacts import ( 

35 determine_destination_for_retrieved_artifact, 

36) 

37from lsst.daf.butler.registry.tests import RegistryTests 

38from lsst.resources import ResourcePath 

39from pydantic import ValidationError 

40 

41try: 

42 import httpx 

43 from lsst.daf.butler.remote_butler import ButlerServerError, RemoteButler, RemoteButlerFactory 

44except ImportError: 

45 # httpx is not available in rubin-env yet, so skip these tests if it's not 

46 # available 

47 RemoteButler = None 

48 

49try: 

50 from lsst.daf.butler.tests.server import create_test_server 

51except ImportError: 

52 create_test_server = None 

53 

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

55 

56 

57@unittest.skipIf(RemoteButler is None, "httpx is not installed") 

58class RemoteButlerConfigTests(unittest.TestCase): 

59 """Test construction of RemoteButler via Butler()""" 

60 

61 def test_bad_config(self): 

62 with self.assertRaises(ValidationError): 

63 Butler({"cls": "lsst.daf.butler.remote_butler.RemoteButler", "remote_butler": {"url": "!"}}) 

64 

65 

66@unittest.skipIf(RemoteButler is None, "httpx is not installed") 

67class RemoteButlerErrorHandlingTests(unittest.TestCase): 

68 """Test RemoteButler error handling.""" 

69 

70 def setUp(self): 

71 self.butler = RemoteButlerFactory.create_factory_for_url( 

72 "https://doesntmatter" 

73 ).create_butler_for_access_token("dontcare") 

74 self.mock = self.enterContext(patch.object(self.butler._client, "request")) 

75 

76 def _mock_error_response(self, content: str) -> None: 

77 self.mock.return_value = httpx.Response( 

78 status_code=422, content=content, request=httpx.Request("GET", "/") 

79 ) 

80 

81 def test_internal_server_error(self): 

82 self.mock.side_effect = httpx.HTTPError("unhandled error") 

83 with self.assertRaises(ButlerServerError): 

84 self.butler.get_dataset_type("int") 

85 

86 def test_unknown_error_type(self): 

87 self.mock.return_value = httpx.Response( 

88 status_code=422, json={"error_type": "not a known error type", "detail": "an error happened"} 

89 ) 

90 with self.assertRaises(UnknownButlerUserError): 

91 self.butler.get_dataset_type("int") 

92 

93 def test_non_json_error(self): 

94 # Server returns a non-JSON body with an error 

95 self._mock_error_response("notvalidjson") 

96 with self.assertRaises(ButlerServerError): 

97 self.butler.get_dataset_type("int") 

98 

99 def test_malformed_error(self): 

100 # Server returns JSON, but not in the expected format. 

101 self._mock_error_response("{}") 

102 with self.assertRaises(ButlerServerError): 

103 self.butler.get_dataset_type("int") 

104 

105 

106class RemoteButlerMiscTests(unittest.TestCase): 

107 """Test miscellaneous RemoteButler functionality.""" 

108 

109 def test_retrieve_artifacts_security(self): 

110 # Make sure that the function used to determine output file paths for 

111 # retrieveArtifacts throws if a malicious server tries to escape its 

112 # destination directory. 

113 with self.assertRaisesRegex(ValueError, "^File path attempts to escape destination directory"): 

114 determine_destination_for_retrieved_artifact( 

115 ResourcePath("output_directory/"), 

116 ResourcePath("../something.txt", forceAbsolute=False), 

117 preserve_path=True, 

118 ) 

119 

120 # Make sure all paths are forced to relative paths, even if the server 

121 # sends an absolute path. 

122 self.assertEqual( 

123 determine_destination_for_retrieved_artifact( 

124 ResourcePath("/tmp/output_directory/"), 

125 ResourcePath("file:///not/relative.txt"), 

126 preserve_path=True, 

127 ), 

128 ResourcePath("/tmp/output_directory/not/relative.txt"), 

129 ) 

130 

131 

132@unittest.skipIf(create_test_server is None, "Server dependencies not installed.") 

133class RemoteButlerRegistryTests(RegistryTests, unittest.TestCase): 

134 """Tests for RemoteButler's `Registry` shim.""" 

135 

136 def setUp(self): 

137 self.server_instance = self.enterContext(create_test_server(TESTDIR)) 

138 

139 @classmethod 

140 def getDataDir(cls) -> str: 

141 return os.path.join(TESTDIR, "data", "registry") 

142 

143 def makeRegistry(self, share_repo_with: Registry | None = None) -> Registry: 

144 if share_repo_with is None: 

145 return self.server_instance.hybrid_butler.registry 

146 else: 

147 return self.server_instance.hybrid_butler._clone().registry 

148 

149 def testBasicTransaction(self): 

150 # RemoteButler will never support transactions. 

151 pass 

152 

153 def testNestedTransaction(self): 

154 # RemoteButler will never support transactions. 

155 pass 

156 

157 def testOpaque(self): 

158 # This tests an internal implementation detail that isn't exposed to 

159 # the client side. 

160 pass 

161 

162 def testAttributeManager(self): 

163 # Tests a non-public API that isn't relevant on the client side. 

164 pass 

165 

166 

167if __name__ == "__main__": 

168 unittest.main()