##// END OF EJS Templates
pytest: restructure fixtures/plugins to fix problems with pkg_resources and Can't perform this operation for unregistered loader type errors....
super-admin -
r4986:8782a2c5 default
parent child Browse files
Show More
@@ -0,0 +1,199 b''
1 # -*- coding: utf-8 -*-
2
3 # Copyright (C) 2010-2020 RhodeCode GmbH
4 #
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
7 # (only), as published by the Free Software Foundation.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
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/>.
16 #
17 # This program is dual-licensed. If you wish to learn more about the
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
21 import pytest
22 from rhodecode.lib import ext_json
23
24
25 pytest_plugins = [
26 "rhodecode.tests.fixture_mods.fixture_pyramid",
27 "rhodecode.tests.fixture_mods.fixture_utils",
28 ]
29
30
31 def pytest_configure(config):
32 from rhodecode.config import patches
33
34
35 def pytest_addoption(parser):
36
37 def _parse_json(value):
38 return ext_json.str_json(value) if value else None
39
40 def _split_comma(value):
41 return value.split(',')
42
43 parser.addoption(
44 '--keep-tmp-path', action='store_true',
45 help="Keep the test temporary directories")
46 parser.addoption(
47 '--backends', action='store', type=_split_comma,
48 default=['git', 'hg', 'svn'],
49 help="Select which backends to test for backend specific tests.")
50 parser.addoption(
51 '--dbs', action='store', type=_split_comma,
52 default=['sqlite'],
53 help="Select which database to test for database specific tests. "
54 "Possible options are sqlite,postgres,mysql")
55 parser.addoption(
56 '--appenlight', '--ae', action='store_true',
57 help="Track statistics in appenlight.")
58 parser.addoption(
59 '--appenlight-api-key', '--ae-key',
60 help="API key for Appenlight.")
61 parser.addoption(
62 '--appenlight-url', '--ae-url',
63 default="https://ae.rhodecode.com",
64 help="Appenlight service URL, defaults to https://ae.rhodecode.com")
65 parser.addoption(
66 '--sqlite-connection-string', action='store',
67 default='', help="Connection string for the dbs tests with SQLite")
68 parser.addoption(
69 '--postgres-connection-string', action='store',
70 default='', help="Connection string for the dbs tests with Postgres")
71 parser.addoption(
72 '--mysql-connection-string', action='store',
73 default='', help="Connection string for the dbs tests with MySQL")
74 parser.addoption(
75 '--repeat', type=int, default=100,
76 help="Number of repetitions in performance tests.")
77
78 parser.addoption(
79 '--test-loglevel', dest='test_loglevel',
80 help="Set default Logging level for tests, critical(default), error, warn , info, debug")
81 group = parser.getgroup('pylons')
82 group.addoption(
83 '--with-pylons', dest='pyramid_config',
84 help="Set up a Pylons environment with the specified config file.")
85 group.addoption(
86 '--ini-config-override', action='store', type=_parse_json,
87 default=None, dest='pyramid_config_override', help=(
88 "Overrides the .ini file settings. Should be specified in JSON"
89 " format, e.g. '{\"section\": {\"parameter\": \"value\", ...}}'"
90 )
91 )
92 parser.addini(
93 'pyramid_config',
94 "Set up a Pyramid environment with the specified config file.")
95
96 vcsgroup = parser.getgroup('vcs')
97 vcsgroup.addoption(
98 '--without-vcsserver', dest='with_vcsserver', action='store_false',
99 help="Do not start the VCSServer in a background process.")
100 vcsgroup.addoption(
101 '--with-vcsserver-http', dest='vcsserver_config_http',
102 help="Start the HTTP VCSServer with the specified config file.")
103 vcsgroup.addoption(
104 '--vcsserver-protocol', dest='vcsserver_protocol',
105 help="Start the VCSServer with HTTP protocol support.")
106 vcsgroup.addoption(
107 '--vcsserver-config-override', action='store', type=_parse_json,
108 default=None, dest='vcsserver_config_override', help=(
109 "Overrides the .ini file settings for the VCSServer. "
110 "Should be specified in JSON "
111 "format, e.g. '{\"section\": {\"parameter\": \"value\", ...}}'"
112 )
113 )
114 vcsgroup.addoption(
115 '--vcsserver-port', action='store', type=int,
116 default=None, help=(
117 "Allows to set the port of the vcsserver. Useful when testing "
118 "against an already running server and random ports cause "
119 "trouble."))
120 parser.addini(
121 'vcsserver_config_http',
122 "Start the HTTP VCSServer with the specified config file.")
123 parser.addini(
124 'vcsserver_protocol',
125 "Start the VCSServer with HTTP protocol support.")
126
127
128 @pytest.hookimpl(tryfirst=True, hookwrapper=True)
129 def pytest_runtest_makereport(item, call):
130 """
131 Adding the remote traceback if the exception has this information.
132
133 VCSServer attaches this information as the attribute `_vcs_server_traceback`
134 to the exception instance.
135 """
136 outcome = yield
137 report = outcome.get_result()
138 if call.excinfo:
139 exc = call.excinfo.value
140 vcsserver_traceback = getattr(exc, '_vcs_server_traceback', None)
141
142 if vcsserver_traceback:
143 section = 'VCSServer remote traceback ' + report.when
144 report.sections.append((section, vcsserver_traceback))
145
146
147 def pytest_collection_modifyitems(session, config, items):
148 # nottest marked, compare nose, used for transition from nose to pytest
149 remaining = [
150 i for i in items if getattr(i.obj, '__test__', True)]
151 items[:] = remaining
152
153 # NOTE(marcink): custom test ordering, db tests and vcstests are slowes and should
154 # be executed at the end for faster test feedback
155 def sorter(item):
156 pos = 0
157 key = item._nodeid
158 if key.startswith('rhodecode/tests/database'):
159 pos = 1
160 elif key.startswith('rhodecode/tests/vcs_operations'):
161 pos = 2
162
163 return pos
164
165 items.sort(key=sorter)
166
167
168 def get_backends_from_metafunc(metafunc):
169 requested_backends = set(metafunc.config.getoption('--backends'))
170 backend_mark = metafunc.definition.get_closest_marker('backends')
171 if backend_mark:
172 # Supported backends by this test function, created from
173 # pytest.mark.backends
174 backends = backend_mark.args
175 elif hasattr(metafunc.cls, 'backend_alias'):
176 # Support class attribute "backend_alias", this is mainly
177 # for legacy reasons for tests not yet using pytest.mark.backends
178 backends = [metafunc.cls.backend_alias]
179 else:
180 backends = metafunc.config.getoption('--backends')
181 return requested_backends.intersection(backends)
182
183
184 def pytest_generate_tests(metafunc):
185
186 # Support test generation based on --backend parameter
187 if 'backend_alias' in metafunc.fixturenames:
188 backends = get_backends_from_metafunc(metafunc)
189 scope = None
190 if not backends:
191 pytest.skip("Not enabled for any of selected backends")
192
193 metafunc.parametrize('backend_alias', backends, scope=scope)
194
195 backend_mark = metafunc.definition.get_closest_marker('backends')
196 if backend_mark:
197 backends = get_backends_from_metafunc(metafunc)
198 if not backends:
199 pytest.skip("Not enabled for any of selected backends")
1 NO CONTENT: new file 100644
NO CONTENT: new file 100644
@@ -27,7 +27,7 b' from rhodecode.tests import TEST_USER_AD'
27 from rhodecode.api.tests.utils import (
27 from rhodecode.api.tests.utils import (
28 build_data, api_call, assert_error, assert_ok, crash, jsonify)
28 build_data, api_call, assert_error, assert_ok, crash, jsonify)
29 from rhodecode.tests.fixture import Fixture
29 from rhodecode.tests.fixture import Fixture
30 from rhodecode.tests.plugin import plain_http_host_only_stub
30 from rhodecode.tests.fixture_mods.fixture_utils import plain_http_host_only_stub
31
31
32 fixture = Fixture()
32 fixture = Fixture()
33
33
@@ -18,10 +18,6 b''
18 # RhodeCode Enterprise Edition, including its added features, Support services,
18 # RhodeCode Enterprise Edition, including its added features, Support services,
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
19 # and proprietary license terms, please see https://rhodecode.com/licenses/
20
20
21 import json
22 import platform
23 import socket
24 import random
25 import pytest
21 import pytest
26
22
27 from rhodecode.lib.pyramid_utils import get_app_config
23 from rhodecode.lib.pyramid_utils import get_app_config
@@ -29,61 +25,6 b' from rhodecode.tests.fixture import Test'
29 from rhodecode.tests.server_utils import RcVCSServer
25 from rhodecode.tests.server_utils import RcVCSServer
30
26
31
27
32 def _parse_json(value):
33 return json.loads(value) if value else None
34
35
36 def pytest_addoption(parser):
37 parser.addoption(
38 '--test-loglevel', dest='test_loglevel',
39 help="Set default Logging level for tests, critical(default), error, warn , info, debug")
40 group = parser.getgroup('pylons')
41 group.addoption(
42 '--with-pylons', dest='pyramid_config',
43 help="Set up a Pylons environment with the specified config file.")
44 group.addoption(
45 '--ini-config-override', action='store', type=_parse_json,
46 default=None, dest='pyramid_config_override', help=(
47 "Overrides the .ini file settings. Should be specified in JSON"
48 " format, e.g. '{\"section\": {\"parameter\": \"value\", ...}}'"
49 )
50 )
51 parser.addini(
52 'pyramid_config',
53 "Set up a Pyramid environment with the specified config file.")
54
55 vcsgroup = parser.getgroup('vcs')
56 vcsgroup.addoption(
57 '--without-vcsserver', dest='with_vcsserver', action='store_false',
58 help="Do not start the VCSServer in a background process.")
59 vcsgroup.addoption(
60 '--with-vcsserver-http', dest='vcsserver_config_http',
61 help="Start the HTTP VCSServer with the specified config file.")
62 vcsgroup.addoption(
63 '--vcsserver-protocol', dest='vcsserver_protocol',
64 help="Start the VCSServer with HTTP protocol support.")
65 vcsgroup.addoption(
66 '--vcsserver-config-override', action='store', type=_parse_json,
67 default=None, dest='vcsserver_config_override', help=(
68 "Overrides the .ini file settings for the VCSServer. "
69 "Should be specified in JSON "
70 "format, e.g. '{\"section\": {\"parameter\": \"value\", ...}}'"
71 )
72 )
73 vcsgroup.addoption(
74 '--vcsserver-port', action='store', type=int,
75 default=None, help=(
76 "Allows to set the port of the vcsserver. Useful when testing "
77 "against an already running server and random ports cause "
78 "trouble."))
79 parser.addini(
80 'vcsserver_config_http',
81 "Start the HTTP VCSServer with the specified config file.")
82 parser.addini(
83 'vcsserver_protocol',
84 "Start the VCSServer with HTTP protocol support.")
85
86
87 @pytest.fixture(scope='session')
28 @pytest.fixture(scope='session')
88 def vcsserver(request, vcsserver_port, vcsserver_factory):
29 def vcsserver(request, vcsserver_port, vcsserver_factory):
89 """
30 """
@@ -146,10 +87,6 b' def vcsserver_factory(tmpdir_factory):'
146 return factory
87 return factory
147
88
148
89
149 def is_cygwin():
150 return 'cygwin' in platform.system().lower()
151
152
153 def _use_log_level(config):
90 def _use_log_level(config):
154 level = config.getoption('test_loglevel') or 'critical'
91 level = config.getoption('test_loglevel') or 'critical'
155 return level.upper()
92 return level.upper()
@@ -74,107 +74,6 b' def cmp(a, b):'
74 # backport cmp from python2 so we can still use it in the custom code in this module
74 # backport cmp from python2 so we can still use it in the custom code in this module
75 return (a > b) - (a < b)
75 return (a > b) - (a < b)
76
76
77
78 def _split_comma(value):
79 return value.split(',')
80
81
82 def pytest_addoption(parser):
83 parser.addoption(
84 '--keep-tmp-path', action='store_true',
85 help="Keep the test temporary directories")
86 parser.addoption(
87 '--backends', action='store', type=_split_comma,
88 default=['git', 'hg', 'svn'],
89 help="Select which backends to test for backend specific tests.")
90 parser.addoption(
91 '--dbs', action='store', type=_split_comma,
92 default=['sqlite'],
93 help="Select which database to test for database specific tests. "
94 "Possible options are sqlite,postgres,mysql")
95 parser.addoption(
96 '--appenlight', '--ae', action='store_true',
97 help="Track statistics in appenlight.")
98 parser.addoption(
99 '--appenlight-api-key', '--ae-key',
100 help="API key for Appenlight.")
101 parser.addoption(
102 '--appenlight-url', '--ae-url',
103 default="https://ae.rhodecode.com",
104 help="Appenlight service URL, defaults to https://ae.rhodecode.com")
105 parser.addoption(
106 '--sqlite-connection-string', action='store',
107 default='', help="Connection string for the dbs tests with SQLite")
108 parser.addoption(
109 '--postgres-connection-string', action='store',
110 default='', help="Connection string for the dbs tests with Postgres")
111 parser.addoption(
112 '--mysql-connection-string', action='store',
113 default='', help="Connection string for the dbs tests with MySQL")
114 parser.addoption(
115 '--repeat', type=int, default=100,
116 help="Number of repetitions in performance tests.")
117
118
119 def pytest_configure(config):
120 from rhodecode.config import patches
121
122
123 def pytest_collection_modifyitems(session, config, items):
124 # nottest marked, compare nose, used for transition from nose to pytest
125 remaining = [
126 i for i in items if getattr(i.obj, '__test__', True)]
127 items[:] = remaining
128
129 # NOTE(marcink): custom test ordering, db tests and vcstests are slowes and should
130 # be executed at the end for faster test feedback
131 def sorter(item):
132 pos = 0
133 key = item._nodeid
134 if key.startswith('rhodecode/tests/database'):
135 pos = 1
136 elif key.startswith('rhodecode/tests/vcs_operations'):
137 pos = 2
138
139 return pos
140
141 items.sort(key=sorter)
142
143
144 def pytest_generate_tests(metafunc):
145
146 # Support test generation based on --backend parameter
147 if 'backend_alias' in metafunc.fixturenames:
148 backends = get_backends_from_metafunc(metafunc)
149 scope = None
150 if not backends:
151 pytest.skip("Not enabled for any of selected backends")
152
153 metafunc.parametrize('backend_alias', backends, scope=scope)
154
155 backend_mark = metafunc.definition.get_closest_marker('backends')
156 if backend_mark:
157 backends = get_backends_from_metafunc(metafunc)
158 if not backends:
159 pytest.skip("Not enabled for any of selected backends")
160
161
162 def get_backends_from_metafunc(metafunc):
163 requested_backends = set(metafunc.config.getoption('--backends'))
164 backend_mark = metafunc.definition.get_closest_marker('backends')
165 if backend_mark:
166 # Supported backends by this test function, created from
167 # pytest.mark.backends
168 backends = backend_mark.args
169 elif hasattr(metafunc.cls, 'backend_alias'):
170 # Support class attribute "backend_alias", this is mainly
171 # for legacy reasons for tests not yet using pytest.mark.backends
172 backends = [metafunc.cls.backend_alias]
173 else:
174 backends = metafunc.config.getoption('--backends')
175 return requested_backends.intersection(backends)
176
177
178 @pytest.fixture(scope='session', autouse=True)
77 @pytest.fixture(scope='session', autouse=True)
179 def activate_example_rcextensions(request):
78 def activate_example_rcextensions(request):
180 """
79 """
@@ -1400,30 +1299,6 b' class UserUtility(object):'
1400 self.fixture.destroy_user(user_id)
1299 self.fixture.destroy_user(user_id)
1401
1300
1402
1301
1403 # TODO: Think about moving this into a pytest-pyro package and make it a
1404 # pytest plugin
1405 @pytest.hookimpl(tryfirst=True, hookwrapper=True)
1406 def pytest_runtest_makereport(item, call):
1407 """
1408 Adding the remote traceback if the exception has this information.
1409
1410 VCSServer attaches this information as the attribute `_vcs_server_traceback`
1411 to the exception instance.
1412 """
1413 outcome = yield
1414 report = outcome.get_result()
1415 if call.excinfo:
1416 _add_vcsserver_remote_traceback(report, call.excinfo.value)
1417
1418
1419 def _add_vcsserver_remote_traceback(report, exc):
1420 vcsserver_traceback = getattr(exc, '_vcs_server_traceback', None)
1421
1422 if vcsserver_traceback:
1423 section = 'VCSServer remote traceback ' + report.when
1424 report.sections.append((section, vcsserver_traceback))
1425
1426
1427 @pytest.fixture(scope='session')
1302 @pytest.fixture(scope='session')
1428 def testrun():
1303 def testrun():
1429 return {
1304 return {
@@ -1722,6 +1597,7 b' def StubIntegrationType():'
1722 integration_type_registry.register_integration_type(_StubIntegrationType)
1597 integration_type_registry.register_integration_type(_StubIntegrationType)
1723 return _StubIntegrationType
1598 return _StubIntegrationType
1724
1599
1600
1725 @pytest.fixture()
1601 @pytest.fixture()
1726 def stub_integration_settings():
1602 def stub_integration_settings():
1727 return {
1603 return {
@@ -34,7 +34,12 b' from webtest.app import TestResponse, Te'
34 from webtest.compat import print_stderr
34 from webtest.compat import print_stderr
35
35
36 import pytest
36 import pytest
37 import rc_testdata
37
38 try:
39 import rc_testdata
40 except ImportError:
41 raise ImportError('Failed to import rc_testdata, '
42 'please make sure this package is installed from requirements_test.txt')
38
43
39 from rhodecode.model.db import User, Repository
44 from rhodecode.model.db import User, Repository
40 from rhodecode.model.meta import Session
45 from rhodecode.model.meta import Session
@@ -424,13 +429,13 b' def commit_change('
424 message=message,
429 message=message,
425 nodes=nodes,
430 nodes=nodes,
426 parent_commit=_commit,
431 parent_commit=_commit,
427 author='{} <admin@rhodecode.com>'.format(TEST_USER_ADMIN_LOGIN),
432 author=f'{TEST_USER_ADMIN_LOGIN} <admin@rhodecode.com>',
428 )
433 )
429 else:
434 else:
430 commit = ScmModel().commit_change(
435 commit = ScmModel().commit_change(
431 repo=repo.scm_instance(), repo_name=repo.repo_name,
436 repo=repo.scm_instance(), repo_name=repo.repo_name,
432 commit=parent, user=TEST_USER_ADMIN_LOGIN,
437 commit=parent, user=TEST_USER_ADMIN_LOGIN,
433 author='{} <admin@rhodecode.com>'.format(TEST_USER_ADMIN_LOGIN),
438 author=f'{TEST_USER_ADMIN_LOGIN} <admin@rhodecode.com>',
434 message=message,
439 message=message,
435 content=content,
440 content=content,
436 f_path=filename
441 f_path=filename
@@ -189,10 +189,6 b' setup('
189 'pyramid.pshell_runner': [
189 'pyramid.pshell_runner': [
190 'ipython = rhodecode.lib.pyramid_shell:ipython_shell_runner',
190 'ipython = rhodecode.lib.pyramid_shell:ipython_shell_runner',
191 ],
191 ],
192 'pytest11': [
193 'pylons=rhodecode.tests.pylons_plugin',
194 'enterprise=rhodecode.tests.plugin',
195 ],
196 'console_scripts': [
192 'console_scripts': [
197 'rc-setup-app=rhodecode.lib.rc_commands.setup_rc:main',
193 'rc-setup-app=rhodecode.lib.rc_commands.setup_rc:main',
198 'rc-upgrade-db=rhodecode.lib.rc_commands.upgrade_db:main',
194 'rc-upgrade-db=rhodecode.lib.rc_commands.upgrade_db:main',
1 NO CONTENT: file was removed
NO CONTENT: file was removed
General Comments 0
You need to be logged in to leave comments. Login now