diff --git a/kformat/kproperty.py b/kformat/kproperty.py index 9ac915c..dda9d1e 100644 --- a/kformat/kproperty.py +++ b/kformat/kproperty.py @@ -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: diff --git a/tests/test_kclass.py b/tests/test_kclass.py index 15bd64f..42c74ce 100644 --- a/tests/test_kclass.py +++ b/tests/test_kclass.py @@ -25,7 +25,7 @@ class Something: sth = Something( 123, 'k-class', - Other(456, 'subclass'), + Other(-456, 'subclass'), [], None ) diff --git a/tests/test_kproperty.py b/tests/test_kproperty.py index 2114643..e4fdbbb 100644 --- a/tests/test_kproperty.py +++ b/tests/test_kproperty.py @@ -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'),