test_swift.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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. # This program is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU General Public License
  8. # as published by the Free Software Foundation; version 2
  9. # of the License or (at your option) any later version of
  10. # the License.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with this program; if not, write to the Free Software
  19. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  20. # MA 02110-1301, USA.
  21. """Tests for dulwich.contrib.swift."""
  22. import posixpath
  23. from time import time
  24. from io import BytesIO
  25. try:
  26. from unittest import skipIf
  27. except ImportError:
  28. from unittest2 import skipIf
  29. from dulwich.tests import (
  30. TestCase,
  31. )
  32. from dulwich.tests.test_object_store import (
  33. ObjectStoreTests,
  34. )
  35. from dulwich.tests.utils import (
  36. build_pack,
  37. )
  38. from dulwich.objects import (
  39. Blob,
  40. Commit,
  41. Tree,
  42. Tag,
  43. parse_timezone,
  44. )
  45. from dulwich.pack import (
  46. REF_DELTA,
  47. write_pack_index_v2,
  48. PackData,
  49. load_pack_index_file,
  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
  58. except ImportError:
  59. missing_libs.append("gevent")
  60. try:
  61. import geventhttpclient
  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
  106. def iteritems(self):
  107. for k, v in self.headers.iteritems():
  108. yield k, v
  109. def read(self):
  110. return self.content
  111. def fake_auth_request_v1(*args, **kwargs):
  112. ret = Response({'X-Storage-Url':
  113. 'http://127.0.0.1:8080/v1.0/AUTH_fakeuser',
  114. 'X-Auth-Token': '12' * 10},
  115. 200)
  116. return ret
  117. def fake_auth_request_v1_error(*args, **kwargs):
  118. ret = Response({},
  119. 401)
  120. return ret
  121. def fake_auth_request_v2(*args, **kwargs):
  122. s_url = 'http://127.0.0.1:8080/v1.0/AUTH_fakeuser'
  123. resp = {'access': {'token': {'id': '12' * 10},
  124. 'serviceCatalog':
  125. [
  126. {'type': 'object-store',
  127. 'endpoints': [{'region': 'test',
  128. 'internalURL': s_url,
  129. },
  130. ]
  131. },
  132. ]
  133. }
  134. }
  135. ret = Response(status=200, content=json_dumps(resp))
  136. return ret
  137. def create_commit(data, marker='Default', blob=None):
  138. if not blob:
  139. blob = Blob.from_string('The blob content %s' % marker)
  140. tree = Tree()
  141. tree.add("thefile_%s" % marker, 0o100644, blob.id)
  142. cmt = Commit()
  143. if data:
  144. assert isinstance(data[-1], Commit)
  145. cmt.parents = [data[-1].id]
  146. cmt.tree = tree.id
  147. author = "John Doe %s <john@doe.net>" % marker
  148. cmt.author = cmt.committer = author
  149. tz = parse_timezone('-0200')[0]
  150. cmt.commit_time = cmt.author_time = int(time())
  151. cmt.commit_timezone = cmt.author_timezone = tz
  152. cmt.encoding = "UTF-8"
  153. cmt.message = "The commit message %s" % marker
  154. tag = Tag()
  155. tag.tagger = "john@doe.net"
  156. tag.message = "Annotated tag"
  157. tag.tag_timezone = parse_timezone('-0200')[0]
  158. tag.tag_time = cmt.author_time
  159. tag.object = (Commit, cmt.id)
  160. tag.name = "v_%s_0.1" % marker
  161. return blob, tree, tag, cmt
  162. def create_commits(length=1, marker='Default'):
  163. data = []
  164. for i in range(0, length):
  165. _marker = "%s_%s" % (marker, i)
  166. blob, tree, tag, cmt = create_commit(data, _marker)
  167. data.extend([blob, tree, tag, cmt])
  168. return data
  169. @skipIf(missing_libs, skipmsg)
  170. class FakeSwiftConnector(object):
  171. def __init__(self, root, conf, store=None):
  172. if store:
  173. self.store = store
  174. else:
  175. self.store = {}
  176. self.conf = conf
  177. self.root = root
  178. self.concurrency = 1
  179. self.chunk_length = 12228
  180. self.cache_length = 1
  181. def put_object(self, name, content):
  182. name = posixpath.join(self.root, name)
  183. if hasattr(content, 'seek'):
  184. content.seek(0)
  185. content = content.read()
  186. self.store[name] = content
  187. def get_object(self, name, range=None):
  188. name = posixpath.join(self.root, name)
  189. if not range:
  190. try:
  191. return BytesIO(self.store[name])
  192. except KeyError:
  193. return None
  194. else:
  195. l, r = range.split('-')
  196. try:
  197. if not l:
  198. r = -int(r)
  199. return self.store[name][r:]
  200. else:
  201. return self.store[name][int(l):int(r)]
  202. except KeyError:
  203. return None
  204. def get_container_objects(self):
  205. return [{'name': k.replace(self.root + '/', '')}
  206. for k in self.store]
  207. def create_root(self):
  208. if self.root in self.store.keys():
  209. pass
  210. else:
  211. self.store[self.root] = ''
  212. def get_object_stat(self, name):
  213. name = posixpath.join(self.root, name)
  214. if not name in self.store:
  215. return None
  216. return {'content-length': len(self.store[name])}
  217. @skipIf(missing_libs, skipmsg)
  218. class TestSwiftObjectStore(TestCase):
  219. def setUp(self):
  220. super(TestSwiftObjectStore, self).setUp()
  221. self.conf = swift.load_conf(file=BytesIO(config_file %
  222. def_config_file))
  223. self.fsc = FakeSwiftConnector('fakerepo', conf=self.conf)
  224. def _put_pack(self, sos, commit_amount=1, marker='Default'):
  225. odata = create_commits(length=commit_amount, marker=marker)
  226. data = [(d.type_num, d.as_raw_string()) for d in odata]
  227. f = BytesIO()
  228. build_pack(f, data, store=sos)
  229. sos.add_thin_pack(f.read, None)
  230. return odata
  231. def test_load_packs(self):
  232. store = {'fakerepo/objects/pack/pack-'+'1'*40+'.idx': '',
  233. 'fakerepo/objects/pack/pack-'+'1'*40+'.pack': '',
  234. 'fakerepo/objects/pack/pack-'+'1'*40+'.info': '',
  235. 'fakerepo/objects/pack/pack-'+'2'*40+'.idx': '',
  236. 'fakerepo/objects/pack/pack-'+'2'*40+'.pack': '',
  237. 'fakerepo/objects/pack/pack-'+'2'*40+'.info': ''}
  238. fsc = FakeSwiftConnector('fakerepo', conf=self.conf, store=store)
  239. sos = swift.SwiftObjectStore(fsc)
  240. packs = sos._load_packs()
  241. self.assertEqual(len(packs), 2)
  242. for pack in packs:
  243. self.assertTrue(isinstance(pack, swift.SwiftPack))
  244. def test_add_thin_pack(self):
  245. sos = swift.SwiftObjectStore(self.fsc)
  246. self._put_pack(sos, 1, 'Default')
  247. self.assertEqual(len(self.fsc.store), 3)
  248. def test_find_missing_objects(self):
  249. commit_amount = 3
  250. sos = swift.SwiftObjectStore(self.fsc)
  251. odata = self._put_pack(sos, commit_amount, 'Default')
  252. head = odata[-1].id
  253. i = sos.iter_shas(sos.find_missing_objects([],
  254. [head, ],
  255. progress=None,
  256. get_tagged=None))
  257. self.assertEqual(len(i), commit_amount * 3)
  258. shas = [d.id for d in odata]
  259. for sha, path in i:
  260. self.assertIn(sha.id, shas)
  261. def test_find_missing_objects_with_tag(self):
  262. commit_amount = 3
  263. sos = swift.SwiftObjectStore(self.fsc)
  264. odata = self._put_pack(sos, commit_amount, 'Default')
  265. head = odata[-1].id
  266. peeled_sha = dict([(sha.object[1], sha.id)
  267. for sha in odata if isinstance(sha, Tag)])
  268. get_tagged = lambda: peeled_sha
  269. i = sos.iter_shas(sos.find_missing_objects([],
  270. [head, ],
  271. progress=None,
  272. get_tagged=get_tagged))
  273. self.assertEqual(len(i), commit_amount * 4)
  274. shas = [d.id for d in odata]
  275. for sha, path in i:
  276. self.assertIn(sha.id, shas)
  277. def test_find_missing_objects_with_common(self):
  278. commit_amount = 3
  279. sos = swift.SwiftObjectStore(self.fsc)
  280. odata = self._put_pack(sos, commit_amount, 'Default')
  281. head = odata[-1].id
  282. have = odata[7].id
  283. i = sos.iter_shas(sos.find_missing_objects([have, ],
  284. [head, ],
  285. progress=None,
  286. get_tagged=None))
  287. self.assertEqual(len(i), 3)
  288. def test_find_missing_objects_multiple_packs(self):
  289. sos = swift.SwiftObjectStore(self.fsc)
  290. commit_amount_a = 3
  291. odataa = self._put_pack(sos, commit_amount_a, 'Default1')
  292. heada = odataa[-1].id
  293. commit_amount_b = 2
  294. odatab = self._put_pack(sos, commit_amount_b, 'Default2')
  295. headb = odatab[-1].id
  296. i = sos.iter_shas(sos.find_missing_objects([],
  297. [heada, headb],
  298. progress=None,
  299. get_tagged=None))
  300. self.assertEqual(len(self.fsc.store), 6)
  301. self.assertEqual(len(i),
  302. commit_amount_a * 3 +
  303. commit_amount_b * 3)
  304. shas = [d.id for d in odataa]
  305. shas.extend([d.id for d in odatab])
  306. for sha, path in i:
  307. self.assertIn(sha.id, shas)
  308. def test_add_thin_pack_ext_ref(self):
  309. sos = swift.SwiftObjectStore(self.fsc)
  310. odata = self._put_pack(sos, 1, 'Default1')
  311. ref_blob_content = odata[0].as_raw_string()
  312. ref_blob_id = odata[0].id
  313. new_blob = Blob.from_string(ref_blob_content.replace('blob',
  314. 'yummy blob'))
  315. blob, tree, tag, cmt = \
  316. create_commit([], marker='Default2', blob=new_blob)
  317. data = [(REF_DELTA, (ref_blob_id, blob.as_raw_string())),
  318. (tree.type_num, tree.as_raw_string()),
  319. (cmt.type_num, cmt.as_raw_string()),
  320. (tag.type_num, tag.as_raw_string())]
  321. f = BytesIO()
  322. build_pack(f, data, store=sos)
  323. sos.add_thin_pack(f.read, None)
  324. self.assertEqual(len(self.fsc.store), 6)
  325. @skipIf(missing_libs, skipmsg)
  326. class TestSwiftRepo(TestCase):
  327. def setUp(self):
  328. super(TestSwiftRepo, self).setUp()
  329. self.conf = swift.load_conf(file=BytesIO(config_file %
  330. def_config_file))
  331. def test_init(self):
  332. store = {'fakerepo/objects/pack': ''}
  333. with patch('dulwich.contrib.swift.SwiftConnector',
  334. new_callable=create_swift_connector,
  335. store=store):
  336. swift.SwiftRepo('fakerepo', conf=self.conf)
  337. def test_init_no_data(self):
  338. with patch('dulwich.contrib.swift.SwiftConnector',
  339. new_callable=create_swift_connector):
  340. self.assertRaises(Exception, swift.SwiftRepo,
  341. 'fakerepo', self.conf)
  342. def test_init_bad_data(self):
  343. store = {'fakerepo/.git/objects/pack': ''}
  344. with patch('dulwich.contrib.swift.SwiftConnector',
  345. new_callable=create_swift_connector,
  346. store=store):
  347. self.assertRaises(Exception, swift.SwiftRepo,
  348. 'fakerepo', self.conf)
  349. def test_put_named_file(self):
  350. store = {'fakerepo/objects/pack': ''}
  351. with patch('dulwich.contrib.swift.SwiftConnector',
  352. new_callable=create_swift_connector,
  353. store=store):
  354. repo = swift.SwiftRepo('fakerepo', conf=self.conf)
  355. desc = 'Fake repo'
  356. repo._put_named_file('description', desc)
  357. self.assertEqual(repo.scon.store['fakerepo/description'],
  358. desc)
  359. def test_init_bare(self):
  360. fsc = FakeSwiftConnector('fakeroot', conf=self.conf)
  361. with patch('dulwich.contrib.swift.SwiftConnector',
  362. new_callable=create_swift_connector,
  363. store=fsc.store):
  364. swift.SwiftRepo.init_bare(fsc, conf=self.conf)
  365. self.assertIn('fakeroot/objects/pack', fsc.store)
  366. self.assertIn('fakeroot/info/refs', fsc.store)
  367. self.assertIn('fakeroot/description', fsc.store)
  368. @skipIf(missing_libs, skipmsg)
  369. class TestPackInfoLoadDump(TestCase):
  370. def setUp(self):
  371. conf = swift.load_conf(file=BytesIO(config_file %
  372. def_config_file))
  373. sos = swift.SwiftObjectStore(
  374. FakeSwiftConnector('fakerepo', conf=conf))
  375. commit_amount = 10
  376. self.commits = create_commits(length=commit_amount, marker="m")
  377. data = [(d.type_num, d.as_raw_string()) for d in self.commits]
  378. f = BytesIO()
  379. fi = BytesIO()
  380. expected = build_pack(f, data, store=sos)
  381. entries = [(sha, ofs, checksum) for
  382. ofs, _, _, sha, checksum in expected]
  383. self.pack_data = PackData.from_file(file=f, size=None)
  384. write_pack_index_v2(
  385. fi, entries, self.pack_data.calculate_checksum())
  386. fi.seek(0)
  387. self.pack_index = load_pack_index_file('', fi)
  388. # def test_pack_info_perf(self):
  389. # dump_time = []
  390. # load_time = []
  391. # for i in range(0, 100):
  392. # start = time()
  393. # dumps = swift.pack_info_create(self.pack_data, self.pack_index)
  394. # dump_time.append(time() - start)
  395. # for i in range(0, 100):
  396. # start = time()
  397. # pack_infos = swift.load_pack_info('', file=BytesIO(dumps))
  398. # load_time.append(time() - start)
  399. # print sum(dump_time) / float(len(dump_time))
  400. # print sum(load_time) / float(len(load_time))
  401. def test_pack_info(self):
  402. dumps = swift.pack_info_create(self.pack_data, self.pack_index)
  403. pack_infos = swift.load_pack_info('', file=BytesIO(dumps))
  404. for obj in self.commits:
  405. self.assertIn(obj.id, pack_infos)
  406. @skipIf(missing_libs, skipmsg)
  407. class TestSwiftInfoRefsContainer(TestCase):
  408. def setUp(self):
  409. super(TestSwiftInfoRefsContainer, self).setUp()
  410. content = \
  411. "22effb216e3a82f97da599b8885a6cadb488b4c5\trefs/heads/master\n" + \
  412. "cca703b0e1399008b53a1a236d6b4584737649e4\trefs/heads/dev"
  413. self.store = {'fakerepo/info/refs': content}
  414. self.conf = swift.load_conf(file=BytesIO(config_file %
  415. def_config_file))
  416. self.fsc = FakeSwiftConnector('fakerepo', conf=self.conf)
  417. self.object_store = {}
  418. def test_init(self):
  419. """info/refs does not exists"""
  420. irc = swift.SwiftInfoRefsContainer(self.fsc, self.object_store)
  421. self.assertEqual(len(irc._refs), 0)
  422. self.fsc.store = self.store
  423. irc = swift.SwiftInfoRefsContainer(self.fsc, self.object_store)
  424. self.assertIn('refs/heads/dev', irc.allkeys())
  425. self.assertIn('refs/heads/master', irc.allkeys())
  426. def test_set_if_equals(self):
  427. self.fsc.store = self.store
  428. irc = swift.SwiftInfoRefsContainer(self.fsc, self.object_store)
  429. irc.set_if_equals('refs/heads/dev',
  430. "cca703b0e1399008b53a1a236d6b4584737649e4", '1'*40)
  431. self.assertEqual(irc['refs/heads/dev'], '1'*40)
  432. def test_remove_if_equals(self):
  433. self.fsc.store = self.store
  434. irc = swift.SwiftInfoRefsContainer(self.fsc, self.object_store)
  435. irc.remove_if_equals('refs/heads/dev',
  436. "cca703b0e1399008b53a1a236d6b4584737649e4")
  437. self.assertNotIn('refs/heads/dev', irc.allkeys())
  438. @skipIf(missing_libs, skipmsg)
  439. class TestSwiftConnector(TestCase):
  440. def setUp(self):
  441. super(TestSwiftConnector, self).setUp()
  442. self.conf = swift.load_conf(file=BytesIO(config_file %
  443. def_config_file))
  444. with patch('geventhttpclient.HTTPClient.request',
  445. fake_auth_request_v1):
  446. self.conn = swift.SwiftConnector('fakerepo', conf=self.conf)
  447. def test_init_connector(self):
  448. self.assertEqual(self.conn.auth_ver, '1')
  449. self.assertEqual(self.conn.auth_url,
  450. 'http://127.0.0.1:8080/auth/v1.0')
  451. self.assertEqual(self.conn.user, 'test:tester')
  452. self.assertEqual(self.conn.password, 'testing')
  453. self.assertEqual(self.conn.root, 'fakerepo')
  454. self.assertEqual(self.conn.storage_url,
  455. 'http://127.0.0.1:8080/v1.0/AUTH_fakeuser')
  456. self.assertEqual(self.conn.token, '12' * 10)
  457. self.assertEqual(self.conn.http_timeout, 1)
  458. self.assertEqual(self.conn.http_pool_length, 1)
  459. self.assertEqual(self.conn.concurrency, 1)
  460. self.conf.set('swift', 'auth_ver', '2')
  461. self.conf.set('swift', 'auth_url', 'http://127.0.0.1:8080/auth/v2.0')
  462. with patch('geventhttpclient.HTTPClient.request',
  463. fake_auth_request_v2):
  464. conn = swift.SwiftConnector('fakerepo', conf=self.conf)
  465. self.assertEqual(conn.user, 'tester')
  466. self.assertEqual(conn.tenant, 'test')
  467. self.conf.set('swift', 'auth_ver', '1')
  468. self.conf.set('swift', 'auth_url', 'http://127.0.0.1:8080/auth/v1.0')
  469. with patch('geventhttpclient.HTTPClient.request',
  470. fake_auth_request_v1_error):
  471. self.assertRaises(swift.SwiftException,
  472. lambda: swift.SwiftConnector('fakerepo',
  473. conf=self.conf))
  474. def test_root_exists(self):
  475. with patch('geventhttpclient.HTTPClient.request',
  476. lambda *args: Response()):
  477. self.assertEqual(self.conn.test_root_exists(), True)
  478. def test_root_not_exists(self):
  479. with patch('geventhttpclient.HTTPClient.request',
  480. lambda *args: Response(status=404)):
  481. self.assertEqual(self.conn.test_root_exists(), None)
  482. def test_create_root(self):
  483. with patch('dulwich.contrib.swift.SwiftConnector.test_root_exists',
  484. lambda *args: None):
  485. with patch('geventhttpclient.HTTPClient.request',
  486. lambda *args: Response()):
  487. self.assertEqual(self.conn.create_root(), None)
  488. def test_create_root_fails(self):
  489. with patch('dulwich.contrib.swift.SwiftConnector.test_root_exists',
  490. lambda *args: None):
  491. with patch('geventhttpclient.HTTPClient.request',
  492. lambda *args: Response(status=404)):
  493. self.assertRaises(swift.SwiftException,
  494. lambda: self.conn.create_root())
  495. def test_get_container_objects(self):
  496. with patch('geventhttpclient.HTTPClient.request',
  497. lambda *args: Response(content=json_dumps(
  498. (({'name': 'a'}, {'name': 'b'}))))):
  499. self.assertEqual(len(self.conn.get_container_objects()), 2)
  500. def test_get_container_objects_fails(self):
  501. with patch('geventhttpclient.HTTPClient.request',
  502. lambda *args: Response(status=404)):
  503. self.assertEqual(self.conn.get_container_objects(), None)
  504. def test_get_object_stat(self):
  505. with patch('geventhttpclient.HTTPClient.request',
  506. lambda *args: Response(headers={'content-length': '10'})):
  507. self.assertEqual(self.conn.get_object_stat('a')['content-length'],
  508. '10')
  509. def test_get_object_stat_fails(self):
  510. with patch('geventhttpclient.HTTPClient.request',
  511. lambda *args: Response(status=404)):
  512. self.assertEqual(self.conn.get_object_stat('a'), None)
  513. def test_put_object(self):
  514. with patch('geventhttpclient.HTTPClient.request',
  515. lambda *args, **kwargs: Response()):
  516. self.assertEqual(self.conn.put_object('a', BytesIO('content')),
  517. None)
  518. def test_put_object_fails(self):
  519. with patch('geventhttpclient.HTTPClient.request',
  520. lambda *args, **kwargs: Response(status=400)):
  521. self.assertRaises(swift.SwiftException,
  522. lambda: self.conn.put_object(
  523. 'a', BytesIO('content')))
  524. def test_get_object(self):
  525. with patch('geventhttpclient.HTTPClient.request',
  526. lambda *args, **kwargs: Response(content='content')):
  527. self.assertEqual(self.conn.get_object('a').read(), 'content')
  528. with patch('geventhttpclient.HTTPClient.request',
  529. lambda *args, **kwargs: Response(content='content')):
  530. self.assertEqual(self.conn.get_object('a', range='0-6'), 'content')
  531. def test_get_object_fails(self):
  532. with patch('geventhttpclient.HTTPClient.request',
  533. lambda *args, **kwargs: Response(status=404)):
  534. self.assertEqual(self.conn.get_object('a'), None)
  535. def test_del_object(self):
  536. with patch('geventhttpclient.HTTPClient.request',
  537. lambda *args: Response()):
  538. self.assertEqual(self.conn.del_object('a'), None)
  539. def test_del_root(self):
  540. with patch('dulwich.contrib.swift.SwiftConnector.del_object',
  541. lambda *args: None):
  542. with patch('dulwich.contrib.swift.SwiftConnector.'
  543. 'get_container_objects',
  544. lambda *args: ({'name': 'a'}, {'name': 'b'})):
  545. with patch('geventhttpclient.HTTPClient.request',
  546. lambda *args: Response()):
  547. self.assertEqual(self.conn.del_root(), None)
  548. @skipIf(missing_libs, skipmsg)
  549. class SwiftObjectStoreTests(ObjectStoreTests, TestCase):
  550. def setUp(self):
  551. TestCase.setUp(self)
  552. conf = swift.load_conf(file=BytesIO(config_file %
  553. def_config_file))
  554. fsc = FakeSwiftConnector('fakerepo', conf=conf)
  555. self.store = swift.SwiftObjectStore(fsc)