def get_codes(s: Union[str, 'ChainedBase']) -> List[str]:
def get_code_indices(s: Union[str, 'ChainedBase']) -> Dict[int, str]:
def get_indices(s: Union[str, 'ChainedBase']) -> Dict[int, str]:
def get_indices_list(s: Union[str, 'ChainedBase']) -> List[str]:
def is_escape_code(s: Union[str, 'ChainedBase']) -> bool:
def strip_codes(s: Union[str, 'ChainedBase']) -> str:
    def __init__(self, text=None):
    def __add__(self, other):
    def __bool__(self):
    def __bytes__(self):
    def __call__(self, text):
    def __eq__(self, other):
    def __format__(self, fmt):
    def __getitem__(self, key):
        def is_out_of_bounds():
    def __hash__(self):
    def __iter__(self):
    def __len__(self):
    def __lt__(self, other):
    def __mul__(self, n):
    def __radd__(self, other):
    def __rmul__(self, n):
    def __repr__(self):
    def __str__(self):
    def _str_just(
            self, methodname, width, fillchar=' ', squeeze=False,
            **colorkwargs):
    def _str_strip(self, methodname, chars=None):
        def strip_parts(method, indexes):
    def append(self, char, length=1):
    def center(self, width, fillchar=' ', squeeze=False, **kwargs):
    def chained(self, data):
    def copy(self):
    def indent(self, length, char=' '):
    def index(self, sub, start=None, end=None):
    def iter_parts(self, text=None):
    def join(self, *args, **colorkwargs):
    def ljust(self, width, fillchar=' ', squeeze=False, **kwargs):
    def lstrip(self, chars=None):
    def parts(self, text=None):
    def prepend(self, char, length=1):
    def rjust(self, width, fillchar=' ', squeeze=False, **kwargs):
    def rstrip(self, chars=None):
    def str(self):
    def strip(self, chars=None):
    def stripped(self):
    def write(self, file=sys.stdout, end='', delay=None):
    def __init__(self, originstr, start=None, stop=None):
    def __eq__(self, other):
    def __hash__(self):
    def __repr__(self):
    def __str__(self):
    def get_slice(self):
    def is_code(self):
    def is_text(self):
    def is_code(self):
    def is_text(self):
    def is_code(self):
    def is_text(self):
class ChainedBase(Sequence):
class ChainedPart(object):
class CodePart(ChainedPart):
class TextPart(ChainedPart): class ColorCode(object):
    """ A color code value that automatically converts from/to hex, term, rgb.
        Initialize with a hex str, code str/int, or rgb tuple/list/generator,
        and the other codes are automatically generated and made available
        through the attributes:
            code   : Terminal code number as a string.
            hexval : Nearest matching hex value.
            rgb    : Tuple of nearest matching (Red, Green, Blue) values.
    """
    __slots__ = ('code', 'hexval', 'rgb', 'rgb_mode', 'name')

    def __init__(
            self,
            code: Optional[Any] = None,
            rgb_mode: Optional[bool] = False) -> None:
        self.rgb = (0, 0, 0)  # type: RGB
        self.hexval = None  # type: Optional[str]
        self.code = None  # type: Optional[str]
        self.name = None  # type: Optional[str]
        self.rgb_mode = rgb_mode  # type: Optional[bool]
        # Init tries to be smart about converting code types.
        typeerrmsg = 'Expecting hex, term-code, or rgb. Got: {}'.format(
            getattr(code, '__name__', type(code).__name__)
        )
        if isinstance(code, (list, tuple, GeneratorType)):
            try:
                # cast is only needed to satisfy mypy. 'code' would work fine.
                r, g, b = cast(RGB, code)
            except ValueError:
                raise TypeError(typeerrmsg)
            self._init_rgb(r, g, b)
        elif isinstance(code, str):
            code = code.lower().strip()
            if (code in code_nums['fore']) or (code in name_data):
                self._init_name(code)
            else:
                try:
                    # Try hex str.
                    rgb = hex2rgb(code)
                    self._init_rgb(*rgb)
                except (TypeError, ValueError):
                    # Int as str.
                    try:
                        termcode = int(code)
                    except (TypeError, ValueError):
                        # Must be hex value.
                        self._init_hex(code)
                    else:
                        # Term code was passed by str.
                        self._init_code(termcode)
        elif isinstance(code, int):
            # Term code was passed.
            self._init_code(code)
        else:
            raise TypeError(typeerrmsg)

    def __format__(self, fmt: str) -> str:
        """ Pass on any format calls to str(self). """
        return format(str(self), fmt)

    def __str__(self) -> str:
        """ A console friendly representation. """
        return ', '.join((
            'Terminal: {s.code:>3}',
            'Hex: {s.hexval:<6}',
            'RGB: {rgb}'
        )).format(s=self, rgb=', '.join('{:>3}'.format(i) for i in self.rgb))

    def _init_code(self, code: int) -> None:
        """ Initialize from an int terminal code. """
        if -1 < code < 256:
            self.code = '{:02}'.format(code)
            self.hexval = term2hex(code)
            self.rgb = hex2rgb(self.hexval or '')
            self.name = self.get_name_by_code(self.code)
        else:
            raise ValueError(' '.join((
                'Code must be in the range 0-255, inclusive.',
                'Got: {} ({})'
            )).format(code, getattr(code, '__name__', type(code).__name__)))

    def _init_hex(self, hexval: str) -> None:
        """ Initialize from a hex value string. """
        self.hexval = hex2termhex(fix_hex(hexval))
        self.code = hex2term(self.hexval)
        self.rgb = hex2rgb(self.hexval)
        self.name = self.get_name_by_code(self.code)

    def _init_name(self, name: str) -> None:
        """ Initialize from a known name. """
        if name.isalpha() and (name in code_nums['fore']):
            self.code = '{:>02}'.format(code_nums['fore'][name] - 30)
            self.hexval = term2hex(self.code)
            self.rgb = hex2rgb(self.hexval or '')
            self.name = name
        elif name in name_data:
            self.code = name_data[name]['code']
            self.hexval = name_data[name]['hexval']
            self.rgb = name_data[name]['rgb']
            self.name = name
        else:
            raise ValueError('Not a known color name: {}'.format(name))

    def _init_rgb(self, r: int, g: int, b: int) -> None:
        """ Initialize from red, green, blue args. """
        if self.rgb_mode:
            self.rgb = (r, g, b)
            self.hexval = rgb2hex(r, g, b)
        else:
            self.rgb = hex2rgb(rgb2termhex(r, g, b))
            self.hexval = rgb2termhex(r, g, b)

        self.code = hex2term(self.hexval)
        self.name = self.get_name_by_code(self.code)

    def example(self) -> str:
        """ Same as str(self), except the color codes are actually used. """
        if self.rgb_mode:
            colorcode = '\033[38;2;{};{};{}m'.format(*self.rgb)
        else:
            colorcode = '\033[38;5;{}m'.format(self.code)
        return '{code}{s}{name}\033[0m'.format(
            code=colorcode,
            name=', Name: {}'.format(self.name) if self.name else '',
            s=self,
        )

    @classmethod
    def from_code(cls, code: int) -> 'ColorCode':
        """ Return a ColorCode from a terminal code. """
        c = cls()
        c._init_code(code)
        return c

    @classmethod
    def from_hex(cls, hexval: str) -> 'ColorCode':
        """ Return a ColorCode from a hex string. """
        c = cls()
        c._init_hex(hexval)
        return c

    @classmethod
    def from_name(cls, name: str) -> 'ColorCode':
        """ Return a ColorCode from a known name. """
        c = cls()
        c._init_name(name)
        return c

    @classmethod
    def from_rgb(cls, r: int, g: int, b: int) -> 'ColorCode':
        """ Return a ColorCode from a RGB tuple. """
        c = cls()
        c._init_rgb(r, g, b)
        return c

    @staticmethod
    def get_name_by_code(code: str) -> Optional[str]:
        coden = int(code)
        # Test basic fore code (30-37, 90-97).
        if coden < 8:
            coden += 30
            name = code_nums_reverse['fore'].get(coden, None)
            if name is not None:
                return name
        # Test extended code.
        name = code_nums_reverse['fore_ext'].get(coden, None)
        if name is not None:
            return name

        for name, nameinfo in name_data.items():
            if str(nameinfo['code']) == code:
                return name
        return None

    def to_dict(self) -> dict:
        """ Return a dict of code, hexval, and rgb values. """
        return {'code': self.code, 'hexval': self.hexval, 'rgb': self.rgb} def fix_hex(hexval: str) -> str:
    hexval = hexval.strip().lstrip('#').lower()
    hexlen = len(hexval)
    if hexlen == 3:
        rgbvals = {'r': hexval[0], 'g': hexval[1], 'b': hexval[2], }
        hexval = '{r}{r}{g}{g}{b}{b}'.format(**rgbvals)
    elif hexlen != 6:
        raise ValueError(
            'Not a length 3 or 6 hex string (#RGB, #RRGGBB), got: {}'.format(
                hexval))
    return hexval def hex2rgb(hexval: str, allow_short: bool = False) -> RGB:
    """ Return a tuple of (R, G, B) from a hex color. """
    if not hexval:
        raise ValueError(
            'Expecting hex string (#RGB, #RRGGBB), got nothing: {!r}'.format(
                hexval
            )
        )
    try:
        hexval = hexval.strip().lstrip('#')
    except AttributeError:
        raise ValueError(
            'Expecting hex string (#RGB, #RRGGBB), got: ({}) {!r}'.format(
                type(hexval).__name__,
                hexval
            )
        )
    if allow_short:
        hexval = fix_hex(hexval)
    if not len(hexval) == 6:
        raise ValueError(
            'Not a length 3 or 6 hex string (#RGB, #RRGGBB), got: {}'.format(
                hexval
            )
        )
    try:
        val = tuple(
            int(''.join(hexval[i:i + 2]), 16)
            for i in range(0, len(hexval), 2)
        )
    except ValueError:
        # Bad hex string.
        raise ValueError('Invalid hex value: {}'.format(hexval))
    # Only needed to satisft typing. `return val` would work fine.
    r, g, b = val
    return r, g, b def hex2term(hexval: str, allow_short: bool = False) -> str:
    """ Convert a hex value into the nearest terminal code number. """
    return rgb2term(*hex2rgb(hexval, allow_short=allow_short)) def hex2termhex(hexval: str, allow_short: bool = False) -> str:
    """ Convert a hex value into the nearest terminal color matched hex. """
    return rgb2termhex(*hex2rgb(hexval, allow_short=allow_short)) def is_code(s: str) -> bool:
    """ Returns True if `s` appears to be a single basic escape code. """
    return re.match('^\033\\[\\d{1,2}m$', s) is not None def is_ext_code(s: str) -> bool:
    """ Returns True if `s` appears to be a single extended 256 escape code.
    """
    return re.match('^\033\\[((38)|(48));5;\\d{1,3}m$', s) is not None def is_rgb_code(s: str) -> bool:
    """ Returns True if `s` appears to be a single rgb escape code. """
    pattern = '^\033\\[((38)|(48));2;\\d{1,3};\\d{1,3};\\d{1,3}m'
    return re.match(pattern, s) is not None def rgb2hex(r: int, g: int, b: int) -> str:
    """ Convert rgb values to a hex code. """
    return '{:02x}{:02x}{:02x}'.format(r, g, b) def rgb2term(r: int, g: int, b: int) -> str:
    """ Convert an rgb value to a terminal code. """
    return hex2term_map[rgb2termhex(r, g, b)] def rgb2termhex(r: int, g: int, b: int) -> str:
    """ Convert an rgb value to the nearest hex value that matches a term code.
        The hex value will be one in `hex2term_map`.
    """
    incs = [0x00, 0x5f, 0x87, 0xaf, 0xd7, 0xff]

    res = []
    parts = r, g, b
    for part in parts:
        if (part < 0) or (part > 255):
            raise ValueError(
                'Expecting 0-255 for RGB code, got: {!r}'.format(parts)
            )
        i = 0
        while i < len(incs) - 1:
            s, b = incs[i], incs[i + 1]  # smaller, bigger
            if s <= part <= b:
                s1 = abs(s - part)
                b1 = abs(b - part)
                if s1 < b1:
                    closest = s
                else:
                    closest = b
                res.append(closest)
                break
            i += 1

    # Convert back into nearest hex value.
    return rgb2hex(*res) def term2hex(code: Numeric, default: Optional[str] = None) -> Optional[str]:
    """ Convenience function for term2hex_map.get(code, None).
        Accepts strs or ints in the form of: 1, 01, 123.
        Returns `default` if the code is not found.
    """
    try:
        val = term2hex_map.get('{:02}'.format(int(code)), default)
    except ValueError:
        raise ValueError(
            'Expecting an int or number string, got: {} ({})'.format(
                code,
                getattr(code, '__name__', type(code).__name__)))
    return val def term2rgb(code: Numeric) -> RGB:
    """ Convert a terminal code to an rgb value. """
    return hex2rgb(term2hex(code) or '') class ColrTestCase(unittest.TestCase):
    # This is how many frames it takes to get back to the test method
    # that calls these assert methods.
    # It's for getting the calling test name when building messages.
    calling_test_level = 5

    def assertAlmostEqual(self, a, b, places=None, msg=None, delta=None):
        """ Like self.assertAlmostEqual, with a better message. """
        try:
            super().assertAlmostEqual(
                a,
                b,
                places=places,
                msg=msg,
                delta=delta,
            )
        except self.failureException:
            raise self.failureException(_equality_msg('!~', a, b, msg=msg))

    def assertAlmostNotEqual(self, a, b, places=None, msg=None, delta=None):
        """ Like self.assertAlmostNotEqual, with a better message. """
        try:
            super().assertAlmostNotEqual(
                a,
                b,
                places=places,
                msg=msg,
                delta=delta,
            )
        except self.failureException:
            raise self.failureException(_equality_msg('~', a, b, msg=msg))

    def assertCallDictEqual(
            self, a, b=NotSet, func=NotSet,
            args=None, kwargs=None,
            otherargs=None, otherkwargs=None, msg=None):
        self.assertUnitTestMethodEqual(
            super().assertDictEqual,
            a,
            b,
            func=func,
            args=args,
            kwargs=kwargs,
            otherargs=otherargs,
            otherkwargs=otherkwargs,
            msg=msg,
        )

    def assertCallEqual(
            self, a, b=NotSet, func=None,
            args=None, kwargs=None,
            otherargs=None, otherkwargs=None, msg=None):
        """ Like self.assertEqual, but includes the func call info. """
        a, b = self.fix_ab_args(a, b, func, args, kwargs)
        if a == b:
            return None
        callargs = args or []
        callkwargs = kwargs or {}
        raise self.failureException(
            call_msg(
                _equality_msg('!=', a, b, msg=msg),
                *callargs,
                **callkwargs,
                _call_func=func,
                _level=self.calling_test_level,
                _other_args=otherargs,
                _other_kwargs=otherkwargs,
                _op='!=',
            )
        )

    def assertCallFalse(
            self, val=NotSet, func=NotSet, args=None, kwargs=None, msg=None):
        """ Like self.assertFalse, but includes the func call info. """
        val = self.fix_val_arg(val, func, args, kwargs)
        if not val:
            return None
        callargs = args or []
        callkwargs = kwargs or {}
        raise self.failureException(
            call_msg(
                _equality_msg('!=', val, False, msg=msg),
                *callargs,
                **callkwargs,
                _call_func=func,
                _level=self.calling_test_level,
                _op='!=',
            )
        )

    def assertCallIsInstance(
            self, obj, cls, func=None,
            args=None, kwargs=None,
            otherargs=None, otherkwargs=None, msg=None):
        try:
            super().assertIsInstance(obj, cls, msg=msg)
        except self.failureException as ex:
            stdmsg = ex.args[0] if ex.args else None
            callargs = args or []
            callkwargs = kwargs or {}
            raise self.failureException(
                call_msg(
                    _equality_msg('is not', obj, cls, msg=stdmsg),
                    *callargs,
                    **callkwargs,
                    _other_args=otherargs,
                    _other_kwargs=otherkwargs,
                    _call_func=func,
                    _level=3,
                    _op='is not',
                )
            )

    def assertCallListEqual(
            self, a, b=NotSet, func=NotSet,
            args=None, kwargs=None,
            otherargs=None, otherkwargs=None, msg=None):
        self.assertUnitTestMethodEqual(
            super().assertListEqual,
            a,
            b,
            func=func,
            args=args,
            kwargs=kwargs,
            otherargs=otherargs,
            otherkwargs=otherkwargs,
            msg=msg,
        )

    def assertCallNotEqual(
            self, a, b=NotSet, func=NotSet,
            args=None, kwargs=None,
            otherargs=None, otherkwargs=None, msg=None):
        """ Like self.assertNotEqual, but includes the func call info. """
        a, b = self.fix_ab_args(a, b, func, args, kwargs)
        if a != b:
            return None

        callargs = args or []
        callkwargs = kwargs or {}
        raise self.failureException(
            call_msg(
                _equality_msg('==', a, b, msg=msg),
                *callargs,
                **callkwargs,
                _call_func=func,
                _level=self.calling_test_level,
                _other_args=otherargs,
                _other_kwargs=otherkwargs,
                _op='==',
            )
        )

    def assertCallRaises(
            self, exception, func=None, args=None, kwargs=None, msg=None):
        """ Like self.assertRaises, but includes the func call info. """
        # TODO: Make func(args, kwargs) callable by this method like the
        #       other assertCall* methods.
        context = ColrAssertRaisesContext(
            exception,
            self,
            func=func,
            args=args,
            kwargs=kwargs
        )
        return context.handle('assertCallRaises', [], {'msg': msg})

    def assertCallTrue(
            self, val=NotSet, func=NotSet, args=None, kwargs=None, msg=None):
        """ Like self.assertTrue, but includes the func call info. """
        val = self.fix_val_arg(val, func, args, kwargs)
        if val:
            return None
        callargs = args or []
        callkwargs = kwargs or {}
        raise self.failureException(
            call_msg(
                _equality_msg('!=', val, True, msg=msg),
                *callargs,
                **callkwargs,
                _call_func=func,
                _level=self.calling_test_level,
                _op='!=',
            )
        )

    def assertCallTupleEqual(
            self, a, b, func=None,
            args=None, kwargs=None,
            otherargs=None, otherkwargs=None, msg=None):

        self.assertUnitTestMethodEqual(
            super().assertTupleEqual,
            a,
            b,
            func=func,
            args=args,
            kwargs=kwargs,
            otherargs=otherargs,
            otherkwargs=otherkwargs,
            msg=msg,
        )

    def assertEqual(self, a, b, msg=None):
        if a == b:
            return None
        raise self.failureException(_equality_msg('!=', a, b, msg=msg))

    def assertGreater(self, a, b, msg=None):
        if a > b:
            return None
        raise self.failureException(_equality_msg('<=', a, b, msg=msg))

    def assertGreaterEqual(self, a, b, msg=None):
        if a >= b:
            return None
        raise self.failureException(_equality_msg('<', a, b, msg=msg))

    def assertLess(self, a, b, msg=None):
        if a < b:
            return None
        raise self.failureException(_equality_msg('>=', a, b, msg=msg))

    def assertLessEqual(self, a, b, msg=None):
        if a <= b:
            return None
        raise self.failureException(_equality_msg('>', a, b, msg=msg))

    def assertNotEqual(self, a, b, msg=None):
        if a != b:
            return None
        raise self.failureException(_equality_msg('==', a, b, msg=msg))

    def assertTupleEqual(self, a, b, msg=None):
        try:
            super().assertTupleEqual(a, b, msg=msg)
        except self.failureException as ex:
            stdmsg = ex.args[0] if ex.args else None
            raise self.failureException(
                _equality_msg('!=', a, b, msg=stdmsg)
            )

    def assertUnitTestMethodEqual(
            self, method, a, b=NotSet, func=NotSet,
            args=None, kwargs=None,
            otherargs=None, otherkwargs=None, msg=None):
        a, b = self.fix_ab_args(a, b, func, args, kwargs)

        try:
            method(a, b, msg=msg)
        except self.failureException as ex:
            stdmsg = None
            if ex.args:
                stdmsg = ex.args[0].rpartition(':')[-1]
            callargs = args or []
            callkwargs = kwargs or {}
            raise self.failureException(
                call_msg(
                    _equality_msg('!=', a, b, msg=stdmsg),
                    *callargs,
                    **callkwargs,
                    _other_args=otherargs,
                    _other_kwargs=otherkwargs,
                    _call_func=func,
                    _level=self.calling_test_level,
                    _op='!=',
                )
            )

    def call_msg(self, s, *args, **kwargs):
        """ Convenience method, a wrapper for `call_msg`. """
        kwargs.setdefault('_level', 4)
        with suppress(KeyError):
            kwargs.setdefault('_call_func', kwargs.pop('func'))
        return call_msg(s, *args, **kwargs)

    def fix_ab_args(self, a, b, func, args, kwargs):
        if b is NotSet:
            if not func:
                raise ValueError('Must supply `b` if not using `func`.')
            # User passed the expected result, compute the returned result.
            b = a
            a = func(*(args or []), **(kwargs or {}))
        return a, b

    def fix_val_arg(self, val, func, args, kwargs):
        if val is NotSet:
            if not func:
                raise ValueError('Must supply `val` if not using `func`.')
            val = func(*(args or []), **(kwargs or {}))
        return val
import sys
import unittest
from colr import (
    __version__,
)
from colr.trans import (
    ColorCode,
    fix_hex,
    hex2rgb,
    hex2term,
    hex2termhex,
    is_code,
    is_ext_code,
    is_rgb_code,
    rgb2hex,
    rgb2term,
    rgb2termhex,
    term2hex,
    term2rgb,
)
from .testing_tools import ColrTestCase
        # known conversions
        self.conversions = (
            {'code': '229', 'hexval': 'ffffaf', 'rgb': (255, 255, 175)},
            {'code': '146', 'hexval': 'afafd7', 'rgb': (175, 175, 215)},
            {'code': '188', 'hexval': 'd7d7d7', 'rgb': (215, 215, 215)},
        )

        # known conversion conflicts
        self.conv_conflicts = (
            (
                {'code': '15', 'hexval': 'ffffff', 'rgb': (255, 255, 255)},
                {'code': '231', 'hexval': 'ffffff', 'rgb': (255, 255, 255)}
            ),
        )

    def test_colorcode(self):
        """ ColorCode should properly translate codes. """

        for v in self.conversions:
            for code in v.values():
                argset = (code,)
                self.assertCallEqual(
                    v,
                    ColorCode(*argset).to_dict(),
                    func=ColorCode,
                    args=argset,
                    msg='Failed to translate.',
                )

        for hexval, termhex in self.termhex_close:
            argset = (hexval,)
            self.assertCallEqual(
                termhex,
                ColorCode(*argset).hexval,
                func=ColorCode,
                args=argset,
                msg='Failed to find known close match.'
            )

    def test_fix_hex(self):
        """ fix_hex should translate short-form hex strings. """
        for argset in (('#f',), ('#ffffffXX',), ('',)):
            with self.assertCallRaises(
                    ValueError,
                    func=fix_hex,
                    args=argset,
                    msg='Failed to raise.'):
                fix_hex(*argset)

        for argset, expected in (
            (('#fff',), 'ffffff'),
            (('fff',), 'ffffff'),
            (('000',), '000000'),
            (('##000',), '000000'),
            (('aaaaaa',), 'aaaaaa')
        ):
            self.assertCallEqual(
                expected,
                fix_hex(*argset),
                func=fix_hex,
                args=argset,
                msg='Failed to fix hex string.',
            )

    def test_hex2rgb(self):
        """ hex2rgb should translate well-formed codes, and raise on errors.
        """
        testargs = (('',), ('00 0000',))
        for argset in testargs:
            with self.assertCallRaises(
                    ValueError,
                    func=hex2rgb,
                    args=argset,
                    msg='Failed to raise.'):
                hex2rgb(*argset)

        argset = ('#f00',)
        kwset = {'allow_short': False}
        with self.assertCallRaises(
                ValueError,
                func=hex2rgb,
                args=argset,
                kwargs=kwset,
                msg='Failed to raise without.'):
            hex2rgb(*argset, **kwset)

        argset = (' #FF0000',)
        self.assertCallTupleEqual(
            hex2rgb(*argset),
            (255, 0, 0),
            func=hex2rgb,
            args=argset,
            msg='Failed to convert padded hex string.',
        )

        argset = ('#f00',)
        kwset = {'allow_short': True}
        self.assertCallTupleEqual(
            hex2rgb(*argset, **kwset),
            (255, 0, 0),
            func=hex2rgb,
            args=argset,
            kwargs=kwset,
            msg='Failed to convert short form hex string.',
        )

    def test_is_code(self):
        """ colr.trans.is_code should recognize a color code. """
        validcodes = ('\033[31m', '\033[41m')
        invalidcode = '\033[38;5;27m'
        for validcode in validcodes:
            self.assertTrue(is_code(validcode))
        self.assertFalse(is_code(invalidcode))

    def test_is_ext_code(self):
        """ colr.trans.is_ext_code should recognize a color code. """
        validcodes = ('\033[38;5;42m', '\033[48;5;42m')
        invalidcode = '\033[10m'
        for validcode in validcodes:
            self.assertTrue(is_ext_code(validcode))

        self.assertFalse(is_ext_code(invalidcode))