tests.py 10.3 KB
Newer Older
1 2 3
#!/usr/bin/env python
#
# ULG - Universal Looking Glass
4
# (C) 2012 CZ.NIC, z.s.p.o.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


# Imports
import os, sys
import random

import defaults

26
import ulgmodel
27
import ulg
28
import ulgcisco
29 30 31 32

import sys
import re
import time
33 34
import traceback

35 36
config = ulgmodel.import_config()

37 38 39 40

def testRouterCommand(router=0,command=0,params=[]):
    r = config.routers[router]
    try:
41 42
        if(not r.runSyncCommand(r.listCommands()[command],params)):
            print "WARN: Output of test running command "+str(command)+" on router "+str(router)+" with parameters:"+str(params)+" is empty."
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
            return False

    except Exception as e:
        print "FAIL: Test running command "+str(command)+" on router "+str(router)+" with parameters:"+str(params)+".\n  Exception="+str(e)
        return False

    print "OK: Test running command "+str(command)+" on router "+str(router)+" with parameters:"+str(params)
    return True


def testULGIndex(routerid=0,commandid=0,sessionid=None):
    try:
        u = ulg.ULGCgi()
        c = u.renderULGIndex(routerid,commandid,sessionid)
        if(c):
            print "OK: Test render ULG CGI index"
            return True
        else:
            print "WARN: Test render ULG CGI index is empty!"
            return False
        
    except Exception as e:
        print "FAIL: Test render ULG CGI index.\n Exception="+str(e)
        return False


def testULGAction(routerid=0,commandid=0,sessionid=None,maxtimes=10,interval=5,**params):
    try:
        u = ulg.ULGCgi()
        rdr = u.renderULGAction(routerid=0,commandid=0,sessionid=None,**params)
        m = re.compile('sessionid=([^"]+)"',re.M).search(rdr)
        if(m):
            sessionid = m.groups()[0]
            print "OK(1/2): Test ULG run action passed with sessionid="+str(sessionid)
        else:
            print "FAILED ULG run action. No session ID returned."
            return False
    except Exception as e:
        print "FAILED ULG run action.\n  Exception="+str(e)
        return False

    i=0
    while(i<maxtimes):
        if(re.compile("refresh",re.M).search(u.renderULGResult(sessionid=sessionid))):
            print "Test ULG result is not complete. Waiting another 5 seconds."
            time.sleep(interval)
            i+=1
        else:
            print "OK(2/2): Test ULG result is complete."
            return True

    print "FAIL: Test ULG result is not complete after "+str(maxtimes)
    return False


def testULGSessions(sessionid=None):
    try:
        s1 = ulg.Session(sessionid,routerid=1,commandid=2,parameters={'baba':'bubu'},result='reeesult')
        sid = s1.getSessionId()
102
        s2 = ulg.loadSession(sid)
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
        if(s1.getSessionId() == s2.getSessionId() and s1.getRouterId() == s2.getRouterId()):
            print "OK: Test sessions."
            return True
        else:
            print "WARN: Test sessions failed!"
            return False
        
    except Exception as e:
        print "FAIL: Test sessions.\n  Exception="+str(e)
        return False

def testULGLock():
    c = ulg.ULGCgi()

    def cleanup(c):
        for i in range(0,defaults.usage_limit):
            c.decreaseUsage()

    for i in range(0,defaults.usage_limit):
        if not c.increaseUsage():
            print """FAIL: Test lock. Increase usage rejected me while it should let me it.
(It can be effect of a real ULG running concurrently to tests."""
            return False
    if(c.increaseUsage()):
        print "FAIL: Test lock. Increase usage accepted overlimit."
        cleanup(c)
        return False

    c.decreaseUsage()

    if(not c.increaseUsage()):
        print """FAIL: Test lock. Increase usage rejected me while it should let me it.
(It can be effect of a real ULG running concurrently to tests."""
        cleanup(c)
        return False

    cleanup(c)
    print "OK: Test lock."
    return True

def testULGRunParameter(router=0,command=4,params=['91.210.16.1']):
    r = config.routers[router]
    try:
146
        if(not r.runSyncCommand(r.listCommands()[command],params)):
147 148 149 150 151 152 153 154 155 156 157
            print "WARN: Output of test running command "+str(command)+" on router "+str(router)+" with parameters:"+str(params)+" is empty."
            return False

    except Exception as e:
        print "FAIL: Test running command "+str(command)+" on router "+str(router)+" with parameters:"+str(params)+".\n  Exception="+str(e)
        print traceback.format_exc()
        return False

    print "OK: Test running command "+str(command)+" on router "+str(router)+" with parameters:"+str(params)
    return True

158 159 160 161 162 163 164 165 166 167
def testULGLog(testmessage="Test message no. 1."):
    try:
        ulgmodel.log(testmessage)
        print "OK: Logging test. Check logfile for message: "+testmessage
        return True
    except Exception as e:
        print "FAIL: Logging test."
        print traceback.format_exc()
        return False

168 169 170 171 172 173 174 175 176 177 178 179 180 181
def testULGRescan():
    try:
        for r in config.routers:
            r.rescanHook()

        print "OK: Test running rescan."
        return True
    except Exception as e:
        print "FAIL: Test running rescan.\n  Exception="+str(e)
        print traceback.format_exc()
        return False

def testULGPersistentStorage():
    try:
182
        ps = ulgmodel.loadPersistentStorage()
183 184 185
        ps.set('test','teststring')
        ps.save()

186
        ps2 = ulgmodel.loadPersistentStorage()
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
        if(ps2.get('test') == 'teststring'):
            ps2.delete('test')
            if(ps2.get('test') == None):
                print "OK: Test persistent storage."
                return True
            else:
                print "FAIL: Test persistent storage: Delete performed no effect."
                return False
        else:
            print "FAIL: Test persistent storage: Set performed no effect."
            return False
    except Exception as e:
        print "FAIL: Test persistent storage.\n  Exception="+str(e)
        print traceback.format_exc()
        return False  

203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
def testULGCiscoParser(header,cisco_input,expect):
    try:
        res = ulgcisco.matchCiscoBGPLines(header,cisco_input)

#        print "DEBUG: Cisco parser input: " + str(cisco_input)
#        print "DEBUG: Cisco parser output: " + str(res)

        if(res == expect):
            print "OK: Test Cisco parser."
            return True
        else:
            print "DEBUG: Cisco parser input: " + str(cisco_input)
            print "DEBUG: Cisco parser output: " + str(res)
            print "FAIL: Test Cisco parser. Wrong output."
            return False

    except Exception as e:
        print "FAIL: Test Cisco parser.\n  Exception="+str(e)
        print traceback.format_exc()
        return False  


def testULGCiscoParser1():
    header = "Stat Network          Next_Hop            Metric LocPrf Weight Path"
    cisco_input = """ *>  62.109.128.0/19  0.0.0.0                  0         32768 i
 *>  91.199.207.0/24  217.31.48.86                 1024      0 44672 i
 *>  91.224.58.0/23   217.31.48.70           100   1024      0 50833 i
 *>  93.170.16.0/21   217.31.48.70           100   1024      0 50833 i
 *>  188.227.128.0/19 0.0.0.0                  0         32768 i
 *>  217.31.48.0/20   0.0.0.0                  0         32768 i"""

    expect = [['*>', '62.109.128.0/19', '0.0.0.0', '0', '', '32768', 'i'],
              ['*>', '91.199.207.0/24', '217.31.48.86', '', '1024', '0', '44672 i'],
              ['*>', '91.224.58.0/23', '217.31.48.70', '100', '1024', '0', '50833 i'],
              ['*>', '93.170.16.0/21', '217.31.48.70', '100', '1024', '0', '50833 i'],
              ['*>', '188.227.128.0/19', '0.0.0.0', '0', '', '32768', 'i'],
              ['*>', '217.31.48.0/20', '0.0.0.0', '0', '', '32768', 'i']]


    return testULGCiscoParser(header,cisco_input.splitlines(),expect)

def testULGCiscoParser2():
    header = "Stat Network          Next_Hop            Metric LocPrf Weight Path"
    cisco_input = " *   195.226.217.0    62.109.128.9                           0 51278 i"
    expect = [['*', '195.226.217.0', '62.109.128.9', '', '', '0', '51278 i']]

    return testULGCiscoParser(header,cisco_input.splitlines(),expect)

def testULGCiscoParser3():
    header = "Stat Network          Next_Hop            Metric LocPrf Weight Path"
    cisco_input = """ *>  2001:67C:278::/48
                       2001:1AB0:7E1F:1:230:48FF:FE8C:A192
                                                    1024      0 51278 i
 *>  2001:1AB0::/32   ::                       0         32768 i
 *>  2A01:8C00::/32   ::                       0         32768 i"""
    expect = [['*>', '2001:67C:278::/48', '2001:1AB0:7E1F:1:230:48FF:FE8C:A192', '', '1024', '0', '51278 i'],
              ['*>', '2001:1AB0::/32', '::', '0', '', '32768', 'i'],
              ['*>', '2A01:8C00::/32', '::', '0', '', '32768', 'i']]

    return testULGCiscoParser(header,cisco_input.splitlines(),expect)

264

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282

#####################################
results = []

def runTest(result):
    global results
    results.append(result)

def reportResults():
    global results
    tests = len(results)
    failed = [ridx for (ridx,r) in enumerate(results) if r == False]
    passed = [ridx for (ridx,r) in enumerate(results) if r == True]

    print """\n***** Results *****
Tests pased: %d/%d
Tests failed: %d/%d""" % (len(passed),tests,len(failed),tests)
    print "Failed numbers: "+str(failed)+"\n"
283 284 285

# main
if __name__=="__main__":
286 287 288 289 290 291
    runTest(testRouterCommand(router=0,command=0,params=[]))
    runTest(testULGRunParameter(router=0,command=4,params=['91.210.16.1']))
    runTest(testULGIndex(routerid=0,commandid=0,sessionid=None))
    runTest(testULGAction(routerid=0,commandid=0,sessionid=None,maxtimes=10,interval=5,**{}))
    runTest(testULGSessions())
    runTest(testULGLock())
292
    runTest(testULGLog())
293 294
    runTest(testULGRescan())
    runTest(testULGPersistentStorage())
295 296 297
    runTest(testULGCiscoParser1())
    runTest(testULGCiscoParser2())
    runTest(testULGCiscoParser3())
298 299


300
    reportResults()