1
0
Fork 0
mirror of https://github.com/retspen/webvirtcloud synced 2026-12-02 08:56:07 +00:00

fix(ui): sizes in the units the forms ask in, percentages as the language writes them

- binary_size filter (common_tags): every size on the pages is B/KiB/MiB/GiB/TiB
  with the language's decimal mark; Django's filesizeformat said GB for GiB, so a
  page showed "512,0 MB / 3,8 GB" beside "0,4 / 3,8 GiB" and a disk "20,0 GB"
  next to a GiB field
- percent filter and Intl percent in charts.js, the job panel and the new-VM
  dialog: 13% in English, %13 in Turkish (pages had "13 %", "%11" and "13%")
- the Jobs page and panel say in whole sentences that the job worker is not
  running and that jobs wait for it, instead of a sentence glued to a date
- job state badges start with a capital, as the VM state badges (CSS, so the
  label stays lowercase inside sentences)
- profile card shows the username under the name only when there is a full name
- Turkish: hostname, revert snapshot, snapshot count, API token and worker texts
This commit is contained in:
catborise 2026-11-22 18:25:15 +03:00
parent 50fa42181b
commit 7408a575d6
52 changed files with 241 additions and 127 deletions

View file

@ -20,7 +20,7 @@
<span class="badge text-bg-secondary">{% trans "Template editor" %}</span>
{% endif %}
</div>
<div class="text-body-secondary text-break">{{ user.username }}</div>
{% if user.get_full_name %}<div class="text-body-secondary text-break">{{ user.username }}</div>{% endif %}
{% if user.email %}<div class="small text-break mt-2">{{ user.email }}</div>{% endif %}
<div class="small text-body-secondary mt-2">{% trans "Last login" %} {{ user.last_login|date:"Y-m-d H:i"|default:_("never") }}</div>
</div>

View file

@ -1,5 +1,6 @@
{% extends "base.html" %}
{% load i18n %}
{% load common_tags %}
{% load static %}
{% load operations %}
{% load bootstrap_icons %}
@ -28,14 +29,14 @@
<div class="col">
<div class="card h-100 shadow-sm"><div class="card-body">
<div class="d-flex justify-content-between mb-2"><span class="fw-semibold">{{ host.name }}</span>
<span class="small text-body-secondary">{% widthratio host.size.0 1 1024 as bytes %}{{ bytes|filesizeformat }}</span></div>
<span class="small text-body-secondary">{% widthratio host.size.0 1 1024 as bytes %}{{ bytes|binary_size }}</span></div>
{% for bar in host.bars %}{% if forloop.first or moves %}
{% if forloop.first %}{% with memory=host.before.0 vcpus=host.before.1 %}
<div class="d-flex justify-content-between small"><span class="text-body-secondary">{% if moves %}{% trans "Now" %}{% else %}{% trans "Running VMs" %}{% endif %}</span>
<span>{% widthratio memory 1 1024 as bytes %}{{ bytes|filesizeformat }}, {% blocktrans count counter=vcpus %}{{ counter }} vCPU{% plural %}{{ counter }} vCPUs{% endblocktrans %} {% blocktrans count counter=host.size.1 %}on {{ counter }} CPU{% plural %}on {{ counter }} CPUs{% endblocktrans %}</span></div>
<span>{% widthratio memory 1 1024 as bytes %}{{ bytes|binary_size }}, {% blocktrans count counter=vcpus %}{{ counter }} vCPU{% plural %}{{ counter }} vCPUs{% endblocktrans %} {% blocktrans count counter=host.size.1 %}on {{ counter }} CPU{% plural %}on {{ counter }} CPUs{% endblocktrans %}</span></div>
{% endwith %}{% else %}{% with memory=host.after.0 vcpus=host.after.1 %}
<div class="d-flex justify-content-between small mt-2"><span class="text-body-secondary">{% trans "After" %}</span>
<span class="fw-semibold">{% widthratio memory 1 1024 as bytes %}{{ bytes|filesizeformat }}, {% blocktrans count counter=vcpus %}{{ counter }} vCPU{% plural %}{{ counter }} vCPUs{% endblocktrans %} {% blocktrans count counter=host.size.1 %}on {{ counter }} CPU{% plural %}on {{ counter }} CPUs{% endblocktrans %}</span></div>
<span class="fw-semibold">{% widthratio memory 1 1024 as bytes %}{{ bytes|binary_size }}, {% blocktrans count counter=vcpus %}{{ counter }} vCPU{% plural %}{{ counter }} vCPUs{% endblocktrans %} {% blocktrans count counter=host.size.1 %}on {{ counter }} CPU{% plural %}on {{ counter }} CPUs{% endblocktrans %}</span></div>
{% endwith %}{% endif %}
<div class="progress" role="progressbar" style="--bs-progress-height: 0.6rem;" aria-label="{% if forloop.first %}{% trans "Memory now" %}{% else %}{% trans "Memory after" %}{% endif %}"
aria-valuenow="{{ bar|floatformat:0 }}" aria-valuemin="0" aria-valuemax="100">
@ -74,7 +75,7 @@
<input type="hidden" name="instance" value="{{ instance.pk }}">
<input type="hidden" name="source" value="{{ instance.compute_id }}">
<input type="hidden" name="target" value="{{ instance.target.pk }}"></td>
<td class="text-end text-nowrap">{% widthratio instance.info.2 1 1024 as bytes %}{{ bytes|filesizeformat }}</td>
<td class="text-end text-nowrap">{% widthratio instance.info.2 1 1024 as bytes %}{{ bytes|binary_size }}</td>
<td class="text-end">{{ instance.info.3 }}</td>
<td>{{ instance.compute.name }} {% bs_icon 'arrow-right' %} {{ instance.target.name }}</td>
</tr>

View file

@ -1,5 +1,6 @@
{% extends "base.html" %}
{% load i18n %}
{% load common_tags %}
{% load static %}
{% load operations %}
{% load bootstrap_icons %}
@ -91,7 +92,7 @@
</td>
<td><label for="bulk-migrate-{{ instance.pk }}">{{ instance.name }}</label></td>
<td>{% include 'instance_state.html' %}</td>
<td class="text-end text-nowrap">{% if instance.info %}{% widthratio instance.info.2 1 1024 as bytes %}{{ bytes|filesizeformat }}{% endif %}</td>
<td class="text-end text-nowrap">{% if instance.info %}{% widthratio instance.info.2 1 1024 as bytes %}{{ bytes|binary_size }}{% endif %}</td>
<td class="text-end">{{ instance.info.3 }}</td>
{% if spreading %}<td>{{ instance.target.name|default:"" }}</td>{% endif %}
<td class="small text-body-secondary">{{ instance.refusal|default:"" }}{{ instance.note|default:"" }}</td>

View file

@ -1,5 +1,5 @@
{% load i18n %}{% autoescape off %}{% if given %}
{% blocktrans count counter=given.vcpus.all with ratio=given.ratio|floatformat:1 assigned=given.assigned.all|filesizeformat %}Given to VMs: {{ counter }} vCPU ({{ ratio }}:1), {{ assigned }} memory.{% plural %}Given to VMs: {{ counter }} vCPUs ({{ ratio }}:1), {{ assigned }} memory.{% endblocktrans %}
{% load i18n common_tags %}{% autoescape off %}{% if given %}
{% blocktrans count counter=given.vcpus.all with ratio=given.ratio|floatformat:1 assigned=given.assigned.all|binary_size %}Given to VMs: {{ counter }} vCPU ({{ ratio }}:1), {{ assigned }} memory.{% plural %}Given to VMs: {{ counter }} vCPUs ({{ ratio }}:1), {{ assigned }} memory.{% endblocktrans %}
{% else %}
{% trans "The capacity could not be read." %}
{% endif %}{% endautoescape %}

View file

@ -1,18 +1,19 @@
{% load i18n %}
{% load common_tags %}
{# the memory a host has given its VMs: given, from views.shown_capacity #}
<div class="fs-4 lh-sm {% if given.bar.over %}text-danger{% elif given.memory_percent > 90 %}text-warning-emphasis{% endif %}">{{ given.memory_percent }} %</div>
<div class="small text-body-secondary mb-1">{{ given.assigned.all|filesizeformat }} / {{ given.memory|filesizeformat }}</div>
<div class="fs-4 lh-sm {% if given.bar.over %}text-danger{% elif given.memory_percent > 90 %}text-warning-emphasis{% endif %}">{{ given.memory_percent|percent }}</div>
<div class="small text-body-secondary mb-1">{{ given.assigned.all|binary_size }} / {{ given.memory|binary_size }}</div>
{# running VMs' memory, then shut-off VMs', on a scale that holds the host's memory or all given, whichever is larger #}
<div class="progress-stacked" style="--bs-progress-height: 0.6rem;" title="{% trans "Dark: running VMs. Light: shut-off VMs, which take their memory again when they start." %}">
<div class="progress" role="progressbar" style="width: {{ given.bar.running|stringformat:".1f" }}%"
aria-label="{% trans "Memory of running VMs" %}" aria-valuenow="{{ given.bar.running|floatformat:0 }}" aria-valuemin="0" aria-valuemax="100"
aria-valuetext="{% blocktrans with running=given.assigned.running|filesizeformat memory=given.memory|filesizeformat %}{{ running }} of the host's {{ memory }}{% endblocktrans %}">
aria-valuetext="{% blocktrans with running=given.assigned.running|binary_size memory=given.memory|binary_size %}{{ running }} of the host's {{ memory }}{% endblocktrans %}">
<div class="progress-bar {% if given.bar.over %}bg-danger{% else %}bg-primary{% endif %}"></div>
</div>
<div class="progress" role="progressbar" style="width: {{ given.bar.stopped|stringformat:".1f" }}%"
aria-label="{% trans "Memory of shut-off VMs" %}" aria-valuenow="{{ given.bar.stopped|floatformat:0 }}" aria-valuemin="0" aria-valuemax="100"
aria-valuetext="{% blocktrans with stopped=given.assigned.stopped|filesizeformat memory=given.memory|filesizeformat %}{{ stopped }} of the host's {{ memory }}{% endblocktrans %}">
aria-valuetext="{% blocktrans with stopped=given.assigned.stopped|binary_size memory=given.memory|binary_size %}{{ stopped }} of the host's {{ memory }}{% endblocktrans %}">
<div class="progress-bar {% if given.bar.over %}bg-danger{% else %}bg-primary{% endif %} bg-opacity-50"></div>
</div>
</div>
<div class="small text-body-secondary mt-1">{% blocktrans with running=given.assigned.running|filesizeformat %}{{ running }} in running VMs{% endblocktrans %}</div>
<div class="small text-body-secondary mt-1">{% blocktrans with running=given.assigned.running|binary_size %}{{ running }} in running VMs{% endblocktrans %}</div>

View file

@ -1,5 +1,6 @@
{% extends "base.html" %}
{% load i18n %}
{% load common_tags %}
{% load static %}
{% load bootstrap_icons %}
{% load operations %}
@ -42,8 +43,8 @@
<div class="col">
<div class="card h-100"><div class="card-body">
<div class="small text-body-secondary">{% bs_icon 'memory' %} {% trans "Memory given" %}</div>
<div class="fs-4 lh-sm">{{ totals.assigned|filesizeformat }}</div>
<div class="small text-body-secondary">{% blocktrans with memory=totals.memory|filesizeformat %}of {{ memory }}{% endblocktrans %}</div>
<div class="fs-4 lh-sm">{{ totals.assigned|binary_size }}</div>
<div class="small text-body-secondary">{% blocktrans with memory=totals.memory|binary_size %}of {{ memory }}{% endblocktrans %}</div>
</div></div>
</div>
</div>

View file

@ -1,8 +1,9 @@
{% load i18n %}
{% load common_tags %}
{# a pool's space; hide_name: the page names the pool next to it #}
{% if not hide_name %}<div class="small">{{ pool.name }}</div>{% endif %}
<div class="progress my-1" role="progressbar" style="--bs-progress-height: 0.3rem;"
aria-label="{% blocktrans with name=pool.name %}{{ name }} used{% endblocktrans %}" aria-valuenow="{{ pool.used_percent|floatformat:0 }}" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar {% if pool.used_percent > 90 %}bg-danger{% elif pool.used_percent > 75 %}bg-warning{% endif %}" style="width: {{ pool.used_percent|stringformat:".1f" }}%"></div>
</div>
<div class="small text-body-secondary">{% blocktrans with free=pool.free|filesizeformat size=pool.size|filesizeformat %}{{ free }} free of {{ size }}{% endblocktrans %}</div>
<div class="small text-body-secondary">{% blocktrans with free=pool.free|binary_size size=pool.size|binary_size %}{{ free }} free of {{ size }}{% endblocktrans %}</div>

View file

@ -1,5 +1,6 @@
{% extends "base.html" %}
{% load i18n %}
{% load common_tags %}
{% load static %}
{% load bootstrap_icons %}
{% load operations %}
@ -192,7 +193,7 @@
</li>
<li class="list-group-item py-1 d-flex justify-content-between align-items-baseline gap-3">
<span class="text-body-secondary">{% trans "Memory" %}</span>
<span class="text-end text-break"><span class="fw-semibold">{{ host.memory|filesizeformat }}</span></span>
<span class="text-end text-break"><span class="fw-semibold">{{ host.memory|binary_size }}</span></span>
</li>
</ul>
</div>

View file

@ -64,12 +64,12 @@ class ComputesPageTests(TestCase):
self.assertIn("2.5:1", cells[2])
self.assertIn("40 vCPUs on 16 CPUs", cells[2])
self.assertIn("24 in running VMs", cells[2])
self.assertIn("75 % 48.0 GB / 64.0 GB", cells[3])
self.assertIn("32.0 GB in running VMs", cells[3])
self.assertIn("75% 48 GiB / 64 GiB", cells[3])
self.assertIn("32 GiB in running VMs", cells[3])
# the totals of the hosts read: host-two's capacity could not be
totals = [" ".join(card.text_content().split()) for card in page.xpath("//div[@class='card-body']")]
self.assertEqual(totals, ["Hosts 2 / 2 connected", "VMs 3 / 6 running", "vCPUs given 40 on 16 CPUs",
"Memory given 48.0 GB of 64.0 GB"])
"Memory given 48 GiB of 64 GiB"])
# host-two could not be read: one cell says so
self.assertIn("capacity could not be read", " ".join(two.text_content().split()))
@ -86,7 +86,7 @@ class SingularTests(TestCase):
line = self.client.get(reverse("compute_capacity", args=[c.id])).content.decode()
(cell,) = page.xpath("//tbody/tr/td[3]")
self.assertIn("1 vCPU on 1 CPU", " ".join(cell.text_content().split()))
self.assertEqual(" ".join(line.split()), "Given to VMs: 1 vCPU (1.0:1), 1.0 GB memory.")
self.assertEqual(" ".join(line.split()), "Given to VMs: 1 vCPU (1.0:1), 1 GiB memory.")
class NewVmDialogLineTests(TestCase):
@ -107,10 +107,10 @@ class NewVmDialogLineTests(TestCase):
given = {"cpus": 16, "memory": 64 * GIB, "vcpus": {"all": 24, "running": 8},
"assigned": {"all": 48 * GIB, "running": 32 * GIB}, "ratio": 1.5,
}
self.assertEqual(self.line(given), "Given to VMs: 24 vCPUs (1.5:1), 48.0 GB memory.")
self.assertEqual(self.line(given), "Given to VMs: 24 vCPUs (1.5:1), 48 GiB memory.")
def test_a_host_without_pools_or_capacity_says_so(self):
given = {"cpus": 2, "memory": 4 * GIB, "vcpus": {"all": 0, "running": 0},
"assigned": {"all": 0, "running": 0}, "ratio": 0}
self.assertEqual(self.line(given), "Given to VMs: 0 vCPUs (0.0:1), 0 bytes memory.")
self.assertEqual(self.line(given), "Given to VMs: 0 vCPUs (0.0:1), 0 B memory.")
self.assertEqual(self.line(None), "The capacity could not be read.")

View file

@ -143,7 +143,7 @@ class GraphScriptTestCase(TestCase):
poll.request();
poll.onData({cpudata: null, memdata: {total: null, usage: null}, timeline: "t"});
poll.request();
const label = charts[0].options.plugins.tooltip.callbacks.label({dataset: {label: "Usage"}, formattedValue: "3", dataIndex: 0});
const label = charts[0].options.plugins.tooltip.callbacks.label({dataset: {label: "Usage"}, formattedValue: "3", parsed: {y: 3}, dataIndex: 0});
console.log(JSON.stringify({requests, timeouts, label, shown, state: elements.graph_state.textContent,
cpu: charts[0].data.datasets[0].data.map((point) => point.y),
mem: charts[1].data.datasets[0].data.map((point) => point.y), memMax: charts[1].options.scales.y.max}));
@ -159,9 +159,9 @@ class GraphScriptTestCase(TestCase):
# a host that could not be read leaves a gap and keeps the memory axis
self.assertEqual((result["mem"], result["memMax"]), ([1, None], 2))
# the readings in words, and since when they are not updated
self.assertEqual(result["shown"], ["3 %", "1 / 2 GiB", "Updated at t."])
self.assertEqual(result["shown"], ["3%", "1 / 2 GiB", "Updated at t."])
self.assertEqual(result["state"], "Not updated since t.")
self.assertTrue(result["label"].endswith(": 3 % (average over 5.1 s)"), result["label"])
self.assertTrue(result["label"].endswith(": 3% (average over 5.1 s)"), result["label"])
@unittest.skipUnless(shutil.which("node"), "node is not installed")

View file

@ -60,11 +60,11 @@ class OverviewTestCase(TestCase):
cards = [" ".join(" ".join(card.itertext()).split()) for card in page.xpath("//div[@class='card h-100']")]
self.assertIn("VMs 6 3 running, 2 shut off, 1 paused Instances →", cards)
self.assertTrue(any(card.startswith("vCPUs 1.5:1 12 vCPUs on 8 CPUs 6 in running VMs") for card in cards), cards)
self.assertTrue(any(card.startswith("Memory 75 % 24.0 GB / 32.0 GB") for card in cards), cards)
self.assertTrue(any("120.0 GB free of 500.0 GB" in card for card in cards), cards)
self.assertTrue(any(card.startswith("Memory 75% 24 GiB / 32 GiB") for card in cards), cards)
self.assertTrue(any("120 GiB free of 500 GiB" in card for card in cards), cards)
hardware = text(page, "//div[@class='card-header'][normalize-space()='Hardware']/..")
self.assertIn("Processor Xeon Architecture x86_64 Logical CPUs 8 Physical cores 4 Sockets 2 NUMA nodes 2 "
"Clock 2.4 GHz Memory 32.0 GB", hardware)
"Clock 2.4 GHz Memory 32 GiB", hardware)
software = text(page, "//div[@class='card-header'][normalize-space()='Software and connection']/..")
self.assertIn("QEMU 10.1.0 libvirt 11.10.0", software)
self.assertIn("x86_64 kvm · qemu", software)
@ -78,7 +78,7 @@ class OverviewTestCase(TestCase):
pool("backup", 900, 800), pool("iso", 100, 90)]
page = self.page(pools=pools)
storage = page.xpath("//div[@class='card-header'][normalize-space()='Storage']/..")[0]
self.assertIn("default 120.0 GB free of 500.0 GB", " ".join(" ".join(storage.xpath("./div/div//text()")).split()))
self.assertIn("default 120 GiB free of 500 GiB", " ".join(" ".join(storage.xpath("./div/div//text()")).split()))
(more,) = storage.xpath(".//details")
self.assertEqual(" ".join(more.xpath("summary")[0].text_content().split()), "3 more pools")
# active pools only, by name after the default one

View file

@ -1,4 +1,5 @@
{% load i18n %}
{% load common_tags %}
{% load bootstrap_icons %}
<div class="table-responsive">
<table class="table table-hover align-middle" data-sortable>
@ -44,9 +45,9 @@
</td>
{% if compute.status is True and compute.ram_usage is not None %}
<td class="d-none d-sm-table-cell">{{ compute.cpu_count }}</td>
<td class="d-none d-sm-table-cell">{{ compute.ram_size|filesizeformat }}</td>
<td class="d-none d-sm-table-cell">{{ compute.ram_size|binary_size }}</td>
<td>
<div class="small text-body-secondary">{% blocktrans with percent=compute.ram_usage %}host memory {{ percent }}% in use{% endblocktrans %}</div>
<div class="small text-body-secondary">{% blocktrans with percent=compute.ram_usage %}Host memory {{ percent }}% in use{% endblocktrans %}</div>
<div class="progress" role="progressbar" style="--bs-progress-height: 0.3rem;" aria-label="{% trans "Host memory in use" %}"
aria-valuenow="{{ compute.ram_usage }}" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar" style="width: {{ compute.ram_usage }}%"></div>

View file

@ -1,4 +1,5 @@
{% load i18n %}
{% load common_tags %}
{% load bootstrap_icons %}
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#AddInstance">
<span aria-hidden="true">{% bs_icon 'plus-lg' %}</span> {% trans "New VM" %}
@ -37,13 +38,13 @@
</div>
</div>
<div class="col-6 col-md-4">
<div class="small text-body-secondary">{% trans "Memory" %} · {{ compute.ram_size|filesizeformat }}</div>
<div class="small text-body-secondary">{% trans "Memory" %} · {{ compute.ram_size|binary_size }}</div>
<div class="d-flex align-items-center gap-2">
<div class="progress flex-grow-1" role="progressbar" aria-label="{% blocktrans with name=compute.name %}Memory usage of {{ name }}{% endblocktrans %}"
aria-valuenow="{{ compute.ram_usage }}" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar" style="width: {{ compute.ram_usage }}%"></div>
</div>
<small>{{ compute.ram_usage }}%</small>
<small>{{ compute.ram_usage|percent }}</small>
</div>
</div>
<div class="col-md-1 d-none d-md-block text-end" aria-hidden="true">{% bs_icon 'chevron-right' %}</div>

View file

@ -1,5 +1,6 @@
{% extends "base.html" %}
{% load static %}
{% load common_tags %}
{% load vm_states %}
{% load i18n %}
{% load operations %}
@ -68,7 +69,7 @@
</div>
<div class="col-auto col-lg-5">
<dt class="fw-normal text-body-secondary d-inline d-lg-block">{% trans "Disks" %}</dt>
<dd class="mb-0 d-inline d-lg-block">{% for disk in instance.disks %}{{ disk.dev }} {{ disk.size|filesizeformat }}{% if not forloop.last %} · {% endif %}{% empty %}{% trans "None" %}{% endfor %}</dd>
<dd class="mb-0 d-inline d-lg-block">{% for disk in instance.disks %}{{ disk.dev }} {{ disk.size|binary_size }}{% if not forloop.last %} · {% endif %}{% empty %}{% trans "None" %}{% endfor %}</dd>
</div>
{% if not instance.is_template %}
<div class="col-auto col-lg-3">

View file

@ -1,4 +1,5 @@
{% load i18n %}
{% load common_tags %}
{% if request.user.is_superuser %}
<button href="#editvol{{ id }}" type="button" class="btn btn-sm btn-outline-secondary" data-bs-toggle="modal">{% trans "Edit" %}</button>
@ -8,7 +9,7 @@
<div class="modal-header align-items-start">
<div>
<h5 class="modal-title" id="editInstanceVolumeLabel{{ id }}">{% blocktrans with dev=disk.dev %}Edit {{ dev }}{% endblocktrans %}</h5>
<p class="small text-body-secondary mb-0 mt-1">{{ disk.bus }} · {{ disk.format|default:"—" }} · {{ disk.size|filesizeformat }}</p>
<p class="small text-body-secondary mb-0 mt-1">{{ disk.bus }} · {{ disk.format|default:"—" }} · {{ disk.size|binary_size }}</p>
</div>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="{% trans "Close" %}"></button>
</div>

View file

@ -1,4 +1,5 @@
{% load i18n %}
{% load common_tags %}
{# the disks of the Migrate tab for the chosen destination: where each goes; data-refused keeps the form from being sent #}
{% if error %}
<div class="alert alert-warning mb-0" data-refused>{% blocktrans %}The disks could not be checked: {{ error }}{% endblocktrans %}</div>
@ -7,7 +8,7 @@
{% else %}
{% for disk in disks %}
<div{% if not forloop.first %} class="border-top pt-3 mt-3"{% endif %}>
<p class="mb-0"><strong>{{ disk.target }}</strong> <span class="text-body-secondary">{{ disk.capacity|filesizeformat }}</span></p>
<p class="mb-0"><strong>{{ disk.target }}</strong> <span class="text-body-secondary">{{ disk.capacity|binary_size }}</span></p>
<p class="small text-body-secondary text-break mb-2">{{ disk.path }}</p>
{% if disk.shared or not disk.refusal and disk.free_pools %}
<label class="form-label small" for="pool-{{ disk.target }}">{% trans "On the destination" %}</label>
@ -16,7 +17,7 @@
{% if not disk.refusal %}
{% for pool in pools %}
{% if pool.name in disk.free_pools %}
<option value="{{ pool.name }}"{% if not disk.shared and pool.name == disk.default %} selected{% endif %}>{% blocktrans with name=pool.name free=pool.free|filesizeformat %}Copy to {{ name }} ({{ free }} free){% endblocktrans %}</option>
<option value="{{ pool.name }}"{% if not disk.shared and pool.name == disk.default %} selected{% endif %}>{% blocktrans with name=pool.name free=pool.free|binary_size %}Copy to {{ name }} ({{ free }} free){% endblocktrans %}</option>
{% else %}
<option value="{{ pool.name }}" disabled>{% blocktrans with name=pool.name %}{{ name }} has a file of this name{% endblocktrans %}</option>
{% endif %}

View file

@ -1,4 +1,5 @@
{% load i18n %}
{% load common_tags %}
{% load bootstrap_icons %}
{% load vm_states %}
<div class="tab-pane" id="resize" role="tabpanel">
@ -83,7 +84,7 @@
<div class="d-flex flex-wrap align-items-center gap-2 gap-sm-3 mb-3">
<div class="memory-bar" aria-hidden="true"><div class="memory-bar-now" style="width: {% widthratio instance.cur_memory instance.memory 100 %}%"></div></div>
<span class="small">{% blocktrans with cur=instance.cur_memory max=instance.memory %}{{ cur }} MiB of {{ max }} MiB{% endblocktrans %}</span>
<span class="small ms-auto text-body-secondary">{% blocktrans with total=memory_host|filesizeformat %}Host: {{ total }}{% endblocktrans %}</span>
<span class="small ms-auto text-body-secondary">{% blocktrans with total=memory_host|binary_size %}Host: {{ total }}{% endblocktrans %}</span>
</div>
<form class="row g-2 align-items-end" action="{% url 'instances:resize_memory' instance.id %}" method="post">{% csrf_token %}
<div class="col-6 col-sm-3">
@ -110,7 +111,7 @@
{% if disk.storage is None %}
<div class="col"><span class="small text-danger">{% trans "Error getting disk info" %}</span></div>
{% else %}
<div class="col-7 col-sm-2 small">{% blocktrans with size=disk.size|filesizeformat %}Now {{ size }}{% endblocktrans %}</div>
<div class="col-7 col-sm-2 small">{% blocktrans with size=disk.size|binary_size %}Now {{ size }}{% endblocktrans %}</div>
<div class="col-12 col-sm-4">
<div class="input-group">
<input class="form-control" type="number" id="disk_size_{{ disk.dev }}" name="disk_size_{{ disk.dev }}" min="1" step="1" placeholder="{% trans "New size" %}" aria-describedby="disks-grow-help">

View file

@ -1,4 +1,5 @@
{% load i18n %}
{% load common_tags %}
{% load django_bootstrap5 %}
{% load bootstrap_icons %}
{% load vm_states %}
@ -215,8 +216,8 @@
{# a qcow2 file's metadata can take it past its capacity: the bar stops full #}
{% if used_percent|add:0 > 100 %}{% widthratio 100 1 1 as used_percent %}{% endif %}
<div class="d-flex flex-wrap justify-content-between gap-1">
<strong>{% trans "Capacity" %} {{ disk.size|filesizeformat }}</strong>
<span class="text-body-secondary">{% blocktrans with used=disk.used|filesizeformat %}{{ used }} used{% endblocktrans %}</span>
<strong>{% trans "Capacity" %} {{ disk.size|binary_size }}</strong>
<span class="text-body-secondary">{% blocktrans with used=disk.used|binary_size %}{{ used }} used{% endblocktrans %}</span>
</div>
<div class="progress my-2" style="height: .25rem;" role="progressbar" aria-label="{% blocktrans with dev=disk.dev %}{{ dev }} used{% endblocktrans %}" aria-valuenow="{{ used_percent }}" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar" style="width: {{ used_percent }}%"></div>

View file

@ -36,7 +36,7 @@ const handlers = {}, requests = [];
const dialog = {addEventListener: (name, fn) => { handlers[name] = fn; },
querySelectorAll: (sel) => sel === ".cpu-usage" ? cells : cells.flatMap((c, i) => [c, lines[i]])};
const page = {
document: {getElementById: () => dialog},
document: {documentElement: {lang: "en"}, getElementById: () => dialog},
$: {get: (url) => {
const r = {url, done: (f) => { r.ok = f; return r; }, fail: (f) => { r.err = f; return r; },
always: (f) => { r.end = f; return r; }};

View file

@ -83,7 +83,7 @@ class DrbdListTestCase(TestCase):
patch.object(Compute, "status", new_callable=PropertyMock, return_value=True), \
patch.object(Instance, "info", new_callable=PropertyMock, return_value=None), \
patch.object(Compute, "proxy", new_callable=PropertyMock,
return_value=MagicMock(**{"get_domain_rows.return_value": {}})), \
return_value=MagicMock(**{"get_domain_rows.return_value": {}, "get_memory_usage.return_value": {"percent": 10}})), \
patch("instances.views.subprocess.run", return_value=SimpleNamespace(returncode=0, stdout=STATUS)) as run:
self.assertEqual(self.client.get(reverse("instances:index")).status_code, 200)
run.assert_called_once()
@ -108,7 +108,7 @@ class DrbdListTestCase(TestCase):
patch.object(Compute, "status", new_callable=PropertyMock, return_value=True), \
patch.object(Instance, "info", new_callable=PropertyMock, return_value=None), \
patch.object(Compute, "proxy", new_callable=PropertyMock,
return_value=MagicMock(**{"get_domain_rows.return_value": {}})), \
return_value=MagicMock(**{"get_domain_rows.return_value": {}, "get_memory_usage.return_value": {"percent": 10}})), \
patch("instances.views.subprocess.run", side_effect=slow) as run:
self.client.get(reverse("instances:index"))
self.assertEqual(run.call_count, 3)

View file

@ -23,7 +23,7 @@ const ids = {
};
const answer = ANSWER;
vm.runInNewContext(SCRIPT, vm.createContext({
document: {getElementById: (id) => ids[id]}, URLSearchParams, Promise, Date, location: {},
document: {documentElement: {lang: "en"}, getElementById: (id) => ids[id]}, URLSearchParams, Promise, Date, location: {},
fetch: () => Promise.resolve({redirected: false, json: () => Promise.resolve(answer)}),
}));
handlers.submit({preventDefault() {}});

View file

@ -27,7 +27,7 @@ class GuestInfoTestCase(TestCase):
{"mountpoint": "/", "type": "xfs", "used": 9 * 2**30, "total": 10 * 2**30}]}
data = self.client.get(reverse("instances:osinfo", args=[self.instance.pk])).json()
self.assertEqual(data["filesystems"], [{"mountpoint": "/", "type": "xfs", "used": 9 * 2**30, "total": 10 * 2**30,
"used_text": "9.0\xa0GB", "total_text": "10.0\xa0GB", "percent": 90}])
"used_text": "9\xa0GiB", "total_text": "10\xa0GiB", "percent": 90}])
def test_a_file_system_used_past_its_total_is_full(self):
# a BSD guest's total leaves out the space reserved for root, which used counts

View file

@ -204,8 +204,8 @@ class MigrateJobTestCase(TransactionTestCase):
self.assertEqual(dest.migration_plan.call_args.args[1:], ("<domain/>", "<domain/>"))
self.assertEqual(Instance.proxy.instance.XMLDesc.call_args_list[-1].args, (VIR_DOMAIN_XML_INACTIVE,))
# the pool on the disk's directory is chosen; one that has a file of the name cannot be
self.assertIn('<option value="default" selected>Copy to default (8.0\xa0GB free)</option>', page)
self.assertIn('<option value="fast">Copy to fast (8.0\xa0GB free)</option>', page)
self.assertIn('<option value="default" selected>Copy to default (8\xa0GiB free)</option>', page)
self.assertIn('<option value="fast">Copy to fast (8\xa0GiB free)</option>', page)
self.assertIn('<option value="fast" disabled>fast has a file of this name</option>', page)
self.assertIn("Cannot be copied: an image is not copied; eject it first", page)
self.assertEqual(page.count("Another disk of the VM has this file name: copy them to different pools."), 1)

View file

@ -142,7 +142,7 @@ class PageControlsTestCase(PageControls, TestCase):
self.assertEqual([a.text_content().strip() for a in admin_page.xpath(links)], ["ctl-compute", "Instances"])
self.assertEqual([a.text_content().strip() for a in owner_page.xpath(links)], ["Instances"])
self.assertIn("Guest agent not connected", self.last_page)
self.assertIn("vda 2.0\xa0GB · vdb 1.0\xa0GB", self.last_page)
self.assertIn("vda 2\xa0GiB · vdb 1\xa0GiB", self.last_page)
# filled by its script once the page has loaded ("—" when it has none)
self.assertEqual(owner_page.xpath("//dt[.='IPv4']/following-sibling::dd/@data-empty"), ["—"])

View file

@ -57,7 +57,7 @@ class ResizeInputTests(TestCase):
disks = [{"dev": "vda", "size": 10 * GIB}, {"dev": "vdb", "size": 20 * GIB}]
messages, proxy = self.post("instances:resize_disk", {"disk_size_vda": "5", "disk_size_vdb": "30"}, disks=disks)
proxy.resize_disk.assert_not_called()
self.assertEqual(messages, ["vda is 10.0\xa0GB: a disk cannot shrink"])
self.assertEqual(messages, ["vda is 10\xa0GiB: a disk cannot shrink"])
def test_vcpus_and_memory_must_be_at_least_one(self):
for view, data, setter in (("instances:resizevm_cpu", {"vcpu": "2", "cur_vcpu": "0"}, "resize_cpu"),

View file

@ -214,7 +214,7 @@ class StatsScriptTestCase(TestDriverVM, TestCase):
poll.request();
fail = false;
poll.request();
const label = charts[0].options.plugins.tooltip.callbacks.label({dataset: {label: "Usage"}, formattedValue: "3", dataIndex: 0});
const label = charts[0].options.plugins.tooltip.callbacks.label({dataset: {label: "Usage"}, formattedValue: "3", parsed: {y: 3}, dataIndex: 0});
console.log(JSON.stringify({requests, label, every: [poll.interval, poll.first], cpu: charts[0].data.datasets[0].data.map((point) => point.y),
disk: charts[2].data.datasets[1].data.map((point) => point.y), net: charts[3].data.datasets[0].data.map((point) => point.y),
mem: charts[1].data.datasets[0].data.map((point) => point.y), memMax: charts[1].options.scales.y.max}));
@ -231,4 +231,4 @@ class StatsScriptTestCase(TestDriverVM, TestCase):
self.assertEqual((result["cpu"], result["disk"], result["net"]), ([3, 4], [None, None], [2, 2]))
# memory that could not be read leaves a gap and keeps the axis
self.assertEqual((result["mem"], result["memMax"]), ([1, None], 1))
self.assertTrue(result["label"].endswith(": 3 % (average over 9.9 s)"), result["label"])
self.assertTrue(result["label"].endswith(": 3% (average over 9.9 s)"), result["label"])

View file

@ -85,7 +85,7 @@ class VmStatesTestCase(TestCase):
with patch.object(Compute, "status", property(lambda c: c.pk == self.up.pk)), \
patch.object(Compute, "connection_error", property(lambda c: None if c.pk == self.up.pk else "unreachable")), \
patch.object(Compute, "proxy", new_callable=PropertyMock,
return_value=MagicMock(**{"get_domain_rows.return_value": {}})), \
return_value=MagicMock(**{"get_domain_rows.return_value": {}, "get_memory_usage.return_value": {"percent": 10}})), \
patch("instances.views.refresh_instance_database"), patch("computes.views.utils.refresh_instance_database"):
for url, states_url in ((reverse("instances:index"), reverse("instances:states")),
(reverse("instances", args=[self.up.pk]),

View file

@ -35,7 +35,7 @@ from django.db import transaction
from django.db.models import Prefetch, prefetch_related_objects
from django.shortcuts import get_object_or_404, redirect, render
from django.urls import reverse
from django.template.defaultfilters import filesizeformat
from webvirtcloud.common_tags import binary_size
from django.utils import timezone
from django.utils.http import url_has_allowed_host_and_scheme
from django.utils.translation import gettext as _
@ -574,7 +574,7 @@ def osinfo(request, pk):
try:
info = instance.proxy.osinfo()
for fs in info.get("filesystems", []): # sizes in the page's words
fs.update(used_text=filesizeformat(fs["used"]), total_text=filesizeformat(fs["total"]),
fs.update(used_text=binary_size(fs["used"]), total_text=binary_size(fs["total"]),
percent=min(100, fs["used"] * 100 // fs["total"])) # used may pass a BSD guest's total
return JsonResponse(info)
except libvirtError as err:
@ -1475,7 +1475,7 @@ def resize_disk(request, pk):
# a disk does not shrink: one smaller size refuses them all
if int(size) << 30 < disk["size"]:
messages.error(request, _("%(dev)s is %(size)s: a disk cannot shrink") % {
"dev": disk["dev"], "size": filesizeformat(disk["size"])})
"dev": disk["dev"], "size": binary_size(disk["size"])})
return redirect(reverse("instances:instance", args=[instance.id]) + "#resizevm_disk")
if int(size) << 30 > disk["size"]:
disk["size_new"] = int(size) << 30

Binary file not shown.

View file

@ -588,7 +588,7 @@ msgstr ""
#: accounts/views.py:93
#, python-format
msgid "You have a token named %(name)s: choose another name."
msgstr "%(name)s adlı bir token'ınız var: başka bir ad seçin."
msgstr "%(name)s adlı bir API anahtarınız var: başka bir ad seçin."
#: accounts/views.py:130
msgid "API token deleted"
@ -1260,7 +1260,7 @@ msgstr "Kullanıcının nasıl oturum açtığı."
#: admin/templates/admin/user_password_form.html:19
msgid "Changing it deletes the user's API tokens."
msgstr "Değiştirmek kullanıcının API token'larını siler."
msgstr "Değiştirmek kullanıcının API anahtarlarını siler."
#: admin/templates/admin/user_password_form.html:22
msgid "Signs in with the password set here."
@ -2238,7 +2238,7 @@ msgstr ""
#: computes/models.py:56
msgid "hostname"
msgstr "sunucuadı"
msgstr "ana bilgisayar adı"
#: computes/models.py:57
msgid "login"
@ -2346,8 +2346,8 @@ msgstr "%%%(percent)s dolu"
#, python-format
msgid "%(counter)s snapshot older than 30 days"
msgid_plural "%(counter)s snapshots older than 30 days"
msgstr[0] "30 günden eski %(counter)s snapshot"
msgstr[1] "30 günden eski %(counter)s snapshot"
msgstr[0] "30 günden eski %(counter)s anlık görüntü"
msgstr[1] "30 günden eski %(counter)s anlık görüntü"
#: computes/templates/computes/attention.html:17
#, python-format
@ -3130,7 +3130,7 @@ msgstr "Yazılım ve bağlantı"
#: computes/templates/overview.html:205
#: instances/templates/instances/info_tab.html:6
msgid "Hostname"
msgstr "Sunucuadı"
msgstr "Ana bilgisayar adı"
#: computes/templates/overview.html:217
msgid "Guest architectures"
@ -3721,7 +3721,7 @@ msgstr "%(quota)s: %(name)s anlık görüntüsüne dönülemiyor."
#: instances/jobs.py:525
msgid "Revert snapshot"
msgstr "Snapshota dön"
msgstr "Anlık görüntüye dön"
#: instances/jobs.py:568
msgid "Reverting the VM"
@ -4575,8 +4575,8 @@ msgstr "daraltıldı"
#: instances/templates/allinstances_index_grouped.html:48
#, python-format
msgid "host memory %(percent)s%% in use"
msgstr "sunucu belleği kullanımı %%%(percent)s"
msgid "Host memory %(percent)s%% in use"
msgstr "Sunucu belleği kullanımı %%%(percent)s"
#: instances/templates/allinstances_index_grouped.html:49
msgid "Host memory in use"
@ -9199,11 +9199,6 @@ msgstr "Başarılı"
msgid "What you checked"
msgstr "Neyi kontrol ettiniz"
#: operations/templates/operations/jobs.html:14
#: operations/templatetags/operations.py:97
msgid "Worker unavailable, last seen"
msgstr "İşçi kullanılamıyor, son görülme"
#: operations/templates/operations/jobs.html:22
msgid "Filter jobs"
msgstr "İşleri filtrele"
@ -9383,7 +9378,7 @@ msgstr ""
#: operations/worker.py:505
msgid "The worker stopped before the job changed anything"
msgstr "Worker, iş herhangi bir şeyi değiştirmeden önce durdu"
msgstr "İş işleyicisi, iş herhangi bir şeyi değiştirmeden önce durdu"
#: storages/api/viewsets.py:148 storages/api/viewsets.py:164
#: storages/api/viewsets.py:200 storages/api/viewsets.py:223
@ -13027,3 +13022,20 @@ msgstr "Hangi sanal makineler"
#: vmbackups/forms.py
msgid "Choose the VMs to back up"
msgstr "Yedeklenecek sanal makineleri seçin"
#: webvirtcloud/common_tags.py:29
#, python-format
msgid "%(percent)s%%"
msgstr "%%%(percent)s"
#: operations/templates/operations/jobs.html:16
#: operations/templatetags/operations.py:98
#, python-format
msgid "The job worker is not running; it was last seen %(when)s. Jobs wait until it runs again."
msgstr "İş işleyicisi çalışmıyor; en son %(when)s görüldü. İşler o yeniden çalışana kadar bekler."
#: operations/templates/operations/jobs.html:16
#: operations/templatetags/operations.py:99
msgid "The job worker has not run yet. Jobs wait until it runs."
msgstr "İş işleyicisi henüz hiç çalışmadı. İşler o çalışana kadar bekler."

Binary file not shown.

View file

@ -4345,7 +4345,7 @@ msgstr "已折叠"
#: instances/templates/allinstances_index_grouped.html:48
#, python-format
msgid "host memory %(percent)s%% in use"
msgid "Host memory %(percent)s%% in use"
msgstr "主机内存已用 %(percent)s%%"
#: instances/templates/allinstances_index_grouped.html:49
@ -8671,11 +8671,6 @@ msgstr "成功"
msgid "What you checked"
msgstr "检查内容"
#: operations/templates/operations/jobs.html:14
#: operations/templatetags/operations.py:97
msgid "Worker unavailable, last seen"
msgstr "工作进程不可用,最后在线时间"
#: operations/templates/operations/jobs.html:22
msgid "Filter jobs"
msgstr "筛选任务"
@ -12302,3 +12297,20 @@ msgstr "哪些虚拟机"
#: vmbackups/forms.py
msgid "Choose the VMs to back up"
msgstr "请选择要备份的虚拟机"
#: webvirtcloud/common_tags.py:29
#, python-format
msgid "%(percent)s%%"
msgstr "%(percent)s%%"
#: operations/templates/operations/jobs.html:16
#: operations/templatetags/operations.py:98
#, python-format
msgid "The job worker is not running; it was last seen %(when)s. Jobs wait until it runs again."
msgstr "工作进程未在运行;最后在线时间 %(when)s。任务将等待它重新运行。"
#: operations/templates/operations/jobs.html:16
#: operations/templatetags/operations.py:99
msgid "The job worker has not run yet. Jobs wait until it runs."
msgstr "工作进程尚未运行过。任务将等待它运行。"

View file

@ -25,6 +25,8 @@ function jobPanel(element, urls, csrfToken, initialIds, states, text) {
var last = { jobs: [], others: [], short_operation: false, worker_last_seen: null, worker_gone: false };
var rendered = null; // the panel's last html: an unchanged one is not rebuilt (focus stays)
var holding = false; // the panel set backgroundJobRunning (no other script holds it)
// a percentage as the page's language writes it: 38% in English, %38 in Turkish
var percentFormat = new Intl.NumberFormat(document.documentElement.lang || undefined, {style: "percent"});
if (initialIds && initialIds.length) {
// a remembered job must not be lost to a status reload before the first poll answers
window.backgroundJobRunning = true;
@ -44,13 +46,13 @@ function jobPanel(element, urls, csrfToken, initialIds, states, text) {
return '<div class="progress mt-2" role="progressbar" aria-valuenow="' + (finishing ? 100 : pct)
+ '" aria-valuemin="0" aria-valuemax="100"><div class="progress-bar'
+ (finishing ? " progress-bar-striped progress-bar-animated" : "") + '" style="width:'
+ (finishing ? 100 : pct) + '%">' + (finishing ? esc(text.finishing) : pct + "%") + "</div></div>";
+ (finishing ? 100 : pct) + '%">' + (finishing ? esc(text.finishing) : percentFormat.format(pct / 100)) + "</div></div>";
}
// label, state badge and muted phase on one line, the buttons on its right
function header(label, state, phase, buttons) {
return '<div class="d-flex flex-wrap align-items-center gap-2"><strong>' + esc(label) + "</strong>"
+ '<span class="badge bg-' + JOB_STATE_COLORS[state]
+ '<span class="badge job-state bg-' + JOB_STATE_COLORS[state]
// the theme draws white text on a warning badge
+ (JOB_STATE_COLORS[state] === "warning" ? " text-dark" : "") + '">' + esc(states[state] || state) + "</span>"
+ (phase ? '<span class="small text-body-secondary">' + esc(phase) + "</span>" : "")
@ -104,8 +106,8 @@ function jobPanel(element, urls, csrfToken, initialIds, states, text) {
// the server tells: the browser's clock may be off
var seen = last.worker_last_seen ? new Date(last.worker_last_seen) : null;
if (waiting && last.worker_gone) {
html += '<div class="alert alert-warning mb-3" role="status">' + esc(text.worker_unavailable) + " "
+ esc(seen ? seen.toLocaleString() : text.never) + ".</div>";
html += '<div class="alert alert-warning mb-3" role="status">'
+ esc(seen ? text.worker_gone.replace("%(when)s", seen.toLocaleString(document.documentElement.lang || undefined)) : text.worker_never) + "</div>";
}
if (html !== rendered) {
element.innerHTML = html;

View file

@ -1,5 +1,6 @@
{% extends "base.html" %}
{% load i18n %}
{% load common_tags %}
{% load bootstrap_icons %}
{% load operations %}
@ -38,9 +39,9 @@
{% widthratio op.progress_done|default:0 op.progress_total 100 as percent %}
<div class="d-flex flex-wrap justify-content-between gap-2 small mb-2">
<span class="text-body-secondary">
{% if progress_bytes %}{{ op.progress_done|default:0|filesizeformat }} / {{ op.progress_total|filesizeformat }}{% else %}{{ op.progress_done|default:0 }} / {{ op.progress_total }}{% endif %}
{% if progress_bytes %}{{ op.progress_done|default:0|binary_size }} / {{ op.progress_total|binary_size }}{% else %}{{ op.progress_done|default:0 }} / {{ op.progress_total }}{% endif %}
</span>
<strong>{{ percent }}%</strong>
<strong>{{ percent|percent }}</strong>
</div>
<div class="progress mb-3" style="height: .5rem;" role="progressbar" aria-label="{% trans 'Progress' %}" aria-valuenow="{{ percent }}" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar" style="width: {{ percent }}%"></div>

View file

@ -1,5 +1,6 @@
{% extends "base.html" %}
{% load i18n %}
{% load common_tags %}
{% load django_bootstrap5 %}
{% load static %}
{% load bootstrap_icons %}
@ -12,8 +13,8 @@
{% block content %}
{% if worker_unavailable %}
<div class="alert alert-warning shadow-sm">
{% bs_icon 'exclamation-triangle' %} {% trans "Worker unavailable, last seen" %}
{% if worker_last_seen %}{{ worker_last_seen|date:"Y-m-d H:i:s T" }}{% else %}{% trans "never" %}{% endif %}
{% bs_icon 'exclamation-triangle' %}
{% if worker_last_seen %}{% blocktrans with when=worker_last_seen|date:"Y-m-d H:i:s T" %}The job worker is not running; it was last seen {{ when }}. Jobs wait until it runs again.{% endblocktrans %}{% else %}{% trans "The job worker has not run yet. Jobs wait until it runs." %}{% endif %}
</div>
{% endif %}
<div class="card mb-3">
@ -73,7 +74,7 @@
{{ row.phase }}
{% if op.progress_total %}
{% if row.phase %}&middot;{% endif %}
{% if op.kind in bytes_kinds %}{{ op.progress_done|default:0|filesizeformat }} / {{ op.progress_total|filesizeformat }}{% else %}{{ op.progress_done|default:0 }} / {{ op.progress_total }}{% endif %}
{% if op.kind in bytes_kinds %}{{ op.progress_done|default:0|binary_size }} / {{ op.progress_total|binary_size }}{% else %}{{ op.progress_done|default:0 }} / {{ op.progress_total }}{% endif %}
{% endif %}
</div>
{% endif %}

View file

@ -1 +1 @@
{% load operations %}{% with color=state|state_color %}<span class="badge bg-{{ color }}{% if color == "warning" %} text-dark{% endif %}">{{ state|state_label }}</span>{% endwith %}
{% load operations %}{% with color=state|state_color %}<span class="badge job-state bg-{{ color }}{% if color == "warning" %} text-dark{% endif %}">{{ state|state_label }}</span>{% endwith %}

View file

@ -95,8 +95,8 @@ def job_panel_script(context, resource):
"finishing": gettext("Finishing…"),
"not_removed": gettext("Files not removed:"),
"short_operation": gettext("A short operation is in progress."),
"worker_unavailable": gettext("Worker unavailable, last seen"),
"never": gettext("never"),
"worker_gone": gettext("The job worker is not running; it was last seen %(when)s. Jobs wait until it runs again."),
"worker_never": gettext("The job worker has not run yet. Jobs wait until it runs."),
"cancel_failed": gettext("Cancel failed (HTTP %(status)s)."),
"cancel_unreachable": gettext("Cancel failed: the server could not be reached."),
},

View file

@ -18,7 +18,7 @@ function advance(ms) {
}
const realNow = Date.now;
Date.now = () => 1700000000000 + now;
global.document = { hidden: false, addEventListener() {}, activeElement: null, querySelector: () => null };
global.document = { documentElement: { lang: "en" }, hidden: false, addEventListener() {}, activeElement: null, querySelector: () => null };
global.window = { backgroundJobRunning: false,
location: { reload() { window.reloaded = true; }, assign(url) { window.opened = url; } } };
@ -55,7 +55,7 @@ const STATES = { queued: "queued", running: "running", cancelling: "cancelling",
failed: "failed", cancelled: "cancelled", uncertain: "uncertain" };
const TEXT = { cancel: "Cancel", cancel_confirm: "Cancel %(job)s?", open: "Open", refresh: "Refresh", dismiss: "Dismiss", finishing: "Finishing\u2026",
not_removed: "Files not removed:", short_operation: "A short operation is in progress.",
worker_unavailable: "Worker unavailable, last seen", never: "never",
worker_gone: "The job worker is not running; it was last seen %(when)s.", worker_never: "The job worker has not run yet.",
cancel_failed: "Cancel failed (HTTP %(status)s).",
cancel_unreachable: "Cancel failed: the server could not be reached." };
const seen = new Date(1700000000000).toISOString();
@ -71,7 +71,7 @@ assert.ok(el.innerHTML.includes("Delete snapshot") && el.innerHTML.includes("25%
// one colour per state (operations/tests/test_views.py checks the same map in the template filter)
assert.deepStrictEqual(JOB_STATE_COLORS, { queued: "secondary", running: "primary", cancelling: "info",
succeeded: "success", failed: "danger", cancelled: "secondary", uncertain: "warning" });
assert.ok(el.innerHTML.includes('class="alert alert-primary') && el.innerHTML.includes('<span class="badge bg-primary">running</span>')
assert.ok(el.innerHTML.includes('class="alert alert-primary') && el.innerHTML.includes('<span class="badge job-state bg-primary">running</span>')
&& el.innerHTML.includes('<span class="small text-body-secondary">Merging</span>'), "state badge and muted phase");
assert.strictEqual(window.backgroundJobRunning, true);
@ -104,7 +104,7 @@ answer("/r", empty);
answer("/j/a", { ...running, state: "succeeded", result: { left_behind: ["/pool/a.one"], warning: "not <thawed>" } });
assert.ok(el.innerHTML.includes('<li class="text-break"><code>/pool/a.one</code></li>'), "shows the warning from the result");
assert.ok(el.innerHTML.includes('<div class="small mt-2">not &lt;thawed&gt;</div>'), "shows the result's warning escaped");
assert.ok(el.innerHTML.includes('class="alert alert-success') && el.innerHTML.includes('<span class="badge bg-success">succeeded</span>')
assert.ok(el.innerHTML.includes('class="alert alert-success') && el.innerHTML.includes('<span class="badge job-state bg-success">succeeded</span>')
&& el.innerHTML.includes('<div class="ms-auto d-flex gap-2"><button type="button" class="btn btn-sm btn-primary" data-refresh'),
"the outcome has the state colour and its buttons on the right");
assert.strictEqual(window.backgroundJobRunning, true, "keeps backgroundJobRunning until dismissed");
@ -141,7 +141,7 @@ const el4 = { addEventListener() {},
jobPanel(el4, urls, "tok", undefined, STATES, TEXT);
advance(0);
answer("/r", { ...empty, jobs: [{ ...running, state: "uncertain", error: "check the disks" }] });
assert.ok(el4.innerHTML.includes('<span class="badge bg-warning text-dark">uncertain</span>'), "dark text on the yellow badge");
assert.ok(el4.innerHTML.includes('<span class="badge job-state bg-warning text-dark">uncertain</span>'), "dark text on the yellow badge");
assert.ok(el4.innerHTML.includes("check the disks") && el4.innerHTML.includes('class="alert alert-warning'),
"an uncertain job in the list shows its error");
// an unchanged answer does not rebuild the panel (a focused button keeps its focus)
@ -194,27 +194,27 @@ const stale = new Date(Date.now() - 120000).toISOString();
jobPanel(el8, urls, "tok", undefined, STATES, TEXT);
advance(0);
answer("/r", { ...empty, worker_last_seen: stale, worker_gone: true, jobs: [running] });
assert.ok(el8.innerHTML.includes("Worker unavailable"), "a running job with a stale lease warns");
assert.ok(el8.innerHTML.includes("The job worker"), "a running job with a stale lease warns");
advance(3000);
answer("/r", { ...empty, worker_last_seen: stale, worker_gone: true, jobs: [{ ...running, state: "cancelling" }] });
assert.ok(el8.innerHTML.includes("Worker unavailable"), "a cancelling job with a stale lease warns");
assert.ok(el8.innerHTML.includes("The job worker"), "a cancelling job with a stale lease warns");
advance(3000);
answer("/r", { ...empty, worker_last_seen: new Date(Date.now()).toISOString(), jobs: [running] });
assert.ok(!el8.innerHTML.includes("Worker unavailable"), "a fresh lease does not warn");
assert.ok(!el8.innerHTML.includes("The job worker"), "a fresh lease does not warn");
advance(3000);
// the server decides: a browser clock two minutes ahead does not make a fresh lease look stale
answer("/r", { ...empty, worker_last_seen: stale, worker_gone: false, jobs: [running] });
assert.ok(!el8.innerHTML.includes("Worker unavailable"), "a lease the server finds fresh does not warn");
assert.ok(!el8.innerHTML.includes("The job worker"), "a lease the server finds fresh does not warn");
advance(3000);
answer("/r", { ...empty, worker_last_seen: stale, worker_gone: true, jobs: [{ ...running, state: "uncertain" }] });
assert.ok(!el8.innerHTML.includes("Worker unavailable"), "an uncertain job waits for an administrator, not the worker");
assert.ok(!el8.innerHTML.includes("The job worker"), "an uncertain job waits for an administrator, not the worker");
advance(3000);
answer("/r", { ...empty, worker_last_seen: stale, worker_gone: true, jobs: [{ ...running, in_request: true }] });
assert.ok(!el8.innerHTML.includes("Worker unavailable"), "a job a request runs does not wait for the worker");
assert.ok(!el8.innerHTML.includes("The job worker"), "a job a request runs does not wait for the worker");
advance(3000);
answer("/r", { ...empty, worker_last_seen: stale, worker_gone: true, jobs: [{ ...running, in_request: true },
{ ...running, id: "w", state: "queued", in_request: false }] });
assert.ok(el8.innerHTML.includes("Worker unavailable"), "a queued job beside it still warns");
assert.ok(el8.innerHTML.includes("The job worker"), "a queued job beside it still warns");
// cancel: the button is disabled while the request runs; a refusal or a network error shows; the list is asked again
open = []; timers = [];
@ -262,7 +262,7 @@ assert.strictEqual(window.backgroundJobRunning, true, "a tracked job holds the p
assert.ok(open.some((r) => r.url === "/r" && !r.settled), "the list is asked for at once");
answer("/r", empty);
answer("/j/t", { ...running, id: "t", label: "Upload", state: "cancelled" });
assert.ok(el10.innerHTML.includes("Upload") && el10.innerHTML.includes('<span class="badge bg-secondary">cancelled</span>'),
assert.ok(el10.innerHTML.includes("Upload") && el10.innerHTML.includes('<span class="badge job-state bg-secondary">cancelled</span>'),
"the tracked job's outcome shows");
// a list answer older than the job, then its detail still active: the panel keeps following it
@ -282,7 +282,7 @@ assert.strictEqual(open.filter((r) => !r.settled && r.url === "/j/u").length, 1,
window.reloaded = false;
answer("/j/u", { ...running, id: "u", label: "Upload", state: "succeeded" });
assert.ok(window.reloaded, "a job that succeeds without a warning reloads the page: it shows the job's effect");
assert.ok(!el11.innerHTML.includes('<span class="badge bg-success">succeeded</span>'), "not shown as well");
assert.ok(!el11.innerHTML.includes('<span class="badge job-state bg-success">succeeded</span>'), "not shown as well");
// a job that made a VM opens its page; a warning keeps the outcome, with Open; only a path of this site
open = []; timers = []; window.reloaded = false; window.opened = null;
@ -314,7 +314,7 @@ for (const [label, doc] of [["dialog", { querySelector: (s) => s === ".modal.sho
advance(0);
answer("/r", empty);
answer("/j/m", { ...running, id: "m", label: "Clone", state: "succeeded" });
assert.ok(!window.reloaded && elm.innerHTML.includes('<span class="badge bg-success">succeeded</span>')
assert.ok(!window.reloaded && elm.innerHTML.includes('<span class="badge job-state bg-success">succeeded</span>')
&& elm.innerHTML.includes("data-refresh"), "with a " + label + ": the outcome with Refresh, no reload");
}
Object.assign(document, { activeElement: null, querySelector: () => null });
@ -369,7 +369,7 @@ console.log("ok");
jobPanel(elt, urls, "tok", undefined, states, { ...TEXT, cancel: "İptal" });
advance(0);
answer("/r", { ...empty, jobs: [{ ...running, id: "t", cancellable: true }] });
assert.ok(elt.innerHTML.includes('<span class="badge bg-primary">çalışıyor</span>')
assert.ok(elt.innerHTML.includes('<span class="badge job-state bg-primary">çalışıyor</span>')
&& elt.innerHTML.includes(">İptal</button>"), "labels and texts of the page's language");
}

View file

@ -240,7 +240,7 @@ class JobsPageTestCase(TransactionTestCase):
self.client.force_login(self.admin)
for response in (self.client.get(reverse("operations:jobs")),
self.client.get(reverse("operations:job", args=[self.op.pk]))):
self.assertContains(response, '<span class="badge bg-danger">failed</span>')
self.assertContains(response, '<span class="badge job-state bg-danger">failed</span>')
detail = self.client.get(reverse("operations:job", args=[self.op.pk]))
self.assertContains(detail, 'class="alert alert-danger"')
@ -272,7 +272,7 @@ class JobsPageTestCase(TransactionTestCase):
(Operation.UNCERTAIN, False), (Operation.SUCCEEDED, False)):
Operation.objects.filter(pk=self.op.pk).update(state=state, worker="" if state == Operation.QUEUED else "h:1:a")
response = self.client.get(reverse("operations:jobs"))
(self.assertContains if warned else self.assertNotContains)(response, "Worker unavailable", msg_prefix=state)
(self.assertContains if warned else self.assertNotContains)(response, "The job worker", msg_prefix=state)
# a job a request runs does not wait for the worker
for state in (Operation.RUNNING, Operation.CANCELLING):
Operation.objects.filter(pk=self.op.pk).update(state=state, worker=Operation.REQUEST)
@ -291,7 +291,7 @@ class JobsPageTestCase(TransactionTestCase):
self.client.force_login(self.admin)
# the app's theme draws white text on bg-warning
self.assertContains(self.client.get(reverse("operations:jobs")),
'<span class="badge bg-warning text-dark">uncertain</span>')
'<span class="badge job-state bg-warning text-dark">uncertain</span>')
def test_a_narrow_list_shows_resource_and_user_under_the_job(self):
Operation.objects.filter(pk=self.op.pk).update(resource_label="wvc-test-host/wvc-test-vm")
@ -325,7 +325,7 @@ class JobsPageTestCase(TransactionTestCase):
listed = self.client.get(reverse("operations:jobs"))
detail = self.client.get(reverse("operations:job", args=[self.op.pk]))
for response in (listed, detail):
self.assertContains(response, '<span class="badge bg-primary">T[running]</span>')
self.assertContains(response, '<span class="badge job-state bg-primary">T[running]</span>')
self.assertContains(response, "T[Merging the snapshot]")
self.assertContains(listed, '<option value="failed">T[failed]</option>')
@ -337,4 +337,4 @@ class JobsPageTestCase(TransactionTestCase):
self.assertContains(response, 'aria-valuenow="50"')
self.assertContains(response, str(3 * 1024 ** 3))
with patch.object(fakes.NoopKind, "progress_bytes", True):
self.assertContains(self.client.get(url), "3.0\xa0GB / 6.0\xa0GB")
self.assertContains(self.client.get(url), "3\xa0GiB / 6\xa0GiB")

View file

@ -279,6 +279,13 @@ button.vcpu-cell:disabled { opacity: .65; }
.nic-wire::after { right: -3px; }
.nic-wire.nic-up { color: var(--bs-success); border-top-style: solid; }
/* a job state badge starts with a capital, as the VM state badges; the label stays
lowercase for sentences ("… is running on this resource"), and the page's lang
gives Turkish its dotted İ */
.job-state::first-letter {
text-transform: uppercase;
}
/* a log message keeps a readable width when its table scrolls on a phone */
.log-message {
min-width: 16rem;

View file

@ -10,6 +10,10 @@ var TICK_ROOM = 60;
// no thousands separator, as the panel's own pages
var PAGE_LANGUAGE = document.documentElement.lang || undefined;
var formatNumber = new Intl.NumberFormat(PAGE_LANGUAGE, {maximumFractionDigits: 1, useGrouping: false}).format;
// a percentage as the language writes it: 13% in English, %13 in Turkish
function formatPercent(value) {
return new Intl.NumberFormat(PAGE_LANGUAGE, {style: "percent", maximumFractionDigits: 1}).format(value / 100);
}
(function () {
var style = getComputedStyle(document.body);
@ -26,6 +30,10 @@ function lineChart(canvas, unit, labels, options) {
return style.getPropertyValue(name).trim();
});
options = options || {};
// a reading with its unit: a percentage as the language writes it
function withUnit(value, text) {
return unit === "%" ? formatPercent(value) : text + " " + unit;
}
return new Chart(canvas, {
type: "line",
data: {
@ -64,7 +72,9 @@ function lineChart(canvas, unit, labels, options) {
},
},
// the axis as Chart.js writes it (its precision, the page language), with the unit
y: {min: 0, max: options.max, ticks: {callback: function () { return Chart.Ticks.formatters.numeric.apply(this, arguments) + " " + unit; }}},
y: {min: 0, max: options.max, ticks: {callback: function (value) {
return withUnit(value, Chart.Ticks.formatters.numeric.apply(this, arguments));
}}},
},
plugins: {
legend: {display: labels.length > 1},
@ -74,7 +84,7 @@ function lineChart(canvas, unit, labels, options) {
return items.length ? labelAt(items[0].chart, items[0].parsed.x) : "";
},
label: function (context) {
var text = context.dataset.label + ": " + context.formattedValue + " " + unit;
var text = context.dataset.label + ": " + withUnit(context.parsed.y, context.formattedValue);
return options.tooltip ? options.tooltip(context, text) : text;
},
},

View file

@ -81,7 +81,7 @@
});
table.classList.toggle("d-none", matches.length === 0);
if (answer.coverage) {
var readAt = fill(text.readAt, "%(time)s", new Date(answer.read_at).toLocaleTimeString());
var readAt = fill(text.readAt, "%(time)s", new Date(answer.read_at).toLocaleTimeString(document.documentElement.lang || undefined));
var none = MAC.test(form.elements.q.value.trim()) ? text.noneMac : text.none;
coverage.textContent = (matches.length ? "" : none + " ") + coverageText(answer.coverage) + " " + readAt;
} else {

View file

@ -50,7 +50,7 @@ pollWhileVisible(5000, function () {
stale();
return;
}
cpuNow.textContent = formatNumber(data.cpudata) + " %";
cpuNow.textContent = formatPercent(data.cpudata);
lastUpdate = data.timeline;
state.textContent = state.dataset.updated.replace("%(time)s", data.timeline);
state.classList.remove("text-danger");

View file

@ -53,7 +53,7 @@
cpuWindows.shift();
}
addPoint(cpuChart, data.timeline, [data.cpudata]);
document.getElementById("cpuNow").textContent = reading(data.cpudata) + " %";
document.getElementById("cpuNow").textContent = data.cpudata == null ? "–" : formatPercent(data.cpudata);
// a VM whose memory could not be read gives total 0: a gap, same axis;
// the RSS may pass the balloon size: then the axis grows to it
if (data.memdata.total) {

View file

@ -5,6 +5,9 @@
const addInstance = document.getElementById("AddInstance");
let opening = 0, queue = [], reading = 0;
// a percentage as the page's language writes it: 13% in English, %13 in Turkish
const percentFormat = new Intl.NumberFormat(document.documentElement.lang || undefined, {style: "percent"});
function setCpuUsage(cell, percent, text) {
const meter = cell.querySelector(".progress");
cell.querySelector(".progress-bar").style.width = (percent || 0) + "%";
@ -23,7 +26,7 @@ function show(element, data) {
return;
}
const usage = data !== null && typeof data.cpudata === "number" ? Math.round(data.cpudata) : null;
setCpuUsage(element, usage, usage === null ? "—" : usage + "%");
setCpuUsage(element, usage, usage === null ? "—" : percentFormat.format(usage / 100));
}
function readNext() {

View file

@ -1,5 +1,6 @@
{% extends "base.html" %}
{% load i18n %}
{% load common_tags %}
{% load operations %}
{% load static %}
{% load bootstrap_icons %}
@ -66,9 +67,9 @@
{% elif not size %}
<div class="text-body-secondary">{% trans "The pool has no size." %}</div>
{% else %}
<div class="fs-4 lh-sm">{{ percent }} %</div>
<div class="fs-4 lh-sm">{{ percent|percent }}</div>
<div class="small text-body-secondary">
{% blocktrans with used=used|filesizeformat size=size|filesizeformat %}{{ used }} used of {{ size }}{% endblocktrans %}
{% blocktrans with used=used|binary_size size=size|binary_size %}{{ used }} used of {{ size }}{% endblocktrans %}
{# what the space is the space of: other pools may share it #}
{% if type == "dir" or type == "fs" or type == "netfs" %}· {% trans "the filesystem of its path" %}
{% elif type == "logical" %}· {% trans "its volume group" %}
@ -78,7 +79,7 @@
aria-valuenow="{{ percent }}" aria-valuemin="0" aria-valuemax="100">
<div class="progress-bar {% if percent > 90 %}bg-danger{% elif percent > 75 %}bg-warning{% endif %}" style="width: {{ percent }}%"></div>
</div>
<div class="small text-body-secondary">{% blocktrans with free=free|filesizeformat %}{{ free }} free{% endblocktrans %}</div>
<div class="small text-body-secondary">{% blocktrans with free=free|binary_size %}{{ free }} free{% endblocktrans %}</div>
{% endif %}
</div>
</div>
@ -160,8 +161,8 @@
{% endif %}
{# capacity: what the guest sees; allocated: what it takes on the storage now #}
<td class="d-none d-sm-table-cell" data-sort="{{ volume.size }}">
<div>{{ volume.size|filesizeformat }}</div>
<div class="small text-body-secondary">{% blocktrans with allocated=volume.allocation|filesizeformat %}{{ allocated }} allocated{% endblocktrans %}</div>
<div>{{ volume.size|binary_size }}</div>
<div class="small text-body-secondary">{% blocktrans with allocated=volume.allocation|binary_size %}{{ allocated }} allocated{% endblocktrans %}</div>
</td>
<td class="text-end text-nowrap">
<div class="btn-group" role="group" aria-label="{% blocktrans with name=volume.name %}Actions for {{ name }}{% endblocktrans %}">

View file

@ -234,8 +234,8 @@ class PoolListTests(TestCase):
page = html.fromstring(self.client.get(reverse("storages", args=[compute.pk])).content)
cards = [" ".join(" ".join(card.itertext()).split()) for card in page.xpath("//div[@class='card h-100']")]
self.assertEqual(cards, [
"default Active Autostart Type dir Path /var/lib/libvirt/images Volumes 3 60 bytes free of 100 bytes",
"ceph-vms Active Type rbd Path vms Volumes 9 5 bytes free of 100 bytes",
"default Active Autostart Type dir Path /var/lib/libvirt/images Volumes 3 60 B free of 100 B",
"ceph-vms Active Type rbd Path vms Volumes 9 5 B free of 100 B",
"backup Stopped Type dir Path /srv/backup Volumes – Space unavailable while stopped",
])
self.assertEqual(page.xpath("//div[contains(@class,'progress-bar')]/@class"),

View file

@ -1,5 +1,6 @@
{% extends "base.html" %}
{% load i18n %}
{% load common_tags %}
{% load static %}
{% load bootstrap_icons %}
{% load django_bootstrap5 %}
@ -67,7 +68,7 @@
<div class="small text-body-secondary text-truncate">{{ backup.compute_name }}{% if backup.policy %}, <a href="{% url 'vmbackups:policy' backup.policy_id %}" title="{% trans "Schedule" %}">{{ backup.policy.name }}</a>{% endif %}</div>
</td>
<td class="d-none d-md-table-cell">{% include "vmbackups/consistency.html" %}</td>
<td class="text-end text-nowrap d-none d-sm-table-cell">{% if backup.size %}{{ backup.size|filesizeformat }}{% else %}–{% endif %}</td>
<td class="text-end text-nowrap d-none d-sm-table-cell">{% if backup.size %}{{ backup.size|binary_size }}{% else %}–{% endif %}</td>
<td>{% include "vmbackups/state.html" %}</td>
<td class="text-end">{% include "vmbackups/delete_form.html" %}</td>
</tr>

View file

@ -1,4 +1,5 @@
{% load i18n %}
{% load common_tags %}
{% load operations %}
{% load bootstrap_icons %}
{% load static %}
@ -47,7 +48,7 @@
<td class="text-nowrap">{{ backup.created_at|date:"Y-m-d H:i" }}</td>
<td class="d-none d-md-table-cell">{{ backup.target.name }}</td>
<td class="d-none d-sm-table-cell">{% include "vmbackups/consistency.html" %}</td>
<td class="text-end text-nowrap d-none d-sm-table-cell">{% if backup.size %}{{ backup.size|filesizeformat }}{% else %}–{% endif %}</td>
<td class="text-end text-nowrap d-none d-sm-table-cell">{% if backup.size %}{{ backup.size|binary_size }}{% else %}–{% endif %}</td>
<td>{% include "vmbackups/state.html" with pending_deletes=backups.pending_deletes %}</td>
<td class="text-end">{% include "vmbackups/delete_form.html" with pending_deletes=backups.pending_deletes %}</td>
</tr>

View file

@ -609,7 +609,7 @@ class BackupTabTests(PageControls, TransactionTestCase):
page = lxml_html.fromstring(self.last_page)
self.assertTrue(page.xpath("//div[@id='backups']//form[contains(@action, '/backups/vm/')]"))
self.assertIn("nfs1", page.xpath("string(//select[@id='backup-target'])"))
self.assertIn("3.0", page.xpath("string(//div[@id='backups']//table)"))
self.assertIn("3\xa0GiB", page.xpath("string(//div[@id='backups']//table)"))
backup_proxy.return_value.backup_plan.side_effect = OperationError("%(vm)s has TPM state", vm="ctl-vm")
self.controls(admin)
page = lxml_html.fromstring(self.last_page)

View file

@ -1,6 +1,8 @@
import re
from django import template
from django.utils import formats
from django.utils.translation import gettext
register = template.Library()
@ -24,3 +26,22 @@ def class_active(request, pattern):
return "active" if re.search(pattern, request.path) else ""
BINARY_UNITS = ("B", "KiB", "MiB", "GiB", "TiB", "PiB")
@register.filter
def binary_size(value):
"""A size in bytes with the binary unit the forms ask in: 1536 -> 1.5 KiB, 2 GiB -> 2 GiB."""
size, unit = float(value or 0), 0
while abs(round(size, 1)) >= 1024 and unit < len(BINARY_UNITS) - 1:
size, unit = size / 1024, unit + 1
size = round(size, 1)
return f"{formats.number_format(size, 0 if size.is_integer() else 1)}\xa0{BINARY_UNITS[unit]}"
@register.filter
def percent(value):
"""A percentage as the page's language writes it: 13% in English, %13 in Turkish."""
return gettext("%(percent)s%%") % {"percent": formats.number_format(value)}

View file

@ -0,0 +1,29 @@
"""Sizes and percentages on the pages: sizes in the binary units the forms ask
in, percentages as the page's language writes them."""
from django.test import SimpleTestCase
from django.utils import translation
from webvirtcloud.common_tags import binary_size, percent
class BinarySizeTests(SimpleTestCase):
def test_a_size_takes_the_largest_unit_with_one_decimal_at_most(self):
for size, shown in ((0, "0 B"), (None, "0 B"), (512, "512 B"), (1536, "1.5 KiB"), (512 * 2**20, "512 MiB"),
(int(3.8 * 2**30), "3.8 GiB"), (20 * 2**30, "20 GiB"), (1023.96 * 2**20, "1 GiB"),
(3 * 2**40, "3 TiB")):
with self.subTest(size=size):
self.assertEqual(binary_size(size), shown.replace(" ", "\xa0"))
def test_the_decimal_mark_is_the_languages(self):
with translation.override("tr"):
self.assertEqual(binary_size(int(3.8 * 2**30)), "3,8\xa0GiB")
class PercentTests(SimpleTestCase):
def test_each_language_puts_the_sign_where_it_writes_it(self):
for language, shown in (("en", "13%"), ("tr", "%13"), ("zh-hans", "13%")):
with self.subTest(language=language), translation.override(language):
self.assertEqual(percent(13), shown)
with translation.override("tr"):
self.assertEqual(percent(12.5), "%12,5")