自定义错误的单一测试

时间:2018-05-06 18:52:02

标签: python unit-testing custom-errors

我有三个不同的文件:

具有以下功能的类文件lang.py

from errors import StatusCodeError
class LangModel:
    def __init__(self, localpath2fst, host="127.0.0.1", port="5000", logfile="log"):
        ...
    def state_update(self):
        """
        Initialize the language model (on the server side)
        """
        try:
            r = requests.post(
            'http://' +
            self.host +
            ':' +
            self.port +
            '/init')
        except requests.ConnectionError:
            raise ConnectionErr(self.host, self.port)
        if not r.status_code == requests.codes.ok:
            raise StatusCodeError(r.status_code)

错误文件errors.py:

class StatusCodeError(Exception):
    def __init__(self, status_code):
        self.dErrArgs = status_code
        Exception.__init__(
            self,
            "Connection was not established and has status code {0}".format(self.dErrArgs))

和第三个文件test.py

import unittest
from lang import LangModel
from errors import StatusCodeError

class TestPreLM(unittest.TestCase):
    def test_incorrect_input(self):
     """
     confirm the process provides
     an error given an incorrect
     input
     """
     abs_path_fst = os.path.abspath("a valid path")
     # local fst
     localfst = abs_path_fst
     # init LMWrapper
     lmodel = LangModel(
      localfst,
      host='127.0.0.1',
      port='5000',
      logfile="lmwrap.log")
      # try to get priors
      with self.assertRaises(StatusCodeError):
         lmodel.state_update(['3'])

奇怪的是,当我在类文件中找到测试代码时,测试成功但是当它被隔离(在test.py中)时,测试失败并且我不确定为什么。如果你能照亮我的方式,我会很开心;)

0 个答案:

没有答案