English 中文(简体)
利用一名环境管理员,用沙捞越
原标题:Using a context manager with Python assertRaises

<代码>unittest的 Python文件意味着assertRaises()方法可用作背景管理人。 下面的法典提供了从Adhury docs中进行单位测试的简单例子。 <assertRaises(>> calls in the testsample(> methods workvy.

现在,在提出这一例外时,我就同意这一例外,但如果我对它发表评论,而不是对我试图利用一名环境主管的下一个障碍作出结论,我就有一个<条码>。 AttributeError: __exit__, 当我试图执行该守则时。 发生这种情况的有2.7.2和3.2.2。 我可以在<条码>栏中捕获这一例外情况,但栏目除外,并且以这种方式查阅,但用于单位测试的文件似乎也意味着环境主管也将这样做。

这里还有什么事情是错的?

class TestSequenceFunctions(unittest.TestCase):

    def setUp(self):
        self.seq = [x for x in range(10)]

    def testshuffle(self):
        # make sure the shuffled sequence does not lose any elements
        random.shuffle(self.seq)
        self.seq.sort()
        self.assertEqual(self.seq, [x for x in range(10)])

    def testchoice(self):
        element = random.choice(self.seq)
        self.assert_(element in self.seq)

    def testsample(self):
        self.assertRaises(ValueError, random.sample, self.seq, 20)

        # with self.assertRaises(ValueError, random.sample, self.seq, 20):
        #     print("Inside cm")

        for element in random.sample(self.seq, 5):
            self.assert_(element in self.seq)

if __name__ ==  __main__ :
    unittest.main()
最佳回答

The source code for unittest doesn t show an exception hook for assertRaises:

class _AssertRaisesContext(object):
    """A context manager used to implement TestCase.assertRaises* methods."""

    def __init__(self, expected, test_case, expected_regexp=None):
        self.expected = expected
        self.failureException = test_case.failureException
        self.expected_regexp = expected_regexp

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, tb):
        if exc_type is None:
            try:
                exc_name = self.expected.__name__
            except AttributeError:
                exc_name = str(self.expected)
            raise self.failureException(
                "{0} not raised".format(exc_name))
        if not issubclass(exc_type, self.expected):
            # let unexpected exceptions pass through
            return False
        self.exception = exc_value # store for later retrieval
        if self.expected_regexp is None:
            return True

        expected_regexp = self.expected_regexp
        if isinstance(expected_regexp, basestring):
            expected_regexp = re.compile(expected_regexp)
        if not expected_regexp.search(str(exc_value)):
            raise self.failureException( "%s" does not match "%s"  %
                     (expected_regexp.pattern, str(exc_value)))
        return True

因此,正如你所怀疑的那样,如果你想要在坚持主张的同时拦截该例外,就行走。 噪音试验:

def testsample(self):
    with self.assertRaises(ValueError):
         try:
             random.sample(self.seq, 20)
         except ValueError as e:
             # do some action with e
             self.assertEqual(e.args,
                              ( sample larger than population ,))
             # now let the context manager do its work
             raise                    
问题回答

似乎没有人建议:

import unittest
# For python < 2.7, do import unittest2 as unittest

class Class(object):
    def should_raise(self):
        raise ValueError( expected arg )

class test_Class(unittest.TestCase):
    def test_something(self):
        DUT = Class()
        with self.assertRaises(ValueError) as exception_context_manager:
            DUT.should_raise()
        exception = exception_context_manager.exception

        self.assertEqual(exception.args, ( expected arg , ))

我通常使用e_cm作为例外使用:context_manager。

根据文件:

如果用可召唤的Obj漏掉或无,将退回背景物体

因此,该法典应当:

with self.assertRaises(ValueError):
    random.sample(self.seq, 20)

鉴于6年前有人问这个问题,我想象,这是现在行之有效的,但当时却不做。 docs 这一点在2.7中出现,但不是微观版本。

import unittest

class TestIntParser(unittest.TestCase):

    def test_failure(self):
        failure_message =  invalid literal for int() with base 10 
        with self.assertRaises(ValueError) as cm:
            int( forty two )
        self.assertIn(failure_message, cm.exception.message)

if __name__ ==  __main__ :
    unittest.main()




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签