Projet

Général

Profil

0004-add-new-API-tests-fixes-7862.patch

Benjamin Dauvergne, 13 novembre 2015 11:03

Télécharger (131 ko)

Voir les différences:

Subject: [PATCH 4/4] add new API tests (fixes #7862)

 tests/conftest.py                         |  87 ++++++++++++++++++++++++++++++
 tests/integration/saml2/__init__.py       |  49 -----------------
 tests/integration/saml2/idp.db            | Bin 549888 -> 0 bytes
 tests/integration/saml2/idp_manage.py     |  21 --------
 tests/integration/saml2/sp.db             | Bin 549888 -> 0 bytes
 tests/integration/saml2/sp_manage.py      |  21 --------
 tests/integration/saml2/test_00_config.py |  44 ---------------
 tests/templates/base.html                 |   8 ---
 tests/test_api.py                         |  66 +++++++++++++++++++++++
 9 files changed, 153 insertions(+), 143 deletions(-)
 create mode 100644 tests/conftest.py
 delete mode 100644 tests/integration/saml2/__init__.py
 delete mode 100644 tests/integration/saml2/idp.db
 delete mode 100644 tests/integration/saml2/idp_manage.py
 delete mode 100644 tests/integration/saml2/sp.db
 delete mode 100644 tests/integration/saml2/sp_manage.py
 delete mode 100644 tests/integration/saml2/test_00_config.py
 delete mode 100644 tests/templates/base.html
 create mode 100644 tests/test_api.py
tests/conftest.py
1
# -*- coding: utf-8 -*-
2

  
3
import pytest
4

  
5
import django_webtest
6

  
7
from django.core.wsgi import get_wsgi_application
8
from django.contrib.auth import get_user_model
9
from django_rbac.utils import get_ou_model
10

  
11
from authentic2.a2_rbac.utils import get_default_ou
12

  
13
import utils
14

  
15

  
16
@pytest.fixture
17
def app(request):
18
    wtm = django_webtest.WebTestMixin()
19
    wtm._patch_settings()
20
    request.addfinalizer(wtm._unpatch_settings)
21
    return django_webtest.DjangoTestApp()
22

  
23

  
24
@pytest.fixture
25
def ou1(db):
26
    OU = get_ou_model()
27
    return OU.objects.create(name='OU1', slug='ou1')
28

  
29

  
30
@pytest.fixture
31
def ou2(db):
32
    OU = get_ou_model()
33
    return OU.objects.create(name='OU2', slug='ou2')
34

  
35
def create_user(**kwargs):
36
    User = get_user_model()
37
    password = kwargs.pop('password', None) or kwargs['username']
38
    user, created = User.objects.get_or_create(**kwargs)
39
    if password:
40
        user.set_password(password)
41
        user.save()
42
    return user
43

  
44

  
45
@pytest.fixture
46
def superuser(db):
47
    return create_user(username='superuser', first_name='super', last_name='user',
48
                       email='superuser@example.net', is_superuser=True, is_staff=True,
49
                       is_active=True, ou=get_default_ou())
50

  
51

  
52
@pytest.fixture
53
def user_ou1(db, ou1):
54
    return create_user(username='john.doe', first_name=u'Jôhn', last_name=u'Dôe',
55
                       email='john.doe@example.net', ou=ou1)
56

  
57

  
58
@pytest.fixture
59
def user_ou2(db, ou2):
60
    return create_user(username='john.doe', first_name=u'Jôhn', last_name=u'Dôe',
61
                       email='john.doe@example.net', ou=ou2)
62

  
63

  
64
@pytest.fixture
65
def admin_ou1(db, ou1):
66
    user = create_user(username='admin.ou1', first_name=u'Admin', last_name=u'OU1',
67
                       email='admin.ou1@example.net', ou=ou1)
68
    user.roles.add(ou1.get_admin_role())
69
    return user
70

  
71

  
72
@pytest.fixture
73
def admin_ou2(db, ou2):
74
    user = create_user(username='admin.ou2', first_name=u'Admin', last_name=u'OU2',
75
                       email='admin.ou2@example.net', ou=ou2)
76
    user.roles.add(ou2.get_admin_role())
77
    return user
78

  
79
@pytest.fixture(params=['superuser', 'user_ou1', 'user_ou2', 'admin_ou1', 'admin_ou2'])
80
def user(request, superuser, user_ou1, user_ou2, admin_ou1, admin_ou2):
81
    return locals().get(request.param)
82

  
83

  
84
@pytest.fixture
85
def logged_app(app, user):
86
    return utils.login(app, user)
87

  
tests/integration/saml2/__init__.py
1
import sys
2
import os
3
import signal
4
import subprocess
5
import time
6
import twill
7
import urllib2
8
import os.path
9
import re
10

  
11
TEST_PATH = os.path.dirname(os.path.abspath(__file__))
12

  
13
def waitforport(port, start):
14
    while True:
15
        if time.time() - start > 900:
16
            raise Exception('Servers did not start in 90 seconds')
17
        time.sleep(1)
18
        try:
19
            urllib2.urlopen('http://localhost:%s' % port)
20
        except urllib2.URLError:
21
            continue
22
        else:
23
            break
24

  
25
pids = []
26

  
27
def setup():
28
    idp_command = ['python', os.path.join(TEST_PATH, 'idp_manage.py'), 'runserver', 'localhost:10000', '--verbosity=2']
29
    p = subprocess.Popen(idp_command)
30
    pids.append(p.pid)
31

  
32
    sp_command = ['python', os.path.join(TEST_PATH, 'sp_manage.py'), 'runserver', 'localhost:10001', '--verbosity=2']
33
    p = subprocess.Popen(sp_command)
34
    pids.append(p.pid)
35

  
36
    # Wait for the daemons to load themselves
37
    starttime = time.time()
38
    waitforport(10000, starttime)
39
    waitforport(10001, starttime)
40

  
41
def teardown():
42
    for pid in pids:
43
        try:
44
            # TODO: do something better...
45
            if os.path.exists("/proc/" + str(pid+2)):
46
                os.kill(pid+2, signal.SIGINT) # In status check the Ppid
47
            os.kill(pid, signal.SIGINT)
48
        except OSError:
49
            print >> sys.stderr, 'failed to kill pid %s or its son' % pid
tests/integration/saml2/idp_manage.py
1
from django.core.management import *
2
import os
3

  
4
TEST_PATH = os.path.dirname(os.path.abspath(__file__))
5

  
6
try:
7
    import settings
8
    settings.DATABASES = {
9
        'default': {
10
            'ENGINE': 'django.db.backends.sqlite3',
11
            'NAME': os.path.join(TEST_PATH, 'idp.db'),
12
        },
13
    }
14

  
15
except ImportError:
16
    import sys
17
    sys.stderr.write("Error: Unable to import settings from %s!\n" % __file__)
18
    sys.exit(1)
19

  
20
if __name__ == "__main__":
21
    execute_manager(settings)
tests/integration/saml2/sp_manage.py
1
from django.core.management import *
2
import os
3

  
4
TEST_PATH = os.path.dirname(os.path.abspath(__file__))
5

  
6
try:
7
    import settings
8
    settings.DATABASES = {
9
        'default': {
10
            'ENGINE': 'django.db.backends.sqlite3',
11
            'NAME': os.path.join(TEST_PATH, 'sp.db'),
12
        },
13
    }
14

  
15
except ImportError:
16
    import sys
17
    sys.stderr.write("Error: Unable to import settings from %s!\n" % __file__)
18
    sys.exit(1)
19

  
20
if __name__ == "__main__":
21
    execute_manager(settings)
tests/integration/saml2/test_00_config.py
1
import twill
2

  
3
print 'test_00_config'
4

  
5
def test_config_idp():
6
    twill.commands.reset_browser()
7
    twill.execute_string('''
8
go http://localhost:10000/admin/
9
fv 1 username admin
10
fv 1 password admin
11
submit
12
go http://localhost:10000/admin/
13
find 'dministration'
14
''')
15
    twill.commands.reset_browser()
16
    twill.execute_string('''
17
go http://localhost:10000
18
fv 1 username user1
19
fv 1 password user1
20
submit
21
url http://localhost:10000
22
find 'You are authenticated'
23
''')
24

  
25
def test_config_sp():
26
    twill.commands.reset_browser()
27
    twill.execute_string('''
28
go http://localhost:10001/admin/
29
fv 1 username admin
30
fv 1 password admin
31
submit
32
go http://localhost:10001/admin/
33
find 'dministration'
34
''')
35
    twill.commands.reset_browser()
36
    twill.execute_string('''
37
go http://localhost:10001
38
fv 1 username user1
39
fv 1 password user1
40
submit
41
url http://localhost:10001
42
find 'You are authenticated'
43
''')
44

  
tests/templates/base.html
1
<html>
2
<head></head>
3
<body>
4
<h1>Django Internal Tests: {% block title %}{% endblock %}</h1>
5
{% block content %}
6
{% endblock %}
7
</body>
8
</html>
tests/test_api.py
1
import pytest
2

  
3
pytestmark = pytest.mark.django_db
4

  
5

  
6
def test_api_user(logged_app):
7
    resp = logged_app.get('/api/user/')
8
    assert isinstance(resp.json, dict)
9
    assert 'username' in resp.json
10
    assert 'username' in resp.json
11

  
12
def test_api_users_list(app, user):
13
    app.authorization = ('Basic', (user.username, user.username))
14
    resp = app.get('/api/users/')
15
    assert isinstance(resp.json, list)
16
    if user.is_superuser:
17
        assert len(resp.json) == 5
18
    elif user.roles.exists():
19
        assert len(resp.json) == 2
20
    else:
21
        assert len(resp.json) == 0
22

  
23
def test_api_users_create(app, user):
24
    from django.contrib.auth import get_user_model
25

  
26
    app.authorization = ('Basic', (user.username, user.username))
27
    payload = {
28
        'ou': None,
29
        'username': 'john.doe',
30
        'first_name': 'John',
31
        'last_name': 'Doe',
32
        'email': 'john.doe@example.net',
33
        'password': 'password',
34
    }
35
    if user.is_superuser:
36
        status = 201
37
    elif user.roles.exists():
38
        status = 201
39
        payload['ou'] = user.ou.slug
40
    else:
41
        status = 403
42

  
43
    resp = app.post_json('/api/users/', payload, status=status)
44
    if user.is_superuser or user.roles.exists():
45
        assert set(['ou', 'id', 'uuid', 'is_staff', 'is_superuser', 'first_name', 'last_name',
46
                   'date_joined', 'last_login', 'username', 'password', 'email', 'is_active']) == set(resp.json.keys())
47
        assert resp.json['first_name'] == payload['first_name']
48
        assert resp.json['last_name'] == payload['last_name']
49
        assert resp.json['email'] == payload['email']
50
        assert resp.json['username'] == payload['username']
51
        assert resp.json['uuid']
52
        assert resp.json['id']
53
        assert resp.json['date_joined']
54
        assert resp.json['last_login']
55
        if user.is_superuser:
56
            assert resp.json['ou'] is None
57
        elif user.roles.exists():
58
            assert resp.json['ou'] == user.ou.slug
59
        new_user = get_user_model().objects.get(id=resp.json['id'])
60
        assert new_user.uuid == resp.json['uuid']
61
        assert new_user.username == resp.json['username']
62
        assert new_user.email == resp.json['email']
63
        assert new_user.first_name == resp.json['first_name']
64
        assert new_user.last_name == resp.json['last_name']
65
        resp2 = app.get('/api/users/%s/' % resp.json['id'])
66
        assert resp.json == resp2.json
0
-