Skip to content

Commit

Permalink
Handle negative numbers
Browse files Browse the repository at this point in the history
Signed-off-by: Sunghyun Hwang <[email protected]>

#7
  • Loading branch information
0xd669 committed Oct 31, 2018
1 parent dce6f78 commit 17f4a1c
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
12 changes: 10 additions & 2 deletions kformat/kproperty.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,17 @@ def __init__(
)

def to_bytes(self, v: Optional) -> bytes:
s = str(int(v)) if v is not None else ''
try:
b = bytes(s, encoding=N.ENCODING).rjust(self.length, self.filler)
p = b'-' if v < 0 else b''
s = str(int(abs(v)))
except TypeError:
p, s = b'', ''

try:
b = p + bytes(s, encoding=N.ENCODING).rjust(
self.length - len(p),
self.filler
)
assert len(b) <= self.length
return b
except AssertionError:
Expand Down
2 changes: 1 addition & 1 deletion tests/test_kclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ class Something:
sth = Something(
123,
'k-class',
Other(456, 'subclass'),
Other(-456, 'subclass'),
[],
None
)
Expand Down
15 changes: 15 additions & 0 deletions tests/test_kproperty.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,29 @@ def test_N_to_bytes(self):
N(5).to_bytes(12345),
b'12345'
)
self.assertEqual(
N(5).to_bytes(-1),
b'-0001'
)
self.assertEqual(
N(3).to_bytes(-12),
b'-12'
)
self.assertEqual(
N(10, filler=b'?').to_bytes(3),
b'?????????3'
)
self.assertEqual(
N(5, filler=b'-').to_bytes(3),
b'----3'
)

with self.assertRaises(ValueError):
N(3).to_bytes(1234)

with self.assertRaises(ValueError):
N(2).to_bytes(-10)

def test_AN_to_bytes(self):
self.assertEqual(
AN(10).to_bytes('sunghyunzz'),
Expand Down

0 comments on commit 17f4a1c

Please sign in to comment.