源码: converts.py
# -.- coding:utf-8 -.-
import unittest
class ComplexConverts(object):
def __init__(self):
self.func_maps = {
"binary": self.binary,
"octal": self.octal,
"decimal": self.decimal,
"hexadecimal": self.hexadecimal
}
def all(self, value):
keys = self.detect(value)
result = {}
if keys:
integer = keys[0][1]
for k, func in self.func_maps.items():
result.update({k: func(integer)})
return result
def detect_and_convert(self, value):
keys = self.detect(value)
return {i: self.func_maps[i[0]](i[1]) for i in keys}
@classmethod
def detect(cls, value):
"""
检测思路
:return: [('binary'|'octal'|'decimal'|'hexadecimal', integer)]
"""
result = []
err_msg = u"仅支持数字或进制字符监测."
if not isinstance(value, (int, str)):
raise RuntimeError(err_msg)
hexadecimal = cls._detect_hexadecimal(value)
if hexadecimal:
result.append(hexadecimal)
decimal = cls._detect_decimal(value)
if decimal:
result.append(decimal)
octal = cls._detect_octal(value)
if octal:
result.append(octal)
binary = cls._detect_binary(value)
if binary:
result.append(binary)
return result
@classmethod
def _detect_binary(cls, value):
if isinstance(value, str):
value = value.lower()
allowed = ("0", "1", "b")
error = [i for i in value if i not in allowed]
if error:
return False
if "b" in value and not value.startswith("0b"):
return False
value = int(value, 2)
return "binary", value
@classmethod
def _detect_octal(cls, value):
if isinstance(value, str):
allowed = ("0", "1", "2", "3", "4", "5", "6", "7")
error = [i for i in value if i not in allowed]
if error:
return False
value = int(value, 8)
return "octal", value
@classmethod
def _detect_decimal(cls, value):
if isinstance(value, str):
if not value.isdigit():
return False
value = int(value, 10)
return "decimal", value
@classmethod
def _detect_hexadecimal(cls, value):
result = "hexadecimal"
if isinstance(value, str):
value = value.lower()
allowed = ("0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "a", "b", "c", "d", "e", "f",
"x")
error = [i for i in value if i not in allowed]
if error:
return False
if value.startswith("0x"):
value = int(value, 16)
return result, value
elif value.isdigit():
value = int(value, 16)
return result, value
else:
return False
return result, value
@classmethod
def binary(cls, value):
return bin(value)
@classmethod
def octal(cls, value):
return oct(value)
@classmethod
def decimal(cls, value):
return int(value)
@classmethod
def hexadecimal(cls, value):
return hex(value)
class TestComplexConverts(unittest.TestCase):
def setUp(self):
self.cc = ComplexConverts()
def test_detect_binary(self):
s = self.cc.detect("0b11111111")
self.assertEqual(s, [("binary", 255)])
def test_detect_hexadecimal(self):
s = self.cc.detect("0xaf")
self.assertEqual(s, [("hexadecimal", 175)])
def test_detect_multi_type(self):
s = self.cc.detect("6")
self.assertEqual(sorted(s),
sorted([("octal", 6),
("decimal", 6),
("hexadecimal", 6)]))
def test_convert_all(self):
value = "6"
s = self.cc.all(value)
self.assertEqual(s, {'octal': oct(int(value)),
'binary': bin(int(value)),
'decimal': int(value),
'hexadecimal': hex(int(value))})
value = "0xaf"
s = self.cc.all(value)
self.assertEqual(s, {'octal': oct(int(value, 16)),
'binary': bin(int(value, 16)),
'decimal': int(value, 16),
'hexadecimal': hex(int(value, 16))})
value = "0b11101010"
s = self.cc.all(value)
self.assertEqual(s, {'octal': oct(int(value, 2)),
'binary': bin(int(value, 2)),
'decimal': int(value, 2),
'hexadecimal': hex(int(value, 2))})
测试: main.py
import unittest
TEST_MODULE = [
"converts",
]
if __name__ == '__main__':
suite = unittest.defaultTestLoader.loadTestsFromNames(TEST_MODULE)
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)