0

Here is my class:

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

Here is my test:

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))

I'm trying to get the above test to simple raise the exception of InvalidAccount but I'm unsure how to mock out the self.db.design.view response. That's what's causing my test to fail because it's trying to make a real call out

dennismonsewicz
  • 25,132
  • 33
  • 116
  • 189

1 Answers1

1

I think this is what you want.

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))
dano
  • 91,354
  • 19
  • 222
  • 219
  • That's gotten me closer! For some reason the exception of `NotFound` is being thrown... Might be because the of the way something is mocked up – dennismonsewicz Jul 28 '14 at 18:02
  • Figured it out! Instead of `self.klass.db.design.return_value = view_mock` it was `self.klass.db.design.return_value.view = view_mock` – dennismonsewicz Jul 28 '14 at 18:05
  • @Ah, sorry about that. I'll edit my answer to reflect the correction. – dano Jul 28 '14 at 18:07