I'm trying to understand FLS/CRUD permissions using a simple test. I have created a user and assigned a no-update,no-delete,no-create permission set on that. In my test I'm trying to run as this new user, but I still see that the object gets updated and the field is updateable. Am I missing something here?
Here is the code:
@isTest
public class sampletest {
static User createuser(){
String username = 'testUser';
Profile p = [SELECT Id FROM Profile WHERE Name='Standard User'];
User newuser = new User(Alias = username, Email='[email protected]',
EmailEncodingKey='UTF-8',lastname='Testing',
LanguageLocaleKey='en_US',LocaleSidKey='en_US',
ProfileId = p.Id, Country='United States',
TimeZoneSidKey='America/Los_Angeles', UserName=username
+ Datetime.now().hour() + Datetime.now().minute()
+ Datetime.now().second() +'@testorg.com');
insert newuser;
system.debug('Creating user: ' + newuser.id);
assignObjectPermission(newUser,'Lead',false,false,false);
return newuser;
}
static testmethod void method1(){
User newuser = createUser();
System.runAs(newuser){
Lead newlead = new Lead(LastName='Some', Company='XYZ');
insert newlead;
Lead lead = [Select name from Lead Limit 1];
String[] strfields = new String[] {'Company', 'FirstName'};
SobjectType objType = Lead.getSobjectType();
Map<String, Schema.SObjectField> fields = objType.getDescribe().fields.getMap();
system.debug('Fields: ' + fields );
for (String strfield : strfields) {
if(fields.get(strfield).getDescribe().isUpdateable()){
system.debug('Field ' + strfield + ' is updateable');
}
}
upsert lead;
}
}
private static void assignObjectPermission(User u, String objectType, Boolean create, Boolean edit, Boolean remove){
PermissionSet ps = new PermissionSet(Name = 'Enable' + objectType, Label = 'Enable ' + objectType);
insert ps;
ObjectPermissions oPerm = new ObjectPermissions(ParentId = ps.Id,
PermissionsRead = true,
PermissionsCreate = create,
PermissionsEdit = edit,
PermissionsDelete = remove,
SObjectType = objectType);
insert oPerm;
system.debug('permission: ' + oPerm);
PermissionSetAssignment assign = new PermissionSetAssignment(AssigneeId = u.Id, PermissionSetId = ps.Id);
insert assign;
system.debug('assign: ' + assign);
}
}
I see the following logs and upsert is successful:
20:20:46:838 USER_DEBUG [34]|DEBUG|Field FirstName is updateable
20:20:46:838 USER_DEBUG [34]|DEBUG|Field Company is updateable