简体   繁体   English

python unittest自己的异常assertRaises

[英]python unittest own exception assertRaises

i'm having problem with unit test that asserts raising my own exception. 我在断言引发我自己的异常的单元测试中遇到问题。 Problem is that test always fails. 问题是测试总是失败。 And I don't know why. 而且我不知道为什么。 Here are my project files: 这是我的项目文件:

foo
 |-  __init__.py
 |-  exceptions.py
 |-  foo.py
tests
 |-  __init__.py
 |-  test_foo.py

exceptions.py exceptions.py

class MyException(Exception):
    def __init__(self, msg=None):
        if msg is None:
            msg = "An error occurred"
        super(MyException, self).__init__(msg)

foo.py foo.py

from exceptions import *


class Foo:
    def bar(self):
        raise MyException

test_foo.py test_foo.py

from unittest import TestCase
from foo.foo import Foo
from foo.exceptions import MyException


class TestFoo(TestCase):
    def setUp(self):
        self.foo = Foo()

    def test_bar(self):
        with self.assertRaises(MyException):
            self.foo.bar()

When I run the test, it fails and script outputs this in console: 当我运行测试时,它失败并且脚本在控制台中输出:

Error
Traceback (most recent call last):
  File "...\lib\unittest\case.py", line 59, in testPartExecutor
    yield
  File "...\lib\unittest\case.py", line 605, in run
    testMethod()
  File "...\tests\test_foo.py", line 14, in test_bar
    self.foo.bar()
  File "...\foo\foo.py", line 8, in bar
    raise MyException
exceptions.MyException: An error occurred



Ran 1 test in 0.002s

FAILED (errors=1)

When I change MyException to Exception in test on line 13, it works. 当我在第13行的测试中将MyException更改为Exception时,它可以工作。 But I wanna test it for specific exception. 但是我想测试它的特定异常。 Any idea why this is not working? 知道为什么这行不通吗?

I fixed it by changing 我通过更改来修复

from exceptions import *

to

from foo.exceptions import *

in foo.py file. 在foo.py文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM