Best Python code snippet using tempest_python
test_authorizers.py
Source:test_authorizers.py
...58 # create user59 auth.add_user(USER, PASSWD, HOME)60 auth.add_anonymous(HOME)61 # check credentials62 auth.validate_authentication(USER, PASSWD, None)63 self.assertRaises(AuthenticationFailed,64 auth.validate_authentication, USER, 'wrongpwd', None)65 auth.validate_authentication('anonymous', 'foo', None)66 auth.validate_authentication('anonymous', '', None) # empty passwd67 # remove them68 auth.remove_user(USER)69 auth.remove_user('anonymous')70 # raise exc if user does not exists71 self.assertRaises(KeyError, auth.remove_user, USER)72 # raise exc if path does not exist73 self.assertRaisesRegex(ValueError,74 'no such directory',75 auth.add_user, USER, PASSWD, '?:\\')76 self.assertRaisesRegex(ValueError,77 'no such directory',78 auth.add_anonymous, '?:\\')79 # raise exc if user already exists80 auth.add_user(USER, PASSWD, HOME)81 auth.add_anonymous(HOME)82 self.assertRaisesRegex(ValueError,83 'user %r already exists' % USER,84 auth.add_user, USER, PASSWD, HOME)85 self.assertRaisesRegex(ValueError,86 "user 'anonymous' already exists",87 auth.add_anonymous, HOME)88 auth.remove_user(USER)89 auth.remove_user('anonymous')90 # raise on wrong permission91 self.assertRaisesRegex(ValueError,92 "no such permission",93 auth.add_user, USER, PASSWD, HOME, perm='?')94 self.assertRaisesRegex(ValueError,95 "no such permission",96 auth.add_anonymous, HOME, perm='?')97 # expect warning on write permissions assigned to anonymous user98 for x in "adfmw":99 self.assertRaisesRegex(100 RuntimeWarning,101 "write permissions assigned to anonymous user.",102 auth.add_anonymous, HOME, perm=x)103 def test_override_perm_interface(self):104 auth = DummyAuthorizer()105 auth.add_user(USER, PASSWD, HOME, perm='elr')106 # raise exc if user does not exists107 self.assertRaises(KeyError, auth.override_perm, USER + 'w',108 HOME, 'elr')109 # raise exc if path does not exist or it's not a directory110 self.assertRaisesRegex(ValueError,111 'no such directory',112 auth.override_perm, USER, '?:\\', 'elr')113 self.assertRaisesRegex(ValueError,114 'no such directory',115 auth.override_perm, USER, self.tempfile, 'elr')116 # raise on wrong permission117 self.assertRaisesRegex(ValueError,118 "no such permission", auth.override_perm,119 USER, HOME, perm='?')120 # expect warning on write permissions assigned to anonymous user121 auth.add_anonymous(HOME)122 for p in "adfmw":123 self.assertRaisesRegex(124 RuntimeWarning,125 "write permissions assigned to anonymous user.",126 auth.override_perm, 'anonymous', HOME, p)127 # raise on attempt to override home directory permissions128 self.assertRaisesRegex(ValueError,129 "can't override home directory permissions",130 auth.override_perm, USER, HOME, perm='w')131 # raise on attempt to override a path escaping home directory132 if os.path.dirname(HOME) != HOME:133 self.assertRaisesRegex(ValueError,134 "path escapes user home directory",135 auth.override_perm, USER,136 os.path.dirname(HOME), perm='w')137 # try to re-set an overridden permission138 auth.override_perm(USER, self.tempdir, perm='w')139 auth.override_perm(USER, self.tempdir, perm='wr')140 def test_override_perm_recursive_paths(self):141 auth = DummyAuthorizer()142 auth.add_user(USER, PASSWD, HOME, perm='elr')143 self.assertEqual(auth.has_perm(USER, 'w', self.tempdir), False)144 auth.override_perm(USER, self.tempdir, perm='w', recursive=True)145 self.assertEqual(auth.has_perm(USER, 'w', HOME), False)146 self.assertEqual(auth.has_perm(USER, 'w', self.tempdir), True)147 self.assertEqual(auth.has_perm(USER, 'w', self.tempfile), True)148 self.assertEqual(auth.has_perm(USER, 'w', self.subtempdir), True)149 self.assertEqual(auth.has_perm(USER, 'w', self.subtempfile), True)150 self.assertEqual(auth.has_perm(USER, 'w', HOME + '@'), False)151 self.assertEqual(auth.has_perm(USER, 'w', self.tempdir + '@'), False)152 path = os.path.join(self.tempdir + '@',153 os.path.basename(self.tempfile))154 self.assertEqual(auth.has_perm(USER, 'w', path), False)155 # test case-sensitiveness156 if (os.name in ('nt', 'ce')) or (sys.platform == 'cygwin'):157 self.assertTrue(auth.has_perm(USER, 'w', self.tempdir.upper()))158 def test_override_perm_not_recursive_paths(self):159 auth = DummyAuthorizer()160 auth.add_user(USER, PASSWD, HOME, perm='elr')161 self.assertEqual(auth.has_perm(USER, 'w', self.tempdir), False)162 auth.override_perm(USER, self.tempdir, perm='w')163 self.assertEqual(auth.has_perm(USER, 'w', HOME), False)164 self.assertEqual(auth.has_perm(USER, 'w', self.tempdir), True)165 self.assertEqual(auth.has_perm(USER, 'w', self.tempfile), True)166 self.assertEqual(auth.has_perm(USER, 'w', self.subtempdir), False)167 self.assertEqual(auth.has_perm(USER, 'w', self.subtempfile), False)168 self.assertEqual(auth.has_perm(USER, 'w', HOME + '@'), False)169 self.assertEqual(auth.has_perm(USER, 'w', self.tempdir + '@'), False)170 path = os.path.join(self.tempdir + '@',171 os.path.basename(self.tempfile))172 self.assertEqual(auth.has_perm(USER, 'w', path), False)173 # test case-sensitiveness174 if (os.name in ('nt', 'ce')) or (sys.platform == 'cygwin'):175 self.assertEqual(auth.has_perm(USER, 'w', self.tempdir.upper()),176 True)177class _SharedAuthorizerTests(object):178 """Tests valid for both UnixAuthorizer and WindowsAuthorizer for179 those parts which share the same API.180 """181 authorizer_class = None182 # --- utils183 def get_users(self):184 return self.authorizer_class._get_system_users()185 def get_current_user(self):186 if POSIX:187 return pwd.getpwuid(os.getuid()).pw_name188 else:189 return os.environ['USERNAME']190 def get_current_user_homedir(self):191 if POSIX:192 return pwd.getpwuid(os.getuid()).pw_dir193 else:194 return os.environ['USERPROFILE']195 def get_nonexistent_user(self):196 # return a user which does not exist on the system197 users = self.get_users()198 letters = string.ascii_lowercase199 while True:200 user = ''.join([random.choice(letters) for i in range(10)])201 if user not in users:202 return user203 def assertRaisesWithMsg(self, excClass, msg, callableObj, *args, **kwargs):204 try:205 callableObj(*args, **kwargs)206 except excClass as err:207 if str(err) == msg:208 return209 raise self.failureException("%s != %s" % (str(err), msg))210 else:211 if hasattr(excClass, '__name__'):212 excName = excClass.__name__213 else:214 excName = str(excClass)215 raise self.failureException("%s not raised" % excName)216 # --- /utils217 def test_get_home_dir(self):218 auth = self.authorizer_class()219 home = auth.get_home_dir(self.get_current_user())220 self.assertTrue(isinstance(home, unicode))221 nonexistent_user = self.get_nonexistent_user()222 self.assertTrue(os.path.isdir(home))223 if auth.has_user('nobody'):224 home = auth.get_home_dir('nobody')225 self.assertRaises(AuthorizerError,226 auth.get_home_dir, nonexistent_user)227 def test_has_user(self):228 auth = self.authorizer_class()229 current_user = self.get_current_user()230 nonexistent_user = self.get_nonexistent_user()231 self.assertTrue(auth.has_user(current_user))232 self.assertFalse(auth.has_user(nonexistent_user))233 auth = self.authorizer_class(rejected_users=[current_user])234 self.assertFalse(auth.has_user(current_user))235 def test_validate_authentication(self):236 # can't test for actual success in case of valid authentication237 # here as we don't have the user password238 if self.authorizer_class.__name__ == 'UnixAuthorizer':239 auth = self.authorizer_class(require_valid_shell=False)240 else:241 auth = self.authorizer_class()242 current_user = self.get_current_user()243 nonexistent_user = self.get_nonexistent_user()244 self.assertRaises(245 AuthenticationFailed,246 auth.validate_authentication, current_user, 'wrongpasswd', None)247 self.assertRaises(248 AuthenticationFailed,249 auth.validate_authentication, nonexistent_user, 'bar', None)250 def test_impersonate_user(self):251 auth = self.authorizer_class()252 nonexistent_user = self.get_nonexistent_user()253 try:254 if self.authorizer_class.__name__ == 'UnixAuthorizer':255 auth.impersonate_user(self.get_current_user(), '')256 self.assertRaises(257 AuthorizerError,258 auth.impersonate_user, nonexistent_user, 'pwd')259 else:260 self.assertRaises(261 Win32ExtError,262 auth.impersonate_user, nonexistent_user, 'pwd')263 self.assertRaises(264 Win32ExtError,265 auth.impersonate_user, self.get_current_user(), '')266 finally:267 auth.terminate_impersonation('')268 def test_terminate_impersonation(self):269 auth = self.authorizer_class()270 auth.terminate_impersonation('')271 auth.terminate_impersonation('')272 def test_get_perms(self):273 auth = self.authorizer_class(global_perm='elr')274 self.assertTrue('r' in auth.get_perms(self.get_current_user()))275 self.assertFalse('w' in auth.get_perms(self.get_current_user()))276 def test_has_perm(self):277 auth = self.authorizer_class(global_perm='elr')278 self.assertTrue(auth.has_perm(self.get_current_user(), 'r'))279 self.assertFalse(auth.has_perm(self.get_current_user(), 'w'))280 def test_messages(self):281 auth = self.authorizer_class(msg_login="login", msg_quit="quit")282 self.assertTrue(auth.get_msg_login, "login")283 self.assertTrue(auth.get_msg_quit, "quit")284 def test_error_options(self):285 wrong_user = self.get_nonexistent_user()286 self.assertRaisesWithMsg(287 AuthorizerError,288 "rejected_users and allowed_users options are mutually exclusive",289 self.authorizer_class, allowed_users=['foo'],290 rejected_users=['bar'])291 self.assertRaisesWithMsg(292 AuthorizerError,293 'invalid username "anonymous"',294 self.authorizer_class, allowed_users=['anonymous'])295 self.assertRaisesWithMsg(296 AuthorizerError,297 'invalid username "anonymous"',298 self.authorizer_class, rejected_users=['anonymous'])299 self.assertRaisesWithMsg(300 AuthorizerError,301 'unknown user %s' % wrong_user,302 self.authorizer_class, allowed_users=[wrong_user])303 self.assertRaisesWithMsg(AuthorizerError,304 'unknown user %s' % wrong_user,305 self.authorizer_class,306 rejected_users=[wrong_user])307 def test_override_user_password(self):308 auth = self.authorizer_class()309 user = self.get_current_user()310 auth.override_user(user, password='foo')311 auth.validate_authentication(user, 'foo', None)312 self.assertRaises(AuthenticationFailed(auth.validate_authentication,313 user, 'bar', None))314 # make sure other settings keep using default values315 self.assertEqual(auth.get_home_dir(user),316 self.get_current_user_homedir())317 self.assertEqual(auth.get_perms(user), "elradfmwMT")318 self.assertEqual(auth.get_msg_login(user), "Login successful.")319 self.assertEqual(auth.get_msg_quit(user), "Goodbye.")320 def test_override_user_homedir(self):321 auth = self.authorizer_class()322 user = self.get_current_user()323 dir = os.path.dirname(getcwdu())324 auth.override_user(user, homedir=dir)325 self.assertEqual(auth.get_home_dir(user), dir)326 # make sure other settings keep using default values327 # self.assertEqual(auth.get_home_dir(user),328 # self.get_current_user_homedir())329 self.assertEqual(auth.get_perms(user), "elradfmwMT")330 self.assertEqual(auth.get_msg_login(user), "Login successful.")331 self.assertEqual(auth.get_msg_quit(user), "Goodbye.")332 def test_override_user_perm(self):333 auth = self.authorizer_class()334 user = self.get_current_user()335 auth.override_user(user, perm="elr")336 self.assertEqual(auth.get_perms(user), "elr")337 # make sure other settings keep using default values338 self.assertEqual(auth.get_home_dir(user),339 self.get_current_user_homedir())340 # self.assertEqual(auth.get_perms(user), "elradfmwMT")341 self.assertEqual(auth.get_msg_login(user), "Login successful.")342 self.assertEqual(auth.get_msg_quit(user), "Goodbye.")343 def test_override_user_msg_login_quit(self):344 auth = self.authorizer_class()345 user = self.get_current_user()346 auth.override_user(user, msg_login="foo", msg_quit="bar")347 self.assertEqual(auth.get_msg_login(user), "foo")348 self.assertEqual(auth.get_msg_quit(user), "bar")349 # make sure other settings keep using default values350 self.assertEqual(auth.get_home_dir(user),351 self.get_current_user_homedir())352 self.assertEqual(auth.get_perms(user), "elradfmwMT")353 # self.assertEqual(auth.get_msg_login(user), "Login successful.")354 # self.assertEqual(auth.get_msg_quit(user), "Goodbye.")355 def test_override_user_errors(self):356 if self.authorizer_class.__name__ == 'UnixAuthorizer':357 auth = self.authorizer_class(require_valid_shell=False)358 else:359 auth = self.authorizer_class()360 this_user = self.get_current_user()361 for x in self.get_users():362 if x != this_user:363 another_user = x364 break365 nonexistent_user = self.get_nonexistent_user()366 self.assertRaisesWithMsg(367 AuthorizerError,368 "at least one keyword argument must be specified",369 auth.override_user, this_user)370 self.assertRaisesWithMsg(AuthorizerError,371 'no such user %s' % nonexistent_user,372 auth.override_user, nonexistent_user,373 perm='r')374 if self.authorizer_class.__name__ == 'UnixAuthorizer':375 auth = self.authorizer_class(allowed_users=[this_user],376 require_valid_shell=False)377 else:378 auth = self.authorizer_class(allowed_users=[this_user])379 auth.override_user(this_user, perm='r')380 self.assertRaisesWithMsg(AuthorizerError,381 '%s is not an allowed user' % another_user,382 auth.override_user, another_user, perm='r')383 if self.authorizer_class.__name__ == 'UnixAuthorizer':384 auth = self.authorizer_class(rejected_users=[this_user],385 require_valid_shell=False)386 else:387 auth = self.authorizer_class(rejected_users=[this_user])388 auth.override_user(another_user, perm='r')389 self.assertRaisesWithMsg(AuthorizerError,390 '%s is not an allowed user' % this_user,391 auth.override_user, this_user, perm='r')392 self.assertRaisesWithMsg(AuthorizerError,393 "can't assign password to anonymous user",394 auth.override_user, "anonymous",395 password='foo')396# =====================================================================397# --- UNIX authorizer398# =====================================================================399@unittest.skipUnless(POSIX, "UNIX only")400@unittest.skipUnless(UnixAuthorizer is not None,401 "UnixAuthorizer class not available")402class TestUnixAuthorizer(_SharedAuthorizerTests, TestCase):403 """Unix authorizer specific tests."""404 authorizer_class = UnixAuthorizer405 def setUp(self):406 try:407 UnixAuthorizer()408 except AuthorizerError: # not root409 self.skipTest("need root access")410 def test_get_perms_anonymous(self):411 auth = UnixAuthorizer(412 global_perm='elr', anonymous_user=self.get_current_user())413 self.assertTrue('e' in auth.get_perms('anonymous'))414 self.assertFalse('w' in auth.get_perms('anonymous'))415 warnings.filterwarnings("ignore")416 auth.override_user('anonymous', perm='w')417 warnings.resetwarnings()418 self.assertTrue('w' in auth.get_perms('anonymous'))419 def test_has_perm_anonymous(self):420 auth = UnixAuthorizer(421 global_perm='elr', anonymous_user=self.get_current_user())422 self.assertTrue(auth.has_perm(self.get_current_user(), 'r'))423 self.assertFalse(auth.has_perm(self.get_current_user(), 'w'))424 self.assertTrue(auth.has_perm('anonymous', 'e'))425 self.assertFalse(auth.has_perm('anonymous', 'w'))426 warnings.filterwarnings("ignore")427 auth.override_user('anonymous', perm='w')428 warnings.resetwarnings()429 self.assertTrue(auth.has_perm('anonymous', 'w'))430 def test_validate_authentication(self):431 # we can only test for invalid credentials432 auth = UnixAuthorizer(require_valid_shell=False)433 self.assertRaises(AuthenticationFailed,434 auth.validate_authentication, '?!foo', '?!foo', None)435 auth = UnixAuthorizer(require_valid_shell=True)436 self.assertRaises(AuthenticationFailed,437 auth.validate_authentication, '?!foo', '?!foo', None)438 def test_validate_authentication_anonymous(self):439 current_user = self.get_current_user()440 auth = UnixAuthorizer(anonymous_user=current_user,441 require_valid_shell=False)442 self.assertRaises(AuthenticationFailed,443 auth.validate_authentication, 'foo', 'passwd', None)444 self.assertRaises(445 AuthenticationFailed,446 auth.validate_authentication, current_user, 'passwd', None)447 auth.validate_authentication('anonymous', 'passwd', None)448 def test_require_valid_shell(self):449 def get_fake_shell_user():450 for user in self.get_users():451 shell = pwd.getpwnam(user).pw_shell452 # On linux fake shell is usually /bin/false, on453 # freebsd /usr/sbin/nologin; in case of other454 # UNIX variants test needs to be adjusted.455 if '/false' in shell or '/nologin' in shell:456 return user457 self.fail("no user found")458 user = get_fake_shell_user()459 self.assertRaisesWithMsg(460 AuthorizerError,461 "user %s has not a valid shell" % user,...
tests.py
Source:tests.py
...60 menu.name = MENU_TEST_DATA['name']61 menu.price = MENU_TEST_DATA['price']62 menu.save()63 self.menu = menu64 def validate_authentication(self):65 request = self.create_request(data={}, __auth=False)66 response = self.view(request)67 self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED, response.data)68 def test_list(self):69 self.create_menu()70 self.method_test = self.factory.get71 self.url_test_request = '/api/menus/'72 self.view = MenuViewSet.as_view({'get': 'list'})73 data = {}74 # Validate authentication75 self.validate_authentication()76 # Validate Gett all data77 response = self.complete_response_request(data=data)78 self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)79 self.assertEqual(len(response.data), 1)80 def test_retrieve(self):81 self.create_menu()82 self.method_test = self.factory.get83 self.url_test_request = '/api/menus/'84 self.view = MenuViewSet.as_view({'get': 'retrieve'})85 data = {}86 # Validate authentication87 self.validate_authentication()88 # Pk is not present89 response = self.complete_response_request(data=data, pk=None)90 self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.data)91 # Validate item not found92 response = self.complete_response_request(data=data, pk=123456)93 self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND, response.data)94 # Validate retrieve item data95 response = self.complete_response_request(data=data, pk=self.menu.id)96 self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)97 self.assertEqual(response.data['data']['name'], self.menu.name, response.data)98 def test_create(self):99 self.method_test = self.factory.post100 self.url_test_request = '/api/menus/'101 self.view = MenuViewSet.as_view({'post': 'create'})102 data = {103 "name": "Menu test data 2",104 "price": 15105 }106 response = self.complete_response_request(data=data)107 self.assertEqual(response.status_code, status.HTTP_201_CREATED, response.data)108 def test_update(self):109 self.create_menu()110 self.method_test = self.factory.put111 self.url_test_request = '/api/menus/'112 self.view = MenuViewSet.as_view({'put': 'update'})113 data = {114 "name": "Menu test data Actualizado",115 "price": 30116 }117 # Validate authentication118 self.validate_authentication()119 # Pk is not present120 response = self.complete_response_request(data=data, pk=None)121 self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.data)122 # Validate item not found123 response = self.complete_response_request(data=data, pk=123456)124 self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND, response.data)125 # Validate update data126 response = self.complete_response_request(data=data, pk=self.menu.id)127 self.assertEqual(response.status_code, status.HTTP_200_OK, response.data)128 def test_destroy(self):129 self.create_menu()130 self.method_test = self.factory.delete131 self.url_test_request = '/api/menus/'132 self.view = MenuViewSet.as_view({'delete': 'destroy'})133 data = {}134 # Validate authentication135 self.validate_authentication()136 # Pk is not present137 response = self.complete_response_request(data=data, pk=None)138 self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.data)139 # Validate item not found140 response = self.complete_response_request(data=data, pk=123456)141 self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND, response.data)142 # Validate delete data143 response = self.complete_response_request(data=data, pk=self.menu.id)...
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!