Python源码示例:bitmath.Byte()

示例1
def setUp(self):
        self.bit = bitmath.Bit(1)
        self.byte = bitmath.Byte(1)
        # NIST units
        self.kib = bitmath.KiB(1)
        self.mib = bitmath.MiB(1)
        self.gib = bitmath.GiB(1)
        self.tib = bitmath.TiB(1)
        self.pib = bitmath.PiB(1)
        self.eib = bitmath.EiB(1)

        # SI units
        self.kb = bitmath.kB(1)
        self.mb = bitmath.MB(1)
        self.gb = bitmath.GB(1)
        self.tb = bitmath.TB(1)
        self.pb = bitmath.PB(1)
        self.eb = bitmath.EB(1)
        self.zb = bitmath.ZB(1)
        self.yb = bitmath.YB(1) 
示例2
def test___init__valid_inputs(self):
        """__init__: accepts valid inputs"""
        inputs = [
            # Comments illustrate what the initialization calls look
            # like after the interpreter expands all the *arg/**kwarg
            # parameters.
            #
            # All pairs are equivalent to Byte(100) (used in the test
            # assertion, below)
            ((100,), dict()),  # Byte(100)
            (tuple(), {"value": 100}),  # Byte(value=100)
            (tuple(), {"bytes": 100}),  # Byte(bytes=100)
            (tuple(), {"bits": 800})  # Byte(bits=800)
        ]

        for args, kwargs in inputs:
            self.assertEqual(bitmath.Byte(*args, **kwargs), bitmath.Byte(100)) 
示例3
def test_best_prefix_negative_less_than_a_byte(self):
        """best_prefix_base: negative values less than a byte stay as bits"""
        # assert that a Byte of -4 bits yields Bit(-4)
        bm1 = bitmath.Byte(bits=-4)
        expected = bitmath.Bit(-4)
        res = bitmath.best_prefix(bm1)
        # Verify that best prefix math works for negative numbers
        self.assertEqual(res, expected)
        # Verify that best prefix guessed the correct type
        self.assertIs(type(res), bitmath.Bit)

    # For instances where x in set { b | b >= 8 } where b is number of
    # bits in an instance:
    #
    # * bitmath.best_prefix(-10**8) -> MiB(-95.367...)
    # * bitmath.best_prefix(10**8) -> MiB(95.367...) 
示例4
def test_parsenum_all_sizes(self, expr, size):
        """
        Send standard size expressions to ``parse_num`` in
        many sizes, we expect to get correct size results.

        :param expr str: A string representing the size expression
        :param size int: A string representing the volume size
        """
        if expr is "KB":
            expected_size = int(KiB(size).to_Byte())
        elif expr is "MB":
            expected_size = int(MiB(size).to_Byte())
        elif expr is "GB":
            expected_size = int(GiB(size).to_Byte())
        elif expr is "TB":
            expected_size = int(TiB(size).to_Byte())
        else:
            expected_size = int(Byte(size).to_Byte())
        return self.assertEqual(expected_size,
                                int(parse_num(str(size)+expr).to_Byte())) 
示例5
def test_foreign_volume(self):
        """
        ``list_volumes`` lists only those volumes
        belonging to the current Flocker cluster.
        """
        try:
            config = get_blockdevice_config()
        except InvalidConfig as e:
            self.skipTest(str(e))
        ec2_client = get_ec2_client_for_test(config)
        meta_client = ec2_client.connection.meta.client
        requested_volume = meta_client.create_volume(
            Size=int(Byte(self.minimum_allocatable_size).to_GiB().value),
            AvailabilityZone=ec2_client.zone)
        created_volume = ec2_client.connection.Volume(
            requested_volume['VolumeId'])
        self.addCleanup(created_volume.delete)

        _wait_for_volume_state_change(VolumeOperations.CREATE,
                                      created_volume)

        self.assertEqual(self.api.list_volumes(), []) 
示例6
def __init__(self, uploaded=None, max_allowed=None):
        detail = {}
        message = "Uploaded blob is larger than allowed by this registry"

        if uploaded is not None and max_allowed is not None:
            detail = {
                "reason": "%s is greater than maximum allowed size %s" % (uploaded, max_allowed),
                "max_allowed": max_allowed,
                "uploaded": uploaded,
            }

            up_str = bitmath.Byte(uploaded).best_prefix().format("{value:.2f} {unit}")
            max_str = bitmath.Byte(max_allowed).best_prefix().format("{value:.2f} {unit}")
            message = "Uploaded blob of %s is larger than %s allowed by this registry" % (
                up_str,
                max_str,
            ) 
示例7
def _pod_stats(pod):
    cpu = sum(
        map(
            parse_cpu, (
                container["usage"]["cpu"]
                for container
                in pod["containers"]
            ),
        ), 0,
    )
    mem = sum(
        map(
            lambda s: parse_memory(s).amount, (
                container["usage"]["memory"]
                for container
                in pod["containers"]
            ),
        ), Byte(0),
    )
    return (_CPU(cpu), _Memory(mem)) 
示例8
def test_render_pod(self):
        pod_usage = {
            "metadata": {
                "name": "foo",
                "namespace": "default",
                "creationTimestamp": "2017-04-07T15:21:22Z"
            },
            "timestamp": "2017-04-07T15:21:00Z",
            "window": "1m0s",
            "containers": [
                {
                    "name": "foo-a",
                    "usage": {
                        "cpu": "100m",
                        "memory": "128Ki"
                    }
                },
            ]
        }
        fields = _render_pod(pod_usage, _Memory(Byte(1024 * 1024))).split()
        self.assertEqual(
            [u'foo', u'10.0', u'128.00', u'KiB', u'12.50'],
            fields,
        ) 
示例9
def unit(self):
        """The string that is this instances prefix unit name in agreement
with this instance value (singular or plural). Following the
convention that only 1 is singular. This will always be the singular
form when :attr:`bitmath.format_plural` is ``False`` (default value).

For example:

   >>> KiB(1).unit == 'KiB'
   >>> Byte(0).unit == 'Bytes'
   >>> Byte(1).unit == 'Byte'
   >>> Byte(1.1).unit == 'Bytes'
   >>> Gb(2).unit == 'Gbs'

        """
        global format_plural

        if self.prefix_value == 1:
            # If it's a '1', return it singular, no matter what
            return self._name_singular
        elif format_plural:
            # Pluralization requested
            return self._name_plural
        else:
            # Pluralization NOT requested, and the value is not 1
            return self._name_singular 
示例10
def unit_plural(self):
        """The string that is an instances prefix unit name in the plural
form.

For example:

   >>> KiB(1).unit_plural == 'KiB'
   >>> Byte(1024).unit_plural == 'Bytes'
   >>> Gb(1).unit_plural == 'Gb'

        """
        return self._name_plural 
示例11
def unit_singular(self):
        """The string that is an instances prefix unit name in the singular
form.

For example:

   >>> KiB(1).unit_singular == 'KiB'
   >>> Byte(1024).unit == 'B'
   >>> Gb(1).unit_singular == 'Gb'
        """
        return self._name_singular

    #: The "prefix" value of an instance 
示例12
def to_Byte(self):
        return Byte(self._byte_value / float(NIST_STEPS['Byte']))

    # Properties 
示例13
def _setup(self):
        return (2, 0, 'Byte', 'Bytes')

######################################################################
# NIST Prefixes for Byte based types 
示例14
def getsize(path, bestprefix=True, system=NIST):
    """Return a bitmath instance in the best human-readable representation
of the file size at `path`. Optionally, provide a preferred unit
system by setting `system` to either `bitmath.NIST` (default) or
`bitmath.SI`.

Optionally, set ``bestprefix`` to ``False`` to get ``bitmath.Byte``
instances back.
    """
    _path = os.path.realpath(path)
    size_bytes = os.path.getsize(_path)
    if bestprefix:
        return Byte(size_bytes).best_prefix(system=system)
    else:
        return Byte(size_bytes) 
示例15
def listdir(search_base, followlinks=False, filter='*',
            relpath=False, bestprefix=False, system=NIST):
    """This is a generator which recurses the directory tree
`search_base`, yielding 2-tuples of:

* The absolute/relative path to a discovered file
* A bitmath instance representing the "apparent size" of the file.

    - `search_base` - The directory to begin walking down.
    - `followlinks` - Whether or not to follow symbolic links to directories
    - `filter` - A glob (see :py:mod:`fnmatch`) to filter results with
      (default: ``*``, everything)
    - `relpath` - ``True`` to return the relative path from `pwd` or
      ``False`` (default) to return the fully qualified path
    - ``bestprefix`` - set to ``False`` to get ``bitmath.Byte``
      instances back instead.
    - `system` - Provide a preferred unit system by setting `system`
      to either ``bitmath.NIST`` (default) or ``bitmath.SI``.

.. note:: This function does NOT return tuples for directory entities.

.. note:: Symlinks to **files** are followed automatically

    """
    for root, dirs, files in os.walk(search_base, followlinks=followlinks):
        for name in fnmatch.filter(files, filter):
            _path = os.path.join(root, name)
            if relpath:
                # RELATIVE path
                _return_path = os.path.relpath(_path, '.')
            else:
                # REAL path
                _return_path = os.path.realpath(_path)

            if followlinks:
                yield (_return_path, getsize(_path, bestprefix=bestprefix, system=system))
            else:
                if os.path.isdir(_path) or os.path.islink(_path):
                    pass
                else:
                    yield (_return_path, getsize(_path, bestprefix=bestprefix, system=system)) 
示例16
def parse_string(s):
    """Parse a string with units and try to make a bitmath object out of
it.

String inputs may include whitespace characters between the value and
the unit.
    """
    # Strings only please
    if not isinstance(s, (str, unicode)):
        raise ValueError("parse_string only accepts string inputs but a %s was given" %
                         type(s))

    # get the index of the first alphabetic character
    try:
        index = list([i.isalpha() for i in s]).index(True)
    except ValueError:
        # If there's no alphabetic characters we won't be able to .index(True)
        raise ValueError("No unit detected, can not parse string '%s' into a bitmath object" % s)

    # split the string into the value and the unit
    val, unit = s[:index], s[index:]

    # see if the unit exists as a type in our namespace

    if unit == "b":
        unit_class = Bit
    elif unit == "B":
        unit_class = Byte
    else:
        if not (hasattr(sys.modules[__name__], unit) and isinstance(getattr(sys.modules[__name__], unit), type)):
            raise ValueError("The unit %s is not a valid bitmath unit" % unit)
        unit_class = globals()[unit]

    try:
        val = float(val)
    except ValueError:
        raise
    try:
        return unit_class(val)
    except:  # pragma: no cover
        raise ValueError("Can't parse string %s into a bitmath object" % s) 
示例17
def update(self, pbar):
        """Updates the widget with the current NIST/SI speed.

Basically, this calculates the average rate of update and figures out
how to make a "pretty" prefix unit"""

        if pbar.seconds_elapsed < 2e-6 or pbar.currval < 2e-6:
            scaled = bitmath.Byte()
        else:
            speed = pbar.currval / pbar.seconds_elapsed
            scaled = bitmath.Byte(speed).best_prefix(system=self.system)

        return scaled.format(self.format) 
示例18
def test_init_no_arguments(self):
        """Instantiation works with no arguments"""
        bm = bitmath.Byte()
        # An instance with 0 arguments will have a value of 0
        self.assertEqual(bm, bitmath.Byte(0)) 
示例19
def test_init_value(self):
        """Instantiation works with only 'value' provided"""
        bm1 = bitmath.Byte(1)
        bm2 = bitmath.Byte(value=1)

        # These instances will be equivalent to each other and
        # congruent to int(1)
        self.assertEqual(bm1, bm2)
        self.assertEqual(bm1, int(1))
        self.assertEqual(bm2, int(1)) 
示例20
def test_init_bytes(self):
        """Instantiation works with the 'bytes' kw arg"""
        bm = bitmath.Byte(bytes=1024)

        # 1024 bytes is 1 KiB, these should be equal
        self.assertEqual(bm, bitmath.KiB(1))
        self.assertEqual(bm.bytes, 1024) 
示例21
def test_init_bits(self):
        """Instantiation works with the 'bits' kw arg"""
        bm = bitmath.Byte(bits=8)

        # 8 bits is 1 byte, these should be equal
        self.assertEqual(bm, bitmath.Byte(1))

    ##################################################################
    # Now, the invalid uses

    # value and bytes 
示例22
def test_bad_init_value_bytes(self):
        """Instantiation fails if value and bytes are both provided"""
        with self.assertRaises(ValueError):
            bitmath.Byte(value=1, bytes=1)

    # value and bits 
示例23
def test_bad_init_bytes_bits(self):
        """Instantiation fails if bytes and bits are both provided"""
        with self.assertRaises(ValueError):
            bitmath.Byte(bytes=1, bits=1)

    # value and bytes and bits 
示例24
def test_bad_init_value_bytes_bits(self):
        """Instantiation fails if value and bytes and bits are all provided"""
        with self.assertRaises(ValueError):
            bitmath.Byte(value=1, bytes=1, bits=1)

    ##################################################################
    # Double check we can't create rogue instances of bitmath.Bitmath 
示例25
def test_cli_script_main_no_units(self):
        """CLI script works if no to/from units are provided"""
        args = ['100', '1024']
        results = bitmath.cli_script_main(args)
        self.assertEqual(results[0], bitmath.Byte(100))
        self.assertEqual(results[1], bitmath.KiB(1)) 
示例26
def test_cli_script_main_from_and_to_unit(self):
        """CLI script returns correct if given FROM and TO units"""
        args = ['-f', 'MiB', '-t', 'Byte', '1']
        # Testing FROM 1 MiB TO equivalent Bytes
        results = bitmath.cli_script_main(args)
        self.assertEqual(results[0], bitmath.Byte(1048576))
        self.assertIs(type(results[0]), bitmath.Byte) 
示例27
def test_from_other_bad_input(self):
        """from_other raises if "other" isn't a bitmath instance"""
        with self.assertRaises(ValueError):
            bitmath.Byte.from_other(str("not a bitmath instance!")) 
示例28
def test_click_BitmathType_good_two_args(self):
        @click.command()
        @click.argument('arg1', type=BitmathType())
        @click.argument('arg2', type=BitmathType())
        def func(arg1, arg2):
            click.echo(arg1)
            click.echo(arg2)

        result = self.runner.invoke(func, ['1337B', '0.001GiB'])
        self.assertFalse(result.exception)
        self.assertEqual(result.output.splitlines(), [str(bitmath.Byte(1337)),
                                                      str(bitmath.GiB(0.001))]) 
示例29
def test___init_multiple_kwargs(self):
        """__init__: respects argument mutual exclusivity"""
        # A 100 Byte object can be initialized with any *single* one
        # of these pairs:
        multi_kwargs = {
            "value": 100,  # bitmath.Byte(100)
            "bytes": 100,  # bitmath.Byte(100)
            "bits": 800  # bitmath.Bit(bytes=100)
        }

        with self.assertRaises(ValueError):
            bitmath.Byte(**multi_kwargs) 
示例30
def test_BitmathType_good_two_args(self):
        """Argparse: BitmathType - Works when given two correct parameters"""
        args = "--two-args 1337B 0.001GiB"
        result = self._parse_two_args(args)
        self.assertEqual(len(result.two_args), 2)
        self.assertIn(bitmath.Byte(1337), result.two_args)
        self.assertIn(bitmath.GiB(0.001), result.two_args)