Add a helper to LeaseInfo for computing size

This lets some code LBYL and avoid writing if the lease won't fit in the
immutable share in the space available.
This commit is contained in:
Jean-Paul Calderone 2021-10-20 14:27:27 -04:00
parent c774256937
commit b3aa1e224f
2 changed files with 35 additions and 2 deletions

View File

@ -13,6 +13,9 @@ if PY2:
import struct, time
# struct format for representation of a lease in an immutable share
IMMUTABLE_FORMAT = ">L32s32sL"
class LeaseInfo(object):
def __init__(self, owner_num=None, renew_secret=None, cancel_secret=None,
expiration_time=None, nodeid=None):
@ -39,12 +42,19 @@ class LeaseInfo(object):
(self.owner_num,
self.renew_secret,
self.cancel_secret,
self.expiration_time) = struct.unpack(">L32s32sL", data)
self.expiration_time) = struct.unpack(IMMUTABLE_FORMAT, data)
self.nodeid = None
return self
def immutable_size(self):
"""
:return int: The size, in bytes, of the representation of this lease in an
immutable share file.
"""
return struct.calcsize(IMMUTABLE_FORMAT)
def to_immutable_data(self):
return struct.pack(">L32s32sL",
return struct.pack(IMMUTABLE_FORMAT,
self.owner_num,
self.renew_secret, self.cancel_secret,
int(self.expiration_time))

View File

@ -117,6 +117,29 @@ class FakeStatsProvider(object):
def register_producer(self, producer):
pass
class LeaseInfoTests(unittest.TestCase):
"""
Tests for ``LeaseInfo``.
"""
@given(
strategies.tuples(
strategies.integers(min_value=0, max_value=2 ** 31 - 1),
strategies.binary(min_size=32, max_size=32),
strategies.binary(min_size=32, max_size=32),
strategies.integers(min_value=0, max_value=2 ** 31 - 1),
strategies.binary(min_size=20, max_size=20),
),
)
def test_immutable_size(self, initializer_args):
"""
``LeaseInfo.immutable_size`` returns the length of the result of
``LeaseInfo.to_immutable_data``.
"""
info = LeaseInfo(*initializer_args)
self.assertEqual(len(info.to_immutable_data()), info.immutable_size())
class Bucket(unittest.TestCase):
def make_workdir(self, name):
basedir = os.path.join("storage", "Bucket", name)