python - 断言错误: Exception not raised

标签 python unit-testing flask pybuilder

我有一个单元测试来测试是否正确引发自定义异常。但我得到了 AssertionError: InvalidLength not raise

下面是我的单元测试

@patch('services.class_entity.validate')
@patch('services.class_entity.jsonify')
def test_should_raise_invalid_length_exception(self, mock_jsonify, mock_validate):
    mock_validate.return_value = True

    data = self.data
    data['traditional_desc'] = "Contrary to popular"
    mock_jsonify.return_value = {
        "success": False,
        "results": {
            "message": "Invalid value for traditional_desc"
        }
    }

    with self.assertRaises(InvalidLength) as cm:
        BenefitTemplateService.create(data)

这是我正在测试的功能

class BenefitTemplateService(object):

    @staticmethod
    def create(params):

        try:
            required_fields = ['company_id', 'name', 'behavior', 'benefit_type']
            valid = is_subset(params, required_fields)

            if not valid:
                raise MissingParameter

            if not validate_string(params['traditional_desc'], 0, 1000, characters_supported="ascii"):
                raise InvalidLength(400, "Invalid value for traditional_desc")

            # Call create here
            response = BenefitTemplateEntityManager.create_template(params)
            return response

        except InvalidLength as e:
            response = {
                "success": False,
                "results": {
                    "message": e.message
                }
            }

            return jsonify(response), e.code

除了 InvalidLength 工作正常,因为如果我尝试打印,它会执行该行代码。所以我假设正在调用 InvalidLength Exception,但我不确定单元测试的结果是否失败。你能帮忙吗

最佳答案

create 引发 InvalidLength 异常,但随后捕获它并静默处理它,您的测试期望它实际引发它。

使用与 assertRaises 不同的断言。 except block 返回一个 json,因此您的测试可以检查 json 的内容。

关于python - 断言错误: Exception not raised,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45691369/

相关文章:

python - 双星号

python - 具有多个 If-Break 条件的 For-Else 语句

Python 用字典值替换字符串

python - 如何设置多个单元测试共享的资源?

python - Py2neo (V4) - 属性错误 : 'Graph' object has no attribute 'find_one'

python - 我的 Kivy 程序在左下角出现一个随机的白色方 block

android - 如何测试 Retrofit2 + RxJava2 api 调用?

python - 模拟 Python 的内置打印功能

python - 无法在 Webfaction 上部署简单的 Flask 应用程序

python - FLASK_ENV 好像被忽略了(进不去调试环境)