to_json -> to_partial_json, fully_serialize -> to_json

This commit is contained in:
Jakub Warmuz
2015-04-18 08:11:28 +00:00
parent 33ba8b9dac
commit f8843c64e1
18 changed files with 180 additions and 182 deletions
+2 -2
View File
@@ -13,7 +13,7 @@ from letsencrypt.acme import other
class Challenge(jose.TypedJSONObjectWithFields): class Challenge(jose.TypedJSONObjectWithFields):
# _fields_to_json | pylint: disable=abstract-method # _fields_to_partial_json | pylint: disable=abstract-method
"""ACME challenge.""" """ACME challenge."""
TYPES = {} TYPES = {}
@@ -27,7 +27,7 @@ class DVChallenge(Challenge): # pylint: disable=abstract-method
class ChallengeResponse(jose.TypedJSONObjectWithFields): class ChallengeResponse(jose.TypedJSONObjectWithFields):
# _fields_to_json | pylint: disable=abstract-method # _fields_to_partial_json | pylint: disable=abstract-method
"""ACME challenge response.""" """ACME challenge response."""
TYPES = {} TYPES = {}
+34 -34
View File
@@ -30,8 +30,8 @@ class SimpleHTTPSTest(unittest.TestCase):
'token': 'evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ+PCt92wr+oA', 'token': 'evaGxfADs6pSRb2LAv9IZf17Dt3juxGJ+PCt92wr+oA',
} }
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.jmsg, self.msg.to_json()) self.assertEqual(self.jmsg, self.msg.to_partial_json())
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.challenges import SimpleHTTPS from letsencrypt.acme.challenges import SimpleHTTPS
@@ -56,8 +56,8 @@ class SimpleHTTPSResponseTest(unittest.TestCase):
self.assertEqual('https://example.com/.well-known/acme-challenge/' self.assertEqual('https://example.com/.well-known/acme-challenge/'
'6tbIMBC5Anhl5bOlWT5ZFA', self.msg.uri('example.com')) '6tbIMBC5Anhl5bOlWT5ZFA', self.msg.uri('example.com'))
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.jmsg, self.msg.to_json()) self.assertEqual(self.jmsg, self.msg.to_partial_json())
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.challenges import SimpleHTTPSResponse from letsencrypt.acme.challenges import SimpleHTTPSResponse
@@ -87,8 +87,8 @@ class DVSNITest(unittest.TestCase):
self.assertEqual('a82d5ff8ef740d12881f6d3c2277ab2e.acme.invalid', self.assertEqual('a82d5ff8ef740d12881f6d3c2277ab2e.acme.invalid',
self.msg.nonce_domain) self.msg.nonce_domain)
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.jmsg, self.msg.to_json()) self.assertEqual(self.jmsg, self.msg.to_partial_json())
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.challenges import DVSNI from letsencrypt.acme.challenges import DVSNI
@@ -136,8 +136,8 @@ class DVSNIResponseTest(unittest.TestCase):
self.assertEqual( self.assertEqual(
'{0}.acme.invalid'.format(z), self.msg.z_domain(challenge)) '{0}.acme.invalid'.format(z), self.msg.z_domain(challenge))
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.jmsg, self.msg.to_json()) self.assertEqual(self.jmsg, self.msg.to_partial_json())
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.challenges import DVSNIResponse from letsencrypt.acme.challenges import DVSNIResponse
@@ -163,8 +163,8 @@ class RecoveryContactTest(unittest.TestCase):
'contact' : 'c********n@example.com', 'contact' : 'c********n@example.com',
} }
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.jmsg, self.msg.to_json()) self.assertEqual(self.jmsg, self.msg.to_partial_json())
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.challenges import RecoveryContact from letsencrypt.acme.challenges import RecoveryContact
@@ -185,7 +185,7 @@ class RecoveryContactTest(unittest.TestCase):
self.assertTrue(msg.activation_url is None) self.assertTrue(msg.activation_url is None)
self.assertTrue(msg.success_url is None) self.assertTrue(msg.success_url is None)
self.assertTrue(msg.contact is None) self.assertTrue(msg.contact is None)
self.assertEqual(self.jmsg, msg.to_json()) self.assertEqual(self.jmsg, msg.to_partial_json())
class RecoveryContactResponseTest(unittest.TestCase): class RecoveryContactResponseTest(unittest.TestCase):
@@ -195,8 +195,8 @@ class RecoveryContactResponseTest(unittest.TestCase):
self.msg = RecoveryContactResponse(token='23029d88d9e123e') self.msg = RecoveryContactResponse(token='23029d88d9e123e')
self.jmsg = {'type': 'recoveryContact', 'token': '23029d88d9e123e'} self.jmsg = {'type': 'recoveryContact', 'token': '23029d88d9e123e'}
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.jmsg, self.msg.to_json()) self.assertEqual(self.jmsg, self.msg.to_partial_json())
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.challenges import RecoveryContactResponse from letsencrypt.acme.challenges import RecoveryContactResponse
@@ -214,7 +214,7 @@ class RecoveryContactResponseTest(unittest.TestCase):
msg = RecoveryContactResponse.from_json(self.jmsg) msg = RecoveryContactResponse.from_json(self.jmsg)
self.assertTrue(msg.token is None) self.assertTrue(msg.token is None)
self.assertEqual(self.jmsg, msg.to_json()) self.assertEqual(self.jmsg, msg.to_partial_json())
class RecoveryTokenTest(unittest.TestCase): class RecoveryTokenTest(unittest.TestCase):
@@ -224,8 +224,8 @@ class RecoveryTokenTest(unittest.TestCase):
self.msg = RecoveryToken() self.msg = RecoveryToken()
self.jmsg = {'type': 'recoveryToken'} self.jmsg = {'type': 'recoveryToken'}
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.jmsg, self.msg.to_json()) self.assertEqual(self.jmsg, self.msg.to_partial_json())
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.challenges import RecoveryToken from letsencrypt.acme.challenges import RecoveryToken
@@ -243,8 +243,8 @@ class RecoveryTokenResponseTest(unittest.TestCase):
self.msg = RecoveryTokenResponse(token='23029d88d9e123e') self.msg = RecoveryTokenResponse(token='23029d88d9e123e')
self.jmsg = {'type': 'recoveryToken', 'token': '23029d88d9e123e'} self.jmsg = {'type': 'recoveryToken', 'token': '23029d88d9e123e'}
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.jmsg, self.msg.to_json()) self.assertEqual(self.jmsg, self.msg.to_partial_json())
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.challenges import RecoveryTokenResponse from letsencrypt.acme.challenges import RecoveryTokenResponse
@@ -262,7 +262,7 @@ class RecoveryTokenResponseTest(unittest.TestCase):
msg = RecoveryTokenResponse.from_json(self.jmsg) msg = RecoveryTokenResponse.from_json(self.jmsg)
self.assertTrue(msg.token is None) self.assertTrue(msg.token is None)
self.assertEqual(self.jmsg, msg.to_json()) self.assertEqual(self.jmsg, msg.to_partial_json())
class ProofOfPossessionHintsTest(unittest.TestCase): class ProofOfPossessionHintsTest(unittest.TestCase):
@@ -298,10 +298,10 @@ class ProofOfPossessionHintsTest(unittest.TestCase):
'authorizedFor': authorized_for, 'authorizedFor': authorized_for,
} }
self.jmsg_from = self.jmsg_to.copy() self.jmsg_from = self.jmsg_to.copy()
self.jmsg_from.update({'jwk': jwk.fully_serialize()}) self.jmsg_from.update({'jwk': jwk.to_json()})
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.jmsg_to, self.msg.to_json()) self.assertEqual(self.jmsg_to, self.msg.to_partial_json())
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.challenges import ProofOfPossession from letsencrypt.acme.challenges import ProofOfPossession
@@ -328,7 +328,7 @@ class ProofOfPossessionHintsTest(unittest.TestCase):
self.assertEqual(msg.issuers, ()) self.assertEqual(msg.issuers, ())
self.assertEqual(msg.authorized_for, ()) self.assertEqual(msg.authorized_for, ())
self.assertEqual(self.jmsg_to, msg.to_json()) self.assertEqual(self.jmsg_to, msg.to_partial_json())
class ProofOfPossessionTest(unittest.TestCase): class ProofOfPossessionTest(unittest.TestCase):
@@ -351,13 +351,13 @@ class ProofOfPossessionTest(unittest.TestCase):
} }
self.jmsg_from = { self.jmsg_from = {
'type': 'proofOfPossession', 'type': 'proofOfPossession',
'alg': jose.RS256.fully_serialize(), 'alg': jose.RS256.to_json(),
'nonce': 'eET5udtV7aoX8Xl8gYiZIA', 'nonce': 'eET5udtV7aoX8Xl8gYiZIA',
'hints': hints.fully_serialize(), 'hints': hints.to_json(),
} }
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.jmsg_to, self.msg.to_json()) self.assertEqual(self.jmsg_to, self.msg.to_partial_json())
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.challenges import ProofOfPossession from letsencrypt.acme.challenges import ProofOfPossession
@@ -397,14 +397,14 @@ class ProofOfPossessionResponseTest(unittest.TestCase):
self.jmsg_from = { self.jmsg_from = {
'type': 'proofOfPossession', 'type': 'proofOfPossession',
'nonce': 'eET5udtV7aoX8Xl8gYiZIA', 'nonce': 'eET5udtV7aoX8Xl8gYiZIA',
'signature': signature.fully_serialize(), 'signature': signature.to_json(),
} }
def test_verify(self): def test_verify(self):
self.assertTrue(self.msg.verify()) self.assertTrue(self.msg.verify())
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.jmsg_to, self.msg.to_json()) self.assertEqual(self.jmsg_to, self.msg.to_partial_json())
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.challenges import ProofOfPossessionResponse from letsencrypt.acme.challenges import ProofOfPossessionResponse
@@ -423,8 +423,8 @@ class DNSTest(unittest.TestCase):
self.msg = DNS(token='17817c66b60ce2e4012dfad92657527a') self.msg = DNS(token='17817c66b60ce2e4012dfad92657527a')
self.jmsg = {'type': 'dns', 'token': '17817c66b60ce2e4012dfad92657527a'} self.jmsg = {'type': 'dns', 'token': '17817c66b60ce2e4012dfad92657527a'}
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.jmsg, self.msg.to_json()) self.assertEqual(self.jmsg, self.msg.to_partial_json())
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.challenges import DNS from letsencrypt.acme.challenges import DNS
@@ -442,8 +442,8 @@ class DNSResponseTest(unittest.TestCase):
self.msg = DNSResponse() self.msg = DNSResponse()
self.jmsg = {'type': 'dns'} self.jmsg = {'type': 'dns'}
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.jmsg, self.msg.to_json()) self.assertEqual(self.jmsg, self.msg.to_partial_json())
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.challenges import DNSResponse from letsencrypt.acme.challenges import DNSResponse
+17 -16
View File
@@ -36,8 +36,8 @@ class JSONDeSerializable(object):
Turning an arbitrary Python object into Python object that can Turning an arbitrary Python object into Python object that can
be encoded into a JSON document. **Full serialization** produces be encoded into a JSON document. **Full serialization** produces
a Python object composed of only basic types as required by the a Python object composed of only basic types as required by the
:ref:`conversion table <conversion-table>`. :ref:`conversion table <conversion-table>`. **Partial
**Partial serialization** (acomplished by :meth:`to_json`) serialization** (acomplished by :meth:`to_partial_json`)
produces a Python object that might also be built from other produces a Python object that might also be built from other
:class:`JSONDeSerializable` objects. :class:`JSONDeSerializable` objects.
@@ -71,15 +71,16 @@ class JSONDeSerializable(object):
Interestingly, ``default`` is required to perform only partial Interestingly, ``default`` is required to perform only partial
serialization, as :func:`json.dumps` applies ``default`` serialization, as :func:`json.dumps` applies ``default``
recursively. This is the idea behind making :meth:`to_json` produce recursively. This is the idea behind making :meth:`to_partial_json`
only partial serialization, while providing custom :meth:`json_dumps` produce only partial serialization, while providing custom
that dumps with ``default`` set to :meth:`json_dump_default`. :meth:`json_dumps` that dumps with ``default`` set to
:meth:`json_dump_default`.
To make further documentation a bit more concrete, please, consider To make further documentation a bit more concrete, please, consider
the following imaginatory implementation example:: the following imaginatory implementation example::
class Foo(JSONDeSerializable): class Foo(JSONDeSerializable):
def to_json(self): def to_partial_json(self):
return 'foo' return 'foo'
@classmethod @classmethod
@@ -87,7 +88,7 @@ class JSONDeSerializable(object):
return Foo() return Foo()
class Bar(JSONDeSerializable): class Bar(JSONDeSerializable):
def to_json(self): def to_partial_json(self):
return [Foo(), Foo()] return [Foo(), Foo()]
@classmethod @classmethod
@@ -98,16 +99,16 @@ class JSONDeSerializable(object):
__metaclass__ = abc.ABCMeta __metaclass__ = abc.ABCMeta
@abc.abstractmethod @abc.abstractmethod
def to_json(self): # pragma: no cover def to_partial_json(self): # pragma: no cover
"""Partially serialize. """Partially serialize.
Following the example, **partial serialization** means the following:: Following the example, **partial serialization** means the following::
assert isinstance(Bar().to_json()[0], Foo) assert isinstance(Bar().to_partial_json()[0], Foo)
assert isinstance(Bar().to_json()[1], Foo) assert isinstance(Bar().to_partial_json()[1], Foo)
# in particular... # in particular...
assert Bar().to_json() != ['foo', 'foo'] assert Bar().to_partial_json() != ['foo', 'foo']
:raises letsencrypt.acme.jose.errors.SerializationError: :raises letsencrypt.acme.jose.errors.SerializationError:
in case of any serialization error. in case of any serialization error.
@@ -116,13 +117,13 @@ class JSONDeSerializable(object):
""" """
raise NotImplementedError() raise NotImplementedError()
def fully_serialize(self): def to_json(self):
"""Fully serialize. """Fully serialize.
Again, following the example from before, **full serialization** Again, following the example from before, **full serialization**
means the following:: means the following::
assert Bar().fully_serialize() == ['foo', 'foo'] assert Bar().to_json() == ['foo', 'foo']
:raises letsencrypt.acme.jose.errors.SerializationError: :raises letsencrypt.acme.jose.errors.SerializationError:
in case of any serialization error. in case of any serialization error.
@@ -131,7 +132,7 @@ class JSONDeSerializable(object):
""" """
def _serialize(obj): def _serialize(obj):
if isinstance(obj, JSONDeSerializable): if isinstance(obj, JSONDeSerializable):
return _serialize(obj.to_json()) return _serialize(obj.to_partial_json())
if isinstance(obj, basestring): # strings are sequence if isinstance(obj, basestring): # strings are sequence
return obj return obj
elif isinstance(obj, list): elif isinstance(obj, list):
@@ -163,7 +164,7 @@ class JSONDeSerializable(object):
""" """
# TypeError: Can't instantiate abstract class <cls> with # TypeError: Can't instantiate abstract class <cls> with
# abstract methods from_json, to_json # abstract methods from_json, to_partial_json
return cls() # pylint: disable=abstract-class-instantiated return cls() # pylint: disable=abstract-class-instantiated
@classmethod @classmethod
@@ -199,6 +200,6 @@ class JSONDeSerializable(object):
""" """
if isinstance(python_object, JSONDeSerializable): if isinstance(python_object, JSONDeSerializable):
return python_object.to_json() return python_object.to_partial_json()
else: # this branch is necessary, cannot just "return" else: # this branch is necessary, cannot just "return"
raise TypeError(repr(python_object) + ' is not JSON serializable') raise TypeError(repr(python_object) + ' is not JSON serializable')
+13 -13
View File
@@ -14,7 +14,7 @@ class JSONDeSerializableTest(unittest.TestCase):
def __init__(self, v): def __init__(self, v):
self.v = v self.v = v
def to_json(self): def to_partial_json(self):
return self.v return self.v
@classmethod @classmethod
@@ -26,7 +26,7 @@ class JSONDeSerializableTest(unittest.TestCase):
self.x = x self.x = x
self.y = y self.y = y
def to_json(self): def to_partial_json(self):
return [self.x, self.y] return [self.x, self.y]
@classmethod @classmethod
@@ -39,7 +39,7 @@ class JSONDeSerializableTest(unittest.TestCase):
self.x = x self.x = x
self.y = y self.y = y
def to_json(self): def to_partial_json(self):
return {self.x: self.y} return {self.x: self.y}
@classmethod @classmethod
@@ -59,21 +59,21 @@ class JSONDeSerializableTest(unittest.TestCase):
self.Sequence = Sequence self.Sequence = Sequence
self.Mapping = Mapping self.Mapping = Mapping
def test_fully_serialize_sequence(self): def test_to_json_sequence(self):
self.assertEqual(self.seq.fully_serialize(), ['foo1', 'foo2']) self.assertEqual(self.seq.to_json(), ['foo1', 'foo2'])
def test_fully_serialize_mapping(self): def test_to_json_mapping(self):
self.assertEqual(self.mapping.fully_serialize(), {'foo1': 'foo2'}) self.assertEqual(self.mapping.to_json(), {'foo1': 'foo2'})
def test_fully_serialize_other(self): def test_to_json_other(self):
mock_value = object() mock_value = object()
self.assertTrue(self.Basic(mock_value).fully_serialize() is mock_value) self.assertTrue(self.Basic(mock_value).to_json() is mock_value)
def test_fully_serialize_nested(self): def test_to_json_nested(self):
self.assertEqual(self.nested.fully_serialize(), [['foo1']]) self.assertEqual(self.nested.to_json(), [['foo1']])
def test_fully_serialize(self): def test_to_json(self):
self.assertEqual(self.tuple.fully_serialize(), (('foo', ))) self.assertEqual(self.tuple.to_json(), (('foo', )))
def test_from_json_not_implemented(self): def test_from_json_not_implemented(self):
from letsencrypt.acme.jose.interfaces import JSONDeSerializable from letsencrypt.acme.jose.interfaces import JSONDeSerializable
+7 -7
View File
@@ -113,7 +113,7 @@ class Field(object):
@classmethod @classmethod
def default_encoder(cls, value): def default_encoder(cls, value):
"""Default (passthrough) encoder.""" """Default (passthrough) encoder."""
# field.to_json() is no good as encoder has to do partial # field.to_partial_json() is no good as encoder has to do partial
# serialization only # serialization only
return value return value
@@ -189,7 +189,7 @@ class JSONObjectWithFields(util.ImmutableMap, interfaces.JSONDeSerializable):
raise errors.DeserializationError('No bar suffix!') raise errors.DeserializationError('No bar suffix!')
return value[:-3] return value[:-3]
assert Foo(bar='baz').to_json() == {'Bar': 'bazbar'} assert Foo(bar='baz').to_partial_json() == {'Bar': 'bazbar'}
assert Foo.from_json({'Bar': 'bazbar'}) == Foo(bar='baz') assert Foo.from_json({'Bar': 'bazbar'}) == Foo(bar='baz')
assert (Foo.from_json({'Bar': 'bazbar', 'Empty': '!'}) assert (Foo.from_json({'Bar': 'bazbar', 'Empty': '!'})
== Foo(bar='baz', empty='!')) == Foo(bar='baz', empty='!'))
@@ -209,7 +209,7 @@ class JSONObjectWithFields(util.ImmutableMap, interfaces.JSONDeSerializable):
super(JSONObjectWithFields, self).__init__( super(JSONObjectWithFields, self).__init__(
**(dict(self._defaults(), **kwargs))) **(dict(self._defaults(), **kwargs)))
def fields_to_json(self): def fields_to_partial_json(self):
"""Serialize fields to JSON.""" """Serialize fields to JSON."""
jobj = {} jobj = {}
for slot, field in self._fields.iteritems(): for slot, field in self._fields.iteritems():
@@ -226,8 +226,8 @@ class JSONObjectWithFields(util.ImmutableMap, interfaces.JSONDeSerializable):
slot, value, error)) slot, value, error))
return jobj return jobj
def to_json(self): def to_partial_json(self):
return self.fields_to_json() return self.fields_to_partial_json()
@classmethod @classmethod
def _check_required(cls, jobj): def _check_required(cls, jobj):
@@ -378,7 +378,7 @@ class TypedJSONObjectWithFields(JSONObjectWithFields):
return type_cls return type_cls
def to_json(self): def to_partial_json(self):
"""Get JSON serializable object. """Get JSON serializable object.
:returns: Serializable JSON object representing ACME typed object. :returns: Serializable JSON object representing ACME typed object.
@@ -387,7 +387,7 @@ class TypedJSONObjectWithFields(JSONObjectWithFields):
:rtype: dict :rtype: dict
""" """
jobj = self.fields_to_json() jobj = self.fields_to_partial_json()
jobj[self.type_field_name] = self.typ jobj[self.type_field_name] = self.typ
return jobj return jobj
+12 -11
View File
@@ -44,7 +44,7 @@ class FieldTest(unittest.TestCase):
def test_default_encoder_is_partial(self): def test_default_encoder_is_partial(self):
class MockField(interfaces.JSONDeSerializable): class MockField(interfaces.JSONDeSerializable):
# pylint: disable=missing-docstring # pylint: disable=missing-docstring
def to_json(self): def to_partial_json(self):
return 'foo' return 'foo'
@classmethod @classmethod
def from_json(cls, jobj): def from_json(cls, jobj):
@@ -113,8 +113,8 @@ class JSONObjectWithFieldsTest(unittest.TestCase):
def test_init_defaults(self): def test_init_defaults(self):
self.assertEqual(self.mock, self.MockJSONObjectWithFields(y=2, z=3)) self.assertEqual(self.mock, self.MockJSONObjectWithFields(y=2, z=3))
def test_fields_to_json_omits_empty(self): def test_fields_to_partial_json_omits_empty(self):
self.assertEqual(self.mock.fields_to_json(), {'y': 2, 'Z': 3}) self.assertEqual(self.mock.fields_to_partial_json(), {'y': 2, 'Z': 3})
def test_fields_from_json_fills_default_for_empty(self): def test_fields_from_json_fills_default_for_empty(self):
self.assertEqual( self.assertEqual(
@@ -135,9 +135,10 @@ class JSONObjectWithFieldsTest(unittest.TestCase):
errors.DeserializationError, errors.DeserializationError,
self.MockJSONObjectWithFields.fields_from_json, {'x': 0, 'Z': 0}) self.MockJSONObjectWithFields.fields_from_json, {'x': 0, 'Z': 0})
def test_fields_to_json_encoder(self): def test_fields_to_partial_json_encoder(self):
self.assertEqual(self.MockJSONObjectWithFields(x=1, y=2, z=3).to_json(), self.assertEqual(
{'x': 2, 'y': 2, 'Z': 3}) self.MockJSONObjectWithFields(x=1, y=2, z=3).to_partial_json(),
{'x': 2, 'y': 2, 'Z': 3})
def test_fields_from_json_decoder(self): def test_fields_from_json_decoder(self):
self.assertEqual( self.assertEqual(
@@ -145,10 +146,10 @@ class JSONObjectWithFieldsTest(unittest.TestCase):
self.MockJSONObjectWithFields.fields_from_json( self.MockJSONObjectWithFields.fields_from_json(
{'x': 4, 'y': 2, 'Z': 3})) {'x': 4, 'y': 2, 'Z': 3}))
def test_fields_to_json_error_passthrough(self): def test_fields_to_partial_json_error_passthrough(self):
self.assertRaises( self.assertRaises(
errors.SerializationError, self.MockJSONObjectWithFields( errors.SerializationError, self.MockJSONObjectWithFields(
x=1, y=500, z=3).to_json) x=1, y=500, z=3).to_partial_json)
def test_fields_from_json_error_passthrough(self): def test_fields_from_json_error_passthrough(self):
self.assertRaises( self.assertRaises(
@@ -262,14 +263,14 @@ class TypedJSONObjectWithFieldsTest(unittest.TestCase):
def fields_from_json(cls, jobj): def fields_from_json(cls, jobj):
return {'foo': jobj['foo']} return {'foo': jobj['foo']}
def fields_to_json(self): def fields_to_partial_json(self):
return {'foo': self.foo} return {'foo': self.foo}
self.parent_cls = MockParentTypedJSONObjectWithFields self.parent_cls = MockParentTypedJSONObjectWithFields
self.msg = MockTypedJSONObjectWithFields(foo='bar') self.msg = MockTypedJSONObjectWithFields(foo='bar')
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.msg.to_json(), { self.assertEqual(self.msg.to_partial_json(), {
'type': 'test', 'type': 'test',
'foo': 'bar', 'foo': 'bar',
}) })
+1 -1
View File
@@ -38,7 +38,7 @@ class JWASignature(JWA):
cls.SIGNATURES[signature_cls.name] = signature_cls cls.SIGNATURES[signature_cls.name] = signature_cls
return signature_cls return signature_cls
def to_json(self): def to_partial_json(self):
return self.name return self.name
@classmethod @classmethod
+3 -3
View File
@@ -43,9 +43,9 @@ class JWASignatureTest(unittest.TestCase):
self.assertEqual('Sig1', repr(self.Sig1)) self.assertEqual('Sig1', repr(self.Sig1))
self.assertEqual('Sig2', repr(self.Sig2)) self.assertEqual('Sig2', repr(self.Sig2))
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.Sig1.to_json(), 'Sig1') self.assertEqual(self.Sig1.to_partial_json(), 'Sig1')
self.assertEqual(self.Sig2.to_json(), 'Sig2') self.assertEqual(self.Sig2.to_partial_json(), 'Sig2')
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.jose.jwa import JWASignature from letsencrypt.acme.jose.jwa import JWASignature
+3 -3
View File
@@ -41,7 +41,7 @@ class JWKES(JWK): # pragma: no cover
""" """
typ = 'ES' typ = 'ES'
def fields_to_json(self): def fields_to_partial_json(self):
raise NotImplementedError() raise NotImplementedError()
@classmethod @classmethod
@@ -62,7 +62,7 @@ class JWKOct(JWK):
typ = 'oct' typ = 'oct'
__slots__ = ('key',) __slots__ = ('key',)
def fields_to_json(self): def fields_to_partial_json(self):
# TODO: An "alg" member SHOULD also be present to identify the # TODO: An "alg" member SHOULD also be present to identify the
# algorithm intended to be used with the key, unless the # algorithm intended to be used with the key, unless the
# application uses another means or convention to determine # application uses another means or convention to determine
@@ -131,7 +131,7 @@ class JWKRSA(JWK):
(cls._decode_param(jobj['n']), (cls._decode_param(jobj['n']),
cls._decode_param(jobj['e']))))) cls._decode_param(jobj['e'])))))
def fields_to_json(self): def fields_to_partial_json(self):
return { return {
'n': self._encode_param(self.key.n), 'n': self._encode_param(self.key.n),
'e': self._encode_param(self.key.e), 'e': self._encode_param(self.key.e),
+5 -5
View File
@@ -23,8 +23,8 @@ class JWKOctTest(unittest.TestCase):
self.jwk = JWKOct(key='foo') self.jwk = JWKOct(key='foo')
self.jobj = {'kty': 'oct', 'k': 'foo'} self.jobj = {'kty': 'oct', 'k': 'foo'}
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.jwk.to_json(), self.jobj) self.assertEqual(self.jwk.to_partial_json(), self.jobj)
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.jose.jwk import JWKOct from letsencrypt.acme.jose.jwk import JWKOct
@@ -82,9 +82,9 @@ class JWKRSATest(unittest.TestCase):
def test_public(self): def test_public(self):
self.assertEqual(self.jwk256, self.jwk256_private.public()) self.assertEqual(self.jwk256, self.jwk256_private.public())
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.jwk256.to_json(), self.jwk256json) self.assertEqual(self.jwk256.to_partial_json(), self.jwk256json)
self.assertEqual(self.jwk512.to_json(), self.jwk512json) self.assertEqual(self.jwk512.to_partial_json(), self.jwk512json)
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.jose.jwk import JWK from letsencrypt.acme.jose.jwk import JWK
+5 -5
View File
@@ -46,7 +46,7 @@ class Header(json_util.JSONObjectWithFields):
Parameter Names (as defined in section 4.1 of the Parameter Names (as defined in section 4.1 of the
protocol). If you need Public Header Parameter Names (4.2) protocol). If you need Public Header Parameter Names (4.2)
or Private Header Parameter Names (4.3), you must subclass or Private Header Parameter Names (4.3), you must subclass
and override :meth:`from_json` and :meth:`to_json` and override :meth:`from_json` and :meth:`to_partial_json`
appropriately. appropriately.
.. warning:: This class does not support any extensions through .. warning:: This class does not support any extensions through
@@ -223,8 +223,8 @@ class Signature(json_util.JSONObjectWithFields):
return cls(protected=protected, header=header, signature=signature) return cls(protected=protected, header=header, signature=signature)
def fields_to_json(self): def fields_to_partial_json(self):
fields = super(Signature, self).fields_to_json() fields = super(Signature, self).fields_to_partial_json()
if not fields['header'].not_omitted(): if not fields['header'].not_omitted():
del fields['header'] del fields['header']
return fields return fields
@@ -294,12 +294,12 @@ class JWS(json_util.JSONObjectWithFields):
signature=json_util.decode_b64jose(signature)) signature=json_util.decode_b64jose(signature))
return cls(payload=json_util.decode_b64jose(payload), signatures=(sig,)) return cls(payload=json_util.decode_b64jose(payload), signatures=(sig,))
def to_json(self, flat=True): # pylint: disable=arguments-differ def to_partial_json(self, flat=True): # pylint: disable=arguments-differ
assert self.signatures assert self.signatures
payload = b64.b64encode(self.payload) payload = b64.b64encode(self.payload)
if flat and len(self.signatures) == 1: if flat and len(self.signatures) == 1:
ret = self.signatures[0].to_json() ret = self.signatures[0].to_partial_json()
ret['payload'] = payload ret['payload'] = payload
return ret return ret
else: else:
+9 -10
View File
@@ -72,7 +72,7 @@ class HeaderTest(unittest.TestCase):
def test_x5c_decoding(self): def test_x5c_decoding(self):
from letsencrypt.acme.jose.jws import Header from letsencrypt.acme.jose.jws import Header
header = Header(x5c=(CERT, CERT)) header = Header(x5c=(CERT, CERT))
jobj = header.to_json() jobj = header.to_partial_json()
cert_b64 = base64.b64encode(CERT.as_der()) cert_b64 = base64.b64encode(CERT.as_der())
self.assertEqual(jobj, {'x5c': [cert_b64, cert_b64]}) self.assertEqual(jobj, {'x5c': [cert_b64, cert_b64]})
self.assertEqual(header, Header.from_json(jobj)) self.assertEqual(header, Header.from_json(jobj))
@@ -152,14 +152,13 @@ class JWSTest(unittest.TestCase):
self.assertRaises(errors.DeserializationError, JWS.from_compact, '.') self.assertRaises(errors.DeserializationError, JWS.from_compact, '.')
def test_json_omitempty(self): def test_json_omitempty(self):
protected_jobj = self.protected.to_json(flat=True) protected_jobj = self.protected.to_partial_json(flat=True)
unprotected_jobj = self.unprotected.to_json(flat=True) unprotected_jobj = self.unprotected.to_partial_json(flat=True)
self.assertTrue('protected' not in unprotected_jobj) self.assertTrue('protected' not in unprotected_jobj)
self.assertTrue('header' not in protected_jobj) self.assertTrue('header' not in protected_jobj)
unprotected_jobj['header'] = unprotected_jobj[ unprotected_jobj['header'] = unprotected_jobj['header'].to_json()
'header'].fully_serialize()
from letsencrypt.acme.jose.jws import JWS from letsencrypt.acme.jose.jws import JWS
self.assertEqual(JWS.from_json(protected_jobj), self.protected) self.assertEqual(JWS.from_json(protected_jobj), self.protected)
@@ -173,9 +172,9 @@ class JWSTest(unittest.TestCase):
'protected': b64.b64encode(self.mixed.signature.protected), 'protected': b64.b64encode(self.mixed.signature.protected),
} }
jobj_from = jobj_to.copy() jobj_from = jobj_to.copy()
jobj_from['header'] = jobj_from['header'].fully_serialize() jobj_from['header'] = jobj_from['header'].to_json()
self.assertEqual(self.mixed.to_json(flat=True), jobj_to) self.assertEqual(self.mixed.to_partial_json(flat=True), jobj_to)
from letsencrypt.acme.jose.jws import JWS from letsencrypt.acme.jose.jws import JWS
self.assertEqual(self.mixed, JWS.from_json(jobj_from)) self.assertEqual(self.mixed, JWS.from_json(jobj_from))
@@ -185,9 +184,9 @@ class JWSTest(unittest.TestCase):
'payload': b64.b64encode('foo'), 'payload': b64.b64encode('foo'),
} }
jobj_from = jobj_to.copy() jobj_from = jobj_to.copy()
jobj_from['signatures'] = [jobj_to['signatures'][0].fully_serialize()] jobj_from['signatures'] = [jobj_to['signatures'][0].to_json()]
self.assertEqual(self.mixed.to_json(flat=False), jobj_to) self.assertEqual(self.mixed.to_partial_json(flat=False), jobj_to)
from letsencrypt.acme.jose.jws import JWS from letsencrypt.acme.jose.jws import JWS
self.assertEqual(self.mixed, JWS.from_json(jobj_from)) self.assertEqual(self.mixed, JWS.from_json(jobj_from))
@@ -198,7 +197,7 @@ class JWSTest(unittest.TestCase):
def test_from_json_hashable(self): def test_from_json_hashable(self):
from letsencrypt.acme.jose.jws import JWS from letsencrypt.acme.jose.jws import JWS
hash(JWS.from_json(self.mixed.fully_serialize())) hash(JWS.from_json(self.mixed.to_json()))
class CLITest(unittest.TestCase): class CLITest(unittest.TestCase):
+1 -1
View File
@@ -9,7 +9,7 @@ from letsencrypt.acme import util
class Message(jose.TypedJSONObjectWithFields): class Message(jose.TypedJSONObjectWithFields):
# _fields_to_json | pylint: disable=abstract-method # _fields_to_partial_json | pylint: disable=abstract-method
# pylint: disable=too-few-public-methods # pylint: disable=too-few-public-methods
"""ACME message.""" """ACME message."""
TYPES = {} TYPES = {}
+4 -4
View File
@@ -57,7 +57,7 @@ class _Constant(jose.JSONDeSerializable):
self.POSSIBLE_NAMES[name] = self self.POSSIBLE_NAMES[name] = self
self.name = name self.name = name
def to_json(self): def to_partial_json(self):
return self.name return self.name
@classmethod @classmethod
@@ -182,9 +182,9 @@ class ChallengeBody(ResourceBody):
status = jose.Field('status', decoder=Status.from_json) status = jose.Field('status', decoder=Status.from_json)
validated = fields.RFC3339Field('validated', omitempty=True) validated = fields.RFC3339Field('validated', omitempty=True)
def to_json(self): def to_partial_json(self):
jobj = super(ChallengeBody, self).to_json() jobj = super(ChallengeBody, self).to_partial_json()
jobj.update(self.chall.to_json()) jobj.update(self.chall.to_partial_json())
return jobj return jobj
@classmethod @classmethod
+16 -16
View File
@@ -22,9 +22,9 @@ class ErrorTest(unittest.TestCase):
def test_typ_prefix(self): def test_typ_prefix(self):
self.assertEqual('malformed', self.error.typ) self.assertEqual('malformed', self.error.typ)
self.assertEqual( self.assertEqual(
'urn:acme:error:malformed', self.error.to_json()['type']) 'urn:acme:error:malformed', self.error.to_partial_json()['type'])
self.assertEqual( self.assertEqual(
'malformed', self.error.from_json(self.error.to_json()).typ) 'malformed', self.error.from_json(self.error.to_partial_json()).typ)
def test_typ_decoder_missing_prefix(self): def test_typ_decoder_missing_prefix(self):
from letsencrypt.acme.messages2 import Error from letsencrypt.acme.messages2 import Error
@@ -44,7 +44,7 @@ class ErrorTest(unittest.TestCase):
def test_from_json_hashable(self): def test_from_json_hashable(self):
from letsencrypt.acme.messages2 import Error from letsencrypt.acme.messages2 import Error
hash(Error.from_json(self.error.fully_serialize())) hash(Error.from_json(self.error.to_json()))
class ConstantTest(unittest.TestCase): class ConstantTest(unittest.TestCase):
@@ -59,9 +59,9 @@ class ConstantTest(unittest.TestCase):
self.const_a = MockConstant('a') self.const_a = MockConstant('a')
self.const_b = MockConstant('b') self.const_b = MockConstant('b')
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual('a', self.const_a.to_json()) self.assertEqual('a', self.const_a.to_partial_json())
self.assertEqual('b', self.const_b.to_json()) self.assertEqual('b', self.const_b.to_partial_json())
def test_from_json(self): def test_from_json(self):
self.assertEqual(self.const_a, self.MockConstant.from_json('a')) self.assertEqual(self.const_a, self.MockConstant.from_json('a'))
@@ -100,10 +100,10 @@ class RegistrationTest(unittest.TestCase):
'key': key, 'key': key,
} }
self.jobj_from = self.jobj_to.copy() self.jobj_from = self.jobj_to.copy()
self.jobj_from['key'] = key.fully_serialize() self.jobj_from['key'] = key.to_json()
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.jobj_to, self.reg.to_json()) self.assertEqual(self.jobj_to, self.reg.to_partial_json())
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.messages2 import Registration from letsencrypt.acme.messages2 import Registration
@@ -144,8 +144,8 @@ class ChallengeBodyTest(unittest.TestCase):
self.jobj_from = self.jobj_to.copy() self.jobj_from = self.jobj_to.copy()
self.jobj_from['status'] = 'valid' self.jobj_from['status'] = 'valid'
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.jobj_to, self.challb.to_json()) self.assertEqual(self.jobj_to, self.challb.to_partial_json())
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.messages2 import ChallengeBody from letsencrypt.acme.messages2 import ChallengeBody
@@ -182,8 +182,8 @@ class AuthorizationTest(unittest.TestCase):
challenges=self.challbs) challenges=self.challbs)
self.jobj_from = { self.jobj_from = {
'identifier': identifier.fully_serialize(), 'identifier': identifier.to_json(),
'challenges': [challb.fully_serialize() for challb in self.challbs], 'challenges': [challb.to_json() for challb in self.challbs],
'combinations': combinations, 'combinations': combinations,
} }
@@ -220,12 +220,12 @@ class RevocationTest(unittest.TestCase):
self.assertEqual(self.rev_date, Revocation.from_json(self.jobj_date)) self.assertEqual(self.rev_date, Revocation.from_json(self.jobj_date))
def test_revoke_encoder(self): def test_revoke_encoder(self):
self.assertEqual(self.jobj_now, self.rev_now.to_json()) self.assertEqual(self.jobj_now, self.rev_now.to_partial_json())
self.assertEqual(self.jobj_date, self.rev_date.to_json()) self.assertEqual(self.jobj_date, self.rev_date.to_partial_json())
def test_from_json_hashable(self): def test_from_json_hashable(self):
from letsencrypt.acme.messages2 import Revocation from letsencrypt.acme.messages2 import Revocation
hash(Revocation.from_json(self.rev_now.fully_serialize())) hash(Revocation.from_json(self.rev_now.to_json()))
if __name__ == '__main__': if __name__ == '__main__':
+34 -37
View File
@@ -86,7 +86,7 @@ class ChallengeTest(unittest.TestCase):
'type': 'challenge', 'type': 'challenge',
'sessionID': 'aefoGaavieG9Wihuk2aufai3aeZ5EeW4', 'sessionID': 'aefoGaavieG9Wihuk2aufai3aeZ5EeW4',
'nonce': '7Nbyb1lI6xPVI3Hg3aKSqQ', 'nonce': '7Nbyb1lI6xPVI3Hg3aKSqQ',
'challenges': [chall.fully_serialize() for chall in challs], 'challenges': [chall.to_json() for chall in challs],
'combinations': [[0, 2], [1, 2]], # TODO array tuples 'combinations': [[0, 2], [1, 2]], # TODO array tuples
} }
@@ -102,8 +102,8 @@ class ChallengeTest(unittest.TestCase):
) )
)) ))
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.msg.to_json(), self.jmsg_to) self.assertEqual(self.msg.to_partial_json(), self.jmsg_to)
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.messages import Challenge from letsencrypt.acme.messages import Challenge
@@ -117,7 +117,7 @@ class ChallengeTest(unittest.TestCase):
msg = Challenge.from_json(self.jmsg_from) msg = Challenge.from_json(self.jmsg_from)
self.assertEqual(msg.combinations, ()) self.assertEqual(msg.combinations, ())
self.assertEqual(msg.to_json(), self.jmsg_to) self.assertEqual(msg.to_partial_json(), self.jmsg_to)
class ChallengeRequestTest(unittest.TestCase): class ChallengeRequestTest(unittest.TestCase):
@@ -131,8 +131,8 @@ class ChallengeRequestTest(unittest.TestCase):
'identifier': 'example.com', 'identifier': 'example.com',
} }
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.msg.to_json(), self.jmsg) self.assertEqual(self.msg.to_partial_json(), self.jmsg)
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.messages import ChallengeRequest from letsencrypt.acme.messages import ChallengeRequest
@@ -155,11 +155,11 @@ class AuthorizationTest(unittest.TestCase):
'jwk': jwk, 'jwk': jwk,
} }
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.msg.to_json(), self.jmsg) self.assertEqual(self.msg.to_partial_json(), self.jmsg)
def test_from_json(self): def test_from_json(self):
self.jmsg['jwk'] = self.jmsg['jwk'].to_json() self.jmsg['jwk'] = self.jmsg['jwk'].to_partial_json()
from letsencrypt.acme.messages import Authorization from letsencrypt.acme.messages import Authorization
self.assertEqual(Authorization.from_json(self.jmsg), self.msg) self.assertEqual(Authorization.from_json(self.jmsg), self.msg)
@@ -175,7 +175,7 @@ class AuthorizationTest(unittest.TestCase):
self.assertTrue(msg.recovery_token is None) self.assertTrue(msg.recovery_token is None)
self.assertTrue(msg.identifier is None) self.assertTrue(msg.identifier is None)
self.assertTrue(msg.jwk is None) self.assertTrue(msg.jwk is None)
self.assertEqual(self.jmsg, msg.to_json()) self.assertEqual(self.jmsg, msg.to_partial_json())
class AuthorizationRequestTest(unittest.TestCase): class AuthorizationRequestTest(unittest.TestCase):
@@ -216,10 +216,9 @@ class AuthorizationRequestTest(unittest.TestCase):
'type': 'authorizationRequest', 'type': 'authorizationRequest',
'sessionID': 'aefoGaavieG9Wihuk2aufai3aeZ5EeW4', 'sessionID': 'aefoGaavieG9Wihuk2aufai3aeZ5EeW4',
'nonce': '7Nbyb1lI6xPVI3Hg3aKSqQ', 'nonce': '7Nbyb1lI6xPVI3Hg3aKSqQ',
'responses': [None if response is None 'responses': [None if response is None else response.to_json()
else response.fully_serialize()
for response in self.responses], for response in self.responses],
'signature': signature.fully_serialize(), 'signature': signature.to_json(),
# TODO: schema validation doesn't recognize tuples as # TODO: schema validation doesn't recognize tuples as
# arrays :( # arrays :(
'contact': list(self.contact), 'contact': list(self.contact),
@@ -237,8 +236,8 @@ class AuthorizationRequestTest(unittest.TestCase):
def test_verify(self): def test_verify(self):
self.assertTrue(self.msg.verify('example.com')) self.assertTrue(self.msg.verify('example.com'))
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.msg.to_json(), self.jmsg_to) self.assertEqual(self.msg.to_partial_json(), self.jmsg_to)
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.messages import AuthorizationRequest from letsencrypt.acme.messages import AuthorizationRequest
@@ -253,7 +252,7 @@ class AuthorizationRequestTest(unittest.TestCase):
msg = AuthorizationRequest.from_json(self.jmsg_from) msg = AuthorizationRequest.from_json(self.jmsg_from)
self.assertEqual(msg.contact, ()) self.assertEqual(msg.contact, ())
self.assertEqual(self.jmsg_to, msg.to_json()) self.assertEqual(self.jmsg_to, msg.to_partial_json())
class CertificateTest(unittest.TestCase): class CertificateTest(unittest.TestCase):
@@ -275,8 +274,8 @@ class CertificateTest(unittest.TestCase):
# TODO: schema validation array tuples # TODO: schema validation array tuples
self.jmsg_from['chain'] = list(self.jmsg_from['chain']) self.jmsg_from['chain'] = list(self.jmsg_from['chain'])
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.msg.to_json(), self.jmsg_to) self.assertEqual(self.msg.to_partial_json(), self.jmsg_to)
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.messages import Certificate from letsencrypt.acme.messages import Certificate
@@ -293,7 +292,7 @@ class CertificateTest(unittest.TestCase):
self.assertEqual(msg.chain, ()) self.assertEqual(msg.chain, ())
self.assertTrue(msg.refresh is None) self.assertTrue(msg.refresh is None)
self.assertEqual(self.jmsg_to, msg.to_json()) self.assertEqual(self.jmsg_to, msg.to_partial_json())
class CertificateRequestTest(unittest.TestCase): class CertificateRequestTest(unittest.TestCase):
@@ -316,8 +315,7 @@ class CertificateRequestTest(unittest.TestCase):
'signature': signature, 'signature': signature,
} }
self.jmsg_from = self.jmsg_to.copy() self.jmsg_from = self.jmsg_to.copy()
self.jmsg_from['signature'] = self.jmsg_from[ self.jmsg_from['signature'] = self.jmsg_from['signature'].to_json()
'signature'].fully_serialize()
def test_create(self): def test_create(self):
from letsencrypt.acme.messages import CertificateRequest from letsencrypt.acme.messages import CertificateRequest
@@ -328,8 +326,8 @@ class CertificateRequestTest(unittest.TestCase):
def test_verify(self): def test_verify(self):
self.assertTrue(self.msg.verify()) self.assertTrue(self.msg.verify())
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.msg.to_json(), self.jmsg_to) self.assertEqual(self.msg.to_partial_json(), self.jmsg_to)
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.messages import CertificateRequest from letsencrypt.acme.messages import CertificateRequest
@@ -351,8 +349,8 @@ class DeferTest(unittest.TestCase):
'message': 'Warming up the HSM', 'message': 'Warming up the HSM',
} }
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.msg.to_json(), self.jmsg) self.assertEqual(self.msg.to_partial_json(), self.jmsg)
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.messages import Defer from letsencrypt.acme.messages import Defer
@@ -367,7 +365,7 @@ class DeferTest(unittest.TestCase):
self.assertTrue(msg.interval is None) self.assertTrue(msg.interval is None)
self.assertTrue(msg.message is None) self.assertTrue(msg.message is None)
self.assertEqual(self.jmsg, msg.to_json()) self.assertEqual(self.jmsg, msg.to_partial_json())
class ErrorTest(unittest.TestCase): class ErrorTest(unittest.TestCase):
@@ -385,8 +383,8 @@ class ErrorTest(unittest.TestCase):
'moreInfo': 'https://ca.example.com/documentation/csr-requirements', 'moreInfo': 'https://ca.example.com/documentation/csr-requirements',
} }
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.msg.to_json(), self.jmsg) self.assertEqual(self.msg.to_partial_json(), self.jmsg)
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.messages import Error from letsencrypt.acme.messages import Error
@@ -401,7 +399,7 @@ class ErrorTest(unittest.TestCase):
self.assertTrue(msg.message is None) self.assertTrue(msg.message is None)
self.assertTrue(msg.more_info is None) self.assertTrue(msg.more_info is None)
self.assertEqual(self.jmsg, msg.to_json()) self.assertEqual(self.jmsg, msg.to_partial_json())
class RevocationTest(unittest.TestCase): class RevocationTest(unittest.TestCase):
@@ -411,8 +409,8 @@ class RevocationTest(unittest.TestCase):
self.msg = Revocation() self.msg = Revocation()
self.jmsg = {'type': 'revocation'} self.jmsg = {'type': 'revocation'}
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.msg.to_json(), self.jmsg) self.assertEqual(self.msg.to_partial_json(), self.jmsg)
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.messages import Revocation from letsencrypt.acme.messages import Revocation
@@ -441,8 +439,7 @@ class RevocationRequestTest(unittest.TestCase):
'signature': signature, 'signature': signature,
} }
self.jmsg_from = self.jmsg_to.copy() self.jmsg_from = self.jmsg_to.copy()
self.jmsg_from['signature'] = self.jmsg_from[ self.jmsg_from['signature'] = self.jmsg_from['signature'].to_json()
'signature'].fully_serialize()
def test_create(self): def test_create(self):
from letsencrypt.acme.messages import RevocationRequest from letsencrypt.acme.messages import RevocationRequest
@@ -452,8 +449,8 @@ class RevocationRequestTest(unittest.TestCase):
def test_verify(self): def test_verify(self):
self.assertTrue(self.msg.verify()) self.assertTrue(self.msg.verify())
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.msg.to_json(), self.jmsg_to) self.assertEqual(self.msg.to_partial_json(), self.jmsg_to)
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.messages import RevocationRequest from letsencrypt.acme.messages import RevocationRequest
@@ -470,8 +467,8 @@ class StatusRequestTest(unittest.TestCase):
'token': u'O7-s9MNq1siZHlgrMzi9_A', 'token': u'O7-s9MNq1siZHlgrMzi9_A',
} }
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.msg.to_json(), self.jmsg) self.assertEqual(self.msg.to_partial_json(), self.jmsg)
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.messages import StatusRequest from letsencrypt.acme.messages import StatusRequest
+5 -5
View File
@@ -42,8 +42,8 @@ class SignatureTest(unittest.TestCase):
self.jsig_from = { self.jsig_from = {
'nonce': b64nonce, 'nonce': b64nonce,
'alg': self.alg.to_json(), 'alg': self.alg.to_partial_json(),
'jwk': self.jwk.to_json(), 'jwk': self.jwk.to_partial_json(),
'sig': b64sig, 'sig': b64sig,
} }
@@ -78,8 +78,8 @@ class SignatureTest(unittest.TestCase):
self.assertEqual(signature.jwk, self.jwk) self.assertEqual(signature.jwk, self.jwk)
self.assertTrue(signature.verify(self.msg)) self.assertTrue(signature.verify(self.msg))
def test_to_json(self): def test_to_partial_json(self):
self.assertEqual(self.signature.to_json(), self.jsig_to) self.assertEqual(self.signature.to_partial_json(), self.jsig_to)
def test_from_json(self): def test_from_json(self):
from letsencrypt.acme.other import Signature from letsencrypt.acme.other import Signature
@@ -88,7 +88,7 @@ class SignatureTest(unittest.TestCase):
def test_from_json_non_schema_errors(self): def test_from_json_non_schema_errors(self):
from letsencrypt.acme.other import Signature from letsencrypt.acme.other import Signature
jwk = self.jwk.to_json() jwk = self.jwk.to_partial_json()
self.assertRaises( self.assertRaises(
jose.DeserializationError, Signature.from_json, { jose.DeserializationError, Signature.from_json, {
'alg': 'RS256', 'sig': 'x', 'nonce': '', 'jwk': jwk}) 'alg': 'RS256', 'sig': 'x', 'nonce': '', 'jwk': jwk})
+9 -9
View File
@@ -88,7 +88,7 @@ class NetworkTest(unittest.TestCase):
# pylint: disable=missing-docstring # pylint: disable=missing-docstring
def __init__(self, value): def __init__(self, value):
self.value = value self.value = value
def to_json(self): def to_partial_json(self):
return self.value return self.value
@classmethod @classmethod
def from_json(cls, value): def from_json(cls, value):
@@ -173,7 +173,7 @@ class NetworkTest(unittest.TestCase):
def test_register(self): def test_register(self):
self.response.status_code = httplib.CREATED self.response.status_code = httplib.CREATED
self.response.json.return_value = self.regr.body.fully_serialize() self.response.json.return_value = self.regr.body.to_json()
self.response.headers['Location'] = self.regr.uri self.response.headers['Location'] = self.regr.uri
self.response.links.update({ self.response.links.update({
'next': {'url': self.regr.new_authzr_uri}, 'next': {'url': self.regr.new_authzr_uri},
@@ -186,7 +186,7 @@ class NetworkTest(unittest.TestCase):
# TODO: split here and separate test # TODO: split here and separate test
reg_wrong_key = self.regr.body.update(key=KEY2.public()) reg_wrong_key = self.regr.body.update(key=KEY2.public())
self.response.json.return_value = reg_wrong_key.fully_serialize() self.response.json.return_value = reg_wrong_key.to_json()
self.assertRaises( self.assertRaises(
errors.UnexpectedUpdate, self.net.register, self.contact) errors.UnexpectedUpdate, self.net.register, self.contact)
@@ -198,20 +198,20 @@ class NetworkTest(unittest.TestCase):
def test_update_registration(self): def test_update_registration(self):
self.response.headers['Location'] = self.regr.uri self.response.headers['Location'] = self.regr.uri
self.response.json.return_value = self.regr.body.fully_serialize() self.response.json.return_value = self.regr.body.to_json()
self._mock_post_get() self._mock_post_get()
self.assertEqual(self.regr, self.net.update_registration(self.regr)) self.assertEqual(self.regr, self.net.update_registration(self.regr))
# TODO: split here and separate test # TODO: split here and separate test
self.response.json.return_value = self.regr.body.update( self.response.json.return_value = self.regr.body.update(
contact=()).fully_serialize() contact=()).to_json()
self.assertRaises( self.assertRaises(
errors.UnexpectedUpdate, self.net.update_registration, self.regr) errors.UnexpectedUpdate, self.net.update_registration, self.regr)
def test_request_challenges(self): def test_request_challenges(self):
self.response.status_code = httplib.CREATED self.response.status_code = httplib.CREATED
self.response.headers['Location'] = self.authzr.uri self.response.headers['Location'] = self.authzr.uri
self.response.json.return_value = self.authz.fully_serialize() self.response.json.return_value = self.authz.to_json()
self.response.links = { self.response.links = {
'next': {'url': self.authzr.new_cert_uri}, 'next': {'url': self.authzr.new_cert_uri},
} }
@@ -222,7 +222,7 @@ class NetworkTest(unittest.TestCase):
# TODO: split here and separate test # TODO: split here and separate test
authz_wrong_key = self.authz.update(key=KEY2.public()) authz_wrong_key = self.authz.update(key=KEY2.public())
self.response.json.return_value = authz_wrong_key.fully_serialize() self.response.json.return_value = authz_wrong_key.to_json()
self.assertRaises( self.assertRaises(
errors.UnexpectedUpdate, self.net.request_challenges, errors.UnexpectedUpdate, self.net.request_challenges,
self.identifier, self.regr) self.identifier, self.regr)
@@ -242,7 +242,7 @@ class NetworkTest(unittest.TestCase):
def test_answer_challenge(self): def test_answer_challenge(self):
self.response.links['up'] = {'url': self.challr.authzr_uri} self.response.links['up'] = {'url': self.challr.authzr_uri}
self.response.json.return_value = self.challr.body.fully_serialize() self.response.json.return_value = self.challr.body.to_json()
chall_response = challenges.DNSResponse() chall_response = challenges.DNSResponse()
@@ -302,7 +302,7 @@ class NetworkTest(unittest.TestCase):
self.net.retry_after(response=self.response, default=10)) self.net.retry_after(response=self.response, default=10))
def test_poll(self): def test_poll(self):
self.response.json.return_value = self.authzr.body.fully_serialize() self.response.json.return_value = self.authzr.body.to_json()
self._mock_post_get() self._mock_post_get()
self.assertEqual((self.authzr, self.response), self.assertEqual((self.authzr, self.response),
self.net.poll(self.authzr)) self.net.poll(self.authzr))