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