Best Python code snippet using localstack_python
decorators.py
Source:decorators.py
...18 return http.JsonResponse(data)19 else:20 return shortcuts.redirect(urlresolvers.reverse(utils.SECURITY_USER_URL_REVERSE))21def required_request_is_ajax(function=None):22 def _decorator(view_func):23 def _view(request, *args, **kwargs):24 if request.is_ajax():25 return view_func(request, *args, **kwargs)26 return shortcuts.redirect(urlresolvers.reverse(utils.SECURITY_USER_URL_REVERSE))27 return _view28 if function is None:29 return _decorator30 else:31 return _decorator(function)32def required_security_user(function=None, security_from_module=''):33 def _decorator(view_func):34 def _view(request, *args, **kwargs):35 if request.SECURITY_USER is not None:36 return view_func(request, *args, **kwargs)37 return jsonresponse_not_permission(request=request, security_from_module=security_from_module)38 return _view39 if function is None:40 return _decorator41 else:42 return _decorator(function)43def required_security_user_has_permission(function=None, security_from_module='', set_identifier___to_verify=set()):44 def _decorator(view_func):45 @required_security_user(security_from_module=security_from_module)46 def _view(request, *args, **kwargs):47 if request.SECURITY_USER.is_superuser is True or request.SECURITY_USER.boolean___has_permission(set_identifier___to_verify=set_identifier___to_verify):48 return view_func(request, *args, **kwargs)49 return jsonresponse_not_permission(request=request, security_from_module=security_from_module)50 return _view51 if function is None:52 return _decorator53 else:54 return _decorator(function)55def required_security_user_is_localuser(function=None, security_from_module=''):56 def _decorator(view_func):57 @required_security_user()58 def _view(request, *args, **kwargs):59 if isinstance(request.SECURITY_USER, models.LOCALUser):60 return view_func(request, *args, **kwargs)61 return jsonresponse_not_permission(request=request, security_from_module=security_from_module)62 return _view63 if function is None:64 return _decorator65 else:66 return _decorator(function)67def required_security_user_is_ldapuser(function=None, security_from_module=''):68 def _decorator(view_func):69 @required_security_user()70 def _view(request, *args, **kwargs):71 if isinstance(request.SECURITY_USER, models.LDAPUser):72 return view_func(request, *args, **kwargs)73 return jsonresponse_not_permission(request=request, security_from_module=security_from_module)74 return _view75 if function is None:76 return _decorator77 else:78 return _decorator(function)79def required_security_user_is_importedldapuser(function=None, security_from_module=''):80 def _decorator(view_func):81 @required_security_user()82 def _view(request, *args, **kwargs):83 if isinstance(request.SECURITY_USER, models.ImportedLDAPUser):84 return view_func(request, *args, **kwargs)85 return jsonresponse_not_permission(request=request, security_from_module=security_from_module)86 return _view87 if function is None:88 return _decorator89 else:90 return _decorator(function)91def required_security_user_is_ldapuser_or_importedldapuser(function=None, security_from_module=''):92 def _decorator(view_func):93 @required_security_user()94 def _view(request, *args, **kwargs):95 if isinstance(request.SECURITY_USER, models.LDAPUser) or isinstance(request.SECURITY_USER, models.ImportedLDAPUser):96 return view_func(request, *args, **kwargs)97 return jsonresponse_not_permission(request=request, security_from_module=security_from_module)98 return _view99 if function is None:100 return _decorator101 else:102 return _decorator(function)103def required_ldap_connection(function=None, security_from_module=''):104 def _decorator(view_func):105 def _view(request, *args, **kwargs):106 boolean___is_there_connection = False107 connection = ldap.connection___ldap()108 try:109 # start the connection110 if connection.bind():111 boolean___is_there_connection = True112 except (Exception,):113 pass114 finally:115 # close the connection116 connection.unbind()117 if boolean___is_there_connection is False:118 data = dict()119 data['BOOLEAN_ERROR'] = True120 messages.add_message(request, messages.ERROR, _('SECURITY_MESSAGE Action not performed, connection to the LDAP could not be established.'))121 data['HTML_DIV_MODAL'] = utils.html_template_div_modal_message(request=request, security_from_module=security_from_module)122 data['HTML_DIV_MODAL_MESSAGE'] = utils.html_template_div_modal_message_message(request=request, security_from_module=security_from_module)123 return http.JsonResponse(data)124 else:125 return view_func(request, *args, **kwargs)126 return _view127 if function is None:128 return _decorator129 else:...
test_environment_decorator_test.py
Source:test_environment_decorator_test.py
1# Copyright 2018 Google Inc.2#3# This program is free software; you can redistribute it and/or modify4# it under the terms of the GNU General Public License as published by5# the Free Software Foundation; either version 2 of the License, or6# (at your option) any later version.7#8# This program is distributed in the hope that it will be useful,9# but WITHOUT ANY WARRANTY; without even the implied warranty of10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the11# GNU General Public License for more details.12#13# You should have received a copy of the GNU General Public License along14# with this program; if not, write to the Free Software Foundation, Inc.,15# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.16"""Tests TestEnvironmentDecorator."""17from __future__ import absolute_import18from __future__ import division19from __future__ import print_function20import os21import tempfile22import unittest23import numpy as np24import six25from PIL import Image26from python.tests.utils import test_environment_decorator27_OBSERVATION_SPEC = [{'name': 'RGB_INTERLEAVED', 'shape': [1, 2, 3]}]28class EnvironmentStub(object):29 def __init__(self):30 self.test_observation_spec = _OBSERVATION_SPEC31 self.test_observations = [32 {33 'RGB_INTERLEAVED':34 np.array(35 [[[255, 0, 0], [128, 0, 0], [0, 0, 255]],36 [[0, 255, 0], [128, 0, 0], [0, 255, 0]]],37 dtype=np.uint8)38 },39 {40 'RGB_INTERLEAVED':41 np.array([[[0, 255, 0], [0, 128, 0]]], dtype=np.uint8)42 },43 {44 'RGB_INTERLEAVED':45 np.array([[[0, 0, 255], [0, 0, 128]]], dtype=np.uint8)46 },47 ]48 self.test_rewards = [0, 1, 2, 3]49 self._frame_index = 050 self.last_actions = None51 self.last_steps = None52 self.events_return = None53 self.is_running_return = None54 self.action_spec_return = None55 self.reset_return = None56 def step(self, actions, steps):57 self.last_actions = actions58 self.last_steps = steps59 self._frame_index += 160 return self.test_rewards[self._frame_index - 1]61 def is_running(self):62 return self.is_running_return63 def observations(self):64 return self.test_observations[self._frame_index]65 def events(self):66 return self.events_return67 def action_spec(self):68 return self.action_spec_return69 def observation_spec(self):70 return self.test_observation_spec71 def reset(self, **_):72 self._frame_index = 073 return self.reset_return74 def num_steps(self):75 return self._frame_index76class TestEnvironmentDecoratorTest(unittest.TestCase):77 def setUp(self):78 self._env = EnvironmentStub()79 self._decorator = test_environment_decorator.TestEnvironmentDecorator(80 self._env)81 def testStepIsCalled(self):82 actions = object()83 steps = 384 self.assertEqual(85 self._decorator.step(actions, steps), self._env.test_rewards[0])86 self.assertEqual(self._env.last_actions, actions)87 self.assertEqual(self._env.last_steps, steps)88 def testAccumulatedReward(self):89 self._decorator.step(None, 1)90 self._decorator.step(None, 1)91 self.assertEqual(self._decorator.accumulated_reward(),92 np.sum(self._env.test_rewards[0:2]))93 def testResetAccumulatedReward(self):94 self._decorator.step(None, 1)95 self._decorator.reset()96 self.assertEqual(self._decorator.accumulated_reward(), 0)97 def testRewardHistory(self):98 self._decorator.step(None, 1)99 self._decorator.step(None, 1)100 six.assertCountEqual(self,101 self._decorator.reward_history(),102 self._env.test_rewards[0:2])103 def testResetRewardHistory(self):104 self._decorator.step(None, 1)105 self._decorator.reset()106 six.assertCountEqual(self, self._decorator.reward_history(), [])107 def testAccumulatedEvents(self):108 events = ['event1', 'event2', 'event3']109 self._env.events_return = events[0]110 self._decorator.reset()111 self._env.events_return = events[1]112 self._decorator.step(None, 1)113 self._env.events_return = events[2]114 self._decorator.step(None, 1)115 six.assertCountEqual(self, self._decorator.accumulated_events(), events)116 def testResetAccumulatedEvents(self):117 events = ['event1', 'event2']118 self._env.events_return = events[0]119 self._decorator.step(None, 1)120 self._env.events_return = events[1]121 self._decorator.reset()122 six.assertCountEqual(self,123 self._decorator.accumulated_events(), [events[1]])124 def testObservationDelegation(self):125 self.assertEqual(self._env.test_observations[0],126 self._decorator.observations())127 def testObservationSpecDelegation(self):128 self.assertEqual(self._env.test_observation_spec,129 self._decorator.observation_spec())130 def testNumSteps(self):131 self._decorator.reset()132 self.assertEqual(self._decorator.num_steps(), 0)133 self._decorator.step(None, None)134 self.assertEqual(self._decorator.num_steps(), 1)135 def testMethodDelegation(self):136 method_names = ['is_running', 'events', 'action_spec', 'reset']137 for name in method_names:138 result = object()139 setattr(self._env, name + '_return', result)140 self.assertEqual(getattr(self._decorator, name)(), result)141 def testSavingFrames(self):142 self._decorator.reset()143 self._decorator.step(None, 1)144 self._decorator.step(None, 1)145 temp_dir = tempfile.mkdtemp()146 self._decorator.save_frames(temp_dir)147 for index, observation in enumerate(self._env.test_observations):148 expected_image = observation['RGB_INTERLEAVED']149 image_file_name = os.path.join(temp_dir, 'frame{0}.png'.format(index))150 image = np.asarray(Image.open(image_file_name))151 self.assertTrue(np.array_equal(image, expected_image))152if __name__ == '__main__':...
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!!