gh-108294: Add time.sleep audit event (GH-108298)

This commit is contained in:
Petr Viktorin 2023-08-23 11:00:22 +02:00 committed by GitHub
parent 2dfbd4f36d
commit 31b61d19ab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 38 additions and 0 deletions

View File

@ -379,6 +379,8 @@ Functions
* Or use ``nanosleep()`` if available (resolution: 1 nanosecond); * Or use ``nanosleep()`` if available (resolution: 1 nanosecond);
* Or use ``select()`` (resolution: 1 microsecond). * Or use ``select()`` (resolution: 1 microsecond).
.. audit-event:: time.sleep secs
.. versionchanged:: 3.11 .. versionchanged:: 3.11
On Unix, the ``clock_nanosleep()`` and ``nanosleep()`` functions are now On Unix, the ``clock_nanosleep()`` and ``nanosleep()`` functions are now
used if available. On Windows, a waitable timer is now used. used if available. On Windows, a waitable timer is now used.
@ -389,6 +391,9 @@ Functions
:pep:`475` for the rationale). :pep:`475` for the rationale).
.. versionchanged:: 3.13
Raises an auditing event.
.. index:: .. index::
single: % (percent); datetime format single: % (percent); datetime format

View File

@ -514,6 +514,21 @@ def test_not_in_gc():
assert hook not in o assert hook not in o
def test_time():
import time
def hook(event, args):
if event.startswith("time."):
print(event, *args)
sys.addaudithook(hook)
time.sleep(0)
time.sleep(0.0625) # 1/16, a small exact float
try:
time.sleep(-1)
except ValueError:
pass
def test_sys_monitoring_register_callback(): def test_sys_monitoring_register_callback():
import sys import sys

View File

@ -256,6 +256,21 @@ class AuditTest(unittest.TestCase):
if returncode: if returncode:
self.fail(stderr) self.fail(stderr)
def test_time(self):
returncode, events, stderr = self.run_python("test_time")
if returncode:
self.fail(stderr)
if support.verbose:
print(*events, sep='\n')
actual = [(ev[0], ev[2]) for ev in events]
expected = [("time.sleep", "0"),
("time.sleep", "0.0625"),
("time.sleep", "-1")]
self.assertEqual(actual, expected)
def test_sys_monitoring_register_callback(self): def test_sys_monitoring_register_callback(self):
returncode, events, stderr = self.run_python("test_sys_monitoring_register_callback") returncode, events, stderr = self.run_python("test_sys_monitoring_register_callback")

View File

@ -0,0 +1 @@
:func:`time.sleep` now raises an auditing event.

View File

@ -414,6 +414,8 @@ Return the clk_id of a thread's CPU time clock.");
static PyObject * static PyObject *
time_sleep(PyObject *self, PyObject *timeout_obj) time_sleep(PyObject *self, PyObject *timeout_obj)
{ {
PySys_Audit("time.sleep", "O", timeout_obj);
_PyTime_t timeout; _PyTime_t timeout;
if (_PyTime_FromSecondsObject(&timeout, timeout_obj, _PyTime_ROUND_TIMEOUT)) if (_PyTime_FromSecondsObject(&timeout, timeout_obj, _PyTime_ROUND_TIMEOUT))
return NULL; return NULL;