-
Notifications
You must be signed in to change notification settings - Fork 3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Report name #2947
Merged
Merged
Report name #2947
Changes from 5 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
ab6ae60
Add host, current time and test name to report filename
9ece97a
Use start time for filename, add duration to html report and add some…
fed146e
Replace unnecessary import and rework doc
31b92ee
Merge branch 'locustio:master' into report-name
obriat 0ff18c3
Fix tests
4ca1787
Simplify format_duration
c6c79a7
Fix hours & add tests
6ec2820
Merge branch 'master' into report-name
obriat 03e13d2
Fix timestamp rounding & add tests on html report duration
15166af
Adding pytest as a dev dependency
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,194 @@ | ||
from datetime import datetime, timezone | ||
import decimal | ||
import numbers | ||
import re | ||
from datetime import datetime, timedelta, timezone | ||
|
||
|
||
def format_utc_timestamp(unix_timestamp): | ||
return datetime.fromtimestamp(unix_timestamp, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") | ||
|
||
|
||
def format_safe_timestamp(unix_timestamp): | ||
return datetime.fromtimestamp(unix_timestamp).strftime("%Y-%m-%d-%Hh%M") | ||
|
||
|
||
def format_duration(start_unix_timestamp, end_unix_timestamp): | ||
""" | ||
Format a timespan between two timestamps as a human readable string. | ||
Taken from xolox/python-humanfriendly | ||
|
||
:param start_unix_timestamp: Start timestamp. | ||
:param end_unix_timestamp: End timestamp. | ||
|
||
""" | ||
# Common time units, used for formatting of time spans. | ||
time_units = ( | ||
dict(divider=1e-9, singular="nanosecond", plural="nanoseconds", abbreviations=["ns"]), | ||
dict(divider=1e-6, singular="microsecond", plural="microseconds", abbreviations=["us"]), | ||
dict(divider=1e-3, singular="millisecond", plural="milliseconds", abbreviations=["ms"]), | ||
dict(divider=1, singular="second", plural="seconds", abbreviations=["s", "sec", "secs"]), | ||
dict(divider=60, singular="minute", plural="minutes", abbreviations=["m", "min", "mins"]), | ||
dict(divider=60 * 60, singular="hour", plural="hours", abbreviations=["h"]), | ||
dict(divider=60 * 60 * 24, singular="day", plural="days", abbreviations=["d"]), | ||
dict(divider=60 * 60 * 24 * 7, singular="week", plural="weeks", abbreviations=["w"]), | ||
dict(divider=60 * 60 * 24 * 7 * 52, singular="year", plural="years", abbreviations=["y"]), | ||
) | ||
|
||
num_seconds = coerce_seconds( | ||
end_unix_timestamp - start_unix_timestamp, | ||
) | ||
if num_seconds < 60: | ||
# Fast path. | ||
return pluralize(round_number(num_seconds), "second") | ||
else: | ||
# Slow path. | ||
result = [] | ||
num_seconds = decimal.Decimal(str(num_seconds)) | ||
relevant_units = list(reversed(time_units[3:])) | ||
for unit in relevant_units: | ||
# Extract the unit count from the remaining time. | ||
divider = decimal.Decimal(str(unit["divider"])) | ||
count = num_seconds / divider | ||
num_seconds %= divider | ||
# Round the unit count appropriately. | ||
if unit != relevant_units[-1]: | ||
# Integer rounding for all but the smallest unit. | ||
count = int(count) | ||
else: | ||
# Floating point rounding for the smallest unit. | ||
count = round_number(count) | ||
# Only include relevant units in the result. | ||
if count not in (0, "0"): | ||
result.append(pluralize(count, unit["singular"], unit["plural"])) | ||
if len(result) == 1: | ||
# A single count/unit combination. | ||
return result[0] | ||
else: | ||
# Format the timespan in a readable way. | ||
return concatenate(result[:3]) | ||
|
||
|
||
def coerce_seconds(value): | ||
""" | ||
Coerce a value to the number of seconds. | ||
|
||
:param value: An :class:`int`, :class:`float` or | ||
:class:`datetime.timedelta` object. | ||
:returns: An :class:`int` or :class:`float` value. | ||
|
||
When `value` is a :class:`datetime.timedelta` object the | ||
:meth:`~datetime.timedelta.total_seconds()` method is called. | ||
""" | ||
if isinstance(value, timedelta): | ||
return value.total_seconds() | ||
if not isinstance(value, numbers.Number): | ||
msg = "Failed to coerce value to number of seconds! (%r)" | ||
raise ValueError(format(msg, value)) | ||
return value | ||
|
||
|
||
def round_number(count, keep_width=False): | ||
""" | ||
Round a floating point number to two decimal places in a human friendly format. | ||
|
||
:param count: The number to format. | ||
:param keep_width: :data:`True` if trailing zeros should not be stripped, | ||
:data:`False` if they can be stripped. | ||
:returns: The formatted number as a string. If no decimal places are | ||
required to represent the number, they will be omitted. | ||
|
||
The main purpose of this function is to be used by functions like | ||
:func:`format_length()`, :func:`format_size()` and | ||
:func:`format_timespan()`. | ||
|
||
Here are some examples: | ||
|
||
>>> from humanfriendly import round_number | ||
>>> round_number(1) | ||
'1' | ||
>>> round_number(math.pi) | ||
'3.14' | ||
>>> round_number(5.001) | ||
'5' | ||
""" | ||
text = "%.2f" % float(count) | ||
if not keep_width: | ||
text = re.sub("0+$", "", text) | ||
text = re.sub(r"\.$", "", text) | ||
return text | ||
|
||
|
||
def concatenate(items, conjunction="and", serial_comma=False): | ||
""" | ||
Concatenate a list of items in a human friendly way. | ||
|
||
:param items: | ||
|
||
A sequence of strings. | ||
|
||
:param conjunction: | ||
|
||
The word to use before the last item (a string, defaults to "and"). | ||
|
||
:param serial_comma: | ||
|
||
:data:`True` to use a `serial comma`_, :data:`False` otherwise | ||
(defaults to :data:`False`). | ||
|
||
:returns: | ||
|
||
A single string. | ||
|
||
>>> from humanfriendly.text import concatenate | ||
>>> concatenate(["eggs", "milk", "bread"]) | ||
'eggs, milk and bread' | ||
|
||
.. _serial comma: https://en.wikipedia.org/wiki/Serial_comma | ||
""" | ||
items = list(items) | ||
if len(items) > 1: | ||
final_item = items.pop() | ||
formatted = ", ".join(items) | ||
if serial_comma: | ||
formatted += "," | ||
return " ".join([formatted, conjunction, final_item]) | ||
elif items: | ||
return items[0] | ||
else: | ||
return "" | ||
|
||
|
||
def pluralize(count, singular, plural=None): | ||
""" | ||
Combine a count with the singular or plural form of a word. | ||
|
||
:param count: The count (a number). | ||
:param singular: The singular form of the word (a string). | ||
:param plural: The plural form of the word (a string or :data:`None`). | ||
:returns: The count and singular or plural word concatenated (a string). | ||
|
||
See :func:`pluralize_raw()` for the logic underneath :func:`pluralize()`. | ||
""" | ||
return f"{count} {pluralize_raw(count, singular, plural)}" | ||
|
||
|
||
def pluralize_raw(count, singular, plural=None): | ||
""" | ||
Select the singular or plural form of a word based on a count. | ||
|
||
:param count: The count (a number). | ||
:param singular: The singular form of the word (a string). | ||
:param plural: The plural form of the word (a string or :data:`None`). | ||
:returns: The singular or plural form of the word (a string). | ||
|
||
When the given count is exactly 1.0 the singular form of the word is | ||
selected, in all other cases the plural form of the word is selected. | ||
|
||
If the plural form of the word is not provided it is obtained by | ||
concatenating the singular form of the word with the letter "s". Of course | ||
this will not always be correct, which is why you have the option to | ||
specify both forms. | ||
""" | ||
if not plural: | ||
plural = singular + "s" | ||
return singular if float(count) == 1.0 else plural |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sorry maybe it wasn't clear, but I think an argument for using our own solution, rather than the library, is because as you can probably see, the library handles a lot more cases than we probably need. In Locust's case, we probably never need nanoseconds, microseconds, weeks, or years. I think we could go with a simpler approach, for example:
(disclaimer: ChatGPT)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Should I keep some methods in order to keep it human friendly (plural, no output for 0 values, ...)?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good idea!
Think something like this would do the trick (disclaimer: haven't tested it)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Since I really want to keep the last "and" 😄 , here a working proposition:
0: 0 seconds
666: 11 minutes and 6 seconds
1332: 22 minutes and 12 seconds
1998: 33 minutes and 18 seconds
2664: 44 minutes and 24 seconds
3330: 55 minutes and 30 seconds
3996: 1 hour, 6 minutes and 36 seconds
4662: 1 hour, 17 minutes and 42 seconds
5328: 1 hour, 28 minutes and 48 seconds
5994: 1 hour, 39 minutes and 54 seconds
6660: 1 hour and 51 minutes
7326: 2 hours, 2 minutes and 6 seconds
7992: 2 hours, 13 minutes and 12 seconds
One thing I don't get, is how to write a test the right way:
At the moment,
swarmReportMock.duration
is a string that is checked inHtmlReport.test.psx
, but it seems like a static markup check not a real verification of the the computed difference betweenswarmReportMock.endTime
andswarmReportMock.startTime
.Should this check be done here (and how) or should the math check be done in another test case (pure python?)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maybe we can do something like so:
To avoid iterating over the list multiple times and help keep things readable?
If you have time, maybe a couple of basic unit tests for the function would also be good?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It returns an error 😞 and I didn't find the way to fix it, so I push my version (which I tested with a loop).
I'll be happy to have some tips about unit tests, I'll add them if I had some more spare times
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah I think the error probably happens in the "0 seconds" case right? In which case you could do:
Some test cases could look like:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I add tests, could not find a way to use parametrize with class / self 😞