test_swift.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. # test_swift.py -- Unittests for the Swift backend.
  2. # Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
  3. #
  4. # Author: Fabien Boucher <fabien.boucher@enovance.com>
  5. #
  6. # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU
  7. # General Public License as public by the Free Software Foundation; version 2.0
  8. # or (at your option) any later version. You can redistribute it and/or
  9. # modify it under the terms of either of these two licenses.
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. # You should have received a copy of the licenses; if not, see
  18. # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License
  19. # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache
  20. # License, Version 2.0.
  21. #
  22. """Tests for dulwich.contrib.swift."""
  23. import posixpath
  24. from time import time
  25. from io import BytesIO
  26. try:
  27. from StringIO import StringIO
  28. except ImportError:
  29. from io import StringIO
  30. import sys
  31. from unittest import skipIf
  32. from dulwich.tests import (
  33. TestCase,
  34. )
  35. from dulwich.tests.test_object_store import (
  36. ObjectStoreTests,
  37. )
  38. from dulwich.tests.utils import (
  39. build_pack,
  40. )
  41. from dulwich.objects import (
  42. Blob,
  43. Commit,
  44. Tree,
  45. Tag,
  46. parse_timezone,
  47. )
  48. from dulwich.pack import (
  49. REF_DELTA,
  50. )
  51. try:
  52. from simplejson import dumps as json_dumps
  53. except ImportError:
  54. from json import dumps as json_dumps
  55. missing_libs = []
  56. try:
  57. import gevent # noqa:F401
  58. except ImportError:
  59. missing_libs.append("gevent")
  60. try:
  61. import geventhttpclient # noqa:F401
  62. except ImportError:
  63. missing_libs.append("geventhttpclient")
  64. try:
  65. from mock import patch
  66. except ImportError:
  67. missing_libs.append("mock")
  68. skipmsg = "Required libraries are not installed (%r)" % missing_libs
  69. if not missing_libs:
  70. from dulwich.contrib import swift
  71. config_file = """[swift]
  72. auth_url = http://127.0.0.1:8080/auth/%(version_str)s
  73. auth_ver = %(version_int)s
  74. username = test;tester
  75. password = testing
  76. region_name = %(region_name)s
  77. endpoint_type = %(endpoint_type)s
  78. concurrency = %(concurrency)s
  79. chunk_length = %(chunk_length)s
  80. cache_length = %(cache_length)s
  81. http_pool_length = %(http_pool_length)s
  82. http_timeout = %(http_timeout)s
  83. """
  84. def_config_file = {'version_str': 'v1.0',
  85. 'version_int': 1,
  86. 'concurrency': 1,
  87. 'chunk_length': 12228,
  88. 'cache_length': 1,
  89. 'region_name': 'test',
  90. 'endpoint_type': 'internalURL',
  91. 'http_pool_length': 1,
  92. 'http_timeout': 1}
  93. def create_swift_connector(store={}):
  94. return lambda root, conf: FakeSwiftConnector(root,
  95. conf=conf,
  96. store=store)
  97. class Response(object):
  98. def __init__(self, headers={}, status=200, content=None):
  99. self.headers = headers
  100. self.status_code = status
  101. self.content = content
  102. def __getitem__(self, key):
  103. return self.headers[key]
  104. def items(self):
  105. return self.headers.items()
  106. def read(self):
  107. return self.content
  108. def fake_auth_request_v1(*args, **kwargs):
  109. ret = Response({'X-Storage-Url':
  110. 'http://127.0.0.1:8080/v1.0/AUTH_fakeuser',
  111. 'X-Auth-Token': '12' * 10},
  112. 200)
  113. return ret
  114. def fake_auth_request_v1_error(*args, **kwargs):
  115. ret = Response({},
  116. 401)
  117. return ret
  118. def fake_auth_request_v2(*args, **kwargs):
  119. s_url = 'http://127.0.0.1:8080/v1.0/AUTH_fakeuser'
  120. resp = {'access': {'token': {'id': '12' * 10},
  121. 'serviceCatalog':
  122. [
  123. {'type': 'object-store',
  124. 'endpoints': [{'region': 'test',
  125. 'internalURL': s_url,
  126. },
  127. ]
  128. },
  129. ]
  130. }
  131. }
  132. ret = Response(status=200, content=json_dumps(resp))
  133. return ret
  134. def create_commit(data, marker=b'Default', blob=None):
  135. if not blob:
  136. blob = Blob.from_string(b'The blob content ' + marker)
  137. tree = Tree()
  138. tree.add(b"thefile_" + marker, 0o100644, blob.id)
  139. cmt = Commit()
  140. if data:
  141. assert isinstance(data[-1], Commit)
  142. cmt.parents = [data[-1].id]
  143. cmt.tree = tree.id
  144. author = b"John Doe " + marker + b" <john@doe.net>"
  145. cmt.author = cmt.committer = author
  146. tz = parse_timezone(b'-0200')[0]
  147. cmt.commit_time = cmt.author_time = int(time())
  148. cmt.commit_timezone = cmt.author_timezone = tz
  149. cmt.encoding = b"UTF-8"
  150. cmt.message = b"The commit message " + marker
  151. tag = Tag()
  152. tag.tagger = b"john@doe.net"
  153. tag.message = b"Annotated tag"
  154. tag.tag_timezone = parse_timezone(b'-0200')[0]
  155. tag.tag_time = cmt.author_time
  156. tag.object = (Commit, cmt.id)
  157. tag.name = b"v_" + marker + b"_0.1"
  158. return blob, tree, tag, cmt
  159. def create_commits(length=1, marker=b'Default'):
  160. data = []
  161. for i in range(0, length):
  162. _marker = ("%s_%s" % (marker, i)).encode()
  163. blob, tree, tag, cmt = create_commit(data, _marker)
  164. data.extend([blob, tree, tag, cmt])
  165. return data
  166. @skipIf(missing_libs, skipmsg)
  167. class FakeSwiftConnector(object):
  168. def __init__(self, root, conf, store=None):
  169. if store:
  170. self.store = store
  171. else:
  172. self.store = {}
  173. self.conf = conf
  174. self.root = root
  175. self.concurrency = 1
  176. self.chunk_length = 12228
  177. self.cache_length = 1
  178. def put_object(self, name, content):
  179. name = posixpath.join(self.root, name)
  180. if hasattr(content, 'seek'):
  181. content.seek(0)
  182. content = content.read()
  183. self.store[name] = content
  184. def get_object(self, name, range=None):
  185. name = posixpath.join(self.root, name)
  186. if not range:
  187. try:
  188. return BytesIO(self.store[name])
  189. except KeyError:
  190. return None
  191. else:
  192. l, r = range.split('-')
  193. try:
  194. if not l:
  195. r = -int(r)
  196. return self.store[name][r:]
  197. else:
  198. return self.store[name][int(l):int(r)]
  199. except KeyError:
  200. return None
  201. def get_container_objects(self):
  202. return [{'name': k.replace(self.root + '/', '')}
  203. for k in self.store]
  204. def create_root(self):
  205. if self.root in self.store.keys():
  206. pass
  207. else:
  208. self.store[self.root] = ''
  209. def get_object_stat(self, name):
  210. name = posixpath.join(self.root, name)
  211. if name not in self.store:
  212. return None
  213. return {'content-length': len(self.store[name])}
  214. @skipIf(missing_libs, skipmsg)
  215. class TestSwiftRepo(TestCase):
  216. def setUp(self):
  217. super(TestSwiftRepo, self).setUp()
  218. self.conf = swift.load_conf(file=StringIO(config_file %
  219. def_config_file))
  220. def test_init(self):
  221. store = {'fakerepo/objects/pack': ''}
  222. with patch('dulwich.contrib.swift.SwiftConnector',
  223. new_callable=create_swift_connector,
  224. store=store):
  225. swift.SwiftRepo('fakerepo', conf=self.conf)
  226. def test_init_no_data(self):
  227. with patch('dulwich.contrib.swift.SwiftConnector',
  228. new_callable=create_swift_connector):
  229. self.assertRaises(Exception, swift.SwiftRepo,
  230. 'fakerepo', self.conf)
  231. def test_init_bad_data(self):
  232. store = {'fakerepo/.git/objects/pack': ''}
  233. with patch('dulwich.contrib.swift.SwiftConnector',
  234. new_callable=create_swift_connector,
  235. store=store):
  236. self.assertRaises(Exception, swift.SwiftRepo,
  237. 'fakerepo', self.conf)
  238. def test_put_named_file(self):
  239. store = {'fakerepo/objects/pack': ''}
  240. with patch('dulwich.contrib.swift.SwiftConnector',
  241. new_callable=create_swift_connector,
  242. store=store):
  243. repo = swift.SwiftRepo('fakerepo', conf=self.conf)
  244. desc = b'Fake repo'
  245. repo._put_named_file('description', desc)
  246. self.assertEqual(repo.scon.store['fakerepo/description'],
  247. desc)
  248. def test_init_bare(self):
  249. fsc = FakeSwiftConnector('fakeroot', conf=self.conf)
  250. with patch('dulwich.contrib.swift.SwiftConnector',
  251. new_callable=create_swift_connector,
  252. store=fsc.store):
  253. swift.SwiftRepo.init_bare(fsc, conf=self.conf)
  254. self.assertIn('fakeroot/objects/pack', fsc.store)
  255. self.assertIn('fakeroot/info/refs', fsc.store)
  256. self.assertIn('fakeroot/description', fsc.store)
  257. @skipIf(missing_libs, skipmsg)
  258. class TestSwiftInfoRefsContainer(TestCase):
  259. def setUp(self):
  260. super(TestSwiftInfoRefsContainer, self).setUp()
  261. content = (
  262. b"22effb216e3a82f97da599b8885a6cadb488b4c5\trefs/heads/master\n"
  263. b"cca703b0e1399008b53a1a236d6b4584737649e4\trefs/heads/dev")
  264. self.store = {'fakerepo/info/refs': content}
  265. self.conf = swift.load_conf(file=StringIO(config_file %
  266. def_config_file))
  267. self.fsc = FakeSwiftConnector('fakerepo', conf=self.conf)
  268. self.object_store = {}
  269. def test_init(self):
  270. """info/refs does not exists"""
  271. irc = swift.SwiftInfoRefsContainer(self.fsc, self.object_store)
  272. self.assertEqual(len(irc._refs), 0)
  273. self.fsc.store = self.store
  274. irc = swift.SwiftInfoRefsContainer(self.fsc, self.object_store)
  275. self.assertIn(b'refs/heads/dev', irc.allkeys())
  276. self.assertIn(b'refs/heads/master', irc.allkeys())
  277. def test_set_if_equals(self):
  278. self.fsc.store = self.store
  279. irc = swift.SwiftInfoRefsContainer(self.fsc, self.object_store)
  280. irc.set_if_equals(b'refs/heads/dev',
  281. b"cca703b0e1399008b53a1a236d6b4584737649e4", b'1'*40)
  282. self.assertEqual(irc[b'refs/heads/dev'], b'1'*40)
  283. def test_remove_if_equals(self):
  284. self.fsc.store = self.store
  285. irc = swift.SwiftInfoRefsContainer(self.fsc, self.object_store)
  286. irc.remove_if_equals(b'refs/heads/dev',
  287. b"cca703b0e1399008b53a1a236d6b4584737649e4")
  288. self.assertNotIn(b'refs/heads/dev', irc.allkeys())
  289. @skipIf(missing_libs, skipmsg)
  290. class TestSwiftConnector(TestCase):
  291. def setUp(self):
  292. super(TestSwiftConnector, self).setUp()
  293. self.conf = swift.load_conf(file=StringIO(config_file %
  294. def_config_file))
  295. with patch('geventhttpclient.HTTPClient.request',
  296. fake_auth_request_v1):
  297. self.conn = swift.SwiftConnector('fakerepo', conf=self.conf)
  298. def test_init_connector(self):
  299. self.assertEqual(self.conn.auth_ver, '1')
  300. self.assertEqual(self.conn.auth_url,
  301. 'http://127.0.0.1:8080/auth/v1.0')
  302. self.assertEqual(self.conn.user, 'test:tester')
  303. self.assertEqual(self.conn.password, 'testing')
  304. self.assertEqual(self.conn.root, 'fakerepo')
  305. self.assertEqual(self.conn.storage_url,
  306. 'http://127.0.0.1:8080/v1.0/AUTH_fakeuser')
  307. self.assertEqual(self.conn.token, '12' * 10)
  308. self.assertEqual(self.conn.http_timeout, 1)
  309. self.assertEqual(self.conn.http_pool_length, 1)
  310. self.assertEqual(self.conn.concurrency, 1)
  311. self.conf.set('swift', 'auth_ver', '2')
  312. self.conf.set('swift', 'auth_url', 'http://127.0.0.1:8080/auth/v2.0')
  313. with patch('geventhttpclient.HTTPClient.request',
  314. fake_auth_request_v2):
  315. conn = swift.SwiftConnector('fakerepo', conf=self.conf)
  316. self.assertEqual(conn.user, 'tester')
  317. self.assertEqual(conn.tenant, 'test')
  318. self.conf.set('swift', 'auth_ver', '1')
  319. self.conf.set('swift', 'auth_url', 'http://127.0.0.1:8080/auth/v1.0')
  320. with patch('geventhttpclient.HTTPClient.request',
  321. fake_auth_request_v1_error):
  322. self.assertRaises(swift.SwiftException,
  323. lambda: swift.SwiftConnector('fakerepo',
  324. conf=self.conf))
  325. def test_root_exists(self):
  326. with patch('geventhttpclient.HTTPClient.request',
  327. lambda *args: Response()):
  328. self.assertEqual(self.conn.test_root_exists(), True)
  329. def test_root_not_exists(self):
  330. with patch('geventhttpclient.HTTPClient.request',
  331. lambda *args: Response(status=404)):
  332. self.assertEqual(self.conn.test_root_exists(), None)
  333. def test_create_root(self):
  334. with patch('dulwich.contrib.swift.SwiftConnector.test_root_exists',
  335. lambda *args: None):
  336. with patch('geventhttpclient.HTTPClient.request',
  337. lambda *args: Response()):
  338. self.assertEqual(self.conn.create_root(), None)
  339. def test_create_root_fails(self):
  340. with patch('dulwich.contrib.swift.SwiftConnector.test_root_exists',
  341. lambda *args: None):
  342. with patch('geventhttpclient.HTTPClient.request',
  343. lambda *args: Response(status=404)):
  344. self.assertRaises(swift.SwiftException,
  345. lambda: self.conn.create_root())
  346. def test_get_container_objects(self):
  347. with patch('geventhttpclient.HTTPClient.request',
  348. lambda *args: Response(content=json_dumps(
  349. (({'name': 'a'}, {'name': 'b'}))))):
  350. self.assertEqual(len(self.conn.get_container_objects()), 2)
  351. def test_get_container_objects_fails(self):
  352. with patch('geventhttpclient.HTTPClient.request',
  353. lambda *args: Response(status=404)):
  354. self.assertEqual(self.conn.get_container_objects(), None)
  355. def test_get_object_stat(self):
  356. with patch('geventhttpclient.HTTPClient.request',
  357. lambda *args: Response(headers={'content-length': '10'})):
  358. self.assertEqual(self.conn.get_object_stat('a')['content-length'],
  359. '10')
  360. def test_get_object_stat_fails(self):
  361. with patch('geventhttpclient.HTTPClient.request',
  362. lambda *args: Response(status=404)):
  363. self.assertEqual(self.conn.get_object_stat('a'), None)
  364. def test_put_object(self):
  365. with patch('geventhttpclient.HTTPClient.request',
  366. lambda *args, **kwargs: Response()):
  367. self.assertEqual(self.conn.put_object('a', BytesIO(b'content')),
  368. None)
  369. def test_put_object_fails(self):
  370. with patch('geventhttpclient.HTTPClient.request',
  371. lambda *args, **kwargs: Response(status=400)):
  372. self.assertRaises(swift.SwiftException,
  373. lambda: self.conn.put_object(
  374. 'a', BytesIO(b'content')))
  375. def test_get_object(self):
  376. with patch('geventhttpclient.HTTPClient.request',
  377. lambda *args, **kwargs: Response(content=b'content')):
  378. self.assertEqual(self.conn.get_object('a').read(), b'content')
  379. with patch('geventhttpclient.HTTPClient.request',
  380. lambda *args, **kwargs: Response(content=b'content')):
  381. self.assertEqual(
  382. self.conn.get_object('a', range='0-6'),
  383. b'content')
  384. def test_get_object_fails(self):
  385. with patch('geventhttpclient.HTTPClient.request',
  386. lambda *args, **kwargs: Response(status=404)):
  387. self.assertEqual(self.conn.get_object('a'), None)
  388. def test_del_object(self):
  389. with patch('geventhttpclient.HTTPClient.request',
  390. lambda *args: Response()):
  391. self.assertEqual(self.conn.del_object('a'), None)
  392. def test_del_root(self):
  393. with patch('dulwich.contrib.swift.SwiftConnector.del_object',
  394. lambda *args: None):
  395. with patch('dulwich.contrib.swift.SwiftConnector.'
  396. 'get_container_objects',
  397. lambda *args: ({'name': 'a'}, {'name': 'b'})):
  398. with patch('geventhttpclient.HTTPClient.request',
  399. lambda *args: Response()):
  400. self.assertEqual(self.conn.del_root(), None)
  401. @skipIf(missing_libs, skipmsg)
  402. class SwiftObjectStoreTests(ObjectStoreTests, TestCase):
  403. def setUp(self):
  404. TestCase.setUp(self)
  405. conf = swift.load_conf(file=StringIO(config_file %
  406. def_config_file))
  407. fsc = FakeSwiftConnector('fakerepo', conf=conf)
  408. self.store = swift.SwiftObjectStore(fsc)