在单元测试用例中重用代码

时间:2018-07-18 15:59:27

标签: python-3.x mocking python-unittest

我正在为调用第三方API的方法编写单元测试用例。 所有方法都相似,它们返回相同的响应。

下面是方法示例:

方法

def cloud_credentials(self, ):
    try:
        url = f"{self.CE_API_URL}/cloudCredentials"
        response = self.ce_api_get_call(url)
        status_code = response.status_code
        status_response = response.text
        if status_code == 200:
            print("Got Account cloudCredentials information")
            return (True, {"response": json.loads(status_response)})

        msg = (f"Failed to cloudCredentials. "
               f"Error {status_code} - {status_response}")
        print(msg)

        if status_code == 401:
            message = {"http_code": 401, "message": "Unauthorized"}
        else:
            message = {
                "http_code": 400,
                "message": "Unable to get Account cloudCredentials "
                           "information."
            }

        return (False, message)
    except Exception as err:
        msg = f"Unknown Error: Account cloudCredentials information: {err}"
        print(msg)
        return (False, {
            "http_code": 500,
            "message": "Unable to get Account cloudCredentials information."
        })

以下是单元测试用例代码。 我正在通过responses库嘲笑第三方API,以避免调用第三方API。我主要处理所有情况-单元测试用例中的200 HTTP响应,401、500和异常。

代码

import sys
import json
import unittest
from uuid import uuid4
import responses

from ce import Cloud


class CE_TEST(unittest.TestCase):
    """ CE TEST class drive from UnitTest """
    def __init__(self, *args, **kwargs):
        """Initialization"""
        super(CE_TEST, self).__init__(*args, **kwargs)
        self.ce_obj = Cloud()

class GetAccountLicensesInfoTest(CE_TEST):
    """Get Account Licenses Info Unit Test Cases
        Function Name: get_licenses
    """
    def __init__(self, *args, **kwargs):
        """Initialization"""
        super(GetAccountLicensesInfoTest, self).__init__(*args, **kwargs)
        self.licenses_url = ""

    def setUp(self):
        """Setup for all Test Cases."""
        self.licenses_url = "{}/licenses".format(self.ce_obj.CE_API_URL)

    @responses.activate
    def test_get_licenses_200(self):
        """Test Case for 200 API Response"""
        responses.add(
            responses.GET,
            url=self.licenses_url,
            body=json.dumps({"msg": "successful"}),
            status=200
        )

        (m_status, m_response) = self.ce_obj.get_licenses()
        self.assertTrue(m_status)

    @responses.activate
    def test_get_licenses_401(self):
        """Test Case for 401 API Response"""
        responses.add(
            responses.GET,
            url=self.licenses_url,
            body=json.dumps({"err-msg": "unsuccessful"}),
            status=401
        )

        (m_status, m_response) = self.ce_obj.get_licenses()
        self.assertFalse(m_status)
        self.assertEqual(m_response.get('http_code'), 401)

    @responses.activate
    def test_get_licenses_400(self):
        """Test Case for 400 API Response"""
        responses.add(
            responses.GET,
            url=self.licenses_url,
            body=json.dumps({"err-msg": "unsuccessful"}),
            status=400
        )

        (m_status, m_response) = self.ce_obj.get_licenses()
        self.assertFalse(m_status)
        self.assertEqual(m_response.get('http_code'), 400)

    @responses.activate
    def test_get_licenses_500(self):
        """Test Case for 500 API Response"""
        responses.add(
            responses.GET,
            url=self.licenses_url,
            body=json.dumps({"err-msg": "unsuccessful"}),
            status=500
        )

        (m_status, m_response) = self.ce_obj.get_licenses()
        self.assertFalse(m_status)
        self.assertEqual(m_response.get('http_code'), 400)

    @responses.activate
    def test_get_licenses_exception(self):
        """Exception Test Case"""
        responses.add(
            responses.GET,
            url=self.licenses_url,
            body=Exception("Exception raised for Unit Test Case"),
            status=500
        )

        (m_status, m_response) = self.ce_obj.get_licenses()
        self.assertFalse(m_status)
        self.assertEqual(m_response.get('http_code'), 500)


class GetJobTest(CE_TEST):
    """Get Job Unit Test Cases
        Function Name: get_job
    """
    def __init__(self, *args, **kwargs):
        """Initialization"""
        super(GetJobTest, self).__init__(*args, **kwargs)
        self.job_id = ""
        self.job_url = ""

    def setUp(self):
        """Setup for all Test Cases."""
        self.ce_obj.project_id = uuid4().__str__()
        self.job_id = uuid4().__str__()
        self.job_url = "{}/projects/{}/jobs/{}".format(
            self.ce_obj.CE_API_URL, self.ce_obj.project_id, self.job_id)

    @responses.activate
    def test_get_job_200(self):
        """Test Case for 200 API Response"""
        responses.add(
            responses.GET,
            url=self.job_url,
            body=json.dumps({"msg": "successful"}),
            status=200
        )

        (m_status, m_response) = self.ce_obj.get_job(self.job_id)
        self.assertTrue(m_status)

    @responses.activate
    def test_get_job_401(self):
        """Test Case for 401 API Response"""
        responses.add(
            responses.GET,
            url=self.job_url,
            body=json.dumps({"err-msg": "unsuccessful"}),
            status=401
        )

        (m_status, m_response) = self.ce_obj.get_job(self.job_id)
        self.assertFalse(m_status)
        self.assertEqual(m_response.get('http_code'), 401)

    @responses.activate
    def test_get_job_400(self):
        """Test Case for 400 API Response"""
        responses.add(
            responses.GET,
            url=self.job_url,
            body=json.dumps({"err-msg": "unsuccessful"}),
            status=400
        )

        (m_status, m_response) = self.ce_obj.get_job(self.job_id)
        self.assertFalse(m_status)
        self.assertEqual(m_response.get('http_code'), 400)

    @responses.activate
    def test_get_job_500(self):
        """Test Case for 500 API Response"""
        responses.add(
            responses.GET,
            url=self.job_url,
            body=json.dumps({"err-msg": "unsuccessful"}),
            status=500
        )

        (m_status, m_response) = self.ce_obj.get_job(self.job_id)
        self.assertFalse(m_status)
        self.assertEqual(m_response.get('http_code'), 400)

    @responses.activate
    def test_get_job_exception(self):
        """Exception Test Case"""
        responses.add(
            responses.GET,
            url=self.job_url,
            body=Exception("Exception raised for Unit Test Case"),
            status=500
        )

        (m_status, m_response) = self.ce_obj.get_job(self.job_id)
        self.assertFalse(m_status)
        self.assertEqual(m_response.get('http_code'), 500)

有很多方法,例如get_licenses,get_job等。 我不想为每种方法重复一个单元测试类。 有什么方法可以创建基类/类,或者可以减少我一次又一次地重写相同代码的工作。

0 个答案:

没有答案