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 15import unittest 16from rsa.transform import int2bytes, bytes2int 17 18 19class Test_int2bytes(unittest.TestCase): 20 def test_accuracy(self): 21 self.assertEqual(int2bytes(123456789), b'\x07[\xcd\x15') 22 23 def test_codec_identity(self): 24 self.assertEqual(bytes2int(int2bytes(123456789, 128)), 123456789) 25 26 def test_chunk_size(self): 27 self.assertEqual(int2bytes(123456789, 6), b'\x00\x00\x07[\xcd\x15') 28 self.assertEqual(int2bytes(123456789, 7), 29 b'\x00\x00\x00\x07[\xcd\x15') 30 31 def test_zero(self): 32 self.assertEqual(int2bytes(0, 4), b'\x00' * 4) 33 self.assertEqual(int2bytes(0, 7), b'\x00' * 7) 34 self.assertEqual(int2bytes(0), b'\x00') 35 36 def test_correctness_against_base_implementation(self): 37 # Slow test. 38 values = [ 39 1 << 512, 40 1 << 8192, 41 1 << 77, 42 ] 43 for value in values: 44 self.assertEqual(bytes2int(int2bytes(value)), 45 value, 46 "Boom %d" % value) 47 48 def test_raises_OverflowError_when_chunk_size_is_insufficient(self): 49 self.assertRaises(OverflowError, int2bytes, 123456789, 3) 50 self.assertRaises(OverflowError, int2bytes, 299999999999, 4) 51 52 def test_raises_ValueError_when_negative_integer(self): 53 self.assertRaises(ValueError, int2bytes, -1) 54 55 def test_raises_TypeError_when_not_integer(self): 56 self.assertRaises(TypeError, int2bytes, None) 57