Skip to main content
 首页 » 编程设计

python之在 Django 应用程序测试中使用 mock 来覆盖函数

2025年02月15日25cloudgamer

我有使用 nmap 扫描网络中设备的查看功能。

View .py

import nmap 
def home(request): 
 
   y=nmap.PortScanner() 
 
   data = y.scan(hosts="192.168.1.*", arguments="-sP") 
   context[status]=data['status']['addresses']['ipv4'] 
   return render_template('home.html',context) 

现在我想针对无设备、1 个已连接设备 和2 个或更多已连接设备 进行测试。我需要覆盖 tests.py 中的数据。

我在想这可以使用模拟函数来完成。我可以在 tests.py 中覆盖它,但是当模拟响应时,它不会在 View 函数中被覆盖。

如何测试这个 nmap 函数?

请您参考如下方法:

猴子补丁对你来说是一个很好的解决方案。

另请查看 this所以关于猴子补丁的问题

这里有一个可能的实现,当然你需要把它集成到你的测试框架中。

import your_module 
 
class MockPortScanner(object): 
 
    # by setting this class member 
    # before a test case 
    # you can determine how many result 
    # should be return from your view 
    count = 0 
 
    def scan(self, *args, **kwargs): 
        return { 
            'status': { 
                'addresses': { 
                    'ipv4': [i for i in range(self.count)] 
                } 
            } 
        } 
 
def your_test_method(): 
    MockPortScanner.count = 5 
 
    request = None # create a Mock Request if you need 
 
    # here is the mocking 
    your_module.nmap.PortScanner = MockPortScanner 
 
    # call your view as a regular function 
    rv = your_module.home(request) 
 
    # check the response 

更新

要在后面的其他部分测试中使用原始的 PortScanner,请在导入 nmap 后将其保存在测试中。

import nmap 
 
OriginalPortScanner = nmap.PortScanner 

然后,您将能够像这样选择 PortScanner(原始的或模拟的):

views.nmap.PortScanner = OriginalPortScanner