How to use test_default_data method in tox

Best Python code snippet using tox_python

test_configuration_sections.py

Source:test_configuration_sections.py Github

copy

Full Screen

1"""2Unit tests for configuration sections3"""4from pathlib import Path5import pytest6from sys_toolkit.configuration.base import ConfigurationList, ConfigurationSection7from sys_toolkit.exceptions import ConfigurationError8CALLABLE_SECTION_NAME = 'callme'9CALLABLE_SECTION_VALUE = 'test callable value'10TEST_DEFAULT_DATA = {11 'test_key': 'test value',12 'nested_level_1': {13 'test_nested_key': 'test nested value'14 }15}16TEST_NESTED_LIST_DATA = {17 'nested_item_1': {18 'list_field': [19 {20 'list_nested_item': {21 'field': 1234,22 }23 },24 'text list item'25 ]26 }27}28TEST_LIST_DATA_REPLACE = [29 1234,30 2234,31 3334,32 4444,33]34TEST_EMPTY_DATA = {35 'test_key_empty': '',36 'nested_level_1': {}37}38TEST_INVALID_VALUES = (39 (1, 'test numeric value'),40 ('spaced out', 'test invalid attr string'),41 ('dashed-string', 'test invalid dashed string'),42)43class EnvDefaultsConfigurationSection(ConfigurationSection):44 """45 Configuration with default settings and environment46 variables47 """48 __default_settings__ = {49 'test_key': 'test value'50 }51 __environment_variables__ = {52 'TEST_RESULT_KEY': 'test_key'53 }54class DefaultsConfigurationSection(ConfigurationSection):55 """56 Configuration with default variables57 """58 __default_settings__ = {59 'test_key': 'test value',60 'nested_default': {61 'test_nested_key': 'nested value'62 }63 }64class EnvConfigurationSection(ConfigurationSection):65 """66 Configuration with environment variables67 """68 __environment_variables__ = {69 'MY_TEST_KEY': 'test_key'70 }71 __environment_variable_prefix__ = 'PREFIXED'72class InvalidDefaultConfigurationSection(ConfigurationSection):73 """74 Configuration with invalid default settings75 """76 __default_settings__ = {77 'test key': 'test value'78 }79class InvalidEnvConfigurationSection(ConfigurationSection):80 """81 Configuration with invalid environment settings82 """83 __environment_variables__ = {84 'TEST_RESULT_KEY': 'test key'85 }86class NestedConfigurationSection(ConfigurationSection):87 """88 Nested configuration section89 """90 __name__ = 'nested'91class NestedDefaultConfigurationSection(ConfigurationSection):92 """93 Nested configuration section default for unnamed sections94 """95class NestedListConfigurationSection(ConfigurationSection):96 """97 Nested configuration section default for list sections98 """99 __name__ = 'lists'100class CallableSetConfigurationSection(ConfigurationSection):101 """102 Configuration section class with a callable set() method103 """104 __name__ = CALLABLE_SECTION_NAME105 def __init__(self, data=dict, parent=None, debug_enabled=False, silent=False):106 super().__init__(data, parent, debug_enabled, silent)107 self.set_call_count = 0108 self.set_call_args = []109 def set(self, attr, value):110 """111 Store set() call arguments to the section112 """113 print(f'set {attr} value {value}')114 self.set_call_count += 1115 self.set_call_args.append((attr, value))116class CallableBaseConfiguration(ConfigurationSection):117 """118 Configuratio section with a child section that has a callable set() method119 """120 __section_loaders__ = (121 CallableSetConfigurationSection,122 )123class NestedRootConfigurationSection(ConfigurationSection):124 """125 NestedRoot configuration section for nested configurations126 """127 __dict_loader_class__ = NestedDefaultConfigurationSection128 __list_loader_class__ = NestedListConfigurationSection129 __section_loaders__ = (130 NestedConfigurationSection,131 NestedListConfigurationSection,132 )133class InvalidRootConfigurationSection(ConfigurationSection):134 """135 NestedRoot configuration section with base ConfigurationSection136 Causes error due to no section name137 """138 __section_loaders__ = (139 ConfigurationSection,140 )141class RequiredSettingsConfigurationSection(ConfigurationSection):142 """143 Configuration section with required settings144 """145 __required_settings__ = (146 'test_key',147 )148class FormattedConfigurationSection(ConfigurationSection):149 """150 Configuration with formatter callback151 """152 @staticmethod153 def format_test_key(value):154 """155 Format expected test key value156 """157 return value.upper()158class ValidatedConfigurationSection(ConfigurationSection):159 """160 Configuration with validator callback161 """162 @staticmethod163 def validate_test_key(value):164 """165 Validate expected test key value166 """167 return value168class InvalidatedConfigurationSection(ConfigurationSection):169 """170 Configuration with validator callback raising error171 """172 @staticmethod173 def validate_test_key(value):174 """175 Validate expected test key value176 """177 raise ValueError('Invalid value')178def validate_configuration_section(section, data, parent=None):179 """180 Validate configuration section details181 """182 assert section.__parent__ == parent183 for key, value in data.items():184 assert hasattr(section, key)185 if isinstance(value, dict):186 validate_configuration_section(187 getattr(section, key),188 value,189 section190 )191 else:192 assert getattr(section, key) == value193def test_configuration_section_default_empty():194 """195 Test loading empty configuration section without data196 """197 section = ConfigurationSection()198 assert isinstance(section.__section_loaders__, tuple)199 assert isinstance(section.__default_settings__, dict)200 assert isinstance(section.__required_settings__, (tuple, list))201def test_configuration_section_invalid_parent():202 """203 Test initializing configuration section with invalid parent204 """205 with pytest.raises(TypeError):206 ConfigurationSection(parent={})207def test_configuration_section_attribute_name():208 """209 Test validation of attribute names for configuration secrion210 """211 configuration = ConfigurationSection()212 for attr in ('test', 'test123'):213 configuration.__validate_attribute__(attr)214 with pytest.raises(ConfigurationError):215 configuration.__validate_attribute__('hähää')216def test_configuration_section_empty_data():217 """218 Test loading configuration section with empty values in data219 """220 configuration = ConfigurationSection(data=TEST_EMPTY_DATA)221 assert configuration.__config_root__ == configuration222 # pylint: disable=no-member223 assert configuration.test_key_empty is None224 with pytest.raises(ConfigurationError):225 configuration.__get_section_loader__('')226 assert configuration.__key_from_attribute__('test') == 'test'227 configuration.__key_attribute_map__ = {228 'other': 'match'229 }230 assert configuration.__key_from_attribute__('match') == 'other'231 assert configuration.__key_from_attribute__('other') == 'other'232def test_configuration_section_list_data():233 """234 Test loading configuration section with list of mixed content235 """236 configuration = ConfigurationSection(data=TEST_NESTED_LIST_DATA)237 # pylint: disable=no-member238 nested_item = configuration.nested_item_1239 assert isinstance(nested_item, ConfigurationSection)240 assert nested_item.__config_root__ == configuration241 list_value = nested_item.list_field242 assert isinstance(list_value.__repr__(), str)243 assert isinstance(list_value, ConfigurationList)244 assert len(list_value) == 2245 assert list_value.__config_root__ == configuration246 assert isinstance(list_value[0], ConfigurationSection)247 assert isinstance(list_value[1], str)248 for item in list_value:249 assert item is not None250 list_value.insert(1, CALLABLE_SECTION_VALUE)251 assert len(list_value) == 3252 list_value.set(None, TEST_LIST_DATA_REPLACE)253 assert len(list_value) == 4254 list_value[1] = None255 assert len(list_value) == 4256 list_value.set(None, None)257 assert len(list_value) == 0258def test_configuration_section_default_with_data():259 """260 Test loading default configuration section with test data261 """262 section = ConfigurationSection(data=TEST_DEFAULT_DATA)263 validate_configuration_section(section, TEST_DEFAULT_DATA)264def test_configuration_section_empty_set_invalid_values():265 """266 Test loading default configuration section with test data267 """268 section = ConfigurationSection()269 for item in TEST_INVALID_VALUES:270 with pytest.raises(ConfigurationError):271 section.set(item[0], item[1])272 for invalid_value in (None, [1, 2, 3]):273 with pytest.raises(ConfigurationError):274 section.__load_dictionary__(invalid_value)275 with pytest.raises(ConfigurationError):276 section.__load_section__('test', invalid_value)277def test_configuration_section_load_section_explicit():278 """279 Load new section explicitly280 """281 configuration = ConfigurationSection()282 configuration.__load_section__(283 'test',284 {'test_key': 'test value'}285 )286 # pylint: disable=no-member287 assert configuration.test.test_key == 'test value'288def test_configuration_section_load_section_nomatch_path():289 """290 Load new section with complex path291 """292 configuration = ConfigurationSection()293 configuration.__load_section__(294 'test',295 '123',296 path='other.bar.test_key'297 )298 # pylint: disable=no-member299 assert configuration.test.other.bar.test_key == '123'300 # pylint: disable=no-member301 configuration.__load_section__(302 'test',303 {'test_key': 'test value'},304 path='other.sub.test_key'305 )306 # pylint: disable=no-member307 assert configuration.test.other.sub.test_key == 'test value'308def test_configuration_section_defaults():309 """310 Test configuration section with default settings311 """312 configuration = DefaultsConfigurationSection()313 assert len(configuration.__valid_settings__) == 1314def test_configuration_section_env(monkeypatch):315 """316 Test configuration section with environment settings317 """318 configuration = EnvConfigurationSection()319 assert len(configuration.__valid_settings__) == 1320 # pylint: disable=no-member321 assert configuration.test_key is None322 value = 'mock me env'323 with monkeypatch.context() as context:324 context.setenv('PREFIXED_TEST_KEY', value)325 configuration = EnvConfigurationSection()326 # pylint: disable=no-member327 assert configuration.test_key == value328 with monkeypatch.context() as context:329 context.setenv('MY_TEST_KEY', value)330 configuration = EnvConfigurationSection()331 # pylint: disable=no-member332 assert configuration.test_key == value333def test_configuration_section_env_defaults():334 """335 Test configuration section with default and environment settings336 """337 configuration = EnvDefaultsConfigurationSection()338 assert len(configuration.__valid_settings__) == 1339 # pylint: disable=no-member340 assert configuration.test_key == 'test value'341def test_configuration_section_invalid_defaults():342 """343 Test configuration section with invalid default settings344 """345 with pytest.raises(ConfigurationError):346 InvalidDefaultConfigurationSection()347def test_configuration_section_invalid_env():348 """349 Test configuration section with invalid environment settings350 """351 with pytest.raises(ConfigurationError):352 InvalidEnvConfigurationSection()353def test_configuration_section_nested_loader_unknown():354 """355 Test configuration sections with nested classes356 """357 configuration = ConfigurationSection()358 loader = configuration.__get_section_loader__('test')359 assert loader == ConfigurationSection360 configuration = NestedRootConfigurationSection()361 loader = configuration.__get_section_loader__(NestedConfigurationSection.__name__)362 assert loader == NestedConfigurationSection363 dict_output = configuration.as_dict()364 assert isinstance(dict_output, dict)365def test_configuration_section_nested_classes():366 """367 Test configuration sections with nested classes368 """369 configuration = NestedRootConfigurationSection()370 subsection = getattr(configuration, 'nested', None)371 assert subsection is not None372 assert isinstance(subsection, NestedConfigurationSection)373 assert subsection.__name__ == 'nested'374 assert configuration.__list_loader__ == NestedListConfigurationSection375 list_section = getattr(configuration, 'lists', None)376 assert list_section is not None377 assert isinstance(list_section, NestedListConfigurationSection)378 assert list_section.__name__ == 'lists'379 loader = configuration.__get_or_create_subsection__('unknown')380 assert loader.__name__ == 'unknown'381 configuration.__load_section__('test', {'test_key': 'test value'})382 # pylint: disable=no-member383 section = configuration.test384 assert isinstance(section, NestedDefaultConfigurationSection)385 assert section.test_key == 'test value'386def test_configuration_register_subsection_fail():387 """388 Test failure registering subsection without name389 """390 with pytest.raises(ConfigurationError):391 InvalidRootConfigurationSection()392def test_configuration_section_required_settings():393 """394 Test loading configuration section with required settings395 """396 section = RequiredSettingsConfigurationSection(data=TEST_DEFAULT_DATA)397 validate_configuration_section(section, TEST_DEFAULT_DATA)398 invalid_data = TEST_DEFAULT_DATA.copy()399 invalid_data['test_key'] = None400 with pytest.raises(ConfigurationError):401 RequiredSettingsConfigurationSection(data=invalid_data)402 with pytest.raises(ConfigurationError):403 RequiredSettingsConfigurationSection()404def test_configuration_section_paths():405 """406 Test loading configuration section with subsection paths407 """408 configuration = ConfigurationSection()409 section, field = configuration.__init_subsection_path__('test', 'test_field')410 assert section.__config_root__ == configuration411 assert section.__name__ == 'test'412 assert field == 'test_field'413 section, field = configuration.__init_subsection_path__('test', 'inner.value')414 assert section.__config_root__ == configuration415 assert isinstance(section, ConfigurationSection)416 assert section.__name__ == 'inner'417 assert section.__parent__.__name__ == 'test'418 assert field == 'value'419 configuration.__load_section__('sub', {'test': 'value'}, path='outer')420 # pylint: disable=no-member421 assert configuration.sub.outer.test == 'value'422 configuration.__load_section__('sub', 'value', path='inner.test')423 # pylint: disable=no-member424 assert configuration.sub.inner.test == 'value'425def test_configuration_section_load_dictionary():426 """427 Test loading dictionaries with __load_dictionary__ method using some more funky formats428 """429 configuration = ConfigurationSection()430 data = {431 'foo.bar': 'test',432 'bar.baz': {433 'zyxxy': 'item'434 }435 }436 configuration.__load_dictionary__(data)437 # pylint: disable=no-member438 assert configuration.foo.bar == 'test'439 # pylint: disable=no-member440 assert configuration.bar.baz.zyxxy == 'item'441 dict_output = configuration.as_dict()442 assert isinstance(dict_output, dict)443def test_configuration_section_set():444 """445 Test set() method of configuration section446 """447 configuration = ConfigurationSection()448 configuration.set('test', {'key': 'value'})449 # pylint: disable=no-member450 assert configuration.test.key == 'value'451 configuration.set('foo.bar', 'baz')452 # pylint: disable=no-member453 assert configuration.foo.bar == 'baz'454def test_configuration_section_set_formatters():455 """456 Test configuration section with number attribute formatters457 """458 configuration = ConfigurationSection()459 configuration.__integer_settings__ = ('integrity',)460 configuration.__float_settings__ = ('floating',)461 configuration.__path_settings__ = ('root',)462 configuration.set('test', {'a': 'a value'})463 # pylint: disable=no-member464 assert isinstance(configuration.test, ConfigurationSection)465 # pylint: disable=no-member466 assert configuration.test.a == 'a value'467 configuration.set('integrity', '123')468 # pylint: disable=no-member469 assert configuration.integrity == 123470 configuration.set('floating', '123.25')471 # pylint: disable=no-member472 assert configuration.floating == 123.25473 configuration.set('root', '/tmp')474 # pylint: disable=no-member475 assert isinstance(configuration.root, Path)476def test_configuration_section_field_formatter_pass():477 """478 Test configuration section with custom formatter passing479 """480 configuration = FormattedConfigurationSection(data=TEST_DEFAULT_DATA)481 # pylint: disable=no-member482 assert configuration.test_key == 'TEST VALUE'483 with pytest.raises(ConfigurationError):484 FormattedConfigurationSection(data={'test_key': 123})485def test_configuration_section_field_validation_pass():486 """487 Test configuration section with custom validation passing488 """489 section = ValidatedConfigurationSection(data=TEST_DEFAULT_DATA)490 validate_configuration_section(section, TEST_DEFAULT_DATA)491def test_configuration_section_field_validation_fail():492 """493 Test configuration section with custom validation fails494 """495 with pytest.raises(ConfigurationError):496 InvalidatedConfigurationSection(data=TEST_DEFAULT_DATA)497def test_configuration_section_callable_set_method():498 """499 Test calling a callable set method in child section loader class500 """501 section = CallableBaseConfiguration()502 assert hasattr(section, CALLABLE_SECTION_NAME)503 called = getattr(section, CALLABLE_SECTION_NAME)504 assert called.set_call_count == 0505 section.set(CALLABLE_SECTION_NAME, CALLABLE_SECTION_VALUE)...

Full Screen

Full Screen

test_config_files.py

Source:test_config_files.py Github

copy

Full Screen

1# Copyright (c) 2013 Mirantis Inc.2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or12# implied.13# See the License for the specific language governing permissions and14# limitations under the License.15import functools16import json17import os18import stat19import jsonschema20import six21import testtools22from stackalytics.processor import normalizer23IGNORED_COMPANIES = ['*robots', 'April', 'Chelsio Communications',24 'CloudRunner.io', 'Datera', 'Facebook',25 'Fermi National Accelerator Laboratory', 'Github',26 'H3C',27 'Huaxin Hospital, First Hospital of Tsinghua University',28 'InfluxDB', 'Kickstarter', 'National Security Agency',29 'OpenStack Foundation', 'OpenStack Korea User Group',30 'ProphetStor', 'SVA System Vertrieb Alexander GmbH',31 'Sencha', 'Stark & Wayne LLC', 'Styra',32 'Suranee University of Technology',33 'The Linux Foundation', 'UTi Worldwide', 'Undead Labs',34 'Violin Memory', 'docCloud', 'npm']35def dict_raise_on_duplicates(ordered_pairs):36 """Reject duplicate keys."""37 d = {}38 for k, v in ordered_pairs:39 if k in d:40 raise ValueError("duplicate key: %s (value: %s)" % (k, v))41 else:42 d[k] = v43 return d44class TestConfigFiles(testtools.TestCase):45 def setUp(self):46 super(TestConfigFiles, self).setUp()47 def _read_raw_file(self, file_name):48 if six.PY3:49 opener = functools.partial(open, encoding='utf8')50 else:51 opener = open52 with opener(file_name, 'r') as content_file:53 return content_file.read()54 def _read_file(self, file_name):55 return json.loads(self._read_raw_file(file_name))56 def _verify_ordering(self, array, key, msg):57 comparator = lambda x, y: (x > y) - (x < y)58 diff_msg = ''59 for i in range(len(array) - 1):60 if comparator(key(array[i]), key(array[i + 1])) > 0:61 diff_msg = ('Order fails at index %(index)s, '62 'elements:\n%(first)s:\n%(second)s' %63 {'index': i, 'first': array[i],64 'second': array[i + 1]})65 break66 if diff_msg:67 self.fail(msg + '\n' + diff_msg)68 def test_corrections(self):69 corrections = self._read_file('etc/corrections.json')70 schema = self._read_file('etc/corrections.schema.json')71 jsonschema.validate(corrections, schema)72 def _verify_default_data_duplicate_keys(self, file_name):73 try:74 json.loads(self._read_raw_file(file_name),75 object_pairs_hook=dict_raise_on_duplicates)76 except ValueError as ve:77 self.fail(ve)78 def test_default_data_duplicate_keys(self):79 self._verify_default_data_duplicate_keys('etc/default_data.json')80 def test_test_default_data_duplicate_keys(self):81 self._verify_default_data_duplicate_keys('etc/test_default_data.json')82 def _verify_default_data_by_schema(self, file_name):83 default_data = self._read_file(file_name)84 schema = self._read_file('etc/default_data.schema.json')85 try:86 jsonschema.validate(default_data, schema)87 except jsonschema.ValidationError as e:88 self.fail(e)89 def test_default_data_schema_conformance(self):90 self._verify_default_data_by_schema('etc/default_data.json')91 def test_test_default_data_schema_conformance(self):92 self._verify_default_data_by_schema('etc/test_default_data.json')93 def _verify_companies_in_alphabetical_order(self, file_name):94 companies = self._read_file(file_name)['companies']95 self._verify_ordering(96 companies, key=lambda x: x['domains'][0],97 msg='List of companies should be ordered by the first domain')98 def test_companies_in_alphabetical_order(self):99 self._verify_companies_in_alphabetical_order('etc/default_data.json')100 def test_companies_in_alphabetical_order_in_test_file(self):101 self._verify_companies_in_alphabetical_order(102 'etc/test_default_data.json')103 def _verify_users_in_alphabetical_order(self, file_name):104 users = self._read_file(file_name)['users']105 self._verify_ordering(106 users, key=lambda x: (x.get('launchpad_id') or x.get('ldap_id') or107 x.get('github_id')),108 msg='List of users should be ordered by launchpad id or ldap id '109 'or github id')110 def test_users_in_alphabetical_order(self):111 self._verify_users_in_alphabetical_order('etc/default_data.json')112 def test_users_in_alphabetical_order_in_test_file(self):113 self._verify_users_in_alphabetical_order('etc/test_default_data.json')114 def _check_collision(self, storage, user, field, field_name):115 self.assertFalse(116 field in storage,117 'Duplicate %s %s, collision between: %s and %s'118 % (field_name, field, storage[field], user))119 storage[field] = user120 def _verify_users_unique(self, file_name):121 users = self._read_file(file_name)['users']122 storage = {}123 for user in users:124 if user.get('launchpad_id'):125 field = user['launchpad_id']126 self.assertFalse(127 field in storage,128 'Duplicate launchpad_id %s, collision between: %s and %s'129 % (field, storage.get(field), user))130 storage[field] = user131 if user.get('gerrit_id'):132 field = user['gerrit_id']133 self.assertFalse(134 ('gerrit:%s' % field) in storage,135 'Duplicate gerrit_id %s, collision between: %s and %s'136 % (field, storage.get(field), user))137 storage['gerrit:%s' % field] = user138 for email in user['emails']:139 self.assertFalse(140 email in storage,141 'Duplicate email %s, collision between: %s and %s'142 % (email, storage.get(email), user))143 storage[email] = user144 def test_users_unique_profiles(self):145 self._verify_users_unique('etc/default_data.json')146 def test_users_unique_profiles_in_test_file(self):147 self._verify_users_unique('etc/test_default_data.json')148 def _verify_default_data_whitespace_issues(self, file_name):149 data = self._read_raw_file(file_name)150 line_n = 1151 for line in data.split('\n'):152 msg = 'Whitespace issue in "%s", line %s: ' % (line, line_n)153 self.assertTrue(line.find('\t') == -1, msg=msg + 'tab character')154 self.assertEqual(line.rstrip(), line,155 message=msg + 'trailing spaces')156 line_n += 1157 def test_default_data_whitespace_issues(self):158 self._verify_default_data_whitespace_issues('etc/default_data.json')159 def test_test_default_data_whitespace_issues(self):160 self._verify_default_data_whitespace_issues(161 'etc/test_default_data.json')162 def _validate_default_data_correctness(self, file_name):163 data = self._read_file(file_name)164 normalizer.normalize_default_data(data)165 def test_default_data_user_profiles_correctness(self):166 self._validate_default_data_correctness('etc/default_data.json')167 def test_test_default_data_user_profiles_correctness(self):168 self._validate_default_data_correctness('etc/test_default_data.json')169 def _validate_user_companies(self, file_name):170 data = self._read_file(file_name)171 users = data['users']172 companies = data['companies']173 company_names = []174 for company in companies:175 company_names.append(company['company_name'])176 for alias in company.get('aliases', []):177 company_names.append(alias)178 for user in users:179 for company in user['companies']:180 if not company['company_name'] in IGNORED_COMPANIES:181 error_msg = ('Company "%s" is unknown. Please add it into'182 ' the list of companies in default_data.json '183 'file' % company['company_name'])184 self.assertTrue(company['company_name'] in company_names,185 error_msg)186 def test_default_data_user_companies(self):187 self._validate_user_companies('etc/default_data.json')188 def test_test_default_data_user_companies(self):189 self._validate_user_companies('etc/test_default_data.json')190 def test_file_mode(self):191 files = os.listdir('etc')192 for f in ('etc/%s' % f for f in files):193 st = os.stat(f)194 x_flag = stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH195 self.assertFalse(bool(st.st_mode & x_flag),...

Full Screen

Full Screen

test_configuration_ini.py

Source:test_configuration_ini.py Github

copy

Full Screen

1"""2Unit tests for INI format configuration files3"""4from pathlib import Path5import pytest6from sys_toolkit.configuration.base import ConfigurationSection7from sys_toolkit.exceptions import ConfigurationError8from sys_toolkit.configuration import IniConfiguration9from ..conftest import MOCK_DATA, NONEXISTING_FILE10from .test_configuration_sections import (11 validate_configuration_section,12 TEST_DEFAULT_DATA13)14# Ini supports only sections15TEST_DEFAULT_DATA = dict(16 (key, item)17 for key, item in TEST_DEFAULT_DATA.items()18 if isinstance(item, dict)19)20TEST_EMPTY = MOCK_DATA.joinpath('configuration/test_empty.ini')21TEST_INVALID = MOCK_DATA.joinpath('configuration/test_invalid.ini')22TEST_VALID = MOCK_DATA.joinpath('configuration/test_valid.ini')23class DefaultsPathsConfiguration(IniConfiguration):24 """25 Configuration file with valid default configurations26 """27 __default_paths__ = [TEST_VALID, NONEXISTING_FILE]28def test_configuration_ini_default_no_file():29 """30 Test loading default ini class without file31 """32 configuration = IniConfiguration()33 assert configuration.__repr__() == ''34 assert configuration.__path__ is None35def test_configuration_ini_nonexisting_file():36 """37 Test loading default ini class with nonexisting file38 """39 configuration = IniConfiguration(NONEXISTING_FILE)40 assert configuration.__repr__() == NONEXISTING_FILE.name41 assert configuration.__path__ == NONEXISTING_FILE42def test_configuration_ini_load_directory():43 """44 Test loading default ini class with directory as path45 """46 with pytest.raises(ConfigurationError):47 IniConfiguration(Path(__file__).parent)48# pylint: disable=unused-argument49def test_configuration_ini_load_inaccessible(tmpdir, mock_path_not_file):50 """51 Test loading default ini class with inaccessible file52 """53 path = Path(tmpdir).joinpath('test.ini')54 with path.open('w', encoding='utf-8') as filedescriptor:55 filedescriptor.write('[defaults]\ntest = value\n')56 with pytest.raises(ConfigurationError):57 IniConfiguration(path)58# pylint: disable=unused-argument59def test_configuration_ini_load_permission_denied(tmpdir, mock_permission_denied):60 """61 Test loading default ini class with no permissions to file62 """63 path = Path(tmpdir).joinpath('test.ini')64 with path.open('w', encoding='utf-8') as filedescriptor:65 filedescriptor.write('[defaults]\ntest = value\n')66 with pytest.raises(ConfigurationError):67 IniConfiguration(path)68def test_configuration_ini_empty_file():69 """70 Test loading empty ini file71 """72 configuration = IniConfiguration(TEST_EMPTY)73 assert isinstance(configuration, ConfigurationSection)74 assert configuration.__repr__() == TEST_EMPTY.name75 with pytest.raises(ConfigurationError):76 configuration.parse_data([])77def test_configuration_ini_invalid_file():78 """79 Test loading invalid YAML file80 """81 with pytest.raises(ConfigurationError):82 IniConfiguration(TEST_INVALID)83def test_configuration_ini_valid_file():84 """85 Test loading valid ini file86 """87 configuration = IniConfiguration(TEST_VALID)88 assert isinstance(configuration, ConfigurationSection)89 validate_configuration_section(configuration, TEST_DEFAULT_DATA)90def test_configuration_ini_default_paths():91 """92 Test loading ini configuration with default paths93 """94 configuration = DefaultsPathsConfiguration()95 validate_configuration_section(configuration, TEST_DEFAULT_DATA)96 # Reload data...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run tox automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful