Skip to content

Commit

Permalink
Add unit tests for pyxx.dev.TimeIt
Browse files Browse the repository at this point in the history
  • Loading branch information
nathan-hess committed Dec 12, 2023
1 parent a9dc750 commit 0908402
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 0 deletions.
1 change: 1 addition & 0 deletions tests/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ def max_array_diff(array1, array2):

# Import and run tests
from .arrays import *
from .dev import *
from .files import *
from .numbers import *
from .strings import *
Expand Down
1 change: 1 addition & 0 deletions tests/dev/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .classes import *
1 change: 1 addition & 0 deletions tests/dev/classes/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .test_timer import *
56 changes: 56 additions & 0 deletions tests/dev/classes/test_timer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import time
import unittest

from pyxx.dev import TimeIt
from tests import CapturePrint


class Test_TimeIt(unittest.TestCase):
def test_duration(self):
# Verifies that duration is measured within a reasonable range
timer = TimeIt(print_duration=False)
with timer:
time.sleep(1.5)

self.assertAlmostEqual(timer.duration(), 1.5, delta=0.1)

def test_default_message(self):
# Verifies that correct default message is printed after code completes
with CapturePrint() as terminal_output:
timer = TimeIt()
with timer:
time.sleep(0.1)

self.assertEqual(
terminal_output.getvalue(),
f'Code duration: {timer.duration()} s\n',
)

def test_custom_message(self):
# Verifies that correct custom message is printed after code completes
with CapturePrint() as terminal_output:
timer = TimeIt(message='Execution time: {time} {units}', units='ms')
with timer:
time.sleep(0.1)

self.assertEqual(
terminal_output.getvalue(),
f'Execution time: {timer.duration() * 1000} ms\n',
)

def test_convert_duration(self):
# Verifies that unit conversion of returned duration is performed correctly
timer = TimeIt(print_duration=False)
with timer:
time.sleep(0.5)

self.assertAlmostEqual(
timer.duration(units='s') * 1000,
timer.duration(units='ms'),
)

def test_invalid_units(self):
# Verify that an error is raised when invalid units are specified
with self.assertRaises(ValueError):
with TimeIt(units='invalid'):
pass

0 comments on commit 0908402

Please sign in to comment.