Beispiel #1
0
    def test_parse_string_unsafe_github_issue_60(self):
        """parse_string_unsafe can parse the examples reported in issue #60

https://github.com/tbielawa/bitmath/issues/60
        """
        issue_input1 = '7.5KB'
        _parsed1 = bitmath.parse_string_unsafe(issue_input1)
        expected_result1 = bitmath.kB(7.5)

        self.assertEqual(
            _parsed1,
            expected_result1)

        issue_input2 = '4.7MB'
        _parsed2 = bitmath.parse_string_unsafe(issue_input2)
        expected_result2 = bitmath.MB(4.7)

        self.assertEqual(
            _parsed2,
            expected_result2)

        issue_input3 = '4.7M'
        _parsed3 = bitmath.parse_string_unsafe(issue_input3)
        expected_result3 = bitmath.MB(4.7)

        self.assertEqual(
            _parsed3,
            expected_result3)
Beispiel #2
0
    def test_with_format(self):
        """bitmath.format context mgr sets and restores formatting"""
        to_print = [
            bitmath.Byte(101),
            bitmath.KiB(202),
            bitmath.MB(303),
            bitmath.GiB(404),
            bitmath.TB(505),
            bitmath.PiB(606),
            bitmath.EB(707)
        ]

        str_reps = [
            "101.00-Byte", "202.00-KiB", "303.00-MB", "404.00-GiB",
            "505.00-TB", "606.00-PiB", "707.00-EB"
        ]

        # Make sure formatting looks right BEFORE the context manager
        self.assertEqual(str(bitmath.KiB(1.337)), "1.337 KiB")

        with bitmath.format("{value:.2f}-{unit}"):
            for (inst, inst_str) in zip(to_print, str_reps):
                self.assertEqual(str(inst), inst_str)

        # Make sure formatting looks right AFTER the context manager
        self.assertEqual(str(bitmath.KiB(1.337)), "1.337 KiB")
    def test_best_prefix_SI_default(self):
        """SI: Best prefix uses the current system if no preference set

Start with a SI unit and assert no preference. The default behavior
returns a prefix from the current system family (GB)"""
        # The MB is == 1 GB, conversion happens, and the result is a
        # unit from the same family (GB)
        should_be_GB = bitmath.MB(1000).best_prefix()
        self.assertIs(type(should_be_GB), bitmath.GB)
 def test_FileTransferSpeed_10_seconds_MB(self):
     """Widget renders a rate after time has elapsed in MB/s"""
     pbar = mock.MagicMock(progressbar.ProgressBar)
     pbar.seconds_elapsed = 10
     # Let's say we've downloaded 512 MB in that time (we need that
     # value in Bytes, though)
     pbar.currval = bitmath.MB(512).bytes
     update = self.widget_SI.update(pbar)
     # 512 MB in 10 seconds is equal to a rate of 51.20 MB/s
     self.assertEqual(update, '51.20 MB/s')
Beispiel #5
0
def to_base_10(n):
    if "K" in n[1]:
        return int(round(bitmath.kB(n[0]).to_Byte()))
    elif "M" in n[1]:
        return int(round(bitmath.MB(n[0]).to_Byte()))
    elif "G" in n[1]:
        return int(round(bitmath.GB(n[0]).to_Byte()))
    elif "T" in n[1]:
        return int(round(bitmath.TB(n[0]).to_Byte()))
    else:
        return int(round(float(n[0])))
    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 test_simple_round_up(self):
     """SI: 1 GB (as a MB()) rounds up into a GB()"""
     # Represent a Gigabyte as a large MB
     GB_in_MB = bitmath.MB(1024)
     # This should turn into a GB
     self.assertIs(type(GB_in_MB.best_prefix()), bitmath.GB)
Beispiel #8
0
 def test_parse_Mo(self):
     """parse_string works on megaoctet strings"""
     self.assertEqual(
         bitmath.parse_string("654 Mo"),
         bitmath.MB(654))
Beispiel #9
0
def get_resource_utilization(vim: KubernetesVim):

    config = client.Configuration()
    config.host = vim.url
    config.api_key = {"authorization": "Bearer " + vim.service_token}

    try:
        ca_cert = b64decode(vim.ccc, validate=True)
    except (Base64DecodingError, ValueError):
        raise VimConnectionError(
            "Error decoding the cluster CA certificate. "
            "Make sure it is a valid base64-encoded string.")

    # Write ca certificate to a temp file for urllib
    ca_cert_file = NamedTemporaryFile(mode="w+b", delete=False)
    ca_cert_file.write(ca_cert)
    ca_cert_file_path = Path(ca_cert_file.name)
    ca_cert_file.close()

    config.verify_ssl = True
    config.ssl_ca_cert = ca_cert_file_path

    try:
        api = client.CoreV1Api(client.ApiClient(config))

        cores_total = 0
        cores_used = 0
        memory_total = bitmath.MB()
        memory_used = bitmath.MB()

        # Aggregate available resources for all nodes
        for node in api.list_node().items:
            allocatable = node.status.allocatable
            cores_total += float(allocatable["cpu"])
            memory_total += bitmath.parse_string_unsafe(allocatable["memory"])

        # Aggregate resource requests for all containers in all pods (like `kubectl
        # describe nodes` does)
        for pod in api.list_pod_for_all_namespaces().items:
            for container in pod.spec.containers:
                resource_requests = container.resources.requests
                if resource_requests is not None:
                    if "cpu" in resource_requests:
                        cores_used += (
                            float(resource_requests["cpu"].replace("m", "")) /
                            1000)
                    if "memory" in resource_requests:
                        memory_used += bitmath.parse_string_unsafe(
                            resource_requests["memory"])

        return {
            "cores": {
                "used": round(cores_used, 3),
                "total": cores_total
            },
            "memory": {
                "used": math.ceil(memory_used.value),
                "total": math.floor(memory_total.value),
            },
        }

    except (ApiException, MaxRetryError) as e:
        if isinstance(e, ApiException) and str(e).startswith("(401)"):
            raise VimConnectionError(
                "Authorization error. Please check the service token.")
        raise VimConnectionError(str(e))
    finally:
        # Remove the temporary ca certificate
        ca_cert_file_path.unlink()