test_swift.py 24 KB

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