gabrielvie
3/28/2018 - 2:10 PM

Exceptions

import unittest
from sqrt import sqrt

class SqrtTestCase(unittest.TestCase):

    def test_sqrt_exception(self):
        self.assertRaises(ValueError, sqrt, -1)

    
    def test_sqrt(self):
        self.assertEqual(sqrt(4), 2)
        self.assertEqual(sqrt(6), 2.449489742783178)


if __name__ == '__main__':
    unittest.main()
import unittest
from convert import convert

class ConvertTestCase(unittest.TestCase):
    
    def test_convert_exception(self):
        self.assertRaises(ValueError, convert, ("3ureuwrt"))
        self.assertRaises(ValueError, convert, ([1, 3, 5]))
        self.assertRaises(ValueError, convert, ("2.4"))

    
    def test_convert(self):
        self.assertEqual(convert("2"), 2)


if __name__ == '__main__':
    unittest.main()
def sqrt(x):
    """Compute square roots using the method of Heron of Alexandria.
    
    Args:
        x: The number of which the square root is to be computed.
        
    Returns:
        The square root of x.
        
    Raises:
        ValueError: If x is negative.
    """
    if x < 0:
        raise ValueError("Cannot compute square root "
                         "of negative number {}".format(x))
                         
    guess = x
    i = 0
    while guess * guess != x and i < 20:
        guess = (guess + x / guess) / 2.0
        i += 1
    return guess
"""A module for demonstrating exceptions."""

import sys

def convert(s):
    """Convert to an integer"""
    try:
        return int(s)
    except (ValueError, TypeError) as e:
        print("Conversion error: {}".format(str(e)), file=sys.sterr)
    return -1