Test exception chaining and traceback output with doctest





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







0















How to test a 'multi traceback' using doctest?
It seems that using several ELLIPSIS and <BLANKLINE> won't do the trick:



def myfunc():
"""

>>> myfunc()
Traceback (most recent call last):
...
ValueError: this is
<BLANKLINE>
The above exception was the direct cause of the following exception:
<BLANKLINE>
Traceback (most recent call last):
...
TypeError: it

"""
try:
raise ValueError('this is')
except ValueError as err:
raise TypeError('it') from err


import doctest
doctest.testmod(optionflags=doctest.REPORT_NDIFF|doctest.ELLIPSIS)


Result:



"test.py" 23L, 490C written
**********************************************************************
File "test.py", line 4, in __main__.myfunc
Failed example:
myfunc()
Differences (ndiff with -expected +actual):
Traceback (most recent call last):
- ...
+ File "test.py", line 17, in myfunc
+ raise ValueError('this is')
ValueError: this is
<BLANKLINE>
The above exception was the direct cause of the following exception:
<BLANKLINE>
Traceback (most recent call last):
- ...
+ File "/usr/lib/python3.7/doctest.py", line 1329, in __run
+ compileflags, 1), test.globs)
+ File "<doctest __main__.myfunc[0]>", line 1, in <module>
+ myfunc()
+ File "test.py", line 19, in myfunc
+ raise TypeError('it') from err
TypeError: it
**********************************************************************
1 items had failures:
1 of 1 in __main__.myfunc
***Test Failed*** 1 failures.


But if I squash all, it will pass:



>>> myfunc()
Traceback (most recent call last):
...
TypeError: it









share|improve this question































    0















    How to test a 'multi traceback' using doctest?
    It seems that using several ELLIPSIS and <BLANKLINE> won't do the trick:



    def myfunc():
    """

    >>> myfunc()
    Traceback (most recent call last):
    ...
    ValueError: this is
    <BLANKLINE>
    The above exception was the direct cause of the following exception:
    <BLANKLINE>
    Traceback (most recent call last):
    ...
    TypeError: it

    """
    try:
    raise ValueError('this is')
    except ValueError as err:
    raise TypeError('it') from err


    import doctest
    doctest.testmod(optionflags=doctest.REPORT_NDIFF|doctest.ELLIPSIS)


    Result:



    "test.py" 23L, 490C written
    **********************************************************************
    File "test.py", line 4, in __main__.myfunc
    Failed example:
    myfunc()
    Differences (ndiff with -expected +actual):
    Traceback (most recent call last):
    - ...
    + File "test.py", line 17, in myfunc
    + raise ValueError('this is')
    ValueError: this is
    <BLANKLINE>
    The above exception was the direct cause of the following exception:
    <BLANKLINE>
    Traceback (most recent call last):
    - ...
    + File "/usr/lib/python3.7/doctest.py", line 1329, in __run
    + compileflags, 1), test.globs)
    + File "<doctest __main__.myfunc[0]>", line 1, in <module>
    + myfunc()
    + File "test.py", line 19, in myfunc
    + raise TypeError('it') from err
    TypeError: it
    **********************************************************************
    1 items had failures:
    1 of 1 in __main__.myfunc
    ***Test Failed*** 1 failures.


    But if I squash all, it will pass:



    >>> myfunc()
    Traceback (most recent call last):
    ...
    TypeError: it









    share|improve this question



























      0












      0








      0








      How to test a 'multi traceback' using doctest?
      It seems that using several ELLIPSIS and <BLANKLINE> won't do the trick:



      def myfunc():
      """

      >>> myfunc()
      Traceback (most recent call last):
      ...
      ValueError: this is
      <BLANKLINE>
      The above exception was the direct cause of the following exception:
      <BLANKLINE>
      Traceback (most recent call last):
      ...
      TypeError: it

      """
      try:
      raise ValueError('this is')
      except ValueError as err:
      raise TypeError('it') from err


      import doctest
      doctest.testmod(optionflags=doctest.REPORT_NDIFF|doctest.ELLIPSIS)


      Result:



      "test.py" 23L, 490C written
      **********************************************************************
      File "test.py", line 4, in __main__.myfunc
      Failed example:
      myfunc()
      Differences (ndiff with -expected +actual):
      Traceback (most recent call last):
      - ...
      + File "test.py", line 17, in myfunc
      + raise ValueError('this is')
      ValueError: this is
      <BLANKLINE>
      The above exception was the direct cause of the following exception:
      <BLANKLINE>
      Traceback (most recent call last):
      - ...
      + File "/usr/lib/python3.7/doctest.py", line 1329, in __run
      + compileflags, 1), test.globs)
      + File "<doctest __main__.myfunc[0]>", line 1, in <module>
      + myfunc()
      + File "test.py", line 19, in myfunc
      + raise TypeError('it') from err
      TypeError: it
      **********************************************************************
      1 items had failures:
      1 of 1 in __main__.myfunc
      ***Test Failed*** 1 failures.


      But if I squash all, it will pass:



      >>> myfunc()
      Traceback (most recent call last):
      ...
      TypeError: it









      share|improve this question
















      How to test a 'multi traceback' using doctest?
      It seems that using several ELLIPSIS and <BLANKLINE> won't do the trick:



      def myfunc():
      """

      >>> myfunc()
      Traceback (most recent call last):
      ...
      ValueError: this is
      <BLANKLINE>
      The above exception was the direct cause of the following exception:
      <BLANKLINE>
      Traceback (most recent call last):
      ...
      TypeError: it

      """
      try:
      raise ValueError('this is')
      except ValueError as err:
      raise TypeError('it') from err


      import doctest
      doctest.testmod(optionflags=doctest.REPORT_NDIFF|doctest.ELLIPSIS)


      Result:



      "test.py" 23L, 490C written
      **********************************************************************
      File "test.py", line 4, in __main__.myfunc
      Failed example:
      myfunc()
      Differences (ndiff with -expected +actual):
      Traceback (most recent call last):
      - ...
      + File "test.py", line 17, in myfunc
      + raise ValueError('this is')
      ValueError: this is
      <BLANKLINE>
      The above exception was the direct cause of the following exception:
      <BLANKLINE>
      Traceback (most recent call last):
      - ...
      + File "/usr/lib/python3.7/doctest.py", line 1329, in __run
      + compileflags, 1), test.globs)
      + File "<doctest __main__.myfunc[0]>", line 1, in <module>
      + myfunc()
      + File "test.py", line 19, in myfunc
      + raise TypeError('it') from err
      TypeError: it
      **********************************************************************
      1 items had failures:
      1 of 1 in __main__.myfunc
      ***Test Failed*** 1 failures.


      But if I squash all, it will pass:



      >>> myfunc()
      Traceback (most recent call last):
      ...
      TypeError: it






      python doctest






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 28 '18 at 12:27







      Yahya Abou Imran

















      asked Nov 23 '18 at 15:30









      Yahya Abou ImranYahya Abou Imran

      829




      829
























          1 Answer
          1






          active

          oldest

          votes


















          0














          I'm afraid that is not possible to check "multi tracebacks" in that way.



          The problem is that doctest ignores everything except the exception class and its message.



          In your example, it will be just:



          TypeError: it


          If you are interested in how this works, check the doctest.py and search for



          exc_msg = traceback.format_exception_only(*exception[:2])[-1]


          That "exc_msg" will only contain the raised exception's details:



          TypeError: it


          Alternatives



          If it is possible, you could change your test to not raise any exception but print the wanted message.



          Another possibility could be use another "doctest engine" like byexample. It works in the same way that doctest does but it's more flexible (quick overview here).



          If you have a lot of tests, you may want to try its compatibility mode with doctest to avoid rewriting everything.



          For your example, this should be:



          """                                                                                                                            
          >>> from your_module import myfunc
          """

          def myfunc():
          """

          >>> myfunc()
          Traceback (most recent call last):
          ...
          ValueError: this is
          <BLANKLINE>
          The above exception was the direct cause of the following exception:
          <BLANKLINE>
          Traceback (most recent call last):
          ...
          TypeError: it

          """
          try:
          raise ValueError('this is')
          except ValueError as err:
          raise TypeError('it') from err


          And to run it you do from the shell:



          byexample -l python -o '+py-doctest -py-pretty-print +ELLIPSIS' your_module.py


          Disclaimer: I'm the author of byexample. I'm a really fan of doctest but I know that has its limitations and checking exceptions is one of them (specially if you work in a dual Python 2.x / 3.x project).



          For that reason I created byexample: It is really useful to me and I really hope that it would be useful to others.



          Ask me any question that you have, here or in github






          share|improve this answer


























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53449365%2ftest-exception-chaining-and-traceback-output-with-doctest%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            I'm afraid that is not possible to check "multi tracebacks" in that way.



            The problem is that doctest ignores everything except the exception class and its message.



            In your example, it will be just:



            TypeError: it


            If you are interested in how this works, check the doctest.py and search for



            exc_msg = traceback.format_exception_only(*exception[:2])[-1]


            That "exc_msg" will only contain the raised exception's details:



            TypeError: it


            Alternatives



            If it is possible, you could change your test to not raise any exception but print the wanted message.



            Another possibility could be use another "doctest engine" like byexample. It works in the same way that doctest does but it's more flexible (quick overview here).



            If you have a lot of tests, you may want to try its compatibility mode with doctest to avoid rewriting everything.



            For your example, this should be:



            """                                                                                                                            
            >>> from your_module import myfunc
            """

            def myfunc():
            """

            >>> myfunc()
            Traceback (most recent call last):
            ...
            ValueError: this is
            <BLANKLINE>
            The above exception was the direct cause of the following exception:
            <BLANKLINE>
            Traceback (most recent call last):
            ...
            TypeError: it

            """
            try:
            raise ValueError('this is')
            except ValueError as err:
            raise TypeError('it') from err


            And to run it you do from the shell:



            byexample -l python -o '+py-doctest -py-pretty-print +ELLIPSIS' your_module.py


            Disclaimer: I'm the author of byexample. I'm a really fan of doctest but I know that has its limitations and checking exceptions is one of them (specially if you work in a dual Python 2.x / 3.x project).



            For that reason I created byexample: It is really useful to me and I really hope that it would be useful to others.



            Ask me any question that you have, here or in github






            share|improve this answer






























              0














              I'm afraid that is not possible to check "multi tracebacks" in that way.



              The problem is that doctest ignores everything except the exception class and its message.



              In your example, it will be just:



              TypeError: it


              If you are interested in how this works, check the doctest.py and search for



              exc_msg = traceback.format_exception_only(*exception[:2])[-1]


              That "exc_msg" will only contain the raised exception's details:



              TypeError: it


              Alternatives



              If it is possible, you could change your test to not raise any exception but print the wanted message.



              Another possibility could be use another "doctest engine" like byexample. It works in the same way that doctest does but it's more flexible (quick overview here).



              If you have a lot of tests, you may want to try its compatibility mode with doctest to avoid rewriting everything.



              For your example, this should be:



              """                                                                                                                            
              >>> from your_module import myfunc
              """

              def myfunc():
              """

              >>> myfunc()
              Traceback (most recent call last):
              ...
              ValueError: this is
              <BLANKLINE>
              The above exception was the direct cause of the following exception:
              <BLANKLINE>
              Traceback (most recent call last):
              ...
              TypeError: it

              """
              try:
              raise ValueError('this is')
              except ValueError as err:
              raise TypeError('it') from err


              And to run it you do from the shell:



              byexample -l python -o '+py-doctest -py-pretty-print +ELLIPSIS' your_module.py


              Disclaimer: I'm the author of byexample. I'm a really fan of doctest but I know that has its limitations and checking exceptions is one of them (specially if you work in a dual Python 2.x / 3.x project).



              For that reason I created byexample: It is really useful to me and I really hope that it would be useful to others.



              Ask me any question that you have, here or in github






              share|improve this answer




























                0












                0








                0







                I'm afraid that is not possible to check "multi tracebacks" in that way.



                The problem is that doctest ignores everything except the exception class and its message.



                In your example, it will be just:



                TypeError: it


                If you are interested in how this works, check the doctest.py and search for



                exc_msg = traceback.format_exception_only(*exception[:2])[-1]


                That "exc_msg" will only contain the raised exception's details:



                TypeError: it


                Alternatives



                If it is possible, you could change your test to not raise any exception but print the wanted message.



                Another possibility could be use another "doctest engine" like byexample. It works in the same way that doctest does but it's more flexible (quick overview here).



                If you have a lot of tests, you may want to try its compatibility mode with doctest to avoid rewriting everything.



                For your example, this should be:



                """                                                                                                                            
                >>> from your_module import myfunc
                """

                def myfunc():
                """

                >>> myfunc()
                Traceback (most recent call last):
                ...
                ValueError: this is
                <BLANKLINE>
                The above exception was the direct cause of the following exception:
                <BLANKLINE>
                Traceback (most recent call last):
                ...
                TypeError: it

                """
                try:
                raise ValueError('this is')
                except ValueError as err:
                raise TypeError('it') from err


                And to run it you do from the shell:



                byexample -l python -o '+py-doctest -py-pretty-print +ELLIPSIS' your_module.py


                Disclaimer: I'm the author of byexample. I'm a really fan of doctest but I know that has its limitations and checking exceptions is one of them (specially if you work in a dual Python 2.x / 3.x project).



                For that reason I created byexample: It is really useful to me and I really hope that it would be useful to others.



                Ask me any question that you have, here or in github






                share|improve this answer















                I'm afraid that is not possible to check "multi tracebacks" in that way.



                The problem is that doctest ignores everything except the exception class and its message.



                In your example, it will be just:



                TypeError: it


                If you are interested in how this works, check the doctest.py and search for



                exc_msg = traceback.format_exception_only(*exception[:2])[-1]


                That "exc_msg" will only contain the raised exception's details:



                TypeError: it


                Alternatives



                If it is possible, you could change your test to not raise any exception but print the wanted message.



                Another possibility could be use another "doctest engine" like byexample. It works in the same way that doctest does but it's more flexible (quick overview here).



                If you have a lot of tests, you may want to try its compatibility mode with doctest to avoid rewriting everything.



                For your example, this should be:



                """                                                                                                                            
                >>> from your_module import myfunc
                """

                def myfunc():
                """

                >>> myfunc()
                Traceback (most recent call last):
                ...
                ValueError: this is
                <BLANKLINE>
                The above exception was the direct cause of the following exception:
                <BLANKLINE>
                Traceback (most recent call last):
                ...
                TypeError: it

                """
                try:
                raise ValueError('this is')
                except ValueError as err:
                raise TypeError('it') from err


                And to run it you do from the shell:



                byexample -l python -o '+py-doctest -py-pretty-print +ELLIPSIS' your_module.py


                Disclaimer: I'm the author of byexample. I'm a really fan of doctest but I know that has its limitations and checking exceptions is one of them (specially if you work in a dual Python 2.x / 3.x project).



                For that reason I created byexample: It is really useful to me and I really hope that it would be useful to others.



                Ask me any question that you have, here or in github







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 1 at 15:08

























                answered Jan 1 at 14:31









                eldipaeldipa

                262




                262
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53449365%2ftest-exception-chaining-and-traceback-output-with-doctest%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    "Incorrect syntax near the keyword 'ON'. (on update cascade, on delete cascade,)

                    Alcedinidae

                    RAC Tourist Trophy