How to use test_resolver method in avocado

Best Python code snippet using avocado_python

auth_test.py

Source:auth_test.py Github

copy

Full Screen

1#!/usr/bin/env python2#3# Copyright 2018 Google Inc. All Rights Reserved.4#5# Licensed under the Apache License, Version 2.0 (the "License");6# you may not use this file except in compliance with the License.7# You may obtain a copy of the License at8#9# http://www.apache.org/licenses/LICENSE-2.010#11# Unless required by applicable law or agreed to in writing, software12# distributed under the License is distributed on an "AS-IS" BASIS,13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.14# See the License for the specific language governing permissions and15# limitations under the License.16#17"""auth module tests."""18import logging19import tests.appenginesdk20import mock21import stubout22from google.appengine.api import oauth23from google.appengine.api import users24from google.appengine.ext import testbed25from google.apputils import app26from google.apputils import basetest27from simian import settings28from simian.mac import models29from simian.mac.common import auth30class AuthModuleTest(basetest.TestCase):31 def setUp(self):32 self.stubs = stubout.StubOutForTesting()33 self.email = 'foouser@example.com'34 self.testbed = testbed.Testbed()35 self.testbed.activate()36 self.testbed.setup_env(37 overwrite=True,38 USER_EMAIL=self.email,39 USER_ID='123',40 USER_IS_ADMIN='0',41 TESTONLY_OAUTH_SKIP_CACHE='1',42 DEFAULT_VERSION_HOSTNAME='example.appspot.com')43 self.testbed.init_all_stubs()44 settings.ADMINS = ['admin@example.com']45 def tearDown(self):46 self.stubs.UnsetAll()47 @mock.patch.object(auth.users, 'get_current_user', return_value=None)48 def testDoUserAuthWithNoUser(self, _):49 self.assertRaises(auth.NotAuthenticated, auth.DoUserAuth)50 def testDoUserAuthAnyDomainUserSuccess(self):51 self.stubs.Set(auth.settings, 'ALLOW_ALL_DOMAIN_USERS_READ_ACCESS', True)52 self.assertEqual(self.email, auth.DoUserAuth().email())53 @mock.patch.object(auth, 'IsAdminUser', return_value=True)54 def testDoUserAuthWithIsAdminTrueSuccess(self, _):55 self.assertEqual(self.email, auth.DoUserAuth(is_admin=True).email())56 @mock.patch.object(auth, 'IsAdminUser', return_value=False)57 def testDoUserAuthWithIsAdminTrueFailure(self, _):58 self.assertRaises(auth.IsAdminMismatch, auth.DoUserAuth, is_admin=True)59 @mock.patch.object(auth, 'IsAdminUser', return_value=False)60 @mock.patch.object(auth, 'IsSupportUser', return_value=False)61 @mock.patch.object(auth, 'IsSecurityUser', return_value=False)62 @mock.patch.object(auth, 'IsPhysicalSecurityUser', return_value=True)63 def testDoUserAuthWithAllDomainUsersOff(self, *_):64 self.stubs.Set(auth.settings, 'ALLOW_ALL_DOMAIN_USERS_READ_ACCESS', False)65 self.assertEqual(self.email, auth.DoUserAuth().email())66 @mock.patch.object(auth, 'IsAdminUser', return_value=False)67 @mock.patch.object(auth, 'IsSupportUser', return_value=False)68 @mock.patch.object(auth, 'IsSecurityUser', return_value=False)69 @mock.patch.object(auth, 'IsPhysicalSecurityUser', return_value=False)70 @mock.patch.object(auth, '_IsAllowedToPropose', return_value=False)71 def testDoUserAuthWithAllDomainUsersOffFailure(self, *_):72 self.stubs.Set(auth.settings, 'ALLOW_ALL_DOMAIN_USERS_READ_ACCESS', False)73 self.assertRaises(auth.NotAuthenticated, auth.DoUserAuth)74 @mock.patch.dict(settings.__dict__, {75 'OAUTH_CLIENT_ID': 'id_123'})76 @mock.patch.object(oauth, 'get_client_id', return_value='id_123')77 def testDoOAuthAuthSuccessSettings(self, _):78 """Test DoOAuthAuth() with success, where user is in settings file."""79 email = 'zerocool@example.com'80 user_service_stub = self.testbed.get_stub(testbed.USER_SERVICE_NAME)81 user_service_stub.SetOAuthUser(email, scopes=[auth.OAUTH_SCOPE])82 auth.settings.OAUTH_USERS = [email]83 self.assertEqual(email, auth.DoOAuthAuth().email())84 @mock.patch.dict(settings.__dict__, {85 'OAUTH_CLIENT_ID': 'id_123'})86 @mock.patch.object(oauth, 'get_client_id', return_value='id_123')87 @mock.patch.object(auth, 'IsAdminUser', return_value=True)88 def testDoOAuthAuthSuccess(self, *_):89 """Test DoOAuthAuth() with success, where user is in KeyValueCache."""90 email = 'hal@example.com'91 user_service_stub = self.testbed.get_stub(testbed.USER_SERVICE_NAME)92 user_service_stub.SetOAuthUser(email, scopes=[auth.OAUTH_SCOPE])93 auth.settings.OAUTH_USERS = []94 auth.models.KeyValueCache.MemcacheWrappedSet(95 'oauth_users', 'text_value', auth.util.Serialize([email]))96 self.assertEqual(email, auth.DoOAuthAuth(is_admin=True).email())97 @mock.patch.object(98 auth.oauth, 'get_current_user', side_effect=auth.oauth.OAuthRequestError)99 def testDoOAuthAuthOAuthNotUsed(self, _):100 """Test DoOAuthAuth() where OAuth was not used at all."""101 self.assertRaises(auth.NotAuthenticated, auth.DoOAuthAuth)102 @mock.patch.dict(settings.__dict__, {103 'OAUTH_CLIENT_ID': 'id_123'})104 @mock.patch.object(oauth, 'get_client_id', return_value='id_123')105 @mock.patch.object(auth, 'IsAdminUser', return_value=False)106 def testDoOAuthAuthAdminMismatch(self, *_):107 """Test DoOAuthAuth(is_admin=True) where user is not admin."""108 email = 'zerocool@example.com'109 user_service_stub = self.testbed.get_stub(testbed.USER_SERVICE_NAME)110 user_service_stub.SetOAuthUser(email, scopes=[auth.OAUTH_SCOPE])111 self.assertRaises(auth.IsAdminMismatch, auth.DoOAuthAuth, is_admin=True)112 def testDoOAuthAuthWhereNotValidOAuthUser(self):113 """Test DoOAuthAuth() where oauth user is not authorized."""114 email = 'zerocool@example.com'115 auth.settings.OAUTH_USERS = []116 user_service_stub = self.testbed.get_stub(testbed.USER_SERVICE_NAME)117 user_service_stub.SetOAuthUser(email, scopes=[auth.OAUTH_SCOPE])118 self.assertRaises(auth.NotAuthenticated, auth.DoOAuthAuth)119 def testDoAnyAuth(self):120 """Test DoAnyAuth()."""121 email = 'zerocool@example.com'122 require_level = 123123 with mock.patch.object(auth, 'DoUserAuth', return_value=email) as m:124 self.assertEqual(auth.DoAnyAuth(is_admin=True), email)125 m.assert_called_once_with(is_admin=True)126 with mock.patch.object(127 auth, 'DoUserAuth', side_effect=auth.IsAdminMismatch):128 self.assertRaises(auth.IsAdminMismatch, auth.DoAnyAuth, is_admin=True)129 with mock.patch.object(130 auth, 'DoUserAuth', side_effect=auth.NotAuthenticated):131 with mock.patch.object(132 auth.gaeserver, 'DoMunkiAuth', return_value='user') as m:133 self.assertEqual(auth.DoAnyAuth(134 is_admin=True, require_level=require_level), 'user')135 m.assert_called_once_with(require_level=require_level)136 with mock.patch.object(137 auth, 'DoUserAuth', side_effect=auth.NotAuthenticated):138 with mock.patch.object(139 auth.gaeserver, 'DoMunkiAuth',140 side_effect=auth.gaeserver.NotAuthenticated):141 self.assertRaises(142 auth.base.NotAuthenticated,143 auth.DoAnyAuth, is_admin=True, require_level=require_level)144 @mock.patch.object(145 auth, '_GetGroupMembers', return_value=['admin4@example.com'])146 def testIsAdminUserTrue(self, _):147 """Test IsAdminUser() with a passed email address that is an admin."""148 admin_email = 'admin4@example.com'149 self.assertTrue(auth.IsAdminUser(admin_email))150 @mock.patch.object(auth, '_GetGroupMembers', return_value=['foo@example.com'])151 def testIsAdminUserFalse(self, _):152 """Test IsAdminUser() with a passed email address that is not an admin."""153 self.assertFalse(auth.IsAdminUser('admin4@example.com'))154 @mock.patch.object(155 auth, '_GetGroupMembers', return_value=['admin5@example.com'])156 def testIsAdminUserWithNoPassedEmail(self, _):157 """Test IsAdminUser() with no passed email address."""158 self.assertFalse(auth.IsAdminUser())159 @mock.patch.object(auth, '_GetGroupMembers', return_value=[])160 def testIsAdminUserBootstrap(self, _):161 """Test IsAdminUser() where no admins are defined."""162 admin_email = 'admin4@example.com'163 self.testbed.setup_env(164 overwrite=True,165 USER_EMAIL=admin_email,166 USER_IS_ADMIN='1')167 self.assertTrue(auth.IsAdminUser(admin_email))168 @mock.patch.object(auth, '_GetGroupMembers', return_value=[])169 def testIsAdminUserBootstrapFalse(self, _):170 """Test IsAdminUser() where no admins are defined, but user not admin."""171 self.assertFalse(auth.IsAdminUser(self.email))172 def testIsGroupMemberWhenSettings(self):173 """Test IsGroupMember()."""174 group_members = ['support1@example.com', 'support2@example.com']175 group_name = 'foo_group'176 setattr(auth.settings, group_name.upper(), group_members)177 models.KeyValueCache.MemcacheWrappedSet(group_name, 'text_value', '[]')178 self.assertTrue(auth.IsGroupMember(group_members[0], group_name=group_name))179 def testIsGroupMemberWhenSettingsWithNoPassedEmail(self):180 """Test IsGroupMember()."""181 group_members = [self.email, 'support2@example.com']182 group_name = 'foo_group_two'183 setattr(auth.settings, group_name.upper(), group_members)184 models.KeyValueCache.MemcacheWrappedSet(group_name, 'text_value', '[]')185 self.assertTrue(auth.IsGroupMember(group_name=group_name))186 def testIsGroupMemberWhenLiveConfigAdminUser(self):187 """Test IsGroupMember()."""188 email = 'support4@example.com'189 group_members = ['support1@example.com', 'support2@example.com']190 group_name = 'foo_group'191 auth.models.KeyValueCache.MemcacheWrappedSet(192 group_name, 'text_value', auth.util.Serialize([email]))193 self.assertTrue(auth.IsGroupMember(email, group_name=group_name))194 def testIsGroupMemberWhenNotAdmin(self):195 """Test IsGroupMember()."""196 email = 'support5@example.com'197 group_members = ['support1@example.com', 'support2@example.com']198 group_name = 'support_users'199 auth.models.KeyValueCache.MemcacheWrappedSet(200 group_name, 'text_value', auth.util.Serialize(group_members))201 self.assertFalse(auth.IsGroupMember(email, group_name=group_name))202 @mock.patch.object(auth, 'DoUserAuth', return_value=True)203 @mock.patch.object(auth.PermissionResolver, '_IsAllowedToPropose')204 def testIsAllowedTo(self, mock_is_allowed_to_propose, _):205 """Test PermissionResolver.IsAllowedTo."""206 test_resolver = auth.PermissionResolver('task')207 test_resolver.email = 'user1@example.com'208 test_resolver.task = 'Propose'209 mock_is_allowed_to_propose.return_value = True210 self.assertTrue(test_resolver.IsAllowedTo())211 mock_is_allowed_to_propose.return_value = False212 self.assertFalse(test_resolver.IsAllowedTo())213 @mock.patch.object(auth, 'DoUserAuth', side_effect=auth.NotAuthenticated)214 def testIsAllowedToWithoutUser(self, _):215 test_resolver = auth.PermissionResolver('task')216 test_resolver.email = 'user1@example.com'217 test_resolver.task = 'Propose'218 self.assertFalse(test_resolver.IsAllowedTo())219 @mock.patch.object(auth, 'DoUserAuth', return_value=True)220 def testIsAllowedToUnknownTask(self, _):221 test_resolver = auth.PermissionResolver('task')222 test_resolver.email = 'user1@example.com'223 test_resolver.task = 'FakeTask'224 self.assertFalse(test_resolver.IsAllowedTo())225 def testIsAllowedToPropose(self):226 """Test PermissionResolver._IsAllowedToPropose()."""227 test_resolver = auth.PermissionResolver('task')228 email_one = 'user1@example.com'229 email_two = 'user2@example.com'230 email_three = 'user3@example.com'231 with mock.patch.object(auth, 'IsAdminUser', return_value=True):232 test_resolver.email = email_one233 self.assertTrue(test_resolver._IsAllowedToPropose())234 def testIsAllowedToUploadProposalsOff(self):235 """Test PermissionResolver._IsAllowedToUpload() with proposals."""236 test_resolver = auth.PermissionResolver('task')237 email_one = 'user1@example.com'238 email_two = 'user2@example.com'239 setattr(auth.settings, 'ENABLE_PROPOSALS_GROUP', False)240 setattr(auth.settings, 'PROPOSALS_GROUP', '')241 with mock.patch.object(auth, 'IsAdminUser', return_value=True):242 test_resolver.email = email_one243 self.assertTrue(test_resolver._IsAllowedToUpload())244 with mock.patch.object(auth, 'IsAdminUser', return_value=False):245 test_resolver.email = email_two246 self.assertFalse(test_resolver._IsAllowedToUpload())247 @mock.patch.object(auth, '_IsAllowedToPropose')248 def testIsAllowedToUploadProposalsOn(self, mock_is_allowed_to_propose):249 """Test PermissionResolver._IsAllowedToUpload() without proposals."""250 test_resolver = auth.PermissionResolver('task')251 email_one = 'user1@example.com'252 email_two = 'user2@example.com'253 setattr(auth.settings, 'ENABLE_PROPOSALS_GROUP', True)254 setattr(auth.settings, 'PROPOSALS_GROUP', 'group')255 test_resolver.email = email_one256 mock_is_allowed_to_propose.return_value = True257 self.assertTrue(test_resolver._IsAllowedToUpload())258 test_resolver.email = email_two259 mock_is_allowed_to_propose.return_value = False260 self.assertFalse(test_resolver._IsAllowedToUpload())261 @mock.patch.object(auth, 'IsSupportUser')262 @mock.patch.object(auth, '_IsAllowedToPropose')263 def testIsAllowedToViewPacakgesProposalsOn(264 self, mock_is_allowed_to_propose, mock_is_support_user):265 """Test PermissionResolver._IsAllowedToViewPackages() with proposals."""266 test_resolver = auth.PermissionResolver('task')267 email_one = 'user1@example.com'268 email_two = 'user2@example.com'269 email_three = 'user3@example.com'270 setattr(auth.settings, 'ENABLE_PROPOSALS_GROUP', True)271 setattr(auth.settings, 'PROPOSALS_GROUP', 'group')272 test_resolver.email = email_one273 mock_is_allowed_to_propose.return_value = True274 self.assertTrue(test_resolver._IsAllowedToViewPackages())275 test_resolver.email = email_two276 mock_is_support_user.return_value = True277 mock_is_allowed_to_propose.return_value = False278 self.assertTrue(test_resolver._IsAllowedToViewPackages())279 test_resolver.email = email_three280 mock_is_support_user.return_value = False281 self.assertFalse(test_resolver._IsAllowedToViewPackages())282 @mock.patch.object(auth, 'IsSupportUser')283 @mock.patch.object(auth, 'IsAdminUser')284 def testIsAllowedToViewPacakgesProposalsOff(285 self, mock_is_admin_user, mock_is_support_user):286 """Test PermissionResolver._IsAllowedToViewPackages() without proposals."""287 test_resolver = auth.PermissionResolver('task')288 email_one = 'user1@example.com'289 email_two = 'user2@example.com'290 email_three = 'user3@example.com'291 setattr(auth.settings, 'ENABLE_PROPOSALS_GROUP', False)292 setattr(auth.settings, 'PROPOSALS_GROUP', '')293 test_resolver.email = email_one294 mock_is_admin_user.return_value = True295 self.assertTrue(test_resolver._IsAllowedToViewPackages())296 test_resolver.email = email_two297 mock_is_admin_user.return_value = False298 mock_is_support_user.return_value = True299 self.assertTrue(test_resolver._IsAllowedToViewPackages())300 test_resolver.email = email_three301 mock_is_support_user.return_value = False302 self.assertFalse(test_resolver._IsAllowedToViewPackages())303 @mock.patch.object(auth, 'IsGroupMember', return_value=False)304 @mock.patch.object(auth, '_GetGroupMembers', return_value=[])305 @mock.patch.dict(settings.__dict__, {306 'ALLOW_SELF_REPORT': True, 'AUTH_DOMAIN': 'example.com'})307 @mock.patch.object(auth.users, 'get_current_user')308 def testDoUserAuthWithSelfReportFallbackAccessDenied(309 self, get_current_user, *_):310 get_current_user.return_value = None311 self.assertRaises(312 auth.NotAuthenticated, auth.DoUserAuthWithSelfReportFallback)313 get_current_user.return_value = users.User(email='user1@example.com')314 self.assertRaises(315 auth.NotAuthenticated,316 auth.DoUserAuthWithSelfReportFallback, constrain_username='user2')317 settings.__dict__['ALLOW_SELF_REPORT'] = False318 get_current_user.return_value = users.User(email='user1@example.com')319 self.assertRaises(320 auth.NotAuthenticated, auth.DoUserAuthWithSelfReportFallback)321 @mock.patch.object(auth, 'IsGroupMember', return_value=False)322 @mock.patch.object(auth, '_GetGroupMembers', return_value=[])323 @mock.patch.dict(auth.settings.__dict__, {324 'ALLOW_SELF_REPORT': True, 'AUTH_DOMAIN': 'example.com'})325 @mock.patch.object(auth.users, 'get_current_user')326 def testDoUserAuthWithSelfReportFallbackSucceed(self, get_current_user, *_):327 get_current_user.return_value = users.User(email='user1@example.com')328 self.assertEqual(329 'user1',330 auth.DoUserAuthWithSelfReportFallback(constrain_username='user1'))331logging.basicConfig(filename='/dev/null')332def main(unused_argv):333 basetest.main()334if __name__ == '__main__':...

Full Screen

Full Screen

path_resover.py

Source:path_resover.py Github

copy

Full Screen

1#!/usr/bin/env python2# -*- coding: utf-8 -*-3"""Tests for the helper for resolving paths."""4import unittest5from dfimagetools import path_resolver6from dfimagetools import resources7from tests import test_lib8class PathResolverTest(test_lib.BaseTestCase):9 """Tests for the path resolver."""10 # pylint: disable=protected-access11 def testExpandEnvironmentVariablesInPathSegments(self):12 """Tests the _ExpandEnvironmentVariablesInPathSegments function."""13 test_resolver = path_resolver.PathResolver()14 environment_variables = []15 environment_variable = resources.EnvironmentVariable(16 case_sensitive=False, name='allusersappdata',17 value='C:\\Documents and Settings\\All Users\\Application Data')18 environment_variables.append(environment_variable)19 environment_variable = resources.EnvironmentVariable(20 case_sensitive=False, name='allusersprofile',21 value='C:\\Documents and Settings\\All Users')22 environment_variables.append(environment_variable)23 environment_variable = resources.EnvironmentVariable(24 case_sensitive=False, name='SystemRoot', value='C:\\Windows')25 environment_variables.append(environment_variable)26 expected_path_segments = [27 '', 'Documents and Settings', 'All Users', 'Application Data',28 'Apache Software Foundation']29 path_segments = test_resolver._ExpandEnvironmentVariablesInPathSegments(30 ['%AllUsersAppData%', 'Apache Software Foundation'],31 environment_variables)32 self.assertEqual(path_segments, expected_path_segments)33 expected_path_segments = [34 '', 'Documents and Settings', 'All Users', 'Start Menu', 'Programs',35 'Startup']36 path_segments = test_resolver._ExpandEnvironmentVariablesInPathSegments(37 ['%AllUsersProfile%', 'Start Menu', 'Programs', 'Startup'],38 environment_variables)39 self.assertEqual(path_segments, expected_path_segments)40 path_segments = test_resolver._ExpandEnvironmentVariablesInPathSegments(41 ['%SystemRoot%', 'System32'], environment_variables)42 self.assertEqual(path_segments, ['', 'Windows', 'System32'])43 path_segments = test_resolver._ExpandEnvironmentVariablesInPathSegments(44 ['C:', 'Windows', 'System32'], environment_variables)45 self.assertEqual(path_segments, ['', 'Windows', 'System32'])46 path_segments = test_resolver._ExpandEnvironmentVariablesInPathSegments(47 ['%SystemRoot%', 'System32'], None)48 self.assertEqual(path_segments, ['%SystemRoot%', 'System32'])49 path_segments = test_resolver._ExpandEnvironmentVariablesInPathSegments(50 ['%Bogus%', 'System32'], environment_variables)51 self.assertEqual(path_segments, ['%Bogus%', 'System32'])52 path_segments = test_resolver._ExpandEnvironmentVariablesInPathSegments(53 ['%%environ_systemroot%%', 'System32'], environment_variables)54 self.assertEqual(path_segments, ['', 'Windows', 'System32'])55 # Test non-string environment variable.56 environment_variables = []57 environment_variable = resources.EnvironmentVariable(58 case_sensitive=False, name='SystemRoot', value=('bogus', 0))59 environment_variables.append(environment_variable)60 path_segments = test_resolver._ExpandEnvironmentVariablesInPathSegments(61 ['%SystemRoot%', 'System32'], environment_variables)62 self.assertEqual(path_segments, ['%SystemRoot%', 'System32'])63 def testExpandUserDirectoryVariableInPathSegments(self):64 """Tests the _ExpandUserDirectoryVariableInPathSegments function."""65 test_resolver = path_resolver.PathResolver()66 user_account_artifact1 = resources.UserAccount(67 user_directory='/home/Test1', username='Test1')68 user_account_artifact2 = resources.UserAccount(69 user_directory='/Users/Test2', username='Test2')70 user_account_artifact3 = resources.UserAccount(username='Test3')71 user_accounts = [72 user_account_artifact1, user_account_artifact2, user_account_artifact3]73 path_segments = ['%%users.homedir%%', '.bashrc']74 expanded_paths = test_resolver._ExpandUserDirectoryVariableInPathSegments(75 path_segments, '/', user_accounts)76 expected_expanded_paths = [77 '/home/Test1/.bashrc',78 '/Users/Test2/.bashrc']79 self.assertEqual(expanded_paths, expected_expanded_paths)80 path_segments = ['%%users.homedir%%', '.bashrc']81 expanded_paths = test_resolver._ExpandUserDirectoryVariableInPathSegments(82 path_segments, '/', [])83 expected_expanded_paths = [84 '/Documents and Settings/*/.bashrc', '/home/*/.bashrc',85 '/Users/*/.bashrc']86 self.assertEqual(expanded_paths, expected_expanded_paths)87 user_account_artifact1 = resources.UserAccount(88 user_directory='C:\\Users\\Test1', user_directory_path_separator='\\',89 username='Test1')90 user_account_artifact2 = resources.UserAccount(91 user_directory='%SystemDrive%\\Users\\Test2',92 user_directory_path_separator='\\', username='Test2')93 user_accounts = [user_account_artifact1, user_account_artifact2]94 path_segments = ['%%users.userprofile%%', 'Profile']95 expanded_paths = test_resolver._ExpandUserDirectoryVariableInPathSegments(96 path_segments, '\\', user_accounts)97 expected_expanded_paths = [98 '\\Users\\Test1\\Profile',99 '\\Users\\Test2\\Profile']100 self.assertEqual(expanded_paths, expected_expanded_paths)101 path_segments = ['C:', 'Temp']102 expanded_paths = test_resolver._ExpandUserDirectoryVariableInPathSegments(103 path_segments, '\\', user_accounts)104 expected_expanded_paths = ['\\Temp']105 self.assertEqual(expanded_paths, expected_expanded_paths)106 path_segments = ['C:', 'Temp', '%%users.userprofile%%']107 expanded_paths = test_resolver._ExpandUserDirectoryVariableInPathSegments(108 path_segments, '\\', user_accounts)109 expected_expanded_paths = ['\\Temp\\%%users.userprofile%%']110 self.assertEqual(expanded_paths, expected_expanded_paths)111 def testExpandUsersVariableInPathSegments(self):112 """Tests the _ExpandUsersVariableInPathSegments function."""113 test_resolver = path_resolver.PathResolver()114 user_account_artifact1 = resources.UserAccount(115 identifier='1000', user_directory='C:\\Users\\Test1',116 user_directory_path_separator='\\', username='Test1')117 user_account_artifact2 = resources.UserAccount(118 identifier='1001', user_directory='%SystemDrive%\\Users\\Test2',119 user_directory_path_separator='\\', username='Test2')120 user_accounts = [user_account_artifact1, user_account_artifact2]121 path_segments = ['%%users.appdata%%', 'Microsoft', 'Windows', 'Recent']122 expanded_paths = test_resolver._ExpandUsersVariableInPathSegments(123 path_segments, '\\', user_accounts)124 expected_expanded_paths = [125 '\\Users\\Test1\\AppData\\Roaming\\Microsoft\\Windows\\Recent',126 '\\Users\\Test1\\Application Data\\Microsoft\\Windows\\Recent',127 '\\Users\\Test2\\AppData\\Roaming\\Microsoft\\Windows\\Recent',128 '\\Users\\Test2\\Application Data\\Microsoft\\Windows\\Recent']129 self.assertEqual(sorted(expanded_paths), expected_expanded_paths)130 path_segments = ['C:', 'Windows']131 expanded_paths = test_resolver._ExpandUsersVariableInPathSegments(132 path_segments, '\\', user_accounts)133 expected_expanded_paths = ['\\Windows']134 self.assertEqual(sorted(expanded_paths), expected_expanded_paths)135 def testIsWindowsDrivePathSegment(self):136 """Tests the _IsWindowsDrivePathSegment function."""137 test_resolver = path_resolver.PathResolver()138 result = test_resolver._IsWindowsDrivePathSegment('C:')139 self.assertTrue(result)140 result = test_resolver._IsWindowsDrivePathSegment('%SystemDrive%')141 self.assertTrue(result)142 result = test_resolver._IsWindowsDrivePathSegment('%%environ_systemdrive%%')143 self.assertTrue(result)144 result = test_resolver._IsWindowsDrivePathSegment('Windows')145 self.assertFalse(result)146 def testExpandEnvironmentVariables(self):147 """Tests the ExpandEnvironmentVariables function."""148 test_resolver = path_resolver.PathResolver()149 environment_variables = []150 environment_variable = resources.EnvironmentVariable(151 case_sensitive=False, name='SystemRoot', value='C:\\Windows')152 environment_variables.append(environment_variable)153 expanded_path = test_resolver.ExpandEnvironmentVariables(154 '%SystemRoot%\\System32', '\\', environment_variables)155 self.assertEqual(expanded_path, '\\Windows\\System32')156 def testExpandGlobStars(self):157 """Tests the ExpandGlobStars function."""158 test_resolver = path_resolver.PathResolver()159 paths = test_resolver.ExpandGlobStars('/etc/sysconfig/**', '/')160 self.assertEqual(len(paths), 10)161 expected_paths = sorted([162 '/etc/sysconfig/*',163 '/etc/sysconfig/*/*',164 '/etc/sysconfig/*/*/*',165 '/etc/sysconfig/*/*/*/*',166 '/etc/sysconfig/*/*/*/*/*',167 '/etc/sysconfig/*/*/*/*/*/*',168 '/etc/sysconfig/*/*/*/*/*/*/*',169 '/etc/sysconfig/*/*/*/*/*/*/*/*',170 '/etc/sysconfig/*/*/*/*/*/*/*/*/*',171 '/etc/sysconfig/*/*/*/*/*/*/*/*/*/*'])172 self.assertEqual(sorted(paths), expected_paths)173 # Test globstar with recursion depth of 4.174 paths = test_resolver.ExpandGlobStars('/etc/sysconfig/**4', '/')175 self.assertEqual(len(paths), 4)176 expected_paths = sorted([177 '/etc/sysconfig/*',178 '/etc/sysconfig/*/*',179 '/etc/sysconfig/*/*/*',180 '/etc/sysconfig/*/*/*/*'])181 self.assertEqual(sorted(paths), expected_paths)182 # Test globstar with unsupported recursion depth of 99.183 paths = test_resolver.ExpandGlobStars('/etc/sysconfig/**99', '/')184 self.assertEqual(len(paths), 10)185 expected_paths = sorted([186 '/etc/sysconfig/*',187 '/etc/sysconfig/*/*',188 '/etc/sysconfig/*/*/*',189 '/etc/sysconfig/*/*/*/*',190 '/etc/sysconfig/*/*/*/*/*',191 '/etc/sysconfig/*/*/*/*/*/*',192 '/etc/sysconfig/*/*/*/*/*/*/*',193 '/etc/sysconfig/*/*/*/*/*/*/*/*',194 '/etc/sysconfig/*/*/*/*/*/*/*/*/*',195 '/etc/sysconfig/*/*/*/*/*/*/*/*/*/*'])196 self.assertEqual(sorted(paths), expected_paths)197 # Test globstar with prefix.198 paths = test_resolver.ExpandGlobStars('/etc/sysconfig/my**', '/')199 self.assertEqual(len(paths), 1)200 self.assertEqual(paths, ['/etc/sysconfig/my**'])201 # Test globstar with suffix.202 paths = test_resolver.ExpandGlobStars('/etc/sysconfig/**.exe', '/')203 self.assertEqual(len(paths), 1)204 self.assertEqual(paths, ['/etc/sysconfig/**.exe'])205 def testExpandUsersVariable(self):206 """Tests the ExpandUsersVariable function."""207 test_resolver = path_resolver.PathResolver()208 user_account_artifact1 = resources.UserAccount(209 user_directory='C:\\Users\\Test1', user_directory_path_separator='\\',210 username='Test1')211 user_account_artifact2 = resources.UserAccount(212 user_directory='%SystemDrive%\\Users\\Test2',213 user_directory_path_separator='\\', username='Test2')214 user_accounts = [user_account_artifact1, user_account_artifact2]215 path = '%%users.appdata%%\\Microsoft\\Windows\\Recent'216 expanded_paths = test_resolver.ExpandUsersVariable(217 path, '\\', user_accounts)218 expected_expanded_paths = [219 '\\Users\\Test1\\AppData\\Roaming\\Microsoft\\Windows\\Recent',220 '\\Users\\Test1\\Application Data\\Microsoft\\Windows\\Recent',221 '\\Users\\Test2\\AppData\\Roaming\\Microsoft\\Windows\\Recent',222 '\\Users\\Test2\\Application Data\\Microsoft\\Windows\\Recent']223 self.assertEqual(sorted(expanded_paths), expected_expanded_paths)224if __name__ == '__main__':...

Full Screen

Full Screen

test_resource_resolver.py

Source:test_resource_resolver.py Github

copy

Full Screen

1import io2import pathlib3import tempfile4import unittest56from resource_resolver import ResourceResolver, ResourceResolverError789class BasicResourceResolverTestSuite(unittest.TestCase):10 @classmethod11 def setUpClass(cls) -> None:12 cls.test_resolver = ResourceResolver()13 return super().setUpClass()1415 def test_define_allows_definition_of_a_valid_file_url(self):16 with tempfile.TemporaryDirectory() as tmpdir:17 p = pathlib.Path(tmpdir) / 'test.txt'18 with p.open('w+') as f:19 f.write('abc')20 self.test_resolver.define('valid_file_url', f'file://{str(p)}')2122 def test_define_allows_definition_of_a_valid_file_path(self):23 with tempfile.TemporaryDirectory() as tmpdir:24 p = pathlib.Path(tmpdir) / 'test.txt'25 with p.open('w+') as f:26 f.write('abc')27 self.test_resolver.define('valid_file_path', p)2829 def test_define_allows_definition_of_a_valid_string_io_resource(self):30 self.test_resolver.define('valid_buffer', io.StringIO())313233class ResourceResolverTestSuite(unittest.TestCase):34 def setUp(self):35 self.tmp_dir = tempfile.TemporaryDirectory()36 self.test_path = (pathlib.Path(self.tmp_dir.name) /37 'test_file.txt').resolve()3839 self.test_file_contents = 'Test text.'4041 self.test_path.touch()42 with self.test_path.open(mode='w+') as f:43 f.write(self.test_file_contents)4445 self.test_resolver = ResourceResolver()46 self.test_io_buffer = io.StringIO()47 self.test_io_buffer.write(self.test_file_contents)4849 self.test_path2 = (pathlib.Path(self.tmp_dir.name) /50 'test_file2.txt').resolve()51 self.test_path2.touch()52 with self.test_path2.open(mode='w+') as f:53 f.write(self.test_file_contents)5455 self.temp_key = 'test_temp_key'56 self.file_url_key = 'test_file_url_key'57 self.file_path_key = 'test_file_path_key'5859 self.test_resolver.define(self.temp_key, self.test_io_buffer)60 self.test_resolver.define(61 self.file_url_key, f'file://{str(self.test_path)}')62 self.test_resolver.define(self.file_path_key, self.test_path2)6364 def tearDown(self):65 self.tmp_dir.cleanup()66 self.test_resolver.clear()6768 def test_has_returns_true_if_a_resource_has_been_defined(self):69 self.assertTrue(self.test_resolver.has(self.temp_key))7071 def test_has_returns_false_if_a_resource_has_not_been_defined(self):72 self.assertFalse(self.test_resolver.has('not'))7374 def test_get_returns_expected_data_when_a_file_resource_is_defined(self):75 expected_result = self.test_file_contents76 received_result = self.test_resolver.get(self.file_path_key, as_a='file_handle')7778 self.assertEqual(expected_result, received_result.read())79 80 def test_get_returns_expected_data_when_a_string_io_resource_is_defined(81 self):82 expected_result = self.test_file_contents83 received_result = self.test_resolver.get(self.temp_key)8485 self.assertEqual(expected_result, received_result)8687 def test_saved_data_returned_after_saving_to_file_resource(self):88 self.test_resolver.define('test2')8990 content = 'abc123'9192 self.test_resolver.save('test2', content)9394 self.assertEqual(self.test_resolver.get('test2'), content)9596 def test_saved_data_returned_after_saving_to_temporary_resource(self):97 content = 'abc123'98 self.test_resolver.save(self.temp_key, content)99100 self.assertEqual(self.test_resolver.get(self.temp_key), content)101102 def test_raises_undefined_resource_when_getting_resource_which_does_exist(103 self):104 with self.assertRaises(ResourceResolverError):105 self.test_resolver.get('doreme')106107 def test_raises_duplicate_key_when_trying_define_a_resource_that_already_exists(108 self):109 with self.assertRaises(ResourceResolverError):110 self.test_resolver.define(self.temp_key, io.StringIO())111112 def test_raises_error_for_unknown_protocol(self):113 with self.assertRaises(ResourceResolverError):114 self.test_resolver.define('abc', 'ftp://file-somewhere')115116 def test_raises_error_for_undefined_get_as_a_format(self):117 with self.assertRaises(ResourceResolverError):118 self.test_resolver.get('test', as_a="abc") # type: ignore119120 def test_returns_buffer_for_get_as_a_buffer_for_io_obj(self):121 buffer = self.test_resolver.get(self.temp_key, as_a="buffer")122 self.assertEqual(type(buffer), io.StringIO)123124 def test_returns_buffer_for_get_as_a_buffer_for_file_obj(self):125 buffer = self.test_resolver.get(self.file_path_key, as_a="buffer")126 self.assertEqual(type(buffer), io.StringIO)127128 def test_does_not_raises_duplicate_key_when_trying_define_a_resource_that_already_exists_using_overwrite(129 self):130 try:131 self.test_resolver.define('test2', io.StringIO(), overwrite=True)132 except ResourceResolverError as e:133 self.fail(e)134135 def test_unsupported_write_type_throws_error(self):136 with self.assertRaises(ResourceResolverError):137 self.test_resolver.save('test', {}) # type: ignore138139 def test_defining_a_resource_with_no_location_creates_an_in_memory_buffer(140 self):141 resolver = self.test_resolver142143 resolver.define('abc123')144145 contents = 'some contents...'146147 resolver.save('abc123', contents)148149 retrieved_value = resolver.get('abc123')150151 self.assertEqual(retrieved_value, contents)152153 def test_writing_to_one_buffer_does_not_affect_another(154 self):155 resolver = self.test_resolver156157 contents = 'some contents...'158 contents2 = 'some contents2...'159160 resolver.define('abc123')161 resolver.define('abc456')162163 resolver.save('abc123', contents)164 resolver.save('abc456', contents2)165166 self.assertEqual(resolver.get('abc123'), contents)167168 def test_saving_to_a_read_only_resource_throws_an_error(169 self):170 resolver = self.test_resolver171172 buffer = io.StringIO()173 contents = 'some contents...'174175 buffer.write(contents)176177 resolver.define('abc123', buffer, read_only=True)178179180 with self.assertRaises(ResourceResolverError):181 resolver.save('abc123', contents)182183184if __name__ == '__main__': ...

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 avocado 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