test_swift.py 24 KB

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