093-Python单元测试 (三)

 

 

 

093-Python单元测试 (三)

 

 

 

 

今天我们要学习一下单元测试中的模拟mocking

 

举个例子

假设我们现在需要从http://company.com这个网站来获取一些信息

如何来测试

看下代码

 

import requests


class Employee:
    raise_amt = 1.05

    def __init__(self, first, last, pay):
        self.first = first
        self.last = last
        self.pay = pay

    @property
    def email(self):
        return '{}.{}@email.com'.format(self.first, self.last)

    @property
    def fullname(self):
        return '{} {}'.format(self.first, self.last)

    def apply_raise(self):
        self.pay = int(self.pay * self.raise_amt)

    def monthly_schedule(self, month):
        response = requests.get(f'http://company.com/{self.last}/{month}')
        if response.ok:
            return response.text
        else:
            return 'Bad Response.'

 

看一下monthly_schedule方法

此方法使用get方法从company.com网站来获取信息

如果response.ok为True,则返回response.text

 

 

 

 

此时进行测试我们就需要用到mock来模拟

import unittest
from emp import Employee
from unittest.mock import patch


class TestEmp(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        print('setUpClass')

    @classmethod
    def tearDownClass(cls):
        print('tearDownClass')

    def setUp(self):
        print('setUp')
        self.emp_1 = Employee('Bill', 'Gates', 1000)
        self.emp_2 = Employee('Steve', 'Jobs', 2000)

    def tearDown(self):
        print('tearDown')

    def test_email(self):
        print('test_email')
        self.assertEqual(self.emp_1.email, '[email protected]')
        self.assertEqual(self.emp_2.email, '[email protected]')

    def test_fullname(self):
        print('test_fullname')
        self.assertEqual(self.emp_1.fullname, 'Bill Gates')
        self.assertEqual(self.emp_2.fullname, 'Steve Jobs')

    def test_apply_raise(self):
        print('test_apply_raise')
        self.emp_1.apply_raise()
        self.emp_2.apply_raise()
        self.assertEqual(self.emp_1.pay, 1050)
        self.assertEqual(self.emp_2.pay, 2100)

    def test_monthly_schedule(self):
        with patch('emp.requests.get') as mocked_get:
            mocked_get.return_value.ok = True
            mocked_get.return_value.text = 'Success'
            schedule = self.emp_1.monthly_schedule('May')
            mocked_get.assert_called_with('http://company.com/Gates/May')
            self.assertEqual(schedule, 'Success')

            mocked_get.return_value.ok = False
            schedule = self.emp_2.monthly_schedule('June')
            mocked_get.assert_called_with('http://company.com/Jobs/June')
            self.assertEqual(schedule, 'Bad Response.')

 

模拟get请求,分别测试value.ok为True

请求对应的LastName和Month,那么assertEqualy是相等的

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(093-Python单元测试 (三))