Source

tracko / tests / test_biginteger.py

Full commit
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '../app'))

from biginteger import BigIntegerProperty
from nose.tools import *


def test_encoding_and_decoding():

  cases = [
    (8, 1, u'p\x01'),
    (16, 1, u'p\x00\x01'),
    (16, 256, u'p\x01\x00'),
    (20, 0x80, u'p\x00\x00\x80'), # 20 is rounded up to 3*8=24
    (10, -9, u'n\xff\xf7'), # negative values represented as (max + 1 - n),
    (8, 0x7f, u'p\x7f'),
    (8, -1, u'n\xff'),
    ]

  def check_encoding(n_bits, n, encoded_n):
    assert_equals(BigIntegerProperty(n_bits=n_bits).encode(n), encoded_n)

  def check_decoding(n_bits, n, encoded_n):
    assert_equals(BigIntegerProperty(n_bits=n_bits).decode(encoded_n), n)

  def check_round_trip(n_bits, n):
    p = BigIntegerProperty(n_bits=n_bits)
    assert_equals(p.decode(p.encode(n)), n)

  def check_serialized_value_is_compatible_with_larger_bigint(n_bits, n):
    e = BigIntegerProperty(n_bits=n_bits).encode(n)
    assert_equals(BigIntegerProperty(n_bits=n_bits*2).decode(e), n)

  for n_bits, n, encoded_n in cases:
    yield check_encoding, n_bits, n, encoded_n
    yield check_decoding, n_bits, n, encoded_n
    yield check_round_trip, n_bits, n
    yield check_serialized_value_is_compatible_with_larger_bigint, n_bits, n


def test_error_is_raised_on_encoding_too_large_value():
  assert_raises(
    ValueError, BigIntegerProperty(n_bits=8).encode, 2**8)


def test_error_is_raised_on_decoding_too_large_value():
  assert_raises(
    ValueError, BigIntegerProperty(n_bits=8).decode, u'p\x01\x00')


def test_sort_order_of_encoded_values_matches_order_of_raw_values():
  raw_values = [1, 3, -10, 28, 0, 2, 0, 1256, -1256]
  encode = BigIntegerProperty(n_bits=32).encode
  pairs = [(raw, encode(raw)) for raw in raw_values]
  assert_equals(
    sorted(pairs, key=lambda p: p[0]),
    sorted(pairs, key=lambda p: p[1]))