Skip to content

Commit

Permalink
Add alternate constructor for values
Browse files Browse the repository at this point in the history
  • Loading branch information
samirelanduk committed Jun 17, 2017
1 parent 61c484c commit 84534e6
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
18 changes: 18 additions & 0 deletions fuzz/values.py
Expand Up @@ -34,3 +34,21 @@ def __init__(self, value, error=0):
raise ValueError("error {} is negative".format(error))
self._value = value
self._error = error


@staticmethod
def create(value, error=0):
"""This is a static method, and serves as an alternate constructor for
Values. It tries to convert some value to an actual Value, and if it
can't because it is the wrong type, it just sends the object back
unaltered.
:param value: The value to convert.
:param error: The error associated with the value.
:returns: Either the converted :py:class:`.value` or the original\
object."""

try:
return Value(value, error)
except TypeError:
return value
23 changes: 23 additions & 0 deletions tests/test_values.py
Expand Up @@ -36,3 +36,26 @@ def test_error_requires_numbers(self):
def test_error_must_be_positive(self):
with self.assertRaises(ValueError):
Value(23, -0.01)



class ValueSafeCreateTests(TestCase):

def test_can_get_simple_value_safely(self):
val = Value.create(10)
self.assertIsInstance(val, Value)
self.assertEqual(val._value, 10)
self.assertEqual(val._error, 0)


def test_can_get_error_value_safely(self):
val = Value.create(10.5, 0.2)
self.assertIsInstance(val, Value)
self.assertEqual(val._value, 10.5)
self.assertEqual(val._error, 0.2)


def test_can_ignore_non_numbers(self):
s = "value"
val = Value.create(s, 0.2)
self.assertIs(val, s)

0 comments on commit 84534e6

Please sign in to comment.