test_transform.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # https://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import unittest
  15. from rsa.transform import int2bytes, bytes2int
  16. class Test_int2bytes(unittest.TestCase):
  17. def test_accuracy(self):
  18. self.assertEqual(int2bytes(123456789), b"\x07[\xcd\x15")
  19. def test_codec_identity(self):
  20. self.assertEqual(bytes2int(int2bytes(123456789, 128)), 123456789)
  21. def test_chunk_size(self):
  22. self.assertEqual(int2bytes(123456789, 6), b"\x00\x00\x07[\xcd\x15")
  23. self.assertEqual(int2bytes(123456789, 7), b"\x00\x00\x00\x07[\xcd\x15")
  24. def test_zero(self):
  25. self.assertEqual(int2bytes(0, 4), b"\x00" * 4)
  26. self.assertEqual(int2bytes(0, 7), b"\x00" * 7)
  27. self.assertEqual(int2bytes(0), b"\x00")
  28. def test_correctness_against_base_implementation(self):
  29. # Slow test.
  30. values = [
  31. 1 << 512,
  32. 1 << 8192,
  33. 1 << 77,
  34. ]
  35. for value in values:
  36. self.assertEqual(bytes2int(int2bytes(value)), value, "Boom %d" % value)
  37. def test_raises_OverflowError_when_chunk_size_is_insufficient(self):
  38. self.assertRaises(OverflowError, int2bytes, 123456789, 3)
  39. self.assertRaises(OverflowError, int2bytes, 299999999999, 4)
  40. def test_raises_ValueError_when_negative_integer(self):
  41. self.assertRaises(ValueError, int2bytes, -1)
  42. def test_raises_TypeError_when_not_integer(self):
  43. self.assertRaises(TypeError, int2bytes, None)