Search code examples
pythonwebdoctestconceptual

Is it possible to do doctests in repl.it?


I am using the website repl.it to code with python and I was wondering how I would use my doctests when using repl.it. Or any other alternative besides the classic print statement checks.


Solution

  • It can be done in the following way. If you execute the following code on repl.it it will give you the output shown below.

    '''
    Credit to the autho-> @pcorkh1
    
    using doctests
    for automatic marking
    '''
    
    import doctest
    
    def testing():
        doctest.run_docstring_examples(square,globals(),name="square")
    
    def square(n):
        '''
        returns a square of n
        >>> square(3)
        9
        >>> square(1)
        1
        >>> square(6)
        36
        '''
        return n+n
    
    testing()
    name = 'Pete'
    age = 35
    num = 1
    
    print(f'name is: {name} Age is: {age: ^10} num is: {num}')
    

    Output:

    **********************************************************************
    File "main.py", line 14, in square
    Failed example:
        square(3)
    Expected:
        9
    Got:
        6
    **********************************************************************
    File "main.py", line 16, in square
    Failed example:
        square(1)
    Expected:
        1
    Got:
        2
    **********************************************************************
    File "main.py", line 18, in square
    Failed example:
        square(6)
    Expected:
        36
    Got:
        12
    name is: Pete Age is:     35     num is: 1
    

    The code is very trivial and once you understand it you can incorporate into your program. You may need to change the structure of your code to achieve this.