Best Python code snippet using Airtest
permissions.py
Source:permissions.py
...109 def __init__(self, permissions):110 Permissions.check_internal_permissions(internal_permissions=permissions)111 self._permissions = permissions112 def __str__(self):113 if self.get_permissions() is None:114 return " null"115 if len(self.get_permissions()) == 0:116 return " {}"117 return_string = ''118 for action, allowed_uuids in self.get_permissions().items():119 return_string += "\n " + StrUtils.str_from(action, quoted=True) + ':' + \120 Permissions.str_from_internal_uuids(internal_uuids=allowed_uuids, sort=True).replace('\n', "\n ")121 return return_string122 def __repr__(self):123 repr_permissions = 'None'124 if self.get_permissions() is not None:125 repr_permissions = '{'126 sorted_actions = sorted(self.get_permissions().keys())127 for action_index, action in enumerate(sorted_actions):128 repr_permissions += repr(action) + ": {"129 sorted_uuids = sorted(list(self.get_permissions()[action]))130 for uuid_index, uuid in enumerate(sorted_uuids):131 repr_permissions += repr(uuid)132 if uuid_index < len(sorted_uuids) - 1:133 repr_permissions += ", "134 repr_permissions += '}'135 if action_index < len(sorted_actions) - 1:136 repr_permissions += ", "137 repr_permissions += '}'138 return f"Permissions(permissions={repr_permissions})"139 def __eq__(self, other):140 if other is None or not isinstance(other, Permissions):141 return False142 return self.get_permissions() == other.get_permissions()143 def get_permissions(self):144 return self._permissions145 def copy(self):146 if self.get_permissions() is None:147 return Permissions(permissions=None)148 copied_permissions = {}149 for action, allowed_uuids in self.get_permissions().items():150 copied_permissions[action] = allowed_uuids.copy() if allowed_uuids is not None else None151 return Permissions(permissions=copied_permissions)152 def to_dict(self):153 if self.get_permissions() is None:154 return None155 permissions_dict = {}156 for action, allowed_uuids in self.get_permissions().items():157 permissions_dict[action] = allowed_uuids158 return permissions_dict159 def is_merge_compatible_with(self, other, explanation=None):160 Permissions.check(other)161 return True162 def is_mergeable_with(self, other, overwrite=False, explanation=None):163 return self.is_merge_compatible_with(other=other, explanation=explanation)164 def merge_with(self, other, overwrite=False, sum=False):165 if not self.is_mergeable_with(other=other, overwrite=overwrite):166 raise MergeException(f"cannot merge permissions that are not mergeable; self: {self} other: {other}")167 if other is None:168 return self.copy()169 if other.get_permissions() is None:170 return self.copy()171 if self.get_permissions() is None:172 return other.copy()173 merged_permissions = {}174 for action, allowed_uuids in self.get_permissions().items():175 if action in other.get_permissions():176 merged_permissions[action] = Permissions.merge_internal_uuids(internal_uuids_a=allowed_uuids, internal_uuids_b=other.get_permissions()[action],177 overwrite=overwrite, sum=sum)178 else:179 merged_permissions[action] = allowed_uuids.copy() if allowed_uuids is not None else None180 for action, allowed_uuids in other.get_permissions().items():181 if action not in self.get_permissions():182 merged_permissions[action] = allowed_uuids.copy() if allowed_uuids is not None else None183 return Permissions(permissions=merged_permissions)184 def is_allowed(self, action, request_uuids=set(), explanation=None):185 Permissions.check_internal_uuids(internal_uuids=request_uuids)186 if action is not None and not Action.is_valid_action(action=action):187 raise Exception(f"action {action} is invalid")188 if self.get_permissions() is None or action is None or request_uuids is None:189 return True190 if action not in self.get_permissions():191 Explanation.dynamic_add_message(explanation=explanation, message=f"Permissions.is_allowed(...): action {action} not contained")192 return False193 if self.get_permissions()[action] is None:194 return True195 if len(self.get_permissions()[action] & request_uuids) == 0:196 Explanation.dynamic_add_message(explanation=explanation,197 message="Permissions.is_allowed(...): "198 f"none of requested uuids {request_uuids} in allowed uuids {self.get_permissions()[action]}")199 return False200 return True201 def is_subset(self, other):202 Permissions.check(permissions=other)203 if other is None or other.get_permissions() is None:204 return True205 if self.get_permissions() is None:206 return False207 for action, allowed_uuids in self.get_permissions().items():208 if action not in other.get_permissions():209 return False210 if other.get_permissions()[action] is not None:211 if allowed_uuids is None:212 return False213 if not allowed_uuids.issubset(other.get_permissions()[action]):214 return False...
defaults.py
Source:defaults.py
...40 return list(41 Permission.objects.filter(content_type__app_label=app_label, content_type__model=model).values_list('id',42 flat=True))43 @classmethod44 def get_permissions(cls, app_label, model_name, codename_list):45 """ Returns list od permission ids of provided code names """46 return list(Permission.objects.filter(content_type__app_label=app_label, content_type__model=model_name,47 codename__in=codename_list).values_list('id', flat=True))48 @classmethod49 def __init__(cls):50 """ Providing values for class variables """51 if cls.access_specifiers is None:52 cls.access_specifiers = {53 # Users54 "add#users": [55 cls.get_permissions(app_label='users', model_name='qmuser',56 codename_list=['add_qmuser']57 )58 ],59 "view#users": [60 cls.get_permissions(app_label='users', model_name='qmuser',61 codename_list=['view_qmuser']62 )63 ],64 "edit#users": [65 cls.get_permissions(app_label='users', model_name='qmuser',66 codename_list=['change_qmuser'])67 ],68 "delete#users": [69 cls.get_permissions(app_label='users', model_name='qmuser',70 codename_list=['delete_qmuser'])71 ],72 # Roles73 "add#roles": [74 cls.get_permissions(app_label='auth', model_name='group',75 codename_list=['add_group']76 ),77 cls.get_permissions(app_label='users', model_name='roles',78 codename_list=['add_roles']79 )80 ],81 "view#roles": [82 cls.get_permissions(app_label='auth', model_name='group',83 codename_list=['view_group']84 ),85 cls.get_permissions(app_label='users', model_name='roles',86 codename_list=['view_roles']87 )88 ],89 "edit#roles": [90 cls.get_permissions(app_label='auth', model_name='group',91 codename_list=['change_group']),92 cls.get_permissions(app_label='users', model_name='roles',93 codename_list=['change_roles'])94 ],95 "delete#roles": [96 cls.get_permissions(app_label='auth', model_name='group',97 codename_list=['delete_group']),98 cls.get_permissions(app_label='users', model_name='roles',99 codename_list=['delete_roles'])100 ]...
utils.py
Source:utils.py
1from django.contrib.auth.models import Permission, Group2from django.contrib.contenttypes.models import ContentType3from django.db.models import Q4def get_permissions(model, permissions):5 """Obtener permisos apartir de modelo y los diferentes permisos que hay en el sistema"""6 perm_q = Q()7 for perm in permissions:8 perm_q |= Q(codename=perm + '_' + model)9 return Permission.objects.filter(perm_q)10def create_special_permissions():11 """Crear los permisos por defecto en el sistema (Permisos extra para los Vales de Solicitud y Movimiento)"""12 # Getting Content Type13 request_ticket_content_type = ContentType.objects.get(app_label='system', model='requestticket')14 movement_ticket_content_type = ContentType.objects.get(app_label='system', model='movementticket')15 # Creating permissions16 own_request_ticket, _ = Permission.objects.get_or_create(codename='own_requestticket',17 name='Can only view own Vale de Solicitud',18 content_type=request_ticket_content_type)19 own_movement_ticket, _ = Permission.objects.get_or_create(codename='own_movementticket',20 name='Can only view own Vale de Movimiento',21 content_type=movement_ticket_content_type)22 return own_request_ticket, own_movement_ticket23def create_default_groups():24 """Crear los grupos de permisos por defecto (Administrador, Jefe de Departamento, Vicedecano)"""25 if Group.objects.filter(26 Q(name='Administrador') | Q(name='Jefe de Departamento') | Q(name='Vicedecano')).count() < 3:27 # Creo el grupo y le asigno los permisos correspondientes28 # Administrador29 admin, created = Group.objects.get_or_create(name='Administrador')30 if created:31 perm = ['view', 'add', 'change', 'delete']32 admin.permissions.set(get_permissions('user', perm) | get_permissions('group', perm))33 admin.save()34 # Jefe de Departamento35 jefe, created = Group.objects.get_or_create(name='Jefe de Departamento')36 if created:37 # Extract special permissions38 own_request_ticket, own_movement_ticket = create_special_permissions()39 perm = ['view', 'add', 'change', 'delete', 'own']40 jefe.permissions.set(get_permissions('basicmediumexpedient', ['view']) |41 get_permissions('movementticket', perm) | get_permissions('requestticket', perm))42 jefe.permissions.add(own_request_ticket)43 jefe.permissions.add(own_movement_ticket)44 jefe.save()45 # Vicedecano46 vicedecano, created = Group.objects.get_or_create(name='Vicedecano')47 if created:48 perm = ['view', 'add', 'change', 'delete']49 vicedecano.permissions.set(get_permissions('basicmediumexpedient', perm) |50 get_permissions('movementticket', perm) |51 get_permissions('requestticket', perm) |52 get_permissions('responsibilitycertificate', perm))...
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!!