Ce serveur Gitlab sera éteint le 30 juin 2020, pensez à migrer vos projets vers les serveurs gitlab-research.centralesupelec.fr et gitlab-student.centralesupelec.fr !

tests.py 31.1 KB
Newer Older
1
# -*- mode: python; coding: utf-8 -*-
Maël Kervella's avatar
Maël Kervella committed
2 3 4 5
# Re2o est un logiciel d'administration développé initiallement au rezometz. Il
# se veut agnostique au réseau considéré, de manière à être installable en
# quelques clics.
#
6
# Copyright © 2018 Maël Kervella
Maël Kervella's avatar
Maël Kervella committed
7 8 9 10 11 12 13 14 15 16 17 18 19 20
#
# 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 2 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
"""Defines the test suite for the API
22
"""
Maël Kervella's avatar
Maël Kervella committed
23

Maël Kervella's avatar
Maël Kervella committed
24
import json
25
import datetime
Maël Kervella's avatar
Maël Kervella committed
26 27 28
from rest_framework.test import APITestCase
from requests import codes

29 30 31 32
import cotisations.models as cotisations
import machines.models as machines
import preferences.models as preferences
import topologie.models as topologie
Maël Kervella's avatar
Maël Kervella committed
33 34 35 36
import users.models as users


class APIEndpointsTestCase(APITestCase):    
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
    """Test case to test that all endpoints are reachable with respects to
    authentication and permission checks.

    Attributes:
        no_auth_endpoints: A list of endpoints that should be reachable
            without authentication.
        auth_no_perm_endpoints: A list of endpoints that should be reachable
            when being authenticated but without permissions.
        auth_perm_endpoints: A list of endpoints that should be reachable
            when being authenticated and having the correct permissions.
        stduser: A standard user with no permission used for the tests and
            initialized at the beggining of this test case.
        superuser: A superuser (with all permissions) used for the tests and
            initialized at the beggining of this test case.
    """
Maël Kervella's avatar
Maël Kervella committed
52 53 54 55 56
    no_auth_endpoints = [
        '/api/'
    ]
    auth_no_perm_endpoints = []
    auth_perm_endpoints = [
Maël Kervella's avatar
Maël Kervella committed
57
        '/api/cotisations/article/',
58
        '/api/cotisations/article/1/',
Maël Kervella's avatar
Maël Kervella committed
59
        '/api/cotisations/banque/',
60
        '/api/cotisations/banque/1/',
Maël Kervella's avatar
Maël Kervella committed
61
        '/api/cotisations/cotisation/',
62
        '/api/cotisations/cotisation/1/',
Maël Kervella's avatar
Maël Kervella committed
63
        '/api/cotisations/facture/',
64
        '/api/cotisations/facture/1/',
Maël Kervella's avatar
Maël Kervella committed
65
        '/api/cotisations/paiement/',
66
        '/api/cotisations/paiement/1/',
Maël Kervella's avatar
Maël Kervella committed
67
        '/api/cotisations/vente/',
68
        '/api/cotisations/vente/1/',
Maël Kervella's avatar
Maël Kervella committed
69
        '/api/machines/domain/',
70
        '/api/machines/domain/1/',
Maël Kervella's avatar
Maël Kervella committed
71
        '/api/machines/extension/',
72
        '/api/machines/extension/1/',
Maël Kervella's avatar
Maël Kervella committed
73
        '/api/machines/interface/',
74
        '/api/machines/interface/1/',
Maël Kervella's avatar
Maël Kervella committed
75
        '/api/machines/iplist/',
76
        '/api/machines/iplist/1/',
Maël Kervella's avatar
Maël Kervella committed
77
        '/api/machines/iptype/',
78
        '/api/machines/iptype/1/',
Maël Kervella's avatar
Maël Kervella committed
79
        '/api/machines/ipv6list/',
80
        '/api/machines/ipv6list/1/',
Maël Kervella's avatar
Maël Kervella committed
81
        '/api/machines/machine/',
82
        '/api/machines/machine/1/',
Maël Kervella's avatar
Maël Kervella committed
83
        '/api/machines/machinetype/',
84
        '/api/machines/machinetype/1/',
Maël Kervella's avatar
Maël Kervella committed
85
        '/api/machines/mx/',
86
        '/api/machines/mx/1/',
Maël Kervella's avatar
Maël Kervella committed
87
        '/api/machines/nas/',
88
        '/api/machines/nas/1/',
Maël Kervella's avatar
Maël Kervella committed
89
        '/api/machines/ns/',
90
        '/api/machines/ns/1/',
Maël Kervella's avatar
Maël Kervella committed
91
        '/api/machines/ouvertureportlist/',
92
        '/api/machines/ouvertureportlist/1/',
Maël Kervella's avatar
Maël Kervella committed
93
        '/api/machines/ouvertureport/',
94
        '/api/machines/ouvertureport/1/',
Maël Kervella's avatar
Maël Kervella committed
95
        '/api/machines/servicelink/',
96
        '/api/machines/servicelink/1/',
Maël Kervella's avatar
Maël Kervella committed
97
        '/api/machines/service/',
98
        '/api/machines/service/1/',
Maël Kervella's avatar
Maël Kervella committed
99
        '/api/machines/soa/',
100
        '/api/machines/soa/1/',
Maël Kervella's avatar
Maël Kervella committed
101
        '/api/machines/srv/',
102
        '/api/machines/srv/1/',
Maël Kervella's avatar
Maël Kervella committed
103
        '/api/machines/txt/',
104
        '/api/machines/txt/1/',
Maël Kervella's avatar
Maël Kervella committed
105
        '/api/machines/vlan/',
106
        '/api/machines/vlan/1/',
107 108 109 110 111
        '/api/preferences/optionaluser/',
        '/api/preferences/optionalmachine/',
        '/api/preferences/optionaltopologie/',
        '/api/preferences/generaloption/',
        '/api/preferences/service/',
112
        '/api/preferences/service/1/',
113 114 115
        '/api/preferences/assooption/',
        '/api/preferences/homeoption/',
        '/api/preferences/mailmessageoption/',
Maël Kervella's avatar
Maël Kervella committed
116
        '/api/topologie/acesspoint/',
117 118
        # 2nd machine to be create (machines_machine_1, topologie_accesspoint_1)
        '/api/topologie/acesspoint/2/',
Maël Kervella's avatar
Maël Kervella committed
119
        '/api/topologie/building/',
120
        '/api/topologie/building/1/',
Maël Kervella's avatar
Maël Kervella committed
121
        '/api/topologie/constructorswitch/',
122
        '/api/topologie/constructorswitch/1/',
Maël Kervella's avatar
Maël Kervella committed
123
        '/api/topologie/modelswitch/',
124
        '/api/topologie/modelswitch/1/',
Maël Kervella's avatar
Maël Kervella committed
125
        '/api/topologie/room/',
126
        '/api/topologie/room/1/',
127
        '/api/topologie/server/',
128 129 130
        # 3rd machine to be create (machines_machine_1, topologie_accesspoint_1,
        # topologie_server_1)
        '/api/topologie/server/3/',
Maël Kervella's avatar
Maël Kervella committed
131
        '/api/topologie/stack/',
132
        '/api/topologie/stack/1/',
Maël Kervella's avatar
Maël Kervella committed
133
        '/api/topologie/switch/',
134 135 136
        # 4th machine to be create (machines_machine_1, topologie_accesspoint_1,
        # topologie_server_1, topologie_switch_1)
        '/api/topologie/switch/4/',
Maël Kervella's avatar
Maël Kervella committed
137
        '/api/topologie/switchbay/',
138
        '/api/topologie/switchbay/1/',
Maël Kervella's avatar
Maël Kervella committed
139
        '/api/topologie/switchport/',
140 141 142
        '/api/topologie/switchport/1/',
        '/api/topologie/switchport/2/',
        '/api/topologie/switchport/3/',
Maël Kervella's avatar
Maël Kervella committed
143
        '/api/users/adherent/',
144 145
        # 3rd user to be create (stduser, superuser, users_adherent_1)
        '/api/users/adherent/3/',
Maël Kervella's avatar
Maël Kervella committed
146
        '/api/users/ban/',
147
        '/api/users/ban/1/',
Maël Kervella's avatar
Maël Kervella committed
148
        '/api/users/club/',
149 150 151
        # 4th user to be create (stduser, superuser, users_adherent_1,
        # users_club_1)
        '/api/users/club/4/', 
Maël Kervella's avatar
Maël Kervella committed
152
        '/api/users/listright/',
153 154
# TODO: Merge !145
#        '/api/users/listright/1/',
Maël Kervella's avatar
Maël Kervella committed
155
        '/api/users/school/',
156
        '/api/users/school/1/',
Maël Kervella's avatar
Maël Kervella committed
157
        '/api/users/serviceuser/',
158
        '/api/users/serviceuser/1/',
Maël Kervella's avatar
Maël Kervella committed
159
        '/api/users/shell/',
160
        '/api/users/shell/1/',
Maël Kervella's avatar
Maël Kervella committed
161
        '/api/users/user/',
162
        '/api/users/user/1/',
Maël Kervella's avatar
Maël Kervella committed
163
        '/api/users/whitelist/',
164
        '/api/users/whitelist/1/',
165 166 167 168 169
        '/api/dns/zones/',
        '/api/dhcp/hostmacip/',
        '/api/mailing/standard',
        '/api/mailing/club',
        '/api/services/regen/',
Maël Kervella's avatar
Maël Kervella committed
170
    ]
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
    not_found_endpoints = [
        '/api/cotisations/article/4242/',
        '/api/cotisations/banque/4242/',
        '/api/cotisations/cotisation/4242/',
        '/api/cotisations/facture/4242/',
        '/api/cotisations/paiement/4242/',
        '/api/cotisations/vente/4242/',
        '/api/machines/domain/4242/',
        '/api/machines/extension/4242/',
        '/api/machines/interface/4242/',
        '/api/machines/iplist/4242/',
        '/api/machines/iptype/4242/',
        '/api/machines/ipv6list/4242/',
        '/api/machines/machine/4242/',
        '/api/machines/machinetype/4242/',
        '/api/machines/mx/4242/',
        '/api/machines/nas/4242/',
        '/api/machines/ns/4242/',
        '/api/machines/ouvertureportlist/4242/',
        '/api/machines/ouvertureport/4242/',
        '/api/machines/servicelink/4242/',
        '/api/machines/service/4242/',
        '/api/machines/soa/4242/',
        '/api/machines/srv/4242/',
        '/api/machines/txt/4242/',
        '/api/machines/vlan/4242/',
        '/api/preferences/service/4242/',
        '/api/topologie/acesspoint/4242/',
        '/api/topologie/building/4242/',
        '/api/topologie/constructorswitch/4242/',
        '/api/topologie/modelswitch/4242/',
        '/api/topologie/room/4242/',
        '/api/topologie/server/4242/',
        '/api/topologie/stack/4242/',
        '/api/topologie/switch/4242/',
        '/api/topologie/switchbay/4242/',
        '/api/topologie/switchport/4242/',
        '/api/users/adherent/4242/',
        '/api/users/ban/4242/',
        '/api/users/club/4242/',
        '/api/users/listright/4242/',
        '/api/users/school/4242/',
        '/api/users/serviceuser/4242/',
        '/api/users/shell/4242/',
        '/api/users/user/4242/',
        '/api/users/whitelist/4242/',
    ]
Maël Kervella's avatar
Maël Kervella committed
218 219 220 221 222 223
    
    stduser = None
    superuser = None

    @classmethod
    def setUpTestData(cls):
224 225 226 227 228 229 230 231
        # Be aware that every object created here is never actually committed
        # to the database. TestCase uses rollbacks after each test to cancel all
        # modifications and recreates the data defined here before each test.
        # For more details, see
        # https://docs.djangoproject.com/en/1.10/topics/testing/tools/#testcase

        super(APIEndpointsTestCase, cls).setUpClass()

Maël Kervella's avatar
Maël Kervella committed
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
        # A user with no rights
        cls.stduser = users.User.objects.create_user(
            "apistduser",
            "apistduser",
            "apistduser@example.net",
            "apistduser"
        )
        # A user with all the rights
        cls.superuser = users.User.objects.create_superuser(
            "apisuperuser",
            "apisuperuser",
            "apisuperuser@example.net",
            "apisuperuser"
        )

247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
        # Creates 1 instance for each object so the "details" endpoints
        # can be tested too. Objects need to be created in the right order.
        # Dependencies (relatedFields, ...) are highlighted by a comment at
        # the end of the concerned line (# Dep <model>).
        cls.users_school_1 = users.School.objects.create(
            name="users_school_1"
        )
        cls.users_school_1.save()
        cls.users_listshell_1 = users.ListShell.objects.create(
            shell="users_listshell_1"
        )
        cls.users_adherent_1 = users.Adherent.objects.create(
            password="password",
            last_login=datetime.datetime.now(datetime.timezone.utc),
            surname="users_adherent_1",
            pseudo="usersadherent1",
            email="users_adherent_1@example.net",
            school=cls.users_school_1,  # Dep users.School
            shell=cls.users_listshell_1,  # Dep users.ListShell
            comment="users Adherent 1 comment",
            pwd_ntlm="",
            state=users.User.STATES[0][0],
            registered=datetime.datetime.now(datetime.timezone.utc),
            telephone="0123456789",
            uid_number=21102,
            rezo_rez_uid=21102
        )
        cls.users_user_1 = cls.users_adherent_1
        cls.cotisations_article_1 = cotisations.Article.objects.create(
            name="cotisations_article_1",
            prix=10,
            duration=1,
            type_user=cotisations.Article.USER_TYPES[0][0],
            type_cotisation=cotisations.Article.COTISATION_TYPE[0][0]
        )
        cls.cotisations_banque_1 = cotisations.Banque.objects.create(
            name="cotisations_banque_1"
        )
        cls.cotisations_paiement_1 = cotisations.Paiement.objects.create(
            moyen="cotisations_paiement_1",
            type_paiement=cotisations.Paiement.PAYMENT_TYPES[0][0]
        )
        cls.cotisations_facture_1 = cotisations.Facture.objects.create(
            user=cls.users_user_1,  # Dep users.User
            paiement=cls.cotisations_paiement_1,  # Dep cotisations.Paiement
            banque=cls.cotisations_banque_1,  # Dep cotisations.Banque
            cheque="1234567890",
            date=datetime.datetime.now(datetime.timezone.utc),
            valid=True,
            control=False
        )
        cls.cotisations_vente_1 = cotisations.Vente.objects.create(
            facture=cls.cotisations_facture_1,  # Dep cotisations.Facture
            number=2,
            name="cotisations_vente_1",
            prix=10,
            duration=1,
            type_cotisation=cotisations.Vente.COTISATION_TYPE[0][0]
        )
306 307 308 309 310 311
        # A cotisation is automatically created by the Vente object and
        # trying to create another cotisation associated with this vente
        # will fail so we simply retrieve it so it can be used in the tests
        cls.cotisations_cotisation_1 = cotisations.Cotisation.objects.get(
            vente=cls.cotisations_vente_1,  # Dep cotisations.Vente
        )
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
        cls.machines_machine_1 = machines.Machine.objects.create(
            user=cls.users_user_1,  # Dep users.User
            name="machines_machine_1",
            active=True
        )
        cls.machines_ouvertureportlist_1 = machines.OuverturePortList.objects.create(
            name="machines_ouvertureportlist_1"
        )
        cls.machines_soa_1 = machines.SOA.objects.create(
            name="machines_soa_1",
            mail="postmaster@example.net",
            refresh=86400,
            retry=7200,
            expire=3600000,
            ttl=172800
        )
        cls.machines_extension_1 = machines.Extension.objects.create(
            name="machines_extension_1",
            need_infra=False,
            # Do not set origin because of circular dependency
            origin_v6="2001:db8:1234::",
            soa=cls.machines_soa_1  # Dep machines.SOA
        )
        cls.machines_vlan_1 = machines.Vlan.objects.create(
            vlan_id=0,
            name="machines_vlan_1",
            comment="machines Vlan 1"
        )
        cls.machines_iptype_1 = machines.IpType.objects.create(
            type="machines_iptype_1",
            extension=cls.machines_extension_1,  # Dep machines.Extension
            need_infra=False,
            domaine_ip_start="10.0.0.1",
            domaine_ip_stop="10.0.0.255",
            prefix_v6="2001:db8:1234::",
            vlan=cls.machines_vlan_1,  # Dep machines.Vlan
            ouverture_ports=cls.machines_ouvertureportlist_1  # Dep machines.OuverturePortList
        )
        # All IPs in the IpType range are autocreated so we can't create
351
        # new ones and thus we only retrieve it if needed in the tests
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
        cls.machines_iplist_1 = machines.IpList.objects.get(
            ipv4="10.0.0.1",
            ip_type=cls.machines_iptype_1,  # Dep machines.IpType
        )
        cls.machines_machinetype_1 = machines.MachineType.objects.create(
            type="machines_machinetype_1",
            ip_type=cls.machines_iptype_1,  # Dep machines.IpType
        )
        cls.machines_interface_1 = machines.Interface.objects.create(
            ipv4=cls.machines_iplist_1,  # Dep machines.IpList
            mac_address="00:00:00:00:00:00",
            machine=cls.machines_machine_1,  # Dep machines.Machine
            type=cls.machines_machinetype_1,  # Dep machines.MachineType
            details="machines Interface 1",
            #port_lists=[cls.machines_ouvertureportlist_1]  # Dep machines.OuverturePortList
        )
        cls.machines_domain_1 = machines.Domain.objects.create(
            interface_parent=cls.machines_interface_1,  # Dep machines.Interface
            name="machinesdomain",
            extension=cls.machines_extension_1  # Dep machines.Extension
            # Do no define cname for circular dependency
        )
        cls.machines_mx_1 = machines.Mx.objects.create(
            zone=cls.machines_extension_1,  # Dep machines.Extension
            priority=10,
            name=cls.machines_domain_1  # Dep machines.Domain
        )
        cls.machines_ns_1 = machines.Ns.objects.create(
            zone=cls.machines_extension_1,  # Dep machines.Extension
            ns=cls.machines_domain_1  # Dep machines.Domain
        )
        cls.machines_txt_1 = machines.Txt.objects.create(
            zone=cls.machines_extension_1,  # Dep machines.Extension
            field1="machines_txt_1",
            field2="machies Txt 1"
        )
        cls.machines_srv_1 = machines.Srv.objects.create(
            service="machines_srv_1",
            protocole=machines.Srv.TCP,
            extension=cls.machines_extension_1,  # Dep machines.Extension
            ttl=172800,
            priority=0,
            port=1,
            target=cls.machines_domain_1,  # Dep machines.Domain
        )
        cls.machines_ipv6list_1 = machines.Ipv6List.objects.create(
            ipv6="2001:db8:1234::",
            interface=cls.machines_interface_1,  # Dep machines.Interface
            slaac_ip=False
        )
        cls.machines_service_1 = machines.Service.objects.create(
            service_type="machines_service_1",
            min_time_regen=datetime.timedelta(minutes=1),
            regular_time_regen=datetime.timedelta(hours=1)
            # Do not define service_link because circular dependency
        )
        cls.machines_servicelink_1 = machines.Service_link.objects.create(
            service=cls.machines_service_1,  # Dep machines.Service
            server=cls.machines_interface_1,  # Dep machines.Interface
            last_regen=datetime.datetime.now(datetime.timezone.utc),
            asked_regen=False
        )
        cls.machines_ouvertureport_1 = machines.OuverturePort.objects.create(
            begin=1,
            end=2,
            port_list=cls.machines_ouvertureportlist_1,  # Dep machines.OuverturePortList
            protocole=machines.OuverturePort.TCP,
            io=machines.OuverturePort.OUT
        )
        cls.machines_nas_1 = machines.Nas.objects.create(
            name="machines_nas_1",
            nas_type=cls.machines_machinetype_1,  # Dep machines.MachineType
            machine_type=cls.machines_machinetype_1,  # Dep machines.MachineType
            port_access_mode=machines.Nas.AUTH[0][0],
            autocapture_mac=False
        )
        cls.preferences_service_1 = preferences.Service.objects.create(
            name="preferences_service_1",
            url="https://example.net",
            description="preferences Service 1",
            image="/media/logo/none.png"
        )
        cls.topologie_stack_1 = topologie.Stack.objects.create(
            name="topologie_stack_1",
            stack_id="1",
            details="topologie Stack 1",
            member_id_min=1,
            member_id_max=10
        )
        cls.topologie_accespoint_1 = topologie.AccessPoint.objects.create(
            user=cls.users_user_1,  # Dep users.User
            name="machines_machine_1",
            active=True,
            location="topologie AccessPoint 1"
        )
        cls.topologie_server_1 = topologie.Server.objects.create(
            user=cls.users_user_1,  # Dep users.User
            name="machines_machine_1",
            active=True
        )
        cls.topologie_building_1 = topologie.Building.objects.create(
            name="topologie_building_1"
        )
        cls.topologie_switchbay_1 = topologie.SwitchBay.objects.create(
            name="topologie_switchbay_1",
            building=cls.topologie_building_1,  # Dep topologie.Building
            info="topologie SwitchBay 1"
        )
        cls.topologie_constructorswitch_1 = topologie.ConstructorSwitch.objects.create(
            name="topologie_constructorswitch_1"
        )
        cls.topologie_modelswitch_1 = topologie.ModelSwitch.objects.create(
            reference="topologie_modelswitch_1",
            constructor=cls.topologie_constructorswitch_1  # Dep topologie.ConstructorSwitch
        )
        cls.topologie_switch_1 = topologie.Switch.objects.create(
            user=cls.users_user_1,  # Dep users.User
            name="machines_machine_1",
            active=True,
            number=10,
            stack=cls.topologie_stack_1,  # Dep topologie.Stack
            stack_member_id=1,
            model=cls.topologie_modelswitch_1,  # Dep topologie.ModelSwitch
            switchbay=cls.topologie_switchbay_1  # Dep topologie.SwitchBay
        )
        cls.topologie_room_1 = topologie.Room.objects.create(
            name="topologie_romm_1",
            details="topologie Room 1"
        )
        cls.topologie_port_1 = topologie.Port.objects.create(
            switch=cls.topologie_switch_1,  # Dep topologie.Switch
            port=1,
            room=cls.topologie_room_1,  # Dep topologie.Room
            radius=topologie.Port.STATES[0][0],
            vlan_force=cls.machines_vlan_1,  # Dep machines.Vlan
            details="topologie_switch_1"
        )
        cls.topologie_port_2 = topologie.Port.objects.create(
            switch=cls.topologie_switch_1,  # Dep topologie.Switch
            port=2,
            machine_interface=cls.machines_interface_1,  # Dep machines.Interface
            radius=topologie.Port.STATES[0][0],
            vlan_force=cls.machines_vlan_1,  # Dep machines.Vlan
            details="topologie_switch_1"
        )
        cls.topologie_port_3 = topologie.Port.objects.create(
            switch=cls.topologie_switch_1,  # Dep topologie.Switch
            port=3,
            room=cls.topologie_room_1,  # Dep topologie.Room
            radius=topologie.Port.STATES[0][0],
            # Do not defines related because circular dependency  # Dep machines.Vlan
            details="topologie_switch_1"
        )
        cls.users_ban_1 = users.Ban.objects.create(
            user=cls.users_user_1,  # Dep users.User
            raison="users Ban 1",
            date_start=datetime.datetime.now(datetime.timezone.utc),
            date_end=datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1),
            state=users.Ban.STATES[0][0]
        )
        cls.users_club_1 = users.Club.objects.create(
            password="password",
            last_login=datetime.datetime.now(datetime.timezone.utc),
            surname="users_club_1",
            pseudo="usersclub1",
            email="users_club_1@example.net",
            school=cls.users_school_1,  # Dep users.School
            shell=cls.users_listshell_1,  # Dep users.ListShell
            comment="users Club 1 comment",
            pwd_ntlm="",
            state=users.User.STATES[0][0],
            registered=datetime.datetime.now(datetime.timezone.utc),
            telephone="0123456789",
            uid_number=21103,
            rezo_rez_uid=21103
        )
# Need merge of MR145 to work
# TODO: Merge !145
#        cls.users_listright_1 = users.ListRight.objects.create(
#            unix_name="userslistright",
#            gid=601,
#            critical=False,
#            details="userslistright"
#        )
        cls.users_serviceuser_1 = users.ServiceUser.objects.create(
            password="password",
            last_login=datetime.datetime.now(datetime.timezone.utc),
            pseudo="usersserviceuser1",
            access_group=users.ServiceUser.ACCESS[0][0],
            comment="users ServiceUser 1"
        )
        cls.users_whitelist_1 = users.Whitelist.objects.create(
            user=cls.users_user_1,
            raison="users Whitelist 1",
            date_start=datetime.datetime.now(datetime.timezone.utc),
            date_end=datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(days=1)
        )
Maël Kervella's avatar
Maël Kervella committed
549

550
    def check_responses_code(self, urls, expected_code, formats=None,
Maël Kervella's avatar
Maël Kervella committed
551
                             assert_more=None):
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
        """Utility function to test if a list of urls answer an expected code.

        Args:
            urls: The list of urls to test
            expected_code: The HTTP return code expected
            formats: The list of formats to use for the request. Default is to
                only test `None` format.
            assert_more: An optional function to assert more specific data in
                the same test. The response object, the url and the format
                used are passed as arguments.

        Raises:
            AssertionError: The response got did not have the expected status
                code.
            Any exception raised in the evalutation of `assert_more`.
Maël Kervella's avatar
Maël Kervella committed
567
        """
568 569
        if formats is None:
            formats = [None]
Maël Kervella's avatar
Maël Kervella committed
570 571 572 573 574
        for url in urls:
            for format in formats:
                with self.subTest(url=url, format=format):
                    response = self.client.get(url, format=format)
                    assert response.status_code == expected_code
575
                    if assert_more is not None:
Maël Kervella's avatar
Maël Kervella committed
576 577 578
                        assert_more(response, url, format)

    def test_no_auth_endpoints_with_no_auth(self):
579 580 581 582 583
        """Tests that every endpoint that does not require to be
        authenticated, returns a Ok (200) response when not authenticated.

        Raises:
            AssertionError: An endpoint did not have a 200 status code.
Maël Kervella's avatar
Maël Kervella committed
584
        """
585
        urls = self.no_auth_endpoints
Maël Kervella's avatar
Maël Kervella committed
586 587 588
        self.check_responses_code(urls, codes.ok)

    def test_auth_endpoints_with_no_auth(self):
589
        """Tests that every endpoint that does require to be authenticated,
Maël Kervella's avatar
Maël Kervella committed
590
        returns a Unauthorized (401) response when not authenticated.
591 592 593

        Raises:
            AssertionError: An endpoint did not have a 401 status code.
Maël Kervella's avatar
Maël Kervella committed
594
        """
595
        urls = self.auth_no_perm_endpoints + self.auth_perm_endpoints
Maël Kervella's avatar
Maël Kervella committed
596 597 598
        self.check_responses_code(urls, codes.unauthorized)

    def test_no_auth_endpoints_with_auth(self):
599 600 601 602 603
        """Tests that every endpoint that does not require to be
        authenticated, returns a Ok (200) response when authenticated.

        Raises:
            AssertionError: An endpoint did not have a 200 status code.
Maël Kervella's avatar
Maël Kervella committed
604 605
        """
        self.client.force_authenticate(user=self.stduser)
606
        urls = self.no_auth_endpoints
Maël Kervella's avatar
Maël Kervella committed
607 608 609
        self.check_responses_code(urls, codes.ok)

    def test_auth_no_perm_endpoints_with_auth_and_no_perm(self):
610 611 612 613 614 615
        """Tests that every endpoint that does require to be authenticated and
        no special permissions, returns a Ok (200) response when authenticated
        but without permissions.

        Raises:
            AssertionError: An endpoint did not have a 200 status code.
Maël Kervella's avatar
Maël Kervella committed
616 617
        """
        self.client.force_authenticate(user=self.stduser)
618
        urls = self.auth_no_perm_endpoints
Maël Kervella's avatar
Maël Kervella committed
619 620 621
        self.check_responses_code(urls, codes.ok)

    def test_auth_perm_endpoints_with_auth_and_no_perm(self):
622
        """Tests that every endpoint that does require to be authenticated and
Maël Kervella's avatar
Maël Kervella committed
623 624
        special permissions, returns a Forbidden (403) response when
        authenticated but without permissions.
625 626 627

        Raises:
            AssertionError: An endpoint did not have a 403 status code.
Maël Kervella's avatar
Maël Kervella committed
628 629
        """
        self.client.force_authenticate(user=self.stduser)
630
        urls = self.auth_perm_endpoints
Maël Kervella's avatar
Maël Kervella committed
631 632 633
        self.check_responses_code(urls, codes.forbidden)

    def test_auth_endpoints_with_auth_and_perm(self):
634 635 636 637 638
        """Tests that every endpoint that does require to be authenticated,
        returns a Ok (200) response when authenticated with all permissions.

        Raises:
            AssertionError: An endpoint did not have a 200 status code.
Maël Kervella's avatar
Maël Kervella committed
639 640
        """
        self.client.force_authenticate(user=self.superuser)
641
        urls = self.auth_no_perm_endpoints + self.auth_perm_endpoints
Maël Kervella's avatar
Maël Kervella committed
642 643 644
        self.check_responses_code(urls, codes.ok)

    def test_endpoints_not_found(self):
645
        """Tests that every endpoint that uses a primary key parameter,
Maël Kervella's avatar
Maël Kervella committed
646
        returns a Not Found (404) response when queried with non-existing
647 648 649 650
        primary key.

        Raises:
            AssertionError: An endpoint did not have a 404 status code.
Maël Kervella's avatar
Maël Kervella committed
651 652 653
        """
        self.client.force_authenticate(user=self.superuser)
        # Select only the URLs with '<pk>' and replace it with '42'
654
        urls = self.not_found_endpoints
Maël Kervella's avatar
Maël Kervella committed
655 656 657
        self.check_responses_code(urls, codes.not_found)

    def test_formats(self):
658 659 660 661 662 663
        """Tests that every endpoint returns a Ok (200) response when using
        different formats. Also checks that 'json' format returns a valid
        JSON object.

        Raises:
            AssertionError: An endpoint did not have a 200 status code.
Maël Kervella's avatar
Maël Kervella committed
664 665 666
        """
        self.client.force_authenticate(user=self.superuser)
        
667 668
        urls = self.no_auth_endpoints + self.auth_no_perm_endpoints + \
               self.auth_perm_endpoints
Maël Kervella's avatar
Maël Kervella committed
669 670 671 672 673 674 675 676 677 678 679

        def assert_more(response, url, format):
            """Assert the response is valid json when format is json"""
            if format is 'json':
                json.loads(response.content.decode())

        self.check_responses_code(urls, codes.ok,
                                  formats=[None, 'json', 'api'],
                                  assert_more=assert_more)

class APIPaginationTestCase(APITestCase):
680 681 682 683 684 685 686 687
    """Test case to check that the pagination is used on all endpoints that
    should use it.

    Attributes:
        endpoints: A list of endpoints that should use the pagination.
        superuser: A superuser used in the tests to access the endpoints.
    """

Maël Kervella's avatar
Maël Kervella committed
688
    endpoints = [
Maël Kervella's avatar
Maël Kervella committed
689 690 691 692 693 694 695 696 697 698 699 700 701 702
        '/api/cotisations/article/',
        '/api/cotisations/banque/',
        '/api/cotisations/cotisation/',
        '/api/cotisations/facture/',
        '/api/cotisations/paiement/',
        '/api/cotisations/vente/',
        '/api/machines/domain/',
        '/api/machines/extension/',
        '/api/machines/interface/',
        '/api/machines/iplist/',
        '/api/machines/iptype/',
        '/api/machines/ipv6list/',
        '/api/machines/machine/',
        '/api/machines/machinetype/',
Maël Kervella's avatar
Maël Kervella committed
703 704 705
        '/api/machines/mx/',
        '/api/machines/nas/',
        '/api/machines/ns/',
Maël Kervella's avatar
Maël Kervella committed
706 707 708 709
        '/api/machines/ouvertureportlist/',
        '/api/machines/ouvertureport/',
        '/api/machines/servicelink/',
        '/api/machines/service/',
Maël Kervella's avatar
Maël Kervella committed
710 711 712
        '/api/machines/soa/',
        '/api/machines/srv/',
        '/api/machines/txt/',
Maël Kervella's avatar
Maël Kervella committed
713
        '/api/machines/vlan/',
714
        '/api/preferences/service/',
Maël Kervella's avatar
Maël Kervella committed
715 716 717 718 719
        '/api/topologie/acesspoint/',
        '/api/topologie/building/',
        '/api/topologie/constructorswitch/',
        '/api/topologie/modelswitch/',
        '/api/topologie/room/',
720
        '/api/topologie/server/',
Maël Kervella's avatar
Maël Kervella committed
721 722 723 724
        '/api/topologie/stack/',
        '/api/topologie/switch/',
        '/api/topologie/switchbay/',
        '/api/topologie/switchport/',
Maël Kervella's avatar
Maël Kervella committed
725 726 727 728 729 730 731 732 733
        '/api/users/adherent/',
        '/api/users/ban/',
        '/api/users/club/',
        '/api/users/listright/',
        '/api/users/school/',
        '/api/users/serviceuser/',
        '/api/users/shell/',
        '/api/users/user/',
        '/api/users/whitelist/',
734 735 736 737 738
        '/api/dns/zones/',
        '/api/dhcp/hostmacip/',
        '/api/mailing/standard',
        '/api/mailing/club',
        '/api/services/regen/',
Maël Kervella's avatar
Maël Kervella committed
739 740 741 742 743 744
    ]
    superuser = None

    @classmethod
    def setUpTestData(cls):
        # A user with all the rights
745 746 747 748
        # We need to use a different username than for the first
        # test case because TestCase is using rollbacks which don't 
        # trigger the ldap_sync() thus the LDAP still have data about
        # the old users.
Maël Kervella's avatar
Maël Kervella committed
749
        cls.superuser = users.User.objects.create_superuser(
750 751 752 753
            "apisuperuser2",
            "apisuperuser2",
            "apisuperuser2@example.net",
            "apisuperuser2"
Maël Kervella's avatar
Maël Kervella committed
754 755 756 757 758 759 760 761
        )

    @classmethod
    def tearDownClass(cls):
        cls.superuser.delete()
        super().tearDownClass()

    def test_pagination(self):
762 763 764 765 766 767
        """Tests that every endpoint is using the pagination correctly.

        Raises:
            AssertionError: An endpoint did not have one the following keyword
                in the JSOn response: 'count', 'next', 'previous', 'results'
                or more that 100 results were returned.
Maël Kervella's avatar
Maël Kervella committed
768 769 770 771 772 773 774 775 776 777 778
        """
        self.client.force_authenticate(self.superuser)
        for url in self.endpoints:
            with self.subTest(url=url):
                response = self.client.get(url, format='json')
                res_json = json.loads(response.content.decode())
                assert 'count' in res_json.keys()
                assert 'next' in res_json.keys()
                assert 'previous' in res_json.keys()
                assert 'results' in res_json.keys()
                assert not len('results') > 100
Maël Kervella's avatar
Maël Kervella committed
779