beam: add clamp primitive with tests
This commit is contained in:
1 parent
d693f682ff
commit
bafefa8156
2 files changed
+32
No files matched your search
@@ -0,0 +1,12 @@
|
||||
"""Clamp a value to [lo, hi]. Handles None by raising, preserves type."""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def clamp(value, lo, hi):
|
||||
if lo > hi:
|
||||
raise ValueError("lo > hi: %r > %r" % (lo, hi))
|
||||
if value < lo:
|
||||
return lo
|
||||
if value > hi:
|
||||
return hi
|
||||
return value
|
||||
@@ -0,0 +1,20 @@
|
||||
import unittest
|
||||
from clamp import clamp
|
||||
|
||||
|
||||
class TestClamp(unittest.TestCase):
|
||||
def test_basic(self):
|
||||
self.assertEqual(clamp(5, 0, 10), 5)
|
||||
self.assertEqual(clamp(-3, 0, 10), 0)
|
||||
self.assertEqual(clamp(15, 0, 10), 10)
|
||||
def test_bounds_equal(self):
|
||||
self.assertEqual(clamp(5, 7, 7), 7)
|
||||
def test_lo_gt_hi_raises(self):
|
||||
with self.assertRaises(ValueError):
|
||||
clamp(5, 10, 0)
|
||||
def test_floats(self):
|
||||
self.assertEqual(clamp(1.5, 0.0, 1.0), 1.0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user