Use more specific asserts in test/unit/proxy tests

I changed asserts with more specific assert methods.
e.g.: from assertTrue(sth == None) to assertIsNone(*) or
assertTrue(isinstance(inst, type)) to assertIsInstace(inst, type)
or assertTrue(not sth) to assertFalse(sth).

The code gets more readable, and a better description will be shown on fail.

Change-Id: If6aad8681aab7c9a41d65a4f449d8abbe3e64616
This commit is contained in:
Gábor Antal 2016-07-15 15:02:00 +02:00
parent 7b28ac1d36
commit 75a58a6dd8
7 changed files with 218 additions and 223 deletions

View File

@ -86,7 +86,7 @@ class TestAccountController(unittest.TestCase):
resp = controller.HEAD(req)
self.assertEqual(2, resp.status_int // 100)
for key in owner_headers:
self.assertTrue(key not in resp.headers)
self.assertNotIn(key, resp.headers)
req = Request.blank('/v1/a', environ={'swift_owner': True})
with mock.patch('swift.proxy.controllers.base.http_connect',
@ -94,7 +94,7 @@ class TestAccountController(unittest.TestCase):
resp = controller.HEAD(req)
self.assertEqual(2, resp.status_int // 100)
for key in owner_headers:
self.assertTrue(key in resp.headers)
self.assertIn(key, resp.headers)
def test_get_deleted_account(self):
resp_headers = {
@ -148,9 +148,9 @@ class TestAccountController(unittest.TestCase):
fake_http_connect(200, 200, give_connect=callback)):
controller.PUT(req)
self.assertEqual(context['method'], 'PUT')
self.assertTrue(sys_meta_key in context['headers'])
self.assertIn(sys_meta_key, context['headers'])
self.assertEqual(context['headers'][sys_meta_key], 'foo')
self.assertTrue(user_meta_key in context['headers'])
self.assertIn(user_meta_key, context['headers'])
self.assertEqual(context['headers'][user_meta_key], 'bar')
self.assertNotEqual(context['headers']['x-timestamp'], '1.0')
@ -171,9 +171,9 @@ class TestAccountController(unittest.TestCase):
fake_http_connect(200, 200, give_connect=callback)):
controller.POST(req)
self.assertEqual(context['method'], 'POST')
self.assertTrue(sys_meta_key in context['headers'])
self.assertIn(sys_meta_key, context['headers'])
self.assertEqual(context['headers'][sys_meta_key], 'foo')
self.assertTrue(user_meta_key in context['headers'])
self.assertIn(user_meta_key, context['headers'])
self.assertEqual(context['headers'][user_meta_key], 'bar')
self.assertNotEqual(context['headers']['x-timestamp'], '1.0')
@ -212,7 +212,7 @@ class TestAccountController(unittest.TestCase):
self.assertEqual(resp.headers.get(header), value)
else:
# blank ACLs should result in no header
self.assertTrue(header not in resp.headers)
self.assertNotIn(header, resp.headers)
def test_add_acls_impossible_cases(self):
# For test coverage: verify that defensive coding does defend, in cases

View File

@ -432,8 +432,8 @@ class TestFuncs(unittest.TestCase):
def test_headers_to_container_info_missing(self):
resp = headers_to_container_info({}, 404)
self.assertEqual(resp['status'], 404)
self.assertEqual(resp['read_acl'], None)
self.assertEqual(resp['write_acl'], None)
self.assertIsNone(resp['read_acl'])
self.assertIsNone(resp['write_acl'])
def test_headers_to_container_info_meta(self):
headers = {'X-Container-Meta-Whatevs': 14,
@ -482,8 +482,8 @@ class TestFuncs(unittest.TestCase):
def test_headers_to_account_info_missing(self):
resp = headers_to_account_info({}, 404)
self.assertEqual(resp['status'], 404)
self.assertEqual(resp['bytes'], None)
self.assertEqual(resp['container_count'], None)
self.assertIsNone(resp['bytes'])
self.assertIsNone(resp['container_count'])
def test_headers_to_account_info_meta(self):
headers = {'X-Account-Meta-Whatevs': 14,
@ -519,8 +519,8 @@ class TestFuncs(unittest.TestCase):
def test_headers_to_object_info_missing(self):
resp = headers_to_object_info({}, 404)
self.assertEqual(resp['status'], 404)
self.assertEqual(resp['length'], None)
self.assertEqual(resp['etag'], None)
self.assertIsNone(resp['length'])
self.assertIsNone(resp['etag'])
def test_headers_to_object_info_meta(self):
headers = {'X-Object-Meta-Whatevs': 14,
@ -564,18 +564,18 @@ class TestFuncs(unittest.TestCase):
def test_base_have_quorum(self):
base = Controller(self.app)
# just throw a bunch of test cases at it
self.assertEqual(base.have_quorum([201, 404], 3), False)
self.assertEqual(base.have_quorum([201, 201], 4), True)
self.assertEqual(base.have_quorum([201], 4), False)
self.assertEqual(base.have_quorum([201, 201, 404, 404], 4), True)
self.assertEqual(base.have_quorum([201, 302, 418, 503], 4), False)
self.assertEqual(base.have_quorum([201, 503, 503, 201], 4), True)
self.assertEqual(base.have_quorum([201, 201], 3), True)
self.assertEqual(base.have_quorum([404, 404], 3), True)
self.assertEqual(base.have_quorum([201, 201], 2), True)
self.assertEqual(base.have_quorum([201, 404], 2), True)
self.assertEqual(base.have_quorum([404, 404], 2), True)
self.assertEqual(base.have_quorum([201, 404, 201, 201], 4), True)
self.assertFalse(base.have_quorum([201, 404], 3))
self.assertTrue(base.have_quorum([201, 201], 4))
self.assertFalse(base.have_quorum([201], 4))
self.assertTrue(base.have_quorum([201, 201, 404, 404], 4))
self.assertFalse(base.have_quorum([201, 302, 418, 503], 4))
self.assertTrue(base.have_quorum([201, 503, 503, 201], 4))
self.assertTrue(base.have_quorum([201, 201], 3))
self.assertTrue(base.have_quorum([404, 404], 3))
self.assertTrue(base.have_quorum([201, 201], 2))
self.assertTrue(base.have_quorum([201, 404], 2))
self.assertTrue(base.have_quorum([404, 404], 2))
self.assertTrue(base.have_quorum([201, 404, 201, 201], 4))
def test_best_response_overrides(self):
base = Controller(self.app)
@ -685,9 +685,9 @@ class TestFuncs(unittest.TestCase):
'x-base-meta-size': '151M',
'connection': 'close'}
for k, v in expected_headers.items():
self.assertTrue(k in dst_headers)
self.assertIn(k, dst_headers)
self.assertEqual(v, dst_headers[k])
self.assertFalse('new-owner' in dst_headers)
self.assertNotIn('new-owner', dst_headers)
def test_generate_request_headers_with_sysmeta(self):
base = Controller(self.app)
@ -699,10 +699,10 @@ class TestFuncs(unittest.TestCase):
req = Request.blank('/v1/a/c/o', headers=hdrs)
dst_headers = base.generate_request_headers(req, transfer=True)
for k, v in good_hdrs.items():
self.assertTrue(k.lower() in dst_headers)
self.assertIn(k.lower(), dst_headers)
self.assertEqual(v, dst_headers[k.lower()])
for k, v in bad_hdrs.items():
self.assertFalse(k.lower() in dst_headers)
self.assertNotIn(k.lower(), dst_headers)
def test_generate_request_headers_with_no_orig_req(self):
base = Controller(self.app)

View File

@ -122,7 +122,7 @@ class TestContainerController(TestRingBase):
resp = controller.HEAD(req)
self.assertEqual(2, resp.status_int // 100)
for key in owner_headers:
self.assertTrue(key not in resp.headers)
self.assertNotIn(key, resp.headers)
req = Request.blank('/v1/a/c', environ={'swift_owner': True})
with mock.patch('swift.proxy.controllers.base.http_connect',
@ -130,7 +130,7 @@ class TestContainerController(TestRingBase):
resp = controller.HEAD(req)
self.assertEqual(2, resp.status_int // 100)
for key in owner_headers:
self.assertTrue(key in resp.headers)
self.assertIn(key, resp.headers)
def test_sys_meta_headers_PUT(self):
# check that headers in sys meta namespace make it through
@ -150,9 +150,9 @@ class TestContainerController(TestRingBase):
fake_http_connect(200, 200, give_connect=callback)):
controller.PUT(req)
self.assertEqual(context['method'], 'PUT')
self.assertTrue(sys_meta_key in context['headers'])
self.assertIn(sys_meta_key, context['headers'])
self.assertEqual(context['headers'][sys_meta_key], 'foo')
self.assertTrue(user_meta_key in context['headers'])
self.assertIn(user_meta_key, context['headers'])
self.assertEqual(context['headers'][user_meta_key], 'bar')
self.assertNotEqual(context['headers']['x-timestamp'], '1.0')
@ -173,9 +173,9 @@ class TestContainerController(TestRingBase):
fake_http_connect(200, 200, give_connect=callback)):
controller.POST(req)
self.assertEqual(context['method'], 'POST')
self.assertTrue(sys_meta_key in context['headers'])
self.assertIn(sys_meta_key, context['headers'])
self.assertEqual(context['headers'][sys_meta_key], 'foo')
self.assertTrue(user_meta_key in context['headers'])
self.assertIn(user_meta_key, context['headers'])
self.assertEqual(context['headers'][user_meta_key], 'bar')
self.assertNotEqual(context['headers']['x-timestamp'], '1.0')

View File

@ -49,7 +49,7 @@ class TestInfoController(unittest.TestCase):
req = Request.blank(
'/info', environ={'REQUEST_METHOD': 'GET'})
resp = controller.GET(req)
self.assertTrue(isinstance(resp, HTTPException))
self.assertIsInstance(resp, HTTPException)
self.assertEqual('403 Forbidden', str(resp))
def test_get_info(self):
@ -60,12 +60,12 @@ class TestInfoController(unittest.TestCase):
req = Request.blank(
'/info', environ={'REQUEST_METHOD': 'GET'})
resp = controller.GET(req)
self.assertTrue(isinstance(resp, HTTPException))
self.assertIsInstance(resp, HTTPException)
self.assertEqual('200 OK', str(resp))
info = json.loads(resp.body)
self.assertTrue('admin' not in info)
self.assertTrue('foo' in info)
self.assertTrue('bar' in info['foo'])
self.assertNotIn('admin', info)
self.assertIn('foo', info)
self.assertIn('bar', info['foo'])
self.assertEqual(info['foo']['bar'], 'baz')
def test_options_info(self):
@ -74,9 +74,9 @@ class TestInfoController(unittest.TestCase):
req = Request.blank(
'/info', environ={'REQUEST_METHOD': 'GET'})
resp = controller.OPTIONS(req)
self.assertTrue(isinstance(resp, HTTPException))
self.assertIsInstance(resp, HTTPException)
self.assertEqual('200 OK', str(resp))
self.assertTrue('Allow' in resp.headers)
self.assertIn('Allow', resp.headers)
def test_get_info_cors(self):
controller = self.get_controller(expose_info=True)
@ -87,15 +87,15 @@ class TestInfoController(unittest.TestCase):
'/info', environ={'REQUEST_METHOD': 'GET'},
headers={'Origin': 'http://example.com'})
resp = controller.GET(req)
self.assertTrue(isinstance(resp, HTTPException))
self.assertIsInstance(resp, HTTPException)
self.assertEqual('200 OK', str(resp))
info = json.loads(resp.body)
self.assertTrue('admin' not in info)
self.assertTrue('foo' in info)
self.assertTrue('bar' in info['foo'])
self.assertNotIn('admin', info)
self.assertIn('foo', info)
self.assertIn('bar', info['foo'])
self.assertEqual(info['foo']['bar'], 'baz')
self.assertTrue('Access-Control-Allow-Origin' in resp.headers)
self.assertTrue('Access-Control-Expose-Headers' in resp.headers)
self.assertIn('Access-Control-Allow-Origin', resp.headers)
self.assertIn('Access-Control-Expose-Headers', resp.headers)
def test_head_info(self):
controller = self.get_controller(expose_info=True)
@ -105,7 +105,7 @@ class TestInfoController(unittest.TestCase):
req = Request.blank(
'/info', environ={'REQUEST_METHOD': 'HEAD'})
resp = controller.HEAD(req)
self.assertTrue(isinstance(resp, HTTPException))
self.assertIsInstance(resp, HTTPException)
self.assertEqual('200 OK', str(resp))
def test_disallow_info(self):
@ -118,13 +118,13 @@ class TestInfoController(unittest.TestCase):
req = Request.blank(
'/info', environ={'REQUEST_METHOD': 'GET'})
resp = controller.GET(req)
self.assertTrue(isinstance(resp, HTTPException))
self.assertIsInstance(resp, HTTPException)
self.assertEqual('200 OK', str(resp))
info = json.loads(resp.body)
self.assertTrue('foo' in info)
self.assertTrue('bar' in info['foo'])
self.assertIn('foo', info)
self.assertIn('bar', info['foo'])
self.assertEqual(info['foo']['bar'], 'baz')
self.assertTrue('foo2' not in info)
self.assertNotIn('foo2', info)
def test_disabled_admin_info(self):
controller = self.get_controller(expose_info=True, admin_key='')
@ -138,7 +138,7 @@ class TestInfoController(unittest.TestCase):
req = Request.blank(
path, environ={'REQUEST_METHOD': 'GET'})
resp = controller.GET(req)
self.assertTrue(isinstance(resp, HTTPException))
self.assertIsInstance(resp, HTTPException)
self.assertEqual('403 Forbidden', str(resp))
def test_get_admin_info(self):
@ -154,12 +154,12 @@ class TestInfoController(unittest.TestCase):
req = Request.blank(
path, environ={'REQUEST_METHOD': 'GET'})
resp = controller.GET(req)
self.assertTrue(isinstance(resp, HTTPException))
self.assertIsInstance(resp, HTTPException)
self.assertEqual('200 OK', str(resp))
info = json.loads(resp.body)
self.assertTrue('admin' in info)
self.assertTrue('qux' in info['admin'])
self.assertTrue('quux' in info['admin']['qux'])
self.assertIn('admin', info)
self.assertIn('qux', info['admin'])
self.assertIn('quux', info['admin']['qux'])
self.assertEqual(info['admin']['qux']['quux'], 'corge')
def test_head_admin_info(self):
@ -175,7 +175,7 @@ class TestInfoController(unittest.TestCase):
req = Request.blank(
path, environ={'REQUEST_METHOD': 'HEAD'})
resp = controller.GET(req)
self.assertTrue(isinstance(resp, HTTPException))
self.assertIsInstance(resp, HTTPException)
self.assertEqual('200 OK', str(resp))
expires = int(time.time() + 86400)
@ -185,7 +185,7 @@ class TestInfoController(unittest.TestCase):
req = Request.blank(
path, environ={'REQUEST_METHOD': 'HEAD'})
resp = controller.GET(req)
self.assertTrue(isinstance(resp, HTTPException))
self.assertIsInstance(resp, HTTPException)
self.assertEqual('200 OK', str(resp))
def test_get_admin_info_invalid_method(self):
@ -201,7 +201,7 @@ class TestInfoController(unittest.TestCase):
req = Request.blank(
path, environ={'REQUEST_METHOD': 'GET'})
resp = controller.GET(req)
self.assertTrue(isinstance(resp, HTTPException))
self.assertIsInstance(resp, HTTPException)
self.assertEqual('401 Unauthorized', str(resp))
def test_get_admin_info_invalid_expires(self):
@ -217,7 +217,7 @@ class TestInfoController(unittest.TestCase):
req = Request.blank(
path, environ={'REQUEST_METHOD': 'GET'})
resp = controller.GET(req)
self.assertTrue(isinstance(resp, HTTPException))
self.assertIsInstance(resp, HTTPException)
self.assertEqual('401 Unauthorized', str(resp))
expires = 'abc'
@ -227,7 +227,7 @@ class TestInfoController(unittest.TestCase):
req = Request.blank(
path, environ={'REQUEST_METHOD': 'GET'})
resp = controller.GET(req)
self.assertTrue(isinstance(resp, HTTPException))
self.assertIsInstance(resp, HTTPException)
self.assertEqual('401 Unauthorized', str(resp))
def test_get_admin_info_invalid_path(self):
@ -243,7 +243,7 @@ class TestInfoController(unittest.TestCase):
req = Request.blank(
path, environ={'REQUEST_METHOD': 'GET'})
resp = controller.GET(req)
self.assertTrue(isinstance(resp, HTTPException))
self.assertIsInstance(resp, HTTPException)
self.assertEqual('401 Unauthorized', str(resp))
def test_get_admin_info_invalid_key(self):
@ -259,7 +259,7 @@ class TestInfoController(unittest.TestCase):
req = Request.blank(
path, environ={'REQUEST_METHOD': 'GET'})
resp = controller.GET(req)
self.assertTrue(isinstance(resp, HTTPException))
self.assertIsInstance(resp, HTTPException)
self.assertEqual('401 Unauthorized', str(resp))
def test_admin_disallow_info(self):
@ -277,15 +277,15 @@ class TestInfoController(unittest.TestCase):
req = Request.blank(
path, environ={'REQUEST_METHOD': 'GET'})
resp = controller.GET(req)
self.assertTrue(isinstance(resp, HTTPException))
self.assertIsInstance(resp, HTTPException)
self.assertEqual('200 OK', str(resp))
info = json.loads(resp.body)
self.assertTrue('foo2' not in info)
self.assertTrue('admin' in info)
self.assertTrue('disallowed_sections' in info['admin'])
self.assertTrue('foo2' in info['admin']['disallowed_sections'])
self.assertTrue('qux' in info['admin'])
self.assertTrue('quux' in info['admin']['qux'])
self.assertNotIn('foo2', info)
self.assertIn('admin', info)
self.assertIn('disallowed_sections', info['admin'])
self.assertIn('foo2', info['admin']['disallowed_sections'])
self.assertIn('qux', info['admin'])
self.assertIn('quux', info['admin']['qux'])
self.assertEqual(info['admin']['qux']['quux'], 'corge')

View File

@ -231,7 +231,7 @@ class BaseObjectControllerMixin(object):
# make sure we have enough local nodes (sanity)
all_local_nodes = [n for n in all_nodes if
self.app.write_affinity_is_local_fn(n)]
self.assertTrue(len(all_local_nodes) >= self.replicas() + 1)
self.assertGreaterEqual(len(all_local_nodes), self.replicas() + 1)
# finally, create the local_first_nodes iter and flatten it out
local_first_nodes = list(controller.iter_nodes_local_first(
@ -280,7 +280,7 @@ class BaseObjectControllerMixin(object):
with set_http_connect(slow_connect=True):
nodes = [dict(ip='', port='', device='')]
res = controller._connect_put_node(nodes, '', req, {}, ('', ''))
self.assertTrue(res is None)
self.assertIsNone(res)
def test_DELETE_simple(self):
req = swift.common.swob.Request.blank('/v1/a/c/o', method='DELETE')
@ -1143,10 +1143,10 @@ class TestReplicatedObjController(BaseObjectControllerMixin,
self.assertEqual(resp.status_int, 201)
for given_headers in put_headers:
self.assertEqual(given_headers.get('X-Delete-At'), t)
self.assertTrue('X-Delete-At-Host' in given_headers)
self.assertTrue('X-Delete-At-Device' in given_headers)
self.assertTrue('X-Delete-At-Partition' in given_headers)
self.assertTrue('X-Delete-At-Container' in given_headers)
self.assertIn('X-Delete-At-Host', given_headers)
self.assertIn('X-Delete-At-Device', given_headers)
self.assertIn('X-Delete-At-Partition', given_headers)
self.assertIn('X-Delete-At-Container', given_headers)
def test_PUT_converts_delete_after_to_delete_at(self):
req = swob.Request.blank('/v1/a/c/o', method='PUT', body='',
@ -1168,10 +1168,10 @@ class TestReplicatedObjController(BaseObjectControllerMixin,
for given_headers in put_headers:
self.assertEqual(given_headers.get('X-Delete-At'),
expected_delete_at)
self.assertTrue('X-Delete-At-Host' in given_headers)
self.assertTrue('X-Delete-At-Device' in given_headers)
self.assertTrue('X-Delete-At-Partition' in given_headers)
self.assertTrue('X-Delete-At-Container' in given_headers)
self.assertIn('X-Delete-At-Host', given_headers)
self.assertIn('X-Delete-At-Device', given_headers)
self.assertIn('X-Delete-At-Partition', given_headers)
self.assertIn('X-Delete-At-Container', given_headers)
def test_container_sync_put_x_timestamp_not_found(self):
test_indexes = [None] + [int(p) for p in POLICIES]
@ -1915,9 +1915,9 @@ class TestECObjController(BaseObjectControllerMixin, unittest.TestCase):
frag_archives = []
for connection_id, info in put_requests.items():
body = unchunk_body(''.join(info['chunks']))
self.assertTrue(info['boundary'] is not None,
"didn't get boundary for conn %r" % (
connection_id,))
self.assertIsNotNone(info['boundary'],
"didn't get boundary for conn %r" % (
connection_id,))
self.assertTrue(size > int(info['backend-content-length']) > 0,
"invalid backend-content-length for conn %r" % (
connection_id,))
@ -2306,9 +2306,9 @@ class TestECObjController(BaseObjectControllerMixin, unittest.TestCase):
# ... regardless we should never need to fetch more than ec_ndata
# frags for any given etag
for etag, frags in collected_responses.items():
self.assertTrue(len(frags) <= self.policy.ec_ndata,
'collected %s frags for etag %s' % (
len(frags), etag))
self.assertLessEqual(len(frags), self.policy.ec_ndata,
'collected %s frags for etag %s' % (
len(frags), etag))
def test_GET_with_many_missed_overwrite_will_need_handoff(self):
obj1 = self._make_ec_object_stub()
@ -2357,9 +2357,9 @@ class TestECObjController(BaseObjectControllerMixin, unittest.TestCase):
# ... regardless we should never need to fetch more than ec_ndata
# frags for any given etag
for etag, frags in collected_responses.items():
self.assertTrue(len(frags) <= self.policy.ec_ndata,
'collected %s frags for etag %s' % (
len(frags), etag))
self.assertLessEqual(len(frags), self.policy.ec_ndata,
'collected %s frags for etag %s' % (
len(frags), etag))
def test_GET_with_missing_and_mixed_frags_will_dig_deep_but_succeed(self):
obj1 = self._make_ec_object_stub()
@ -2420,9 +2420,9 @@ class TestECObjController(BaseObjectControllerMixin, unittest.TestCase):
# ... regardless we should never need to fetch more than ec_ndata
# frags for any given etag
for etag, frags in collected_responses.items():
self.assertTrue(len(frags) <= self.policy.ec_ndata,
'collected %s frags for etag %s' % (
len(frags), etag))
self.assertLessEqual(len(frags), self.policy.ec_ndata,
'collected %s frags for etag %s' % (
len(frags), etag))
def test_GET_with_missing_and_mixed_frags_will_dig_deep_but_stop(self):
obj1 = self._make_ec_object_stub()
@ -2480,9 +2480,9 @@ class TestECObjController(BaseObjectControllerMixin, unittest.TestCase):
# ... regardless we should never need to fetch more than ec_ndata
# frags for any given etag
for etag, frags in collected_responses.items():
self.assertTrue(len(frags) <= self.policy.ec_ndata,
'collected %s frags for etag %s' % (
len(frags), etag))
self.assertLessEqual(len(frags), self.policy.ec_ndata,
'collected %s frags for etag %s' % (
len(frags), etag))
def test_GET_mixed_success_with_range(self):
fragment_size = self.policy.fragment_size
@ -2682,8 +2682,8 @@ class TestECObjController(BaseObjectControllerMixin, unittest.TestCase):
error_lines = self.logger.get_lines_for_level('error')
self.assertEqual(1, len(error_lines))
msg = error_lines[0]
self.assertTrue('Error decoding fragments' in msg)
self.assertTrue('/a/c/o' in msg)
self.assertIn('Error decoding fragments', msg)
self.assertIn('/a/c/o', msg)
log_msg_args, log_msg_kwargs = self.logger.log_dict['error'][0]
self.assertEqual(log_msg_kwargs['exc_info'][0], ECDriverError)
@ -2713,9 +2713,9 @@ class TestECObjController(BaseObjectControllerMixin, unittest.TestCase):
self.assertEqual(self.replicas(), len(error_lines))
nparity = self.policy.ec_nparity
for line in error_lines[:nparity]:
self.assertTrue('retrying' in line)
self.assertIn('retrying', line)
for line in error_lines[nparity:]:
self.assertTrue('ChunkReadTimeout (0.01s)' in line)
self.assertIn('ChunkReadTimeout (0.01s)', line)
def test_GET_read_timeout_resume(self):
segment_size = self.policy.ec_segment_size
@ -2741,7 +2741,7 @@ class TestECObjController(BaseObjectControllerMixin, unittest.TestCase):
self.assertTrue(md5(resp.body).hexdigest(), etag)
error_lines = self.logger.get_lines_for_level('error')
self.assertEqual(1, len(error_lines))
self.assertTrue('retrying' in error_lines[0])
self.assertIn('retrying', error_lines[0])
def test_fix_response_HEAD(self):
headers = {'X-Object-Sysmeta-Ec-Content-Length': '10',
@ -2799,7 +2799,7 @@ class TestECObjController(BaseObjectControllerMixin, unittest.TestCase):
resp = req.get_response(self.app)
response_time = time.time() - start
self.assertEqual(resp.status_int, 201)
self.assertTrue(response_time < response_sleep)
self.assertLess(response_time, response_sleep)
def test_PUT_with_just_enough_durable_responses(self):
req = swift.common.swob.Request.blank('/v1/a/c/o', method='PUT',
@ -2861,7 +2861,7 @@ class TestECObjController(BaseObjectControllerMixin, unittest.TestCase):
headers = {'X-Object-Sysmeta-Ec-Content-Length': str(len(real_body)),
'X-Object-Sysmeta-Ec-Etag': body_etag}
start = int(req_range.split('-')[0])
self.assertTrue(start >= 0) # sanity
self.assertGreaterEqual(start, 0) # sanity
title, exp = swob.RESPONSE_REASONS[416]
range_not_satisfiable_body = \
'<html><h1>%s</h1><p>%s</p></html>' % (title, exp)

View File

@ -350,7 +350,7 @@ class TestController(unittest.TestCase):
partition, nodes, count = \
self.controller.account_info(self.account, self.request)
self.check_account_info_return(partition, nodes, True)
self.assertEqual(count, None)
self.assertIsNone(count)
# Test the internal representation in memcache
# 'container_count' changed from 0 to None
@ -368,7 +368,7 @@ class TestController(unittest.TestCase):
partition, nodes, count = \
self.controller.account_info(self.account, self.request)
self.check_account_info_return(partition, nodes, True)
self.assertEqual(count, None)
self.assertIsNone(count)
# tests if some http status codes are not cached
def test_account_info_no_cache(self):
@ -378,7 +378,7 @@ class TestController(unittest.TestCase):
self.controller.account_info(self.account, self.request)
self.assertEqual(len(self.memcache.keys()), 0)
self.check_account_info_return(partition, nodes, True)
self.assertEqual(count, None)
self.assertIsNone(count)
with save_globals():
# We cache if we have two 404 responses - fail if only one
@ -394,7 +394,7 @@ class TestController(unittest.TestCase):
partition, nodes, count = \
self.controller.account_info(self.account, self.request)
self.check_account_info_return(partition, nodes, is_none=True)
self.assertEqual(count, None)
self.assertIsNone(count)
def check_container_info_return(self, ret, is_none=False):
if is_none:
@ -433,7 +433,7 @@ class TestController(unittest.TestCase):
cache_key = get_cache_key(self.account, self.container)
cache_value = self.memcache.get(cache_key)
self.assertTrue(isinstance(cache_value, dict))
self.assertIsInstance(cache_value, dict)
self.assertEqual(200, cache_value.get('status'))
set_http_connect()
@ -455,7 +455,7 @@ class TestController(unittest.TestCase):
cache_key = get_cache_key(self.account, self.container)
cache_value = self.memcache.get(cache_key)
self.assertTrue(isinstance(cache_value, dict))
self.assertIsInstance(cache_value, dict)
self.assertEqual(404, cache_value.get('status'))
set_http_connect()
@ -470,7 +470,7 @@ class TestController(unittest.TestCase):
cache_key = get_cache_key(self.account, self.container)
cache_value = self.memcache.get(cache_key)
self.assertTrue(isinstance(cache_value, dict))
self.assertIsInstance(cache_value, dict)
self.assertEqual(404, cache_value.get('status'))
set_http_connect()
@ -507,17 +507,17 @@ class TestController(unittest.TestCase):
# Test info is returned as strings
self.assertEqual(ai.get('foo'), '\xe2\x98\x83')
self.assertTrue(isinstance(ai.get('foo'), str))
self.assertIsInstance(ai.get('foo'), str)
# Test info['meta'] is returned as strings
m = ai.get('meta', {})
self.assertEqual(m.get('bar'), '\xe2\x98\x83')
self.assertTrue(isinstance(m.get('bar'), str))
self.assertIsInstance(m.get('bar'), str)
# Test info['sysmeta'] is returned as strings
m = ai.get('sysmeta', {})
self.assertEqual(m.get('baz'), '\xe2\x98\x83')
self.assertTrue(isinstance(m.get('baz'), str))
self.assertIsInstance(m.get('baz'), str)
def test_get_container_info_returns_values_as_strings(self):
app = mock.MagicMock()
@ -533,22 +533,22 @@ class TestController(unittest.TestCase):
# Test info is returned as strings
self.assertEqual(ci.get('foo'), '\xe2\x98\x83')
self.assertTrue(isinstance(ci.get('foo'), str))
self.assertIsInstance(ci.get('foo'), str)
# Test info['meta'] is returned as strings
m = ci.get('meta', {})
self.assertEqual(m.get('bar'), '\xe2\x98\x83')
self.assertTrue(isinstance(m.get('bar'), str))
self.assertIsInstance(m.get('bar'), str)
# Test info['sysmeta'] is returned as strings
m = ci.get('sysmeta', {})
self.assertEqual(m.get('baz'), '\xe2\x98\x83')
self.assertTrue(isinstance(m.get('baz'), str))
self.assertIsInstance(m.get('baz'), str)
# Test info['cors'] is returned as strings
m = ci.get('cors', {})
self.assertEqual(m.get('expose_headers'), '\xe2\x98\x83')
self.assertTrue(isinstance(m.get('expose_headers'), str))
self.assertIsInstance(m.get('expose_headers'), str)
@patch_policies([StoragePolicy(0, 'zero', True, object_ring=FakeRing())])
@ -814,7 +814,7 @@ class TestProxyServer(unittest.TestCase):
FakeMemcache(),
container_ring=FakeRing(),
account_ring=FakeRing())
self.assertEqual(baseapp.concurrent_gets, True)
self.assertTrue(baseapp.concurrent_gets)
self.assertEqual(baseapp.concurrency_timeout, 0)
baseapp.update_request(req)
resp = baseapp.handle_request(req)
@ -852,11 +852,11 @@ class TestProxyServer(unittest.TestCase):
container_ring=FakeRing())
self.assertTrue(app.expose_info)
self.assertTrue(isinstance(app.disallowed_sections, list))
self.assertIsInstance(app.disallowed_sections, list)
self.assertEqual(1, len(app.disallowed_sections))
self.assertEqual(['swift.valid_api_versions'],
app.disallowed_sections)
self.assertTrue(app.admin_key is None)
self.assertIsNone(app.admin_key)
def test_get_info_controller(self):
req = Request.blank('/info')
@ -866,11 +866,11 @@ class TestProxyServer(unittest.TestCase):
controller, path_parts = app.get_controller(req)
self.assertTrue('version' in path_parts)
self.assertTrue(path_parts['version'] is None)
self.assertTrue('disallowed_sections' in path_parts)
self.assertTrue('expose_info' in path_parts)
self.assertTrue('admin_key' in path_parts)
self.assertIn('version', path_parts)
self.assertIsNone(path_parts['version'])
self.assertIn('disallowed_sections', path_parts)
self.assertIn('expose_info', path_parts)
self.assertIn('admin_key', path_parts)
self.assertEqual(controller.__name__, 'InfoController')
@ -947,8 +947,8 @@ class TestProxyServer(unittest.TestCase):
except Exception as e1:
app.exception_occurred(node, 'test1', 'test1 msg')
line = logger.get_lines_for_level('error')[-1]
self.assertTrue('test1 server' in line)
self.assertTrue('test1 msg' in line)
self.assertIn('test1 server', line)
self.assertIn('test1 msg', line)
log_args, log_kwargs = logger.log_dict['error'][-1]
self.assertTrue(log_kwargs['exc_info'])
self.assertEqual(log_kwargs['exc_info'][1], e1)
@ -961,8 +961,8 @@ class TestProxyServer(unittest.TestCase):
app.exception_occurred(node, 'test2', 'test2 msg',
level=logging.WARNING)
line = logger.get_lines_for_level('warning')[-1]
self.assertTrue('test2 server' in line)
self.assertTrue('test2 msg' in line)
self.assertIn('test2 server', line)
self.assertIn('test2 msg', line)
log_args, log_kwargs = logger.log_dict['warning'][-1]
self.assertTrue(log_kwargs['exc_info'])
self.assertEqual(log_kwargs['exc_info'][1], e2)
@ -980,8 +980,8 @@ class TestProxyServer(unittest.TestCase):
app.exception_occurred(node, 'test3', 'test3 msg',
level=logging.WARNING, exc_info=e3_info)
line = logger.get_lines_for_level('warning')[-1]
self.assertTrue('test3 server' in line)
self.assertTrue('test3 msg' in line)
self.assertIn('test3 server', line)
self.assertIn('test3 msg', line)
log_args, log_kwargs = logger.log_dict['warning'][-1]
self.assertTrue(log_kwargs['exc_info'])
self.assertEqual(log_kwargs['exc_info'][1], e3)
@ -1011,7 +1011,7 @@ class TestProxyServer(unittest.TestCase):
'/v1.0/a/c/o']:
req = Request.blank(path)
controller, path_parts = app.get_controller(req)
self.assertTrue(controller is not None)
self.assertIsNotNone(controller)
# Ensure settings valid API version constraint works
for version in ["42", 42]:
@ -1025,7 +1025,7 @@ class TestProxyServer(unittest.TestCase):
req = Request.blank('/%s/a' % version)
controller, _ = app.get_controller(req)
self.assertTrue(controller is not None)
self.assertIsNotNone(controller)
# In this case v1 is invalid
req = Request.blank('/v1/a')
@ -1379,7 +1379,7 @@ class TestObjectController(unittest.TestCase):
try:
df.open()
except DiskFileNotExist as e:
self.assertTrue(float(e.timestamp) > 0)
self.assertGreater(float(e.timestamp), 0)
else:
self.fail('did not raise DiskFileNotExist')
@ -1456,7 +1456,7 @@ class TestObjectController(unittest.TestCase):
self.assertEqual(ct, 'multipart/byteranges')
boundary = dict(params).get('boundary')
self.assertTrue(boundary is not None)
self.assertIsNotNone(boundary)
got_mime_docs = []
for mime_doc_fh in iter_multipart_mime_documents(StringIO(res.body),
@ -1652,12 +1652,12 @@ class TestObjectController(unittest.TestCase):
pass
self.assertEqual(res.status_int, 206)
self.assertTrue(kaboomed[0] > 0) # sanity check
self.assertGreater(kaboomed[0], 0) # sanity check
ct, params = parse_content_type(res.headers['Content-Type'])
self.assertEqual(ct, 'multipart/byteranges') # sanity check
boundary = dict(params).get('boundary')
self.assertTrue(boundary is not None) # sanity check
self.assertIsNotNone(boundary) # sanity check
got_byteranges = []
for mime_doc_fh in iter_multipart_mime_documents(StringIO(body),
boundary):
@ -1723,12 +1723,12 @@ class TestObjectController(unittest.TestCase):
body = ''.join(res.app_iter)
self.assertEqual(res.status_int, 206)
self.assertTrue(kaboomed[0] >= 1) # sanity check
self.assertGreaterEqual(kaboomed[0], 1) # sanity check
ct, params = parse_content_type(res.headers['Content-Type'])
self.assertEqual(ct, 'multipart/byteranges') # sanity check
boundary = dict(params).get('boundary')
self.assertTrue(boundary is not None) # sanity check
self.assertIsNotNone(boundary) # sanity check
got_byteranges = []
for mime_doc_fh in iter_multipart_mime_documents(StringIO(body),
boundary):
@ -1761,12 +1761,12 @@ class TestObjectController(unittest.TestCase):
body = ''.join(res.app_iter)
self.assertEqual(res.status_int, 206)
self.assertTrue(kaboomed[0] >= 1) # sanity check
self.assertGreaterEqual(kaboomed[0], 1) # sanity check
ct, params = parse_content_type(res.headers['Content-Type'])
self.assertEqual(ct, 'multipart/byteranges') # sanity check
boundary = dict(params).get('boundary')
self.assertTrue(boundary is not None) # sanity check
self.assertIsNotNone(boundary) # sanity check
got_byteranges = []
for mime_doc_fh in iter_multipart_mime_documents(StringIO(body),
boundary):
@ -1860,7 +1860,7 @@ class TestObjectController(unittest.TestCase):
# verify at least 2 puts made it all the way to the end of 2nd
# phase, ie at least 2 .durable statuses were written
num_durable_puts = sum(d is True for d in got_durable)
self.assertTrue(num_durable_puts >= 2)
self.assertGreaterEqual(num_durable_puts, 2)
@unpatch_policies
def test_PUT_ec_multiple_segments(self):
@ -1948,7 +1948,7 @@ class TestObjectController(unittest.TestCase):
# verify at least 2 puts made it all the way to the end of 2nd
# phase, ie at least 2 .durable statuses were written
num_durable_puts = sum(d is True for d in got_durable)
self.assertTrue(num_durable_puts >= 2)
self.assertGreaterEqual(num_durable_puts, 2)
@unpatch_policies
def test_PUT_ec_object_etag_mismatch(self):
@ -2353,8 +2353,8 @@ class TestObjectController(unittest.TestCase):
# our EC segment size is 4 KiB, so this is multiple (3) segments;
# we'll verify that with a sanity check
obj = 'a moose once bit my sister' * 400
self.assertTrue(
len(obj) > POLICIES.get_by_name("ec").ec_segment_size * 2,
self.assertGreater(
len(obj), POLICIES.get_by_name("ec").ec_segment_size * 2,
"object is too small for proper testing")
prolis = _test_sockets[0]
@ -3300,9 +3300,9 @@ class TestObjectController(unittest.TestCase):
self.assertEqual(res.status[:len(str(expected))],
str(expected))
if expected < 400:
self.assertTrue('x-works' in res.headers)
self.assertIn('x-works', res.headers)
self.assertEqual(res.headers['x-works'], 'yes')
self.assertTrue('accept-ranges' in res.headers)
self.assertIn('accept-ranges', res.headers)
self.assertEqual(res.headers['accept-ranges'], 'bytes')
test_status_map((200, 200, 200, 404, 404), 200)
@ -3621,7 +3621,7 @@ class TestObjectController(unittest.TestCase):
resp.body
except ChunkReadTimeout:
got_exc = True
self.assertTrue(not got_exc)
self.assertFalse(got_exc)
self.app.recoverable_node_timeout = 0.1
set_http_connect(200, 200, 200, slow=1.0)
resp = req.get_response(self.app)
@ -3668,7 +3668,7 @@ class TestObjectController(unittest.TestCase):
self.assertEqual(resp.body, 'lalala')
except ChunkReadTimeout:
got_exc = True
self.assertTrue(not got_exc)
self.assertFalse(got_exc)
set_http_connect(200, 200, 200, body='lalala',
slow=[1.0, 1.0], etags=['a', 'a', 'a'])
@ -3678,7 +3678,7 @@ class TestObjectController(unittest.TestCase):
self.assertEqual(resp.body, 'lalala')
except ChunkReadTimeout:
got_exc = True
self.assertTrue(not got_exc)
self.assertFalse(got_exc)
set_http_connect(200, 200, 200, body='lalala',
slow=[1.0, 1.0], etags=['a', 'b', 'a'])
@ -3688,7 +3688,7 @@ class TestObjectController(unittest.TestCase):
self.assertEqual(resp.body, 'lalala')
except ChunkReadTimeout:
got_exc = True
self.assertTrue(not got_exc)
self.assertFalse(got_exc)
req = Request.blank('/v1/a/c/o', environ={'REQUEST_METHOD': 'GET'})
set_http_connect(200, 200, 200, body='lalala',
@ -3863,11 +3863,11 @@ class TestObjectController(unittest.TestCase):
object_ring = self.app.get_object_ring(None)
first_nodes = list(self.app.iter_nodes(object_ring, 0))
second_nodes = list(self.app.iter_nodes(object_ring, 0))
self.assertTrue(first_nodes[0] in second_nodes)
self.assertIn(first_nodes[0], second_nodes)
self.app.error_limit(first_nodes[0], 'test')
second_nodes = list(self.app.iter_nodes(object_ring, 0))
self.assertTrue(first_nodes[0] not in second_nodes)
self.assertNotIn(first_nodes[0], second_nodes)
def test_iter_nodes_gives_extra_if_error_limited_inline(self):
object_ring = self.app.get_object_ring(None)
@ -3918,7 +3918,7 @@ class TestObjectController(unittest.TestCase):
req = Request.blank('/v1/a/c/o', environ={'REQUEST_METHOD': 'GET'})
resp = controller.best_response(req, [200] * 3, ['OK'] * 3, [''] * 3,
'Object')
self.assertEqual(resp.etag, None)
self.assertIsNone(resp.etag)
resp = controller.best_response(req, [200] * 3, ['OK'] * 3, [''] * 3,
'Object',
etag='68b329da9893e34099c7d8ad5cb9c940'
@ -4414,7 +4414,7 @@ class TestObjectController(unittest.TestCase):
headers = readuntil2crlfs(fd)
exp = 'HTTP/1.1 204'
self.assertEqual(headers[:len(exp)], exp)
self.assertTrue('\r\nContent-Length: 0\r\n' in headers)
self.assertIn('\r\nContent-Length: 0\r\n', headers)
@unpatch_policies
def test_chunked_put_utf8_all_the_way_down(self):
@ -4449,7 +4449,7 @@ class TestObjectController(unittest.TestCase):
exp = 'HTTP/1.1 200'
self.assertEqual(headers[:len(exp)], exp)
containers = fd.read().split('\n')
self.assertTrue(ustr in containers)
self.assertIn(ustr, containers)
# List account with ustr container (test json)
sock = connect_tcp(('localhost', prolis.getsockname()[1]))
fd = sock.makefile()
@ -4461,7 +4461,7 @@ class TestObjectController(unittest.TestCase):
exp = 'HTTP/1.1 200'
self.assertEqual(headers[:len(exp)], exp)
listing = json.loads(fd.read())
self.assertTrue(ustr.decode('utf8') in [l['name'] for l in listing])
self.assertIn(ustr.decode('utf8'), [l['name'] for l in listing])
# List account with ustr container (test xml)
sock = connect_tcp(('localhost', prolis.getsockname()[1]))
fd = sock.makefile()
@ -4472,7 +4472,7 @@ class TestObjectController(unittest.TestCase):
headers = readuntil2crlfs(fd)
exp = 'HTTP/1.1 200'
self.assertEqual(headers[:len(exp)], exp)
self.assertTrue('<name>%s</name>' % ustr in fd.read())
self.assertIn('<name>%s</name>' % ustr, fd.read())
# Create ustr object with ustr metadata in ustr container
sock = connect_tcp(('localhost', prolis.getsockname()[1]))
fd = sock.makefile()
@ -4496,7 +4496,7 @@ class TestObjectController(unittest.TestCase):
exp = 'HTTP/1.1 200'
self.assertEqual(headers[:len(exp)], exp)
objects = fd.read().split('\n')
self.assertTrue(ustr in objects)
self.assertIn(ustr, objects)
# List ustr container with ustr object (test json)
sock = connect_tcp(('localhost', prolis.getsockname()[1]))
fd = sock.makefile()
@ -4521,7 +4521,7 @@ class TestObjectController(unittest.TestCase):
headers = readuntil2crlfs(fd)
exp = 'HTTP/1.1 200'
self.assertEqual(headers[:len(exp)], exp)
self.assertTrue('<name>%s</name>' % ustr in fd.read())
self.assertIn('<name>%s</name>' % ustr, fd.read())
# Retrieve ustr object with ustr metadata
sock = connect_tcp(('localhost', prolis.getsockname()[1]))
fd = sock.makefile()
@ -4533,8 +4533,8 @@ class TestObjectController(unittest.TestCase):
headers = readuntil2crlfs(fd)
exp = 'HTTP/1.1 200'
self.assertEqual(headers[:len(exp)], exp)
self.assertTrue('\r\nX-Object-Meta-%s: %s\r\n' %
(quote(ustr_short).lower(), quote(ustr)) in headers)
self.assertIn('\r\nX-Object-Meta-%s: %s\r\n' %
(quote(ustr_short).lower(), quote(ustr)), headers)
@unpatch_policies
def test_chunked_put_chunked_put(self):
@ -4652,7 +4652,7 @@ class TestObjectController(unittest.TestCase):
self.app, 'account', 'container', 'object')
set_http_connect(200, 200, 200)
resp = controller.GET(req)
self.assertTrue('accept-ranges' in resp.headers)
self.assertIn('accept-ranges', resp.headers)
self.assertEqual(resp.headers['accept-ranges'], 'bytes')
def test_response_head_accept_ranges_header(self):
@ -4664,7 +4664,7 @@ class TestObjectController(unittest.TestCase):
self.app, 'account', 'container', 'object')
set_http_connect(200, 200, 200)
resp = controller.HEAD(req)
self.assertTrue('accept-ranges' in resp.headers)
self.assertIn('accept-ranges', resp.headers)
self.assertEqual(resp.headers['accept-ranges'], 'bytes')
def test_GET_calls_authorize(self):
@ -4984,8 +4984,8 @@ class TestObjectController(unittest.TestCase):
'https://foo.bar',
resp.headers['access-control-allow-origin'])
for verb in 'OPTIONS GET POST PUT DELETE HEAD'.split():
self.assertTrue(
verb in resp.headers['access-control-allow-methods'])
self.assertIn(verb,
resp.headers['access-control-allow-methods'])
self.assertEqual(
len(resp.headers['access-control-allow-methods'].split(', ')),
6)
@ -5002,8 +5002,7 @@ class TestObjectController(unittest.TestCase):
resp = controller.OPTIONS(req)
self.assertEqual(200, resp.status_int)
for verb in 'OPTIONS GET POST PUT DELETE HEAD'.split():
self.assertTrue(
verb in resp.headers['Allow'])
self.assertIn(verb, resp.headers['Allow'])
self.assertEqual(len(resp.headers['Allow'].split(', ')), 6)
req = Request.blank(
'/v1/a/c/o.jpg',
@ -5038,8 +5037,8 @@ class TestObjectController(unittest.TestCase):
self.assertEqual(200, resp.status_int)
self.assertEqual('*', resp.headers['access-control-allow-origin'])
for verb in 'OPTIONS GET POST PUT DELETE HEAD'.split():
self.assertTrue(
verb in resp.headers['access-control-allow-methods'])
self.assertIn(verb,
resp.headers['access-control-allow-methods'])
self.assertEqual(
len(resp.headers['access-control-allow-methods'].split(', ')),
6)
@ -5412,7 +5411,7 @@ class TestECMismatchedFA(unittest.TestCase):
environ={"REQUEST_METHOD": "PUT"},
headers={"X-Storage-Policy": "ec", "X-Auth-Token": "t"})
resp = ensure_container.get_response(prosrv)
self.assertTrue(resp.status_int in (201, 202))
self.assertIn(resp.status_int, (201, 202))
obj1 = "first version..."
put_req1 = Request.blank(
@ -5920,7 +5919,7 @@ class TestObjectECRangedGET(unittest.TestCase):
self.assertEqual(content_type, 'multipart/byteranges')
boundary = content_type_params.get('boundary')
self.assertTrue(boundary is not None)
self.assertIsNotNone(boundary)
got_byteranges = self._parse_multipart(headers['Content-Type'],
gotten_obj)
@ -5999,7 +5998,7 @@ class TestObjectECRangedGET(unittest.TestCase):
self.assertEqual(content_type, 'multipart/byteranges')
boundary = content_type_params.get('boundary')
self.assertTrue(boundary is not None)
self.assertIsNotNone(boundary)
got_byteranges = self._parse_multipart(headers['Content-Type'],
gotten_obj)
@ -6055,7 +6054,7 @@ class TestObjectECRangedGET(unittest.TestCase):
self.assertEqual(content_type, 'multipart/byteranges')
boundary = content_type_params.get('boundary')
self.assertTrue(boundary is not None)
self.assertIsNotNone(boundary)
got_byteranges = self._parse_multipart(headers['Content-Type'],
gotten_obj)
@ -6103,7 +6102,7 @@ class TestContainerController(unittest.TestCase):
# default test
req = Request.blank('/a/c', headers={'Content-Length': '0',
'Content-Type': 'text/plain'})
self.assertEqual(controller._convert_policy_to_index(req), None)
self.assertIsNone(controller._convert_policy_to_index(req))
# negative test
req = Request.blank('/a/c',
headers={'Content-Length': '0',
@ -6140,7 +6139,7 @@ class TestContainerController(unittest.TestCase):
resp = req.get_response(self.app)
self.assertRaises(StopIteration, fake_conn.code_iter.next)
self.assertEqual(resp.status_int, 404)
self.assertEqual(resp.headers['X-Storage-Policy'], None)
self.assertIsNone(resp.headers['X-Storage-Policy'])
def test_error_convert_index_to_name(self):
req = Request.blank('/v1/a/c')
@ -6150,13 +6149,13 @@ class TestContainerController(unittest.TestCase):
resp = req.get_response(self.app)
self.assertRaises(StopIteration, fake_conn.code_iter.next)
self.assertEqual(resp.status_int, 200)
self.assertEqual(resp.headers['X-Storage-Policy'], None)
self.assertIsNone(resp.headers['X-Storage-Policy'])
error_lines = self.app.logger.get_lines_for_level('error')
self.assertEqual(2, len(error_lines))
for msg in error_lines:
expected = "Could not translate " \
"X-Backend-Storage-Policy-Index ('-1')"
self.assertTrue(expected in msg)
self.assertIn(expected, msg)
def test_transfer_headers(self):
src_headers = {'x-remove-versions-location': 'x',
@ -6233,7 +6232,7 @@ class TestContainerController(unittest.TestCase):
str(expected))
infocache = res.environ.get('swift.infocache', {})
if expected < 400:
self.assertTrue('x-works' in res.headers)
self.assertIn('x-works', res.headers)
self.assertEqual(res.headers['x-works'], 'yes')
if c_expected:
self.assertIn('container/a/c', infocache)
@ -6295,9 +6294,9 @@ class TestContainerController(unittest.TestCase):
self.assertEqual(res.status_int, 400)
self.assertEqual(0, len(backend_requests))
expected = 'is deprecated'
self.assertTrue(expected in res.body,
'%r did not include %r' % (
res.body, expected))
self.assertIn(expected, res.body,
'%r did not include %r' % (
res.body, expected))
return
self.assertEqual(res.status_int, 201)
self.assertEqual(
@ -6305,16 +6304,16 @@ class TestContainerController(unittest.TestCase):
len(backend_requests))
for headers in backend_requests:
if not requested_policy:
self.assertFalse('X-Backend-Storage-Policy-Index' in
self.assertNotIn('X-Backend-Storage-Policy-Index',
headers)
self.assertTrue(
'X-Backend-Storage-Policy-Default' in headers)
self.assertIn('X-Backend-Storage-Policy-Default',
headers)
self.assertEqual(
int(expected_policy),
int(headers['X-Backend-Storage-Policy-Default']))
else:
self.assertTrue('X-Backend-Storage-Policy-Index' in
headers)
self.assertIn('X-Backend-Storage-Policy-Index',
headers)
self.assertEqual(int(headers
['X-Backend-Storage-Policy-Index']),
int(policy))
@ -6420,9 +6419,9 @@ class TestContainerController(unittest.TestCase):
self.assertEqual(10, len(calls))
for call in calls[3:6]:
self.assertEqual('/account', call['path'])
self.assertTrue(key in call['headers'],
'%s call, key %s missing in headers %s' %
(call['method'], key, call['headers']))
self.assertIn(key, call['headers'],
'%s call, key %s missing in headers %s' % (
call['method'], key, call['headers']))
self.assertEqual(value, call['headers'][key])
def test_POST(self):
@ -6644,7 +6643,7 @@ class TestContainerController(unittest.TestCase):
req = Request.blank('/v1/a/c?format=json')
self.app.update_request(req)
res = controller.GET(req)
self.assertTrue('accept-ranges' in res.headers)
self.assertIn('accept-ranges', res.headers)
self.assertEqual(res.headers['accept-ranges'], 'bytes')
def test_response_head_accept_ranges_header(self):
@ -6655,7 +6654,7 @@ class TestContainerController(unittest.TestCase):
req = Request.blank('/v1/a/c?format=json')
self.app.update_request(req)
res = controller.HEAD(req)
self.assertTrue('accept-ranges' in res.headers)
self.assertIn('accept-ranges', res.headers)
self.assertEqual(res.headers['accept-ranges'], 'bytes')
def test_PUT_metadata(self):
@ -6862,7 +6861,7 @@ class TestContainerController(unittest.TestCase):
ic = res.environ['swift.infocache']
self.assertEqual(ic['container/a/c']['status'], 204)
self.assertEqual(res.content_length, 0)
self.assertTrue('transfer-encoding' not in res.headers)
self.assertNotIn('transfer-encoding', res.headers)
def test_GET_calls_authorize(self):
called = [False]
@ -6994,7 +6993,7 @@ class TestContainerController(unittest.TestCase):
headers={'Origin': 'http://foo.com',
'Access-Control-Request-Method': 'GET'})
controller.OPTIONS(req)
self.assertTrue(count[0] < 11)
self.assertLess(count[0], 11)
def test_OPTIONS(self):
with save_globals():
@ -7042,8 +7041,8 @@ class TestContainerController(unittest.TestCase):
'https://foo.bar',
resp.headers['access-control-allow-origin'])
for verb in 'OPTIONS GET POST PUT DELETE HEAD'.split():
self.assertTrue(
verb in resp.headers['access-control-allow-methods'])
self.assertIn(verb,
resp.headers['access-control-allow-methods'])
self.assertEqual(
len(resp.headers['access-control-allow-methods'].split(', ')),
6)
@ -7060,8 +7059,7 @@ class TestContainerController(unittest.TestCase):
resp = controller.OPTIONS(req)
self.assertEqual(200, resp.status_int)
for verb in 'OPTIONS GET POST PUT DELETE HEAD'.split():
self.assertTrue(
verb in resp.headers['Allow'])
self.assertIn(verb, resp.headers['Allow'])
self.assertEqual(len(resp.headers['Allow'].split(', ')), 6)
req = Request.blank(
'/v1/a/c',
@ -7097,8 +7095,8 @@ class TestContainerController(unittest.TestCase):
self.assertEqual(200, resp.status_int)
self.assertEqual('*', resp.headers['access-control-allow-origin'])
for verb in 'OPTIONS GET POST PUT DELETE HEAD'.split():
self.assertTrue(
verb in resp.headers['access-control-allow-methods'])
self.assertIn(verb,
resp.headers['access-control-allow-methods'])
self.assertEqual(
len(resp.headers['access-control-allow-methods'].split(', ')),
6)
@ -7150,7 +7148,7 @@ class TestContainerController(unittest.TestCase):
self.assertEqual('red', resp.headers['x-container-meta-color'])
# X-Super-Secret is in the response, but not "exposed"
self.assertEqual('hush', resp.headers['x-super-secret'])
self.assertTrue('access-control-expose-headers' in resp.headers)
self.assertIn('access-control-expose-headers', resp.headers)
exposed = set(
h.strip() for h in
resp.headers['access-control-expose-headers'].split(','))
@ -7369,8 +7367,7 @@ class TestAccountController(unittest.TestCase):
resp = controller.OPTIONS(req)
self.assertEqual(200, resp.status_int)
for verb in 'OPTIONS GET POST HEAD'.split():
self.assertTrue(
verb in resp.headers['Allow'])
self.assertIn(verb, resp.headers['Allow'])
self.assertEqual(len(resp.headers['Allow'].split(', ')), 4)
# Test a CORS OPTIONS request (i.e. including Origin and
@ -7385,8 +7382,7 @@ class TestAccountController(unittest.TestCase):
resp = controller.OPTIONS(req)
self.assertEqual(200, resp.status_int)
for verb in 'OPTIONS GET POST HEAD'.split():
self.assertTrue(
verb in resp.headers['Allow'])
self.assertIn(verb, resp.headers['Allow'])
self.assertEqual(len(resp.headers['Allow'].split(', ')), 4)
self.app.allow_account_management = True
@ -7396,8 +7392,7 @@ class TestAccountController(unittest.TestCase):
resp = controller.OPTIONS(req)
self.assertEqual(200, resp.status_int)
for verb in 'OPTIONS GET POST PUT DELETE HEAD'.split():
self.assertTrue(
verb in resp.headers['Allow'])
self.assertIn(verb, resp.headers['Allow'])
self.assertEqual(len(resp.headers['Allow'].split(', ')), 6)
def test_GET(self):
@ -7525,9 +7520,9 @@ class TestAccountController(unittest.TestCase):
give_connect=callback)
self.assertEqual(9, len(calls))
for call in calls:
self.assertTrue(key in call['headers'],
'%s call, key %s missing in headers %s' %
(call['method'], key, call['headers']))
self.assertIn(key, call['headers'],
'%s call, key %s missing in headers %s' %
(call['method'], key, call['headers']))
self.assertEqual(value, call['headers'][key])
def test_connection_refused(self):
@ -7559,7 +7554,7 @@ class TestAccountController(unittest.TestCase):
req = Request.blank('/v1/a?format=json')
self.app.update_request(req)
res = controller.GET(req)
self.assertTrue('accept-ranges' in res.headers)
self.assertIn('accept-ranges', res.headers)
self.assertEqual(res.headers['accept-ranges'], 'bytes')
def test_response_head_accept_ranges_header(self):
@ -7570,7 +7565,7 @@ class TestAccountController(unittest.TestCase):
self.app.update_request(req)
res = controller.HEAD(req)
res.body
self.assertTrue('accept-ranges' in res.headers)
self.assertIn('accept-ranges', res.headers)
self.assertEqual(res.headers['accept-ranges'], 'bytes')
def test_PUT(self):
@ -7907,7 +7902,7 @@ class TestAccountControllerFakeGetResponse(unittest.TestCase):
# Not a swift_owner -- ACLs should NOT be in response
header = 'X-Account-Access-Control'
self.assertTrue(header not in resp.headers, '%r was in %r' % (
self.assertNotIn(header, resp.headers, '%r was in %r' % (
header, resp.headers))
# Same setup -- mock acct server will provide ACLs
@ -7917,7 +7912,7 @@ class TestAccountControllerFakeGetResponse(unittest.TestCase):
resp = app.handle_request(req)
# For a swift_owner, the ACLs *should* be in response
self.assertTrue(header in resp.headers, '%r not in %r' % (
self.assertIn(header, resp.headers, '%r not in %r' % (
header, resp.headers))
def test_account_acls_through_delegation(self):
@ -8143,7 +8138,7 @@ class TestSwiftInfo(unittest.TestCase):
container_ring=FakeRing())
si = utils.get_swift_info()['swift']
self.assertTrue('version' in si)
self.assertIn('version', si)
self.assertEqual(si['max_file_size'], constraints.MAX_FILE_SIZE)
self.assertEqual(si['max_meta_name_length'],
constraints.MAX_META_NAME_LENGTH)
@ -8163,9 +8158,9 @@ class TestSwiftInfo(unittest.TestCase):
constraints.MAX_CONTAINER_NAME_LENGTH)
self.assertEqual(si['max_object_name_length'],
constraints.MAX_OBJECT_NAME_LENGTH)
self.assertTrue('strict_cors_mode' in si)
self.assertEqual(si['allow_account_management'], False)
self.assertEqual(si['account_autocreate'], False)
self.assertIn('strict_cors_mode', si)
self.assertFalse(si['allow_account_management'])
self.assertFalse(si['account_autocreate'])
# This setting is by default excluded by disallowed_sections
self.assertEqual(si['valid_api_versions'],
constraints.VALID_API_VERSIONS)
@ -8173,7 +8168,7 @@ class TestSwiftInfo(unittest.TestCase):
# other items are added to swift info
self.assertEqual(len(si), 18)
self.assertTrue('policies' in si)
self.assertIn('policies', si)
sorted_pols = sorted(si['policies'], key=operator.itemgetter('name'))
self.assertEqual(len(sorted_pols), 3)
for policy in sorted_pols:

View File

@ -119,15 +119,15 @@ class TestObjectSysmeta(unittest.TestCase):
def _assertInHeaders(self, resp, expected):
for key, val in expected.items():
self.assertTrue(key in resp.headers,
'Header %s missing from %s' % (key, resp.headers))
self.assertIn(key, resp.headers,
'Header %s missing from %s' % (key, resp.headers))
self.assertEqual(val, resp.headers[key],
'Expected header %s:%s, got %s:%s'
% (key, val, key, resp.headers[key]))
def _assertNotInHeaders(self, resp, unexpected):
for key, val in unexpected.items():
self.assertFalse(key in resp.headers,
self.assertNotIn(key, resp.headers,
'Header %s not expected in %s'
% (key, resp.headers))