2

ラップされた例外をテストしているコードがあります。失敗して例外が伝播した場合、エラーメッセージとバックトレースは十分に詳細ではないと思いました。これは主に、テストに対して何が期待されているかがわからなかったためです。 、例外と期待の詳細を教えてください。

テストを調整しました(以下のサンプルコードを参照)。このタイプのアプローチが有効であるかどうか、およびPythonテストまたはモックフレームワークのいずれかがそれを直接実装できるかどうかを知りたいですか?(現在、unittestとmoxを使用しています)

この質問に対する回答の1つは、このシナリオでself.failを使用することの適切性について簡単に触れていますが、実際には詳しく説明していません。私の仮定は、テストを1つの領域に制限しようとすると、テストに失敗しても大丈夫だということです。

注:コード例を実行すると、私が見たい動作を示すために失敗するはずです。Python 2.7、Mox0.5.3を使用しています

import sys
import urllib2
from contextlib import closing

try:
    import lxml.etree as ET
except ImportError:
    import xml.etree.ElementTree as ET


class Defect(Exception):
    """Wrapped exception, for module error detection"""
    def __init__(self, *args):
        Exception.__init__(self, *args)
        self.wrapped_exc = sys.exc_info()


class StudioResources:
    """Dummy class"""
    def _opener(self, request, html=False):
        with closing(urllib2.urlopen(request)) as response:
            try:
                if html:
                    import lxml.html
                    return lxml.html.parse(response)
                else:
                    return ET.parse(response)
            except urllib2.HTTPError, e:
                if e.code in [400, 500]: # Bad Request, Internal Server Error
                    raise Defect, "report error to the library maintainer"
                else:
                    raise


###
# Tests
###
import unittest
import mox
import traceback
import difflib
import urllib
import httplib


def format_expectation(exc_expected=None, exc_instance=None):
    """Synopsis - For exceptions, inspired by _AssertRaisesContext

    try:
        self.assertRaises(myexc, self.studio._opener, None)
    except Exception, e:
        self.fail(format_expectation(exc_expected=myexc, exc_instance=e))
    """
    if not isinstance(exc_expected, type) or exc_instance is None:
        raise ValueError, "check __init__ args"

    differ = difflib.Differ()
    inst_class = exc_instance.__class__
    def fullname(c): return "%s.%s" % (c.__module__, c.__name__)
    diff = differ.compare(
        (fullname(inst_class),), (fullname(exc_expected),))
    _str = ("Unexpected Exception type.  unexpected:-  expected:+\n%s"
        % ("\n".join(diff),))
    return _str


class StudioTest(mox.MoxTestBase):
    def setUp(self):
        mox.MoxTestBase.setUp(self)
        self.studio = StudioResources()

    def test_opener_defect(self):
        f = urllib.addinfourl(urllib2.StringIO('dummy'), None, None)
        RESP_CODE = 501
        self.mox.StubOutWithMock(f, 'read')
        self.mox.StubOutWithMock(urllib2, 'urlopen')
        urllib2.urlopen(mox.IgnoreArg()).AndReturn(f)
        f.read(mox.IgnoreArg()).AndRaise(urllib2.HTTPError(
            'http://c.com', RESP_CODE, httplib.responses[RESP_CODE], "", None))
        self.mox.ReplayAll()
        try:
            with self.assertRaises(Defect) as exc_info:
                self.studio._opener(None)
        except Exception, e:
            traceback.print_exc()
            self.fail(format_expectation(exc_expected=Defect, exc_instance=e))
        # check the response code
        exc, inst, tb = exc_info.exception.wrapped_exc
        self.assertEquals(inst.code, RESP_CODE)
        self.mox.VerifyAll()


if __name__ == '__main__':
    unittest.main()
4

1 に答える 1

1

単体テストを作成するときは、テストを1つに制限することをお勧めします。私はあなたのコードに何も悪いことは見ていませんが、私は全体をコンテキストマネージャーでラップします。私は、AssertionErrorを失敗として扱うunittestではなくnoseを使用し(これは、呼び出す必要がないことを意味しますself.fail())、このケースを処理するために独自のコンテキストマネージャーを作成しました。興味がある場合のコードは次のとおりです。

class assert_raises:

    def __init__(self, exception):
        self.exception = exception

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        assert exc_type is self.exception, "Got '{}', expected '{}'"\
            .format('None' if exc_type is None else exc_type.__name__,
                    self.exception.__name__)
        return True

そして、次の例のように使用します。

>>> with assert_raised(ValueError):
...    raise ValueError

>>> with assert_raised(ValueError):
...    pass
Traceback (most recent call last):
    ...
AssertionError: Got 'None', expected 'ValueError'

>>> with assert_raised(ValueError):
...     raise TypeError
Traceback (most recent call last):
    ...
AssertionError: Got 'TypeError', expected 'ValueError'

AssertionErrorが発生したため、noseはそれを失敗と見なし、とにかく完全なトレースバックを出力します。これは鼻用に設計されていますが、代わりにunittestとmox用に調整するのは簡単なことです。障害の正確なモードについてあまり心配していない場合は、そのまま使用することもできます。

于 2012-03-07T12:43:11.800 に答える