Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing of methods define inside a class using doctesting

I need to define: 1. doctests for 'init' which creates a circle 'c1' with radius 2.5 and checks that accessing attribute 'radius' return 2.5. 2. Define a doc test for 'area' which creates a circle 'c1' with radius 2.5 and checks that it computed area is 19.63.

I have written below mentioned code but not getting the output. Please suggest.

class Circle:

    def __init__(self, radius):

        """
        >>> c1=Circle(2.5).__init__()
        2.5
        """
        self.radius = radius

    def area(self):

        """
        >>> c1=Circle(2.5).area()
        19.63

        """

        return round(math.pi*(self.radius**2),2)
like image 689
user2384052 Avatar asked Oct 29 '25 07:10

user2384052


2 Answers

This is how your class with doctests can be probably written:

import math

class Circle:

    def __init__(self, radius):

        """
        >>> c1 = Circle(2.5)
        >>> c1.radius
        2.5
        """
        self.radius = radius

    def area(self):

        """
        >>> c1 = Circle(2.5)
        >>> c1.area()
        19.63

        """

        return round(math.pi*(self.radius**2),2)

And this is how you should run doctest to get detailed output:

$ python -m doctest -v file.py
Trying:
    c1 = Circle(2.5)
Expecting nothing
ok
Trying:
    c1.radius
Expecting:
    2.5
ok
Trying:
    c1 = Circle(2.5)
Expecting nothing
ok
Trying:
    c1.area()
Expecting:
    19.63
ok
2 items had no tests:
    file
    file.Circle
2 items passed all tests:
   2 tests in file.Circle.__init__
   2 tests in file.Circle.area
4 tests in 4 items.
4 passed and 0 failed.
Test passed.
like image 127
sanyassh Avatar answered Oct 31 '25 00:10

sanyassh


__init__() does not return the radius, rather the Circle object you created. If you update the doctest to something like

>>> Circle(2.5).radius
2.5

it should work. Also note that you should not call __init__() directly, that's what Circle(2.5) does. In your case you should get an error, since you're not passing the right amount of arguments.

like image 27
c0lon Avatar answered Oct 31 '25 01:10

c0lon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!