test.py 8.53 KB
Newer Older
1
#!/bin/bash /usr/scripts/python.sh
2
# -*- coding: utf-8 -*-
3 4

# import lib standard
5
import psycopg2
6 7 8
import traceback
import random
import string
9 10
import os
import sys
11 12 13 14 15 16

## import locaux
import lc_ldap
import shortcuts
import variables

17 18 19 20
## import dans /usr/scripts/
sys.path.append("/usr/scripts/")
from gestion.affich_tools import anim, OK, cprint, ERREUR

21
mail_format = False
22
show_traceback = False
23 24 25 26 27
if "--traceback" in sys.argv:
    show_traceback = True
fast_test = False
if "--fast" in sys.argv:
    fast_test = True
28 29 30 31
if "--mail" in sys.argv:
    mail_format = True
    OK = "OK"
    ERREUR = "ERREUR"
32 33 34 35 36
def randomMAC():
    mac = [ 0x00, 0x16, 0x3e,
        random.randint(0x00, 0x7f),
        random.randint(0x00, 0xff),
        random.randint(0x00, 0xff) ]
37
    return u':'.join(map(lambda x: u"%02x" % x, mac))
38 39 40 41 42

def randomStr(n=10):
    return ''.join( random.choice(string.lowercase + string.digits) for i in range(n))

adherent_ldif = {
43 44 45 46 47 48
 'prenom' : [u'Totoé'],
 'nom' : [u'passoir'],
 'chbre' : [u'EXT'],
 'tel' : [u'0000000000'],
 'mail' : [u'nobody@test.org'],
 'etudes' : [u'ÉNS', u'1', u'A0'],
49 50 51 52
}

machine_ldif = {
 'macAddress' : [randomMAC()],
53
 'host' : [u"autotest-%s.crans.org" % randomStr() ]
54 55
}

56 57
borne_ldif  = {
 'macAddress' : [randomMAC()],
58 59
 'host' : [u"autotest-%s.crans.org" % randomStr() ],
 'canal' : [u"11"],
60
 'puissance' : [u"52"],
61
 'hotspot' : [u'FALSE'],
62 63
}

64
club_ldif = {
65 66
 'nom' : [ u'autotest-club' ],
 'chbre' : [ u'EXT' ],
67 68
}

69
facture_ldif = {
70
 'modePaiement' : [u'liquide'],
71
}
72 73


74
def keys_of_list_of_dict(l, type=''):
Valentin Samir's avatar
Valentin Samir committed
75 76
    """Récupère la liste de tous les attributs existant.
    Teste l'écriture des objets si on est en mode rw"""
77
    keys = set()
78
    if l:
79
        anime=anim("Test des objets %r" % type, 0 if mail_format else len(l))
80 81
        anime.reinit()
    ok=True
82
    for item in l:
83 84 85
        keys = keys.union(item.attrs.keys())
        try:
            if item.mode in  ['w', 'rw']:
86 87
                with item:
                    item.save()
88 89 90
        except Exception as error:
            anime.reinit()
            print ERREUR
91
            print item
92 93 94
            if show_traceback: print traceback.format_exc()
            else: print "\t%r" % error
            ok = False
95 96
        if not mail_format:
            anime.cycle()
Valentin Samir's avatar
Valentin Samir committed
97 98 99
    if l:
        anime.reinit()
        print OK if ok else ERREUR
100 101 102 103 104
    keys = list(keys)
    keys.sort()
    return keys

def test_list_of_dict(keys, list):
Valentin Samir's avatar
Valentin Samir committed
105
    """Test l'instanciation des attributs"""
106 107 108 109 110
    for key in keys:
        anim("\tTest de l'attribut %s" % key)
        ok = True
        for item in list:
            try: item.get(key, [])
111 112 113 114 115
            except psycopg2.OperationalError as error:
                print ERREUR
                if show_traceback: print traceback.format_exc()
                else: print "\t%r" % error
                return
116 117
            except Exception as error:
                if ok: print ERREUR
118
                print item
119 120 121 122 123 124
                if show_traceback: print traceback.format_exc()
                else: print "\t%r" % error
                ok = False
        if ok: print OK

def tests_machines(parent_dn, realm_list, ipsec=False):
Valentin Samir's avatar
Valentin Samir committed
125
    """Test la création et la suppression de machines dans la realm_list"""
126 127 128
    for realm in realm_list:
        anim("Creation de machines %s" % realm)
        try: 
129 130 131 132
            if realm == 'bornes':
                mldif = borne_ldif
            else:
                mldif = machine_ldif
133 134 135
            with conn.newMachine(parent_dn, realm,  mldif) as machine:
                if ipsec: machine['ipsec'] = u'auto'
                machine.create()
136 137 138 139 140 141 142 143
        except Exception as error:
            print ERREUR
            if show_traceback: print traceback.format_exc()
            else: print "\t%r" % error
        else:
            print OK
            anim("Suppression d'une machines %s" % realm)
            try:
144 145 146
                with conn.search(u'mid=%s' % machine['mid'][0], mode='rw')[0] as machine:
                    machine.delete()
                    del(machine)
147 148 149 150 151 152
            except Exception as error:
                print ERREUR
                if show_traceback: print traceback.format_exc()
                else: print "\t%r" % error
            else: print OK

153 154
if not mail_format:
    print "Test de la librairie lc_ldap"
155

156
    print "Connexion"
157
conn = shortcuts.lc_ldap_test()
158

159 160
if not mail_format:
    print u"Tests effectués avec les droits %s " % ', '.join(conn.droits)
161 162 163 164 165 166

###############################################
# Instanciation de tous les attributs de tous #
# les adhérents et de toutes les machines     #
###############################################

167 168 169
anim("Appel de allMachinesAdherents en %s" % ('ro' if fast_test else 'rw'))
try:
    if fast_test:
170 171
        machines, adherents = conn.allMachinesAdherents()
    else:
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
        machines, adherents = conn.allMachinesAdherents(mode='rw')
except EnvironmentError as error:
    print ERREUR
    if show_traceback: print traceback.format_exc()
    else: print "\t%s" % error
    exit(1)
except Exception as error:
    print ERREUR
    if show_traceback: print traceback.format_exc()
    else: print "\t%r" % error
    anim("Fallback en ro")
    machines, adherents = conn.allMachinesAdherents()
    print OK
else:
    print OK

machines_attrs_keys = keys_of_list_of_dict(machines, 'machines')
189 190
if not mail_format:
    print "Test des attributs des machines"
191 192 193
test_list_of_dict(machines_attrs_keys, machines)

adherents_attrs_keys = keys_of_list_of_dict(adherents, 'adherents')
194 195
if not mail_format:
    print "Test des attributs des adhérents"
196
test_list_of_dict(adherents_attrs_keys, adherents)
197

198 199 200 201 202 203 204 205 206 207 208
factures = conn.search(u"fid=*", sizelimit=-1, mode='ro' if fast_test else 'rw')
factures_attrs_keys = keys_of_list_of_dict(factures, 'factures')
if not mail_format:
    print "Test des attributs des factures"
test_list_of_dict(factures_attrs_keys, factures)

certificats = conn.search(u"xid=*", sizelimit=-1, mode='ro' if fast_test else 'rw')
certificats_attrs_keys = keys_of_list_of_dict(certificats, 'certificats')
if not mail_format:
    print "Test des attributs des certificats"
test_list_of_dict(certificats_attrs_keys, certificats)
209

210 211 212
if not mail_format:
    print "Test de création d'objets"
    print "Instanciation"
213 214 215 216 217 218 219 220


##############################################
# Création  d'un Adhérent et de ses machines #
##############################################

anim("Creation d'un adherent")
try:
221 222
    with conn.newAdherent(adherent_ldif) as adherent:
        adherent.create()
223
except Exception:
224 225 226 227 228 229
    print ERREUR
    print traceback.format_exc()
    adherent = None
else:
    print OK

230 231
    tests_machines(adherent.dn, ["adherents", "adherents-v6", "personnel-ens"])
    tests_machines(adherent.dn, ["wifi-adh", "wifi-adh-v6"], ipsec=True)
232 233 234 235 236 237


#############################################
# Création et suppression de machines Crans #
#############################################

238 239
tests_machines(variables.base_dn, ["adm", "serveurs", "serveurs-v6", "adm-v6"])
tests_machines(variables.base_dn, ["bornes"])
240 241 242 243 244 245 246 247


######################
# Création d'un club #
######################

anim("Creation d'un club")
try:
248 249 250
    with conn.newClub(club_ldif) as club:
        club['responsable'] = unicode(adherent['aid'][0])
        club.create()
251
except Exception:
252 253 254 255 256 257 258 259 260
    print ERREUR
    print traceback.format_exc()
else:
    print OK

    tests_machines(club.dn, ["adherents"])

    anim("Suppression d'un club")
    try:
261 262
        with conn.search(u'cid=%s' % club['cid'][0], mode='rw')[0] as club:
            club.delete()
263
    except Exception:
264 265 266 267 268 269 270 271 272
        print ERREUR
        print traceback.format_exc()
    else: print OK


#######################################
# Création et suppression de factures #
#######################################

273 274
if adherent:
    anim("Creation d'une facture")
275
    try:
276 277 278
        with conn.newFacture(adherent.dn, facture_ldif) as facture:
            facture.create()
    except Exception as error:
279
        print ERREUR
280 281 282 283 284 285 286 287 288 289 290 291
        if show_traceback: print traceback.format_exc()
        else: print "\t%r" % error
    else:
        print OK
        anim("Suppression d'une facture")
        try:
            with conn.search(u'fid=%s' % facture['fid'][0], mode='rw')[0] as facture:
                facture.delete()
        except Exception:
            print ERREUR
            print traceback.format_exc()
        else: print OK
292

293 294 295 296 297 298 299 300

############################
# Supression d'un adhérent #
############################

if adherent:
    anim("Suppression d'un adherent")
    try:
301 302
        with conn.search(u'aid=%s' % adherent['aid'][0], mode='rw')[0] as adherent:
            adherent.delete()
303 304 305 306
    except Exception:
        print ERREUR
        print traceback.format_exc()
    else: print OK