1. 程式人生 > >python的mock功能,感覺入門了~~~

python的mock功能,感覺入門了~~~

主要實現語法有patch, patch.object, Mock()。

下面的測試太赤裸裸了,只是為了熟悉語法。

import unittest
from unittest.mock import patch, Mock


def multiply(x, y):
    return x * y


class Calculator:
    def add(self, a, b):
        return a + b


class TestMock(unittest.TestCase):
    def setUp(self):
        self.calcu 
= Calculator() self.multiply = multiply @patch('__main__.multiply') def test_patch_multiply(self, mock_multiply): mock_multiply.return_value = 34 self.assertEqual(multiply(4, 5), 34) @patch.object(Calculator, 'add') def test_patch_add(self, mock_add): mock_add.return_value
= 55 self.assertEqual(self.calcu.add(4, 6), 55) def test_mock_multiply(self): mock_multiply = Mock(return_value=35) self.multiply = mock_multiply self.assertEqual(self.multiply(4, 5), 35) def test_mock_add(self): mock_add = Mock(return_value=99) self.calcu.add
= mock_add self.assertEqual(self.calcu.add(4, 6), 99) if __name__ == "__main__": unittest.main()

 

最適合mock測試,是網上那個例子,測試上一層功能,將其下一層mock掉。

client.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import requests


def send_request(url):
    r = requests.get(url)
    return r.status_code


def visit_ustack():
    return send_request('http://www.ustack.com')

tests.py

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import unittest

import mock

import client


class TestClient(unittest.TestCase):

    def test_success_request(self):
        success_send = mock.Mock(return_value='200')
        client.send_request = success_send
        self.assertEqual(client.visit_ustack(), '200')

    def test_fail_request(self):
        fail_send = mock.Mock(return_value='404')
        client.send_request = fail_send
        self.assertEqual(client.visit_ustack(), '404')