Python:难以理解如何为类编写单元测试

时间:2014-07-25 16:59:30

标签: python unit-testing

这是我的班级:

class EDACloudantDocument(WorkflowsCloudant):

    def __init__(self, id, workflow=None):
        super(EDACloudantDocument, self).__init__()
        self.id = "%s_eda" % id

        if not workflow:
            workflow = dict()

        self.payload = dict(workflow=workflow, account_id=g.account_id)
        self.payload["_id"] = self.id
        self.response = None

    def create(self):
        self.response = self.db.document(None).post(params=self.payload)

        self._process_response()

    def update(self):
        original_doc = self._get_original_doc()
        self.payload['_rev'] = original_doc.get("_rev")

        self.response = self.db.document(self.id).put(params=self.payload)

        self._process_response()

    def _process_response(self):

        if self.response.status_code == 409:
            return error_helpers.conflict(self.response.json().get("reason"))
        elif not self.response.ok:
            logging.exception("Unexpected response from Cloudant: %d", self.response.status_code)
            return error_helpers.server_error()

        return self.response.json()

    def _get_original_doc(self):
        doc = self.db.document(self.id).get()

        if doc:
            if doc.json().get("account_id") != g.account_id:
                return error_helpers.forbidden('Invalid Account')

            return doc.json()
        else:
            return error_helpers.not_found('Workflow Cannot Be Found')

这是我的测试:

def successful_creation():
    return {
        'ok': True,
        'id': '123',
        'rev': '1-bar'
    }


class TestEDACloudant(unittest.TestCase):

    def setUp(self):
        self.app = app.test_client()
        self.test_id = '123abc'
        self.account_id = 100

    @mock.patch("app.utils.eda_cloudant.g")
    def test_init(self, g):
        g.account_id = self.account_id
        eda_class = EDACloudantDocument(self.test_id)

        self.assertEqual(eda_class.id, "%s_eda" % self.test_id)
        self.assertDictEqual(
            eda_class.payload,
            {
                '_id': '123abc_eda',
                'account_id': self.account_id,
                'workflow': {}
            }
        )
        self.assertEqual(eda_class.response, None)
        self.assertTrue(issubclass(EDACloudantDocument, WorkflowsCloudant))

    @mock.patch("app.utils.eda_cloudant.g")
    def test_create(self, g):
        g.account_id = self.account_id
        eda_class = EDACloudantDocument(self.test_id, workflow=test_workflow())
        eda_class.create = mock.MagicMock(return_value=successful_creation())
        eda_class.create()

        self.assertDictEqual(
            eda_class.create(),
            {
                'ok': True,
                'id': '123',
                'rev': '1-bar'
            }
        )

我不确定的一项测试是test_create()测试。就像现在一样,它过去了。但我只是不确定它是否正在测试正确的事物

0 个答案:

没有答案