test_swift.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  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. import sys
  30. from unittest import skipIf
  31. from dulwich.tests import (
  32. TestCase,
  33. )
  34. from dulwich.tests.test_object_store import (
  35. ObjectStoreTests,
  36. )
  37. from dulwich.tests.utils import (
  38. build_pack,
  39. )
  40. from dulwich.objects import (
  41. Blob,
  42. Commit,
  43. Tree,
  44. Tag,
  45. parse_timezone,
  46. )
  47. from dulwich.pack import (
  48. REF_DELTA,
  49. write_pack_index_v2,
  50. PackData,
  51. load_pack_index_file,
  52. )
  53. try:
  54. from simplejson import dumps as json_dumps
  55. except ImportError:
  56. from json import dumps as json_dumps
  57. missing_libs = []
  58. try:
  59. import gevent
  60. except ImportError:
  61. missing_libs.append("gevent")
  62. try:
  63. import geventhttpclient
  64. except ImportError:
  65. missing_libs.append("geventhttpclient")
  66. try:
  67. from mock import patch
  68. except ImportError:
  69. missing_libs.append("mock")
  70. skipmsg = "Required libraries are not installed (%r)" % missing_libs
  71. skipIfPY3 = skipIf(sys.version_info[0] == 3, "SWIFT module not yet ported to python3.")
  72. if not missing_libs:
  73. from dulwich.contrib import swift
  74. config_file = """[swift]
  75. auth_url = http://127.0.0.1:8080/auth/%(version_str)s
  76. auth_ver = %(version_int)s
  77. username = test;tester
  78. password = testing
  79. region_name = %(region_name)s
  80. endpoint_type = %(endpoint_type)s
  81. concurrency = %(concurrency)s
  82. chunk_length = %(chunk_length)s
  83. cache_length = %(cache_length)s
  84. http_pool_length = %(http_pool_length)s
  85. http_timeout = %(http_timeout)s
  86. """
  87. def_config_file = {'version_str': 'v1.0',
  88. 'version_int': 1,
  89. 'concurrency': 1,
  90. 'chunk_length': 12228,
  91. 'cache_length': 1,
  92. 'region_name': 'test',
  93. 'endpoint_type': 'internalURL',
  94. 'http_pool_length': 1,
  95. 'http_timeout': 1}
  96. def create_swift_connector(store={}):
  97. return lambda root, conf: FakeSwiftConnector(root,
  98. conf=conf,
  99. store=store)
  100. class Response(object):
  101. def __init__(self, headers={}, status=200, content=None):
  102. self.headers = headers
  103. self.status_code = status
  104. self.content = content
  105. def __getitem__(self, key):
  106. return self.headers[key]
  107. def items(self):
  108. return self.headers.items()
  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=b'Default', blob=None):
  138. if not blob:
  139. blob = Blob.from_string(b'The blob content ' + marker)
  140. tree = Tree()
  141. tree.add(b"thefile_" + 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 = b"John Doe " + marker + b" <john@doe.net>"
  148. cmt.author = cmt.committer = author
  149. tz = parse_timezone(b'-0200')[0]
  150. cmt.commit_time = cmt.author_time = int(time())
  151. cmt.commit_timezone = cmt.author_timezone = tz
  152. cmt.encoding = b"UTF-8"
  153. cmt.message = b"The commit message " + marker
  154. tag = Tag()
  155. tag.tagger = b"john@doe.net"
  156. tag.message = b"Annotated tag"
  157. tag.tag_timezone = parse_timezone(b'-0200')[0]
  158. tag.tag_time = cmt.author_time
  159. tag.object = (Commit, cmt.id)
  160. tag.name = b"v_" + marker + b"_0.1"
  161. return blob, tree, tag, cmt
  162. def create_commits(length=1, marker=b'Default'):
  163. data = []
  164. for i in range(0, length):
  165. _marker = ("%s_%s" % (marker, i)).encode()
  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. @skipIfPY3
  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. @skipIfPY3
  371. class TestPackInfoLoadDump(TestCase):
  372. def setUp(self):
  373. conf = swift.load_conf(file=StringIO(config_file %
  374. def_config_file))
  375. sos = swift.SwiftObjectStore(
  376. FakeSwiftConnector('fakerepo', conf=conf))
  377. commit_amount = 10
  378. self.commits = create_commits(length=commit_amount, marker="m")
  379. data = [(d.type_num, d.as_raw_string()) for d in self.commits]
  380. f = BytesIO()
  381. fi = BytesIO()
  382. expected = build_pack(f, data, store=sos)
  383. entries = [(sha, ofs, checksum) for
  384. ofs, _, _, sha, checksum in expected]
  385. self.pack_data = PackData.from_file(file=f, size=None)
  386. write_pack_index_v2(
  387. fi, entries, self.pack_data.calculate_checksum())
  388. fi.seek(0)
  389. self.pack_index = load_pack_index_file('', fi)
  390. # def test_pack_info_perf(self):
  391. # dump_time = []
  392. # load_time = []
  393. # for i in range(0, 100):
  394. # start = time()
  395. # dumps = swift.pack_info_create(self.pack_data, self.pack_index)
  396. # dump_time.append(time() - start)
  397. # for i in range(0, 100):
  398. # start = time()
  399. # pack_infos = swift.load_pack_info('', file=BytesIO(dumps))
  400. # load_time.append(time() - start)
  401. # print sum(dump_time) / float(len(dump_time))
  402. # print sum(load_time) / float(len(load_time))
  403. def test_pack_info(self):
  404. dumps = swift.pack_info_create(self.pack_data, self.pack_index)
  405. pack_infos = swift.load_pack_info('', file=BytesIO(dumps))
  406. for obj in self.commits:
  407. self.assertIn(obj.id, pack_infos)
  408. @skipIf(missing_libs, skipmsg)
  409. class TestSwiftInfoRefsContainer(TestCase):
  410. def setUp(self):
  411. super(TestSwiftInfoRefsContainer, self).setUp()
  412. content = \
  413. b"22effb216e3a82f97da599b8885a6cadb488b4c5\trefs/heads/master\n" + \
  414. b"cca703b0e1399008b53a1a236d6b4584737649e4\trefs/heads/dev"
  415. self.store = {'fakerepo/info/refs': content}
  416. self.conf = swift.load_conf(file=StringIO(config_file %
  417. def_config_file))
  418. self.fsc = FakeSwiftConnector('fakerepo', conf=self.conf)
  419. self.object_store = {}
  420. def test_init(self):
  421. """info/refs does not exists"""
  422. irc = swift.SwiftInfoRefsContainer(self.fsc, self.object_store)
  423. self.assertEqual(len(irc._refs), 0)
  424. self.fsc.store = self.store
  425. irc = swift.SwiftInfoRefsContainer(self.fsc, self.object_store)
  426. self.assertIn(b'refs/heads/dev', irc.allkeys())
  427. self.assertIn(b'refs/heads/master', irc.allkeys())
  428. def test_set_if_equals(self):
  429. self.fsc.store = self.store
  430. irc = swift.SwiftInfoRefsContainer(self.fsc, self.object_store)
  431. irc.set_if_equals(b'refs/heads/dev',
  432. b"cca703b0e1399008b53a1a236d6b4584737649e4", b'1'*40)
  433. self.assertEqual(irc[b'refs/heads/dev'], b'1'*40)
  434. def test_remove_if_equals(self):
  435. self.fsc.store = self.store
  436. irc = swift.SwiftInfoRefsContainer(self.fsc, self.object_store)
  437. irc.remove_if_equals(b'refs/heads/dev',
  438. b"cca703b0e1399008b53a1a236d6b4584737649e4")
  439. self.assertNotIn(b'refs/heads/dev', irc.allkeys())
  440. @skipIf(missing_libs, skipmsg)
  441. class TestSwiftConnector(TestCase):
  442. def setUp(self):
  443. super(TestSwiftConnector, self).setUp()
  444. self.conf = swift.load_conf(file=StringIO(config_file %
  445. def_config_file))
  446. with patch('geventhttpclient.HTTPClient.request',
  447. fake_auth_request_v1):
  448. self.conn = swift.SwiftConnector('fakerepo', conf=self.conf)
  449. def test_init_connector(self):
  450. self.assertEqual(self.conn.auth_ver, '1')
  451. self.assertEqual(self.conn.auth_url,
  452. 'http://127.0.0.1:8080/auth/v1.0')
  453. self.assertEqual(self.conn.user, 'test:tester')
  454. self.assertEqual(self.conn.password, 'testing')
  455. self.assertEqual(self.conn.root, 'fakerepo')
  456. self.assertEqual(self.conn.storage_url,
  457. 'http://127.0.0.1:8080/v1.0/AUTH_fakeuser')
  458. self.assertEqual(self.conn.token, '12' * 10)
  459. self.assertEqual(self.conn.http_timeout, 1)
  460. self.assertEqual(self.conn.http_pool_length, 1)
  461. self.assertEqual(self.conn.concurrency, 1)
  462. self.conf.set('swift', 'auth_ver', '2')
  463. self.conf.set('swift', 'auth_url', 'http://127.0.0.1:8080/auth/v2.0')
  464. with patch('geventhttpclient.HTTPClient.request',
  465. fake_auth_request_v2):
  466. conn = swift.SwiftConnector('fakerepo', conf=self.conf)
  467. self.assertEqual(conn.user, 'tester')
  468. self.assertEqual(conn.tenant, 'test')
  469. self.conf.set('swift', 'auth_ver', '1')
  470. self.conf.set('swift', 'auth_url', 'http://127.0.0.1:8080/auth/v1.0')
  471. with patch('geventhttpclient.HTTPClient.request',
  472. fake_auth_request_v1_error):
  473. self.assertRaises(swift.SwiftException,
  474. lambda: swift.SwiftConnector('fakerepo',
  475. conf=self.conf))
  476. def test_root_exists(self):
  477. with patch('geventhttpclient.HTTPClient.request',
  478. lambda *args: Response()):
  479. self.assertEqual(self.conn.test_root_exists(), True)
  480. def test_root_not_exists(self):
  481. with patch('geventhttpclient.HTTPClient.request',
  482. lambda *args: Response(status=404)):
  483. self.assertEqual(self.conn.test_root_exists(), None)
  484. def test_create_root(self):
  485. with patch('dulwich.contrib.swift.SwiftConnector.test_root_exists',
  486. lambda *args: None):
  487. with patch('geventhttpclient.HTTPClient.request',
  488. lambda *args: Response()):
  489. self.assertEqual(self.conn.create_root(), None)
  490. def test_create_root_fails(self):
  491. with patch('dulwich.contrib.swift.SwiftConnector.test_root_exists',
  492. lambda *args: None):
  493. with patch('geventhttpclient.HTTPClient.request',
  494. lambda *args: Response(status=404)):
  495. self.assertRaises(swift.SwiftException,
  496. lambda: self.conn.create_root())
  497. def test_get_container_objects(self):
  498. with patch('geventhttpclient.HTTPClient.request',
  499. lambda *args: Response(content=json_dumps(
  500. (({'name': 'a'}, {'name': 'b'}))))):
  501. self.assertEqual(len(self.conn.get_container_objects()), 2)
  502. def test_get_container_objects_fails(self):
  503. with patch('geventhttpclient.HTTPClient.request',
  504. lambda *args: Response(status=404)):
  505. self.assertEqual(self.conn.get_container_objects(), None)
  506. def test_get_object_stat(self):
  507. with patch('geventhttpclient.HTTPClient.request',
  508. lambda *args: Response(headers={'content-length': '10'})):
  509. self.assertEqual(self.conn.get_object_stat('a')['content-length'],
  510. '10')
  511. def test_get_object_stat_fails(self):
  512. with patch('geventhttpclient.HTTPClient.request',
  513. lambda *args: Response(status=404)):
  514. self.assertEqual(self.conn.get_object_stat('a'), None)
  515. def test_put_object(self):
  516. with patch('geventhttpclient.HTTPClient.request',
  517. lambda *args, **kwargs: Response()):
  518. self.assertEqual(self.conn.put_object('a', BytesIO(b'content')),
  519. None)
  520. def test_put_object_fails(self):
  521. with patch('geventhttpclient.HTTPClient.request',
  522. lambda *args, **kwargs: Response(status=400)):
  523. self.assertRaises(swift.SwiftException,
  524. lambda: self.conn.put_object(
  525. 'a', BytesIO(b'content')))
  526. def test_get_object(self):
  527. with patch('geventhttpclient.HTTPClient.request',
  528. lambda *args, **kwargs: Response(content=b'content')):
  529. self.assertEqual(self.conn.get_object('a').read(), b'content')
  530. with patch('geventhttpclient.HTTPClient.request',
  531. lambda *args, **kwargs: Response(content=b'content')):
  532. self.assertEqual(self.conn.get_object('a', range='0-6'), b'content')
  533. def test_get_object_fails(self):
  534. with patch('geventhttpclient.HTTPClient.request',
  535. lambda *args, **kwargs: Response(status=404)):
  536. self.assertEqual(self.conn.get_object('a'), None)
  537. def test_del_object(self):
  538. with patch('geventhttpclient.HTTPClient.request',
  539. lambda *args: Response()):
  540. self.assertEqual(self.conn.del_object('a'), None)
  541. def test_del_root(self):
  542. with patch('dulwich.contrib.swift.SwiftConnector.del_object',
  543. lambda *args: None):
  544. with patch('dulwich.contrib.swift.SwiftConnector.'
  545. 'get_container_objects',
  546. lambda *args: ({'name': 'a'}, {'name': 'b'})):
  547. with patch('geventhttpclient.HTTPClient.request',
  548. lambda *args: Response()):
  549. self.assertEqual(self.conn.del_root(), None)
  550. @skipIf(missing_libs, skipmsg)
  551. class SwiftObjectStoreTests(ObjectStoreTests, TestCase):
  552. def setUp(self):
  553. TestCase.setUp(self)
  554. conf = swift.load_conf(file=StringIO(config_file %
  555. def_config_file))
  556. fsc = FakeSwiftConnector('fakerepo', conf=conf)
  557. self.store = swift.SwiftObjectStore(fsc)