newbiee查询:在python中进行模拟

我正在尝试同时学习
Python
Python中的基础架构(由于我工作场所的要求).我还应该提一下,我也不熟悉用C或任何其他语言模拟特征.

到目前为止,根据我的理解,通过模拟,我可以使用制作操作系统的应用程序代码.网络等相关的调用,而不实际调用这些操作.

假设我有一个应用程序,实现为network.py

#!/usr/bin/env python

import sys
import socket

class NetworkService(object):
    def sock_create(self):
        try:
            s = socket.socket()
            s.close()
            print "closed socket"
        except Exception, err:    
            print "error creating socket"
            sys.exit(1) 

我希望通过单元测试实现的目标是:

>确保测试正常路径和故障路径.

在这种情况下,为了实现,我试图想出一个样本单元测试用例来运行sock_create方法,如下所示:

#!/usr/bin/env python

import unittest
import mock
from network import NetworkService

class NetworkServiceTest(unittest.TestCase):
    @mock.patch('network.socket')
    def test_01_sock_create(self, mock_sock):
        reference = NetworkService()
        mock_sock.return_value = False
        # NetworkService::sock_create::s.close() should NOT get called  
        reference.sock_create()
        self.assertFalse(mock_sock.close.called, "Failed to not call close")

        mock_sock.socket.return_value = True
        # NetworkService::sock_create::s.close() should get called
        reference.sock_create()
        # how to test this ???
        #mock_sock.close.assert_called_with("")

if __name__ == '__main__':
    unittest.main()

如上所示,最后的’assert’语句目前已被注释掉;我不确定,怎么检查这个?以下给出了错误:

#!/usr/bin/env python

import unittest
import mock
from network import NetworkService

class NetworkServiceTest(unittest.TestCase):
    @mock.patch('network.socket')
    def test_01_sock_create(self, mock_sock):
        reference = NetworkService()
        mock_sock.return_value = False
        reference.sock_create()
        self.assertFalse(mock_sock.close.called, "Failed to not call close")

        mock_sock.socket.return_value = True
        reference.sock_create()
        self.assertTrue(mock_sock.close.called, "Should have called s.close")

if __name__ == '__main__':
    unittest.main()

和错误:

$python tester.py
F
======================================================================
FAIL: test_01_sock_create (__main__.NetworkServiceTest)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched
    return func(*args, **keywargs)
  File "tester.py", line 17, in test_01_sock_create
    self.assertTrue(mock_sock.close.called, "Should have called s.close")
AssertionError: Should have called s.close

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (failures=1)
closed socket
error creating socket

请注意,我在Python 2.7中使用模拟(模拟需要作为单独的模块安装)

最佳答案 在network.py中,您将打印出一个字符串.如果您打印出实际错误,您将看到它失败的原因.在这种情况下你会看到它因为AttributeError而失败. AttributeError(“’bool’对象没有属性’close’”,)

之所以发生这种情况,是因为你给模拟对象提供了True或False的返回值.由于bool没有任何打开或关闭方法,因此会抛出该错误.

其他一些提示.您正在使用Exception来捕获所有异常.相反,只捕获您知道会发生的异常.找出套接字可能抛出的异常.

那样你早就发现了这个.

点赞