def test_print_two_digits_precision(self): """MiB(1/3.0) prints out with two digits of precision""" expected_result = "0.33MiB" fmt_str = "{value:.2f}{unit}" third_MiB = bitmath.MiB(1 / 3.0) actual_result = third_MiB.format(fmt_str) self.assertEqual(expected_result, actual_result)
def test_BitmathType_good_spaces_in_value(self): """Argparse: BitmathType - 'Quoted values' can be separated from the units by whitespace""" args = "--two-args '100 MiB' '200 KiB'" result = self._parse_two_args(args) self.assertEqual(len(result.two_args), 2) self.assertIn(bitmath.MiB(100), result.two_args) self.assertIn(bitmath.KiB(200), result.two_args)
def test_print_scientific_four_digits_precision(self): """MiB(102.4754) prints out with four digits of precision""" expected_result = "102.5MiB" fmt_str = "{value:.4g}{unit}" third_MiB = bitmath.MiB(102.4754) actual_result = third_MiB.format(fmt_str) self.assertEqual(expected_result, actual_result)
def test_parse_string_unsafe_request_NIST(self): """parse_string_unsafe can convert to NIST on request""" unsafe_input = "100M" _parsed = bitmath.parse_string_unsafe(unsafe_input, system=bitmath.NIST) expected = bitmath.MiB(100) self.assertEqual(_parsed, expected) self.assertIs(type(_parsed), type(expected)) unsafe_input2 = "100k" _parsed2 = bitmath.parse_string_unsafe(unsafe_input2, system=bitmath.NIST) expected2 = bitmath.KiB(100) self.assertEqual(_parsed2, expected2) self.assertIs(type(_parsed2), type(expected2)) unsafe_input3 = "100" _parsed3 = bitmath.parse_string_unsafe(unsafe_input3, system=bitmath.NIST) expected3 = bitmath.Byte(100) self.assertEqual(_parsed3, expected3) self.assertIs(type(_parsed3), type(expected3)) unsafe_input4 = "100kb" _parsed4 = bitmath.parse_string_unsafe(unsafe_input4, system=bitmath.NIST) expected4 = bitmath.KiB(100) self.assertEqual(_parsed4, expected4) self.assertIs(type(_parsed4), type(expected4))
def test_best_prefix_NIST_default(self): """NIST: Best prefix uses the current system if no preference set Start with a NIST unit and assert no preference. The default behavior returns a prefix from the current system family (GiB)""" # The MiB is == 1 GiB, conversion happens, and the result is a # unit from the same family (GiB) should_be_GiB = bitmath.MiB(1024).best_prefix() self.assertIs(type(should_be_GiB), bitmath.GiB)
def test_FileTransferSpeed_10_seconds_MiB(self): """Widget renders a rate after time has elapsed in MiB/s""" pbar = mock.MagicMock(progressbar.ProgressBar) pbar.seconds_elapsed = 10 # Let's say we've downloaded 512 MiB in that time (we need # that value in Bytes, though) pbar.currval = bitmath.MiB(512).bytes update = self.widget_NIST.update(pbar) # 512 MiB in 10 seconds is equal to a rate of 51.20 MiB/s self.assertEqual(update, '51.20 MiB/s')
def to_MiB(n): if "K" in n[1]: return int(round(bitmath.KiB(n[0]).to_MiB())) elif "M" in n[1]: return int(round(bitmath.MiB(n[0]).to_MiB())) elif "G" in n[1]: return int(round(bitmath.GiB(n[0]).to_MiB())) elif "T" in n[1]: return int(round(bitmath.TiB(n[0]).to_MiB())) else: return int(round(float(n[0])))
def test_click_BitmathType_good_spaces_in_value(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, ['100 MiB', '200 KiB']) self.assertFalse(result.exception) self.assertEqual(result.output.splitlines(), [str(bitmath.MiB(100)), str(bitmath.KiB(200))])
def main(no_dry, wheel_dir): """Remove old Python Wheels from local directory.""" pruned_bytes = bitmath.MiB() for old_wheel in old_wheels(wheel_dir): pruned_bytes += bitmath.getsize(old_wheel.path) if no_dry: old_wheel.path.unlink() LOG.info('Removed: %s', old_wheel.path) else: LOG.info('Would delete: %s', old_wheel.path) LOG.info('Freed: %s', pruned_bytes)
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)
def setUp(self): self.kib = bitmath.KiB(1) self.kib_repr = 'KiB(1.0)' self.kib_str = '1.0 KiB' self.kib_unit = 'KiB' self.kib_system = 'NIST' self.kib_bin = '0b10000000000000' self.kib_binary = self.kib_bin self.kib_power = 10 self.kib_base = 2 self.half_mib = bitmath.MiB(0.5) self.half_mib_repr = 'MiB(0.5)' self.half_mib_str = '0.5 MiB' self.kB = bitmath.kB(1) self.kB_unit = 'kB' self.kb_system = 'SI' self.kib_str_changed = 'KiB 1.000'
def size_to_bytes(human_size): PARSE_REGEXP = r"(\d+)([MGTPE]i)" parse = re.compile(PARSE_REGEXP) try: size, unit = re.match(parse, human_size).group(1, 2) size = int(size) assert size > 0 if unit == 'Mi': return int(bitmath.MiB(size).to_Byte()) elif unit == 'Gi': return int(bitmath.GiB(size).to_Byte()) elif unit == 'Ti': return int(bitmath.TiB(size).to_Byte()) elif unit == 'Pi': return int(bitmath.PiB(size).to_Byte()) elif unit == 'Ei': return int(bitmath.EiB(size).to_Byte()) else: return 0 except Exception as e: return 0
def from_dict(cls, info): """Build a :obj:`ContainerLabel` instance from a dictionary. Args: info (:obj:`dict`): Container information in dictionary format structured in the manner of ffprobe json output. Returns: Instance populated wtih data from the given dictionary. """ title = info.get('format', {}).get('tags', {}).get('title', '') f_bytes = int(info.get('format', {}).get('size', 0)) size = round(bitmath.MiB(bytes=f_bytes).value, 2) if f_bytes else '' bits = int(info.get('format', {}).get('bit_rate', 0)) bitrate = round(bitmath.Mib(bits=bits).value, 2) if bits else '' container_format = info.get('format', {}).get('format_long_name', '') duration = float(info.get('format', {}).get('duration', 0)) length = datetime.timedelta(0, round(duration)) if duration else '' return cls(title=title, size=size, bitrate=bitrate, container_format=container_format, length=length)
def test_allocate_with_string_params(): user = USER_23 with ExitStack() as stack: stack.enter_context(disable_pytest_stdin()) stack.enter_context(set_up_key_location(user)) stack.enter_context(reset_environment(user)) stack.enter_context(set_password(get_test_user_password(user))) cluster = show_cluster(name=TEST_CLUSTER) nodes = cluster.allocate_nodes(walltime='0:10:00', memory_per_node='500MiB') stack.enter_context(cancel_on_exit(nodes)) assert len(nodes) == 1 node = nodes[0] nodes.wait(timeout=SLURM_WAIT_TIMEOUT) assert nodes.running() assert node.resources.cpu_cores == 1 assert node.resources.memory_total == bitmath.MiB(500) print(node) assert node.run('whoami') == user
def convert_to_mbs(self, number_of_bytes): ''' Return Megabit per second from byte per second ''' try: return bitmath.MiB(bytes=number_of_bytes) except: return 'NULL'
def test_cli_script_main_to_unit(self): """CLI script returns correct TO units""" args = ['-t', 'MiB', '1048576'] results = bitmath.cli_script_main(args) self.assertEqual(results[0], bitmath.MiB(1)) self.assertIs(type(results[0]), bitmath.MiB)
precision = 1 number_of_bytes = round(number_of_bytes, precision) return number_of_bytes, unit import bitmath # han = 2424708.6729394053 # # print convert_byte(han) # # # test = bitmath.kb(bytes=han) # # test2 = bitmath.kB(bits=han) test1 = bitmath.MiB(bytes=han) # test2 = bitmath.MiB(bits=han) # test3 = bitmath.Mib(bytes=han) # test4 = bitmath.Mib(bits=han) # # test5 = bitmath.Kib(bits=han) # # # # print test # # print test2 # # print test3 # # print test4 # # print test5 print test1 # print test2 # print test3 # print test4
def mb_to_gb(mib): return bitmath.MiB(mib).to_GiB().value
def setUp(self): self.kib = bitmath.KiB(1) self.mib = bitmath.MiB(1) self.gib = bitmath.GiB(1)
def test_parse_Mio(self): """parse_string works on mebioctet strings""" self.assertEqual( bitmath.parse_string("654 Mio"), bitmath.MiB(654))
def execute(self): headers = ["ID", "Name", "Status", "Created", "Updated"] if self.args["stack"]: print(tabulate(orch.get_list(), headers=headers, tablefmt="grid")) exit() set_file = self.args["--file"] default_file = orch.check_manifest_file() if self.args["vm"]: try: data_instance = list() for instance in vm_lib.get_list(): pre_instance = [ instance.id, instance.name, instance.key_name ] pre_instance.append( image.detail(instance.image["id"]).name) flavors = vm_lib.detail_flavor(instance.flavor["id"]) flavors_name = flavors.name flavors_vcpu = flavors.vcpus flavors_ram = bitmath.MiB( flavors.ram).to_GiB().best_prefix() pre_instance.append(flavors_name) pre_instance.append(flavors_ram) pre_instance.append(flavors_vcpu) # Address addr = list() addr_objs = utils.get_index(instance.addresses) if len(addr_objs) > 0: for addr_obj in addr_objs: addr.append("network : {}".format(addr_obj)) for addr_ip in instance.addresses[addr_obj]: addr_meta = "{} IP : {}".format( addr_ip["OS-EXT-IPS:type"], addr_ip["addr"]) addr.append(addr_meta) if len(addr) > 0: pre_instance.append("\n".join(addr)) else: pre_instance.append("") pre_instance.append(instance.status) data_instance.append(pre_instance) if len(data_instance) == 0: utils.log_err("No Data...") print(self.__doc__) except Exception as e: utils.log_err(e) exit() print( tabulate( data_instance, headers=[ "ID", "Name", "Key Pair", "Image", "Flavor", "RAM (GiB)", "vCPU", "Addresses", "Status", ], tablefmt="grid", )) exit() if self.args["network"]: data_network = [[ network["id"], network["name"], network["status"] ] for network in network_lib.get_list()] if len(data_network) == 0: utils.log_err("No Data...") print(self.__doc__) exit() print( tabulate(data_network, headers=["ID", "Name", "Status"], tablefmt="grid")) exit() if self.args["floatingips"]: data_floatingips = [[ floatingips["floating_ip_address"], floatingips["created_at"], floatingips["status"], ] for floatingips in network_lib.get_floatingips()] if len(data_floatingips) == 0: utils.log_err("No Data...") print(self.__doc__) exit() print( tabulate( data_floatingips, headers=["IP Address", "Created at", "Status"], tablefmt="grid", )) exit() if self.args["--outputs"]: stack_name = self.args["--outputs"].split(".") if len(stack_name) is 1: for meta in orch.get_meta_stack(stack_name[0]): print(meta["output_key"], " :") print(meta["output_value"]) print("") if len(stack_name) is 2: print(orch.get_metadata(stack_name[0], stack_name[1])) exit() if set_file: if os.path.exists(set_file): default_file = "{}".format(set_file) else: utils.log_err("{} file is not exists!".format(set_file)) print(self.__doc__) exit() if not default_file: utils.log_err("Oops!! Can't find neo.yml manifest file!") print(self.__doc__) exit() projects = utils.get_project(default_file) project_list = list() for project in projects: proj = orch.get_stack(project) if proj: project_list.append(proj) if len(project_list) > 0: print(tabulate(project_list, headers=headers, tablefmt="grid")) else: utils.log_err("No Data...") print(self.__doc__)
REMOTES = [ # patch-3.0.70.gz 20-Mar-2013 20:02 1.0M 'https://www.kernel.org/pub/linux/kernel/v3.0/patch-3.4.92.xz', # patch-3.16.gz 03-Aug-2014 22:39 8.0M 'https://www.kernel.org/pub/linux/kernel/v3.0/patch-3.16.gz', # patch-3.2.gz 05-Jan-2012 00:43 22M 'https://www.kernel.org/pub/linux/kernel/v3.0/patch-3.2.gz', ] ###################################################################### p = argparse.ArgumentParser(description='bitmath demo suite') p.add_argument('-d', '--down', help="Download Rate", type=bitmath.integrations.BitmathType, default=bitmath.MiB(4)) p.add_argument('-s', '--slowdown', help='Randomly pause to slow down the transfer rate', action='store_true', default=False) args = p.parse_args() ###################################################################### # Save our example files somewhere. And then clean up every trace that # anything every happened there. shhhhhhhhhhhhhhhh DESTDIR = tempfile.mkdtemp('demosuite', 'bitmath') @atexit.register def cleanup(): for f in os.listdir(DESTDIR): os.remove(os.path.join(DESTDIR, f))
def test_simple_round_up(self): """NIST: 1 GiB (as a MiB()) rounds up into a GiB()""" # Represent a Gibibyte as a large MiB GiB_in_MiB = bitmath.MiB(1024) # This should turn into a GiB self.assertIs(type(GiB_in_MiB.best_prefix()), bitmath.GiB)
def test_MiB(self): self.assertEqual(bitmath.parse_string("654 MiB"), bitmath.MiB(654))