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

Using mock in testing of django application to override a function

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

views.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 进行测试。我需要覆盖 tests.py.

中的数据

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

如何测试这个 nmap 功能?

Monkey 补丁将是您的一个很好的解决方案。

也看看 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

然后,您将能够 select PortScanner(原始的或模拟的),如:

views.nmap.PortScanner = OriginalPortScanner