diff --git a/python/common/org/python/stdlib/math/math.java b/python/common/org/python/stdlib/math/math.java new file mode 100644 index 0000000000..d12296cdaa --- /dev/null +++ b/python/common/org/python/stdlib/math/math.java @@ -0,0 +1,39 @@ +package python; + +@org.python.Module( + __doc__ = + "Math module" +) +public class math extends org.python.types.Module { + public math() { + super(); + } + + @org.python.Method( + __doc__ = "Return the square root of number", + args ={"number"} + ) + public static org.python.Object sqrt(org.python.Object number) { + if (number instanceof org.python.types.Float){ + if(((org.python.types.Float) number).value < 0.0){ + throw new org.python.exceptions.ValueError("math domain error"); + } + return new org.python.types.Float(Math.sqrt(((org.python.types.Float) number.__float__()).value)); + } + else if(number instanceof org.python.types.Int){ + if(((org.python.types.Int) number).value < 0){ + throw new org.python.exceptions.ValueError("math domain error"); + } + return new org.python.types.Float(Math.sqrt(((org.python.types.Float) number.__float__()).value)); + } + else if(number instanceof org.python.types.Bool) { + boolean val = ((org.python.types.Bool) number).value; + return new org.python.types.Float(val ? 1 : 0); + } + else{ + throw new org.python.exceptions.TypeError("sqrt() argument must be real number, not "+ number.typeName()); + } + + } + +} diff --git a/tests/stdlib/test_math.py b/tests/stdlib/test_math.py new file mode 100644 index 0000000000..c58c681633 --- /dev/null +++ b/tests/stdlib/test_math.py @@ -0,0 +1,51 @@ +import unittest + +from unittest import expectedFailure +from ..utils import TranspileTestCase + + +class MathModuleTests(TranspileTestCase): + + @expectedFailure + def test_sqrt_no_number(self): + self.assertCodeExecution(""" + import math + print(math.sqrt("no number")) + """) + + @expectedFailure + def test_sqrt_negatives(self): + self.assertCodeExecution(""" + import math + print(math.sqrt(-1.0)) + """) + + def test_sqrt_int(self): + self.assertCodeExecution(""" + import math + print(math.sqrt(4)) + """) + + def test_sqrt_floats(self): + self.assertCodeExecution(""" + import math + print(math.sqrt(4.2)) + """) + + def test_sqrt_bool_true(self): + self.assertCodeExecution(""" + import math + print(math.sqrt(True)) + """) + + def test_sqrt_bool_false(self): + self.assertCodeExecution(""" + import math + print(math.sqrt(False)) + """) + + def test_sqrt_zero(self): + self.assertCodeExecution(""" + import math + print(math.sqrt(0)) + """) \ No newline at end of file diff --git a/tests/utils.py b/tests/utils.py index 1383eb052d..94418abd72 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -76,7 +76,7 @@ def remove_output_dir(): ) try: - out, err = proc.communicate(timeout=30) + out, err = proc.communicate(timeout=60) except subprocess.TimeoutExpired: proc.kill() out, err = proc.communicate()