##// END OF EJS Templates
tests: small fixes
ergo -
Show More
@@ -1,184 +1,185 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2016 RhodeCode GmbH
3 # Copyright (C) 2010-2016 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # AppEnlight Enterprise Edition, including its added features, Support
18 # AppEnlight Enterprise Edition, including its added features, Support
19 # services, and proprietary license terms, please see
19 # services, and proprietary license terms, please see
20 # https://rhodecode.com/licenses/
20 # https://rhodecode.com/licenses/
21
21
22 import mock
22 import mock
23 import os
23 import os
24 import pytest
24 import pytest
25 import transaction
25 import transaction
26 from datetime import datetime
26 from datetime import datetime
27
27
28 from alembic.config import Config
28 from alembic.config import Config
29 from alembic import command
29 from alembic import command
30 from collections import OrderedDict
30 from collections import OrderedDict
31 from zope.sqlalchemy import mark_changed
31 from zope.sqlalchemy import mark_changed
32 from pyramid.paster import get_appsettings
32 from pyramid.paster import get_appsettings
33 from pyramid import testing
33 from pyramid import testing
34
34
35 from appenlight.models import Base, DBSession
35 from appenlight.models import Base, DBSession
36
36
37
37
38 @pytest.fixture
38 @pytest.fixture
39 def base_app(request):
39 def base_app(request):
40 from appenlight import main
40 from appenlight import main
41 import transaction
41 import transaction
42 current_dir = os.path.dirname(os.path.abspath(__file__))
42 current_dir = os.path.dirname(os.path.abspath(__file__))
43 path = os.path.join(current_dir, '../../../../',
43 path = os.path.join(current_dir, '../../../../',
44 os.environ.get("APPENLIGHT_INI", 'testing.ini'))
44 os.environ.get("APPENLIGHT_INI", 'testing.ini'))
45 # appsettings from ini
45 # appsettings from ini
46 app_settings = get_appsettings(path, name="appenlight")
46 app_settings = get_appsettings(path, name="appenlight")
47 app = main({}, **app_settings)
47 app = main({}, **app_settings)
48 app_request = testing.DummyRequest(base_url='https://appenlight.com')
48 app_request = testing.DummyRequest(base_url='https://appenlight.com')
49 app_request.tm = transaction.manager
49 app_request.tm = transaction.manager
50 app_request.add_flash_to_headers = mock.Mock()
50 app_request.add_flash_to_headers = mock.Mock()
51 testing.setUp(registry=app.registry, request=app_request)
51 testing.setUp(registry=app.registry, request=app_request)
52
52
53 def teardown():
53 def teardown():
54 testing.tearDown()
54 testing.tearDown()
55
55
56 request.addfinalizer(teardown)
56 request.addfinalizer(teardown)
57
57
58 return app
58 return app
59
59
60
60
61 @pytest.fixture
61 @pytest.fixture
62 def with_migrations(request, base_app):
62 def with_migrations(request, base_app):
63 settings = base_app.registry.settings
63 settings = base_app.registry.settings
64 alembic_cfg = Config()
64 alembic_cfg = Config()
65 alembic_cfg.set_main_option("script_location",
65 alembic_cfg.set_main_option("script_location",
66 "ziggurat_foundations:migrations")
66 "ziggurat_foundations:migrations")
67 alembic_cfg.set_main_option("sqlalchemy.url", settings["sqlalchemy.url"])
67 alembic_cfg.set_main_option("sqlalchemy.url", settings["sqlalchemy.url"])
68 command.upgrade(alembic_cfg, "head")
68 command.upgrade(alembic_cfg, "head")
69 alembic_cfg = Config()
69 alembic_cfg = Config()
70 alembic_cfg.set_main_option("script_location", "appenlight:migrations")
70 alembic_cfg.set_main_option("script_location", "appenlight:migrations")
71 alembic_cfg.set_main_option("sqlalchemy.url", settings["sqlalchemy.url"])
71 alembic_cfg.set_main_option("sqlalchemy.url", settings["sqlalchemy.url"])
72 command.upgrade(alembic_cfg, "head")
72 command.upgrade(alembic_cfg, "head")
73
73
74 for plugin_name, config in base_app.registry.appenlight_plugins.items():
74 for plugin_name, config in base_app.registry.appenlight_plugins.items():
75 if config['sqlalchemy_migrations']:
75 if config['sqlalchemy_migrations']:
76 alembic_cfg = Config()
76 alembic_cfg = Config()
77 alembic_cfg.set_main_option("script_location",
77 alembic_cfg.set_main_option("script_location",
78 config['sqlalchemy_migrations'])
78 config['sqlalchemy_migrations'])
79 alembic_cfg.set_main_option(
79 alembic_cfg.set_main_option(
80 "sqlalchemy.url",
80 "sqlalchemy.url",
81 base_app.registry.settings["sqlalchemy.url"])
81 base_app.registry.settings["sqlalchemy.url"])
82 command.upgrade(alembic_cfg, "head")
82 command.upgrade(alembic_cfg, "head")
83
83
84
84
85 @pytest.fixture
85 @pytest.fixture
86 def default_data(base_app):
86 def default_data(base_app):
87 from appenlight.models.services.config import ConfigService
87 from appenlight.models.services.config import ConfigService
88 from appenlight.lib import get_callable
88 from appenlight.lib import get_callable
89 transaction.begin()
89 transaction.begin()
90 ConfigService.setup_default_values()
90 ConfigService.setup_default_values()
91 for plugin_name, config in base_app.registry.appenlight_plugins.items():
91 for plugin_name, config in base_app.registry.appenlight_plugins.items():
92 if config['default_values_setter']:
92 if config['default_values_setter']:
93 get_callable(config['default_values_setter'])()
93 get_callable(config['default_values_setter'])()
94 transaction.commit()
94 transaction.commit()
95
95
96
96
97 @pytest.fixture
97 @pytest.fixture
98 def clean_tables():
98 def clean_tables():
99 tables = Base.metadata.tables.keys()
99 tables = Base.metadata.tables.keys()
100 transaction.begin()
100 transaction.begin()
101 for t in tables:
101 for t in tables:
102 if not t.startswith('alembic_'):
102 if not t.startswith('alembic_'):
103 DBSession.execute('truncate %s cascade' % t)
103 DBSession.execute('truncate %s cascade' % t)
104 session = DBSession()
104 session = DBSession()
105 mark_changed(session)
105 mark_changed(session)
106 transaction.commit()
106 transaction.commit()
107
107
108
108
109 @pytest.fixture
109 @pytest.fixture
110 def default_user():
110 def default_user():
111 from appenlight.models.user import User
111 from appenlight.models.user import User
112 from appenlight.models.auth_token import AuthToken
112 from appenlight.models.auth_token import AuthToken
113 transaction.begin()
113 transaction.begin()
114 user = User(user_name='testuser',
114 user = User(id=1,
115 user_name='testuser',
115 status=1,
116 status=1,
116 email='ergo14@gmail.com')
117 email='foo@barbaz99.com')
117 DBSession.add(user)
118 DBSession.add(user)
118 token = AuthToken(token='1234')
119 token = AuthToken(token='1234')
119 user.auth_tokens.append(token)
120 user.auth_tokens.append(token)
120 DBSession.flush()
121 DBSession.flush()
121 transaction.commit()
122 transaction.commit()
122 return user
123 return user
123
124
124
125
125 @pytest.fixture
126 @pytest.fixture
126 def default_application(default_user):
127 def default_application(default_user):
127 from appenlight.models.application import Application
128 from appenlight.models.application import Application
128
129
129 transaction.begin()
130 transaction.begin()
130 application = Application(
131 application = Application(
131 resource_id=1, resource_name='testapp', api_key='xxxx')
132 resource_id=1, resource_name='testapp', api_key='xxxx')
132 DBSession.add(application)
133 DBSession.add(application)
133 default_user.resources.append(application)
134 default_user.resources.append(application)
134 DBSession.flush()
135 DBSession.flush()
135 transaction.commit()
136 transaction.commit()
136 return application
137 return application
137
138
138
139
139 @pytest.fixture
140 @pytest.fixture
140 def report_type_matrix():
141 def report_type_matrix():
141 from appenlight.models.report import REPORT_TYPE_MATRIX
142 from appenlight.models.report import REPORT_TYPE_MATRIX
142 return REPORT_TYPE_MATRIX
143 return REPORT_TYPE_MATRIX
143
144
144
145
145 @pytest.fixture
146 @pytest.fixture
146 def chart_series():
147 def chart_series():
147 series = []
148 series = []
148
149
149 for x in range(1, 7):
150 for x in range(1, 7):
150 tmp_list = [('key', 'X'), ('0_1', x)]
151 tmp_list = [('key', 'X'), ('0_1', x)]
151 if x % 2 == 0:
152 if x % 2 == 0:
152 tmp_list.append(('0_2', x))
153 tmp_list.append(('0_2', x))
153 if x % 3 == 0:
154 if x % 3 == 0:
154 tmp_list.append(('0_3', x))
155 tmp_list.append(('0_3', x))
155
156
156 series.append(
157 series.append(
157 OrderedDict(tmp_list)
158 OrderedDict(tmp_list)
158 )
159 )
159 return series
160 return series
160
161
161
162
162 @pytest.fixture
163 @pytest.fixture
163 def log_schema():
164 def log_schema():
164 from appenlight.validators import LogListSchema
165 from appenlight.validators import LogListSchema
165 schema = LogListSchema().bind(utcnow=datetime.utcnow())
166 schema = LogListSchema().bind(utcnow=datetime.utcnow())
166 return schema
167 return schema
167
168
168 @pytest.fixture
169 @pytest.fixture
169 def general_metrics_schema():
170 def general_metrics_schema():
170 from appenlight.validators import GeneralMetricsListSchema
171 from appenlight.validators import GeneralMetricsListSchema
171 schema = GeneralMetricsListSchema().bind(utcnow=datetime.utcnow())
172 schema = GeneralMetricsListSchema().bind(utcnow=datetime.utcnow())
172 return schema
173 return schema
173
174
174 @pytest.fixture
175 @pytest.fixture
175 def request_metrics_schema():
176 def request_metrics_schema():
176 from appenlight.validators import MetricsListSchema
177 from appenlight.validators import MetricsListSchema
177 schema = MetricsListSchema().bind(utcnow=datetime.utcnow())
178 schema = MetricsListSchema().bind(utcnow=datetime.utcnow())
178 return schema
179 return schema
179
180
180 @pytest.fixture
181 @pytest.fixture
181 def report_05_schema():
182 def report_05_schema():
182 from appenlight.validators import ReportListSchema_0_5
183 from appenlight.validators import ReportListSchema_0_5
183 schema = ReportListSchema_0_5().bind(utcnow=datetime.utcnow())
184 schema = ReportListSchema_0_5().bind(utcnow=datetime.utcnow())
184 return schema
185 return schema
@@ -1,115 +1,115 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2
2
3 # Copyright (C) 2010-2016 RhodeCode GmbH
3 # Copyright (C) 2010-2016 RhodeCode GmbH
4 #
4 #
5 # This program is free software: you can redistribute it and/or modify
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License, version 3
6 # it under the terms of the GNU Affero General Public License, version 3
7 # (only), as published by the Free Software Foundation.
7 # (only), as published by the Free Software Foundation.
8 #
8 #
9 # This program is distributed in the hope that it will be useful,
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
12 # GNU General Public License for more details.
13 #
13 #
14 # You should have received a copy of the GNU Affero General Public License
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 #
16 #
17 # This program is dual-licensed. If you wish to learn more about the
17 # This program is dual-licensed. If you wish to learn more about the
18 # AppEnlight Enterprise Edition, including its added features, Support
18 # AppEnlight Enterprise Edition, including its added features, Support
19 # services, and proprietary license terms, please see
19 # services, and proprietary license terms, please see
20 # https://rhodecode.com/licenses/
20 # https://rhodecode.com/licenses/
21 import pytest
21 import pytest
22 import json
22 import json
23 from webtest import TestApp
23 from webtest import TestApp
24
24
25
25
26 @pytest.mark.usefixtures('base_app', 'with_migrations', 'clean_tables',
26 @pytest.mark.usefixtures('base_app', 'with_migrations', 'clean_tables',
27 'default_application')
27 'default_application')
28 class TestIntegrationAPIReportsView(object):
28 class TestAPIReportsView(object):
29 def test_no_json_payload(self, base_app):
29 def test_no_json_payload(self, base_app):
30 app = TestApp(base_app)
30 app = TestApp(base_app)
31 url_path = '/api/reports'
31 url_path = '/api/reports'
32 headers = {'x-appenlight-api-key': 'xxxx'}
32 headers = {'x-appenlight-api-key': 'xxxx'}
33 res = app.post(url_path, {}, status=400,
33 res = app.post(url_path, {}, status=400,
34 headers=headers)
34 headers=headers)
35
35
36 def test_wrong_json_payload(self, base_app):
36 def test_wrong_json_payload(self, base_app):
37 app = TestApp(base_app)
37 app = TestApp(base_app)
38 url_path = '/api/reports'
38 url_path = '/api/reports'
39 headers = {'x-appenlight-api-key': 'xxxx'}
39 headers = {'x-appenlight-api-key': 'xxxx'}
40 res = app.post(url_path, {}, status=400, headers=headers)
40 res = app.post(url_path, {}, status=400, headers=headers)
41
41
42 def test_correct_json_payload(self, base_app):
42 def test_correct_json_payload(self, base_app):
43 import appenlight.tests.payload_examples as payload_examples
43 import appenlight.tests.payload_examples as payload_examples
44 app = TestApp(base_app)
44 app = TestApp(base_app)
45 url_path = '/api/reports'
45 url_path = '/api/reports'
46 headers = {'x-appenlight-api-key': 'xxxx'}
46 headers = {'x-appenlight-api-key': 'xxxx'}
47 res = app.post_json(url_path, [payload_examples.PYTHON_PAYLOAD_0_5],
47 res = app.post_json(url_path, [payload_examples.PYTHON_PAYLOAD_0_5],
48 headers=headers)
48 headers=headers)
49
49
50 def test_json_payload_wrong_key(self, base_app):
50 def test_json_payload_wrong_key(self, base_app):
51 import appenlight.tests.payload_examples as payload_examples
51 import appenlight.tests.payload_examples as payload_examples
52 app = TestApp(base_app)
52 app = TestApp(base_app)
53 url_path = '/api/reports'
53 url_path = '/api/reports'
54 res = app.post(url_path,
54 res = app.post(url_path,
55 json.dumps([payload_examples.PYTHON_PAYLOAD_0_5]),
55 json.dumps([payload_examples.PYTHON_PAYLOAD_0_5]),
56 status=403)
56 status=403)
57
57
58
58
59 @pytest.mark.usefixtures('base_app', 'with_migrations', 'clean_tables',
59 @pytest.mark.usefixtures('base_app', 'with_migrations', 'clean_tables',
60 'default_data', 'default_application')
60 'default_data', 'default_application')
61 class TestIntegrationRegistrationView(object):
61 class TestRegistrationView(object):
62 def test_register_empty(self, base_app):
62 def test_register_empty(self, base_app):
63 url_path = '/register'
63 url_path = '/register'
64 app = TestApp(base_app)
64 app = TestApp(base_app)
65 resp = app.get('/')
65 resp = app.get('/')
66 cookies = resp.headers.getall('Set-Cookie')
66 cookies = resp.headers.getall('Set-Cookie')
67 cookie = None
67 cookie = None
68 for name, value in [c.split('=', 1) for c in cookies]:
68 for name, value in [c.split('=', 1) for c in cookies]:
69 if name == 'XSRF-TOKEN':
69 if name == 'XSRF-TOKEN':
70 cookie = value.split(';')[0]
70 cookie = value.split(';')[0]
71 headers = {'X-XSRF-TOKEN': cookie}
71 headers = {'X-XSRF-TOKEN': cookie}
72 res = app.post(url_path,
72 res = app.post(url_path,
73 params={'user_name': '',
73 params={'user_name': '',
74 'user_password': '',
74 'user_password': '',
75 'email': ''},
75 'email': ''},
76 headers=headers)
76 headers=headers)
77 assert 'This field is required.' in res
77 assert 'This field is required.' in res
78
78
79 def test_register_proper(self, base_app):
79 def test_register_proper(self, base_app):
80 url_path = '/register'
80 url_path = '/register'
81 app = TestApp(base_app)
81 app = TestApp(base_app)
82 resp = app.get('/')
82 resp = app.get('/')
83 cookies = resp.headers.getall('Set-Cookie')
83 cookies = resp.headers.getall('Set-Cookie')
84 cookie = None
84 cookie = None
85 for name, value in [c.split('=', 1) for c in cookies]:
85 for name, value in [c.split('=', 1) for c in cookies]:
86 if name == 'XSRF-TOKEN':
86 if name == 'XSRF-TOKEN':
87 cookie = value.split(';')[0]
87 cookie = value.split(';')[0]
88 headers = {'X-XSRF-TOKEN': cookie}
88 headers = {'X-XSRF-TOKEN': cookie}
89 res = app.post(url_path,
89 res = app.post(url_path,
90 params={'user_name': 'user_foo',
90 params={'user_name': 'user_foo',
91 'user_password': 'passbar',
91 'user_password': 'passbar',
92 'email': 'foobar@blablabla.com'},
92 'email': 'foobar@blablabla.com'},
93 headers=headers,
93 headers=headers,
94 status=302)
94 status=302)
95
95
96
96
97 @pytest.mark.usefixtures('base_app', 'with_migrations', 'clean_tables',
97 @pytest.mark.usefixtures('base_app', 'with_migrations', 'clean_tables',
98 'default_data', 'default_application')
98 'default_data', 'default_application')
99 class TestIntegrationRegistrationAuthTokenView(object):
99 class TestRegistrationAuthTokenView(object):
100
100
101 def test_create_application_bad(self, base_app):
101 def test_create_application_bad(self, base_app):
102 url_path = '/applications'
102 url_path = '/applications'
103 app = TestApp(base_app)
103 app = TestApp(base_app)
104 headers = {'x-appenlight-auth-token': ''}
104 headers = {'x-appenlight-auth-token': ''}
105 app.post_json(url_path,
105 app.post_json(url_path,
106 params={'resource_name': 'user_foo'},
106 params={'resource_name': 'user_foo'},
107 headers=headers, status=403)
107 headers=headers, status=403)
108
108
109 def test_create_application_proper(self, base_app):
109 def test_create_application_proper(self, base_app):
110 url_path = '/applications'
110 url_path = '/applications'
111 app = TestApp(base_app)
111 app = TestApp(base_app)
112 headers = {'x-appenlight-auth-token': '1234'}
112 headers = {'x-appenlight-auth-token': '1234'}
113 app.post_json(url_path,
113 app.post_json(url_path,
114 params={'resource_name': 'user_foo'},
114 params={'resource_name': 'user_foo'},
115 headers=headers, status=200)
115 headers=headers, status=200)
General Comments 0
You need to be logged in to leave comments. Login now