Skip to content

Commit 5949729

Browse files
committed
Changed name of Binary type to Bytes.
Test Plan: Updated tests. Reviewers: qiming, krieb
1 parent e3d1c4a commit 5949729

File tree

10 files changed

+55
-34
lines changed

10 files changed

+55
-34
lines changed

babelapi/babel/tower.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111
DeprecationInfo,
1212
)
1313
from ..data_type import (
14-
Binary,
1514
Boolean,
15+
Bytes,
1616
CompositeType,
1717
DataType,
1818
Float32,
@@ -68,7 +68,7 @@ class Environment(dict):
6868
class TowerOfBabel(object):
6969

7070
data_types = [
71-
Binary,
71+
Bytes,
7272
Boolean,
7373
Float32,
7474
Float64,

babelapi/data_type.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -134,15 +134,15 @@ def check_example(self, ex_field):
134134
ex_field.lineno, ex_field.path)
135135

136136

137-
class Binary(PrimitiveType):
137+
class Bytes(PrimitiveType):
138138

139139
def check(self, val):
140140
if not isinstance(val, str):
141-
raise ValueError('%r is not valid binary (Python str)' % val)
141+
raise ValueError('%r is not valid bytes' % val)
142142

143143
def check_example(self, ex_field):
144144
if not isinstance(ex_field.value, bytes):
145-
raise InvalidSpec("'%s' is not valid binary",
145+
raise InvalidSpec("'%s' is not valid bytes",
146146
ex_field.lineno, ex_field.path)
147147

148148

@@ -1405,8 +1405,8 @@ def get_underlying_type(data_type):
14051405
return unwrap_nullable(data_type)
14061406

14071407

1408-
def is_binary_type(data_type):
1409-
return isinstance(data_type, Binary)
1408+
def is_bytes_type(data_type):
1409+
return isinstance(data_type, Bytes)
14101410
def is_boolean_type(data_type):
14111411
return isinstance(data_type, Boolean)
14121412
def is_composite_type(data_type):

doc/generator_ref.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,7 @@ default
264264
========================== ============ ============
265265
Primitive Python 2.x Python 3.x
266266
========================== ============ ============
267-
Binary str bytes
267+
Bytes str bytes
268268
Boolean bool bool
269269
Float{32,64} float float
270270
Int{32,64}, UInt{32,64} long int

doc/json_serializer.rst

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ Primitive Types
1212
========================== ====================================================
1313
Babel Primitive JSON Representation
1414
========================== ====================================================
15-
Binary String: Base64-encoded
1615
Boolean Boolean
16+
Bytes String: Base64-encoded
1717
Float{32,64} Number
1818
Int{32,64}, UInt{32,64} Number
1919
List Array

doc/lang_ref.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ table of all primitive types and the arguments they take:
106106
Type Arguments (**bold** are required Notes
107107
and positional)
108108
======================= ================================= =====================
109-
Binary -- An array of bytes.
109+
Bytes -- An array of bytes.
110110
Boolean --
111111
Float{32,64} * min_value
112112
* max_value
@@ -152,7 +152,7 @@ Here are some more examples::
152152
y Int64
153153

154154
struct Example
155-
f1 Binary
155+
f1 Bytes
156156
f2 Boolean
157157
f3 Float64(min_value=0)
158158
# List of primitive types
@@ -754,7 +754,7 @@ Type Reference::
754754

755755
Primitives::
756756

757-
PrimitiveType ::= 'Binary' | 'Boolean' | 'Float32' | 'Float64' | 'Int32'
757+
PrimitiveType ::= 'Bytes' | 'Boolean' | 'Float32' | 'Float64' | 'Int32'
758758
| 'Int64' | 'UInt32' | 'UInt64' | 'String' | 'Timestamp'
759759

760760
Basic::

doc/using_generator.rst

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -93,17 +93,17 @@ Primitive Types
9393
The following table shows the mapping between a Babel `primitive type
9494
<lang_ref.rst#primitive-types>`_ and its corresponding type in Python.
9595

96-
========================== ============ =======================================
97-
Primitive Python 2.x Notes
98-
========================== ============ =======================================
99-
Binary str
96+
========================== ============== =====================================
97+
Primitive Python 2.x / 3 Notes
98+
========================== ============== =====================================
99+
Bytes bytes
100100
Boolean bool
101-
Float{32,64} float long type within range is converted.
101+
Float{32,64} float long type within range is converted.
102102
Int{32,64}, UInt{32,64} long
103103
List list
104-
String unicode str type is converted to unicode.
104+
String unicode / str str type is converted to unicode.
105105
Timestamp datetime
106-
========================== ============ =======================================
106+
========================== ============== =====================================
107107

108108
Struct
109109
------

generator/python/babel_serializers.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ def _make_json_friendly(data_type, val):
259259
return None
260260
elif isinstance(data_type, bv.Timestamp):
261261
return val.strftime(data_type.format)
262-
elif isinstance(data_type, bv.Binary):
262+
elif isinstance(data_type, bv.Bytes):
263263
return base64.b64encode(val).decode('ascii')
264264
elif isinstance(data_type, bv.Integer) and isinstance(val, bool):
265265
# A bool is a subclass of an int so it passes Integer validation. But,
@@ -286,7 +286,7 @@ def json_decode(data_type, serialized_obj, strict=True, old_style=False):
286286
287287
Returns:
288288
The returned object depends on the input data_type.
289-
- Binary -> bytes
289+
- Bytes -> bytes
290290
- Boolean -> bool
291291
- Float -> float
292292
- Integer -> long
@@ -612,11 +612,11 @@ def _make_babel_friendly(data_type, val, strict, validate):
612612
return datetime.datetime.strptime(val, data_type.format)
613613
except ValueError as e:
614614
raise bv.ValidationError(e.args[0])
615-
elif isinstance(data_type, bv.Binary):
615+
elif isinstance(data_type, bv.Bytes):
616616
try:
617617
return base64.b64decode(val)
618618
except TypeError:
619-
raise bv.ValidationError('invalid base64-encoded binary')
619+
raise bv.ValidationError('invalid base64-encoded bytes')
620620
elif isinstance(data_type, bv.Void):
621621
if strict and val is not None:
622622
raise bv.ValidationError("expected null, got value")

generator/python/babel_validators.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
else:
2525
_binary_types = (bytes, buffer)
2626

27+
2728
class ValidationError(Exception):
2829
"""Raised when a value doesn't pass validation by its validator."""
2930

@@ -63,6 +64,7 @@ def __repr__(self):
6364
# Not a perfect repr, but includes the error location information.
6465
return 'ValidationError(%r)' % str(self)
6566

67+
6668
def generic_type_name(v):
6769
"""Return a descriptive type name that isn't Python specific. For example,
6870
an int value will return 'integer' rather than 'int'."""
@@ -80,6 +82,7 @@ def generic_type_name(v):
8082
else:
8183
return type(v).__name__
8284

85+
8386
class Validator(object):
8487
"""All primitive and composite data types should be a subclass of this."""
8588
__metaclass__ = ABCMeta
@@ -99,17 +102,20 @@ def has_default(self):
99102
def get_default(self):
100103
raise AssertionError('No default available.')
101104

105+
102106
class Primitive(Validator):
103107
"""A basic type that is defined by Babel."""
104108
pass
105109

110+
106111
class Boolean(Primitive):
107112

108113
def validate(self, val):
109114
if not isinstance(val, bool):
110115
raise ValidationError('%r is not a valid boolean' % val)
111116
return val
112117

118+
113119
class Integer(Primitive):
114120
"""
115121
Do not use this class directly. Extend it and specify a 'minimum' and
@@ -150,22 +156,27 @@ def validate(self, val):
150156
def __repr__(self):
151157
return '%s()' % self.__class__.__name__
152158

159+
153160
class Int32(Integer):
154161
minimum = -2**31
155162
maximum = 2**31 - 1
156163

164+
157165
class UInt32(Integer):
158166
minimum = 0
159167
maximum = 2**32 - 1
160168

169+
161170
class Int64(Integer):
162171
minimum = -2**63
163172
maximum = 2**63 - 1
164173

174+
165175
class UInt64(Integer):
166176
minimum = 0
167177
maximum = 2**64 - 1
168178

179+
169180
class Real(Primitive):
170181
"""
171182
Do not use this class directly. Extend it and optionally set a 'minimum'
@@ -231,14 +242,17 @@ def validate(self, val):
231242
def __repr__(self):
232243
return '%s()' % self.__class__.__name__
233244

245+
234246
class Float32(Real):
235247
# Maximum and minimums from the IEEE 754-1985 standard
236248
minimum = -3.40282 * 10**38
237249
maximum = 3.40282 * 10**38
238250

251+
239252
class Float64(Real):
240253
pass
241254

255+
242256
class String(Primitive):
243257
"""Represents a unicode string."""
244258

@@ -296,7 +310,8 @@ def validate(self, val):
296310
% (val, self.pattern))
297311
return val
298312

299-
class Binary(Primitive):
313+
314+
class Bytes(Primitive):
300315

301316
def __init__(self, min_length=None, max_length=None):
302317
if min_length is not None:
@@ -315,7 +330,7 @@ def __init__(self, min_length=None, max_length=None):
315330

316331
def validate(self, val):
317332
if not isinstance(val, _binary_types):
318-
raise ValidationError("expected binary type, got %s"
333+
raise ValidationError("expected bytes type, got %s"
319334
% generic_type_name(val))
320335
elif self.max_length is not None and len(val) > self.max_length:
321336
raise ValidationError("'%s' must have at most %d bytes, got %d"
@@ -325,6 +340,7 @@ def validate(self, val):
325340
% (val, self.min_length, len(val)))
326341
return val
327342

343+
328344
class Timestamp(Primitive):
329345
"""Note that while a format is specified, it isn't used in validation
330346
since a native Python datetime object is preferred. The format, however,
@@ -446,6 +462,7 @@ def get_default(self):
446462
assert not self.definition._has_required_fields, 'No default available.'
447463
return self.definition()
448464

465+
449466
class StructTree(Struct):
450467
"""Validator for structs with enumerated subtypes.
451468
@@ -456,6 +473,7 @@ class StructTree(Struct):
456473
def __init__(self, definition):
457474
super(StructTree, self).__init__(definition)
458475

476+
459477
class Union(Composite):
460478

461479
def __init__(self, definition):
@@ -498,6 +516,7 @@ def validate_type_only(self, val):
498516
raise ValidationError('expected type %s or subtype, got %s' %
499517
(self.definition.__name__, generic_type_name(val)))
500518

519+
501520
class Void(Primitive):
502521

503522
def validate(self, val):
@@ -511,6 +530,7 @@ def has_default(self):
511530
def get_default(self):
512531
return None
513532

533+
514534
class Nullable(Validator):
515535

516536
def __init__(self, validator):

generator/python/python.babelg.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@
1010
import shutil
1111
from babelapi.data_type import (
1212
get_underlying_type,
13-
is_binary_type,
1413
is_boolean_type,
14+
is_bytes_type,
1515
is_composite_type,
1616
is_float_type,
1717
is_integer_type,
@@ -164,8 +164,8 @@ def _python_type_mapping(self, ns, data_type):
164164
for documentation purposes."""
165165
if is_string_type(data_type):
166166
return 'str'
167-
elif is_binary_type(data_type):
168-
return 'str'
167+
elif is_bytes_type(data_type):
168+
return 'bytes'
169169
elif is_boolean_type(data_type):
170170
return 'bool'
171171
elif is_float_type(data_type):

generator/python/test_python_gen.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
json_decode,
2121
)
2222

23+
2324
class TestDropInModules(unittest.TestCase):
2425
"""
2526
Tests the babel_serializers and babel_validators modules.
@@ -103,8 +104,8 @@ def test_float_validator(self):
103104
# Passes
104105
f32.validate(0)
105106

106-
def test_binary_validator(self):
107-
b = bv.Binary(min_length=1, max_length=10)
107+
def test_bytes_validator(self):
108+
b = bv.Bytes(min_length=1, max_length=10)
108109
# Not a valid binary type
109110
self.assertRaises(bv.ValidationError, lambda: b.validate(u'asdf'))
110111
# Too short
@@ -195,7 +196,7 @@ def test_json_encoder(self):
195196
self.assertEqual(json_encode(bv.Timestamp('%a, %d %b %Y %H:%M:%S +0000'), now),
196197
json.dumps(now.strftime(f)))
197198
b = b'\xff' * 5
198-
self.assertEqual(json_encode(bv.Binary(), b),
199+
self.assertEqual(json_encode(bv.Bytes(), b),
199200
json.dumps(base64.b64encode(b).decode('ascii')))
200201
self.assertEqual(json_encode(bv.Nullable(bv.String()), None), json.dumps(None))
201202
self.assertEqual(json_encode(bv.Nullable(bv.String()), u'abc'), json.dumps('abc'))
@@ -339,11 +340,11 @@ def test_json_decoder(self):
339340
json.dumps(now.strftime(f))),
340341
now)
341342
b = b'\xff' * 5
342-
self.assertEqual(json_decode(bv.Binary(),
343+
self.assertEqual(json_decode(bv.Bytes(),
343344
json.dumps(base64.b64encode(b).decode('ascii'))),
344345
b)
345346
self.assertRaises(bv.ValidationError,
346-
lambda: json_decode(bv.Binary(), json.dumps(1)))
347+
lambda: json_decode(bv.Bytes(), json.dumps(1)))
347348
self.assertEqual(json_decode(bv.Nullable(bv.String()), json.dumps(None)), None)
348349
self.assertEqual(json_decode(bv.Nullable(bv.String()), json.dumps('abc')), 'abc')
349350

@@ -521,7 +522,7 @@ def get_t(self):
521522
b Int64
522523
523524
struct B extends A
524-
c Binary
525+
c Bytes
525526
526527
struct C extends B
527528
d Float64

0 commit comments

Comments
 (0)