用单元测试理解magicmock的问题



这是我的类:

class WorkflowsCloudant(cloudant.Account):
    def __init__(self, account_id):
        super(WorkflowsCloudant, self).__init__(settings.COUCH_DB_ACCOUNT_NAME,
                                                auth=(settings.COUCH_PUBLIC_KEY, settings.COUCH_PRIVATE_KEY))
        self.db = self.database(settings.COUCH_DB_NAME)
        self.account_id = account_id
    def get_by_id(self, key, design='by_workflow_id', view='by_workflow_id', limit=None):
        params = dict(key=key, include_docs=True, limit=limit)
        docs = self.db.design(design).view(view, params=params)
        if limit is 1:
            doc = [doc['doc'] for doc in docs]
            if doc:
                workflow = doc[0]
                if workflow.get("account_id") != self.account_id:
                    raise InvalidAccount("Invalid Account")
                return workflow
            else:
                raise NotFound("Autoresponder Cannot Be Found")
        return docs

下面是我的测试:

def test_get_by_id_single_invalid_account(self):
    self.klass.account_id = 200
    self.klass.db = mock.MagicMock()
    self.klass.db.design.return_value.view.return_value = [{
        'doc': test_workflow()
    }]
    # wc.get_by_id = mock.MagicMock(side_effect=InvalidAccount("Invalid Account"))
    with self.assertRaises(InvalidAccount("Invalid Account")) as context:
        self.klass.get_by_id('workflow_id', limit=1)
    self.assertEqual('Invalid Account', str(context.exception))

我试图让上面的测试简单地提出InvalidAccount的例外,但我不确定如何模拟self.db.design.view的响应。这就是导致测试失败的原因因为它试图使真正的呼出

我想这就是你想要的。

def test_get_by_id_single_invalid_account(self):
    self.klass.account_id = 200
    self.klass.db = mock.MagicMock()
    self.klass.db.design = mock.MagicMock()
    view_mock = mock.MagicMock()
    view_mock.return_value =[{
        'doc': test_workflow()
    }]
    self.klass.db.design.return_value.view = view_mock 
    # wc.get_by_id = mock.MagicMock(side_effect=InvalidAccount("Invalid Account"))
    with self.assertRaises(InvalidAccount("Invalid Account")) as context:
        self.klass.get_by_id('workflow_id', limit=1)
    self.assertEqual('Invalid Account', str(context.exception))

相关内容

  • 没有找到相关文章

最新更新