在Django应用程序测试中使用mock重写函数

2024-04-27 02:21:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有查看功能,使用nmap扫描网络中的设备。你知道吗

你知道吗视图.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)

现在我想测试一下no devices1 device connected2 or more device connected。我需要覆盖数据测试.py. 你知道吗

我在想可以用mock函数来实现。我可以在测试.py但当模拟响应时,它不会在视图函数中得到覆盖。你知道吗

如何测试这个nmap函数?你知道吗


Tags: 函数pyimport功能网络视图homedata
1条回答
网友
1楼 · 发布于 2024-04-27 02:21:35

猴子修补将是一个很好的解决方案在你的情况。你知道吗

还有一个关于猴子修补的问题

这里有一个可能的实现,当然您需要将其集成到您的测试框架中。你知道吗

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

相关问题 更多 >