2017-09-01 71 views
2

我有查看功能,它使用nmap来扫描网络中的设备。使用模拟测试django应用程序来覆盖功能

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函数?

回答

1

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

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

UPDATE

要在以后有原来的端口扫描工具在测试其他部分,将其保存在测试进口NMAP后。

import nmap 

OriginalPortScanner = nmap.PortScanner 

然后,您将能够选择端口扫描工具(原始的或模拟),如:

views.nmap.PortScanner = OriginalPortScanner 
+0

your_module意味着我的views.py,对不对? –

+0

可能是的。它是您的主页视图被定义的模块。实际上,它看起来像:'from yourapp import views' – ohannes

+0

但是这里的模拟函数是如何工作的。没有从模拟进口。 MockPortScanner –

相关问题