'Test permission check with policy 8'

def testPolicy8(self):

    auth = current.auth
    s3db = current.s3db
    current.deployment_settings.security.policy = 8
    auth.permission = S3Permission(auth)
    user = auth.s3_user_pe_id(auth.s3_get_user_id('normaluser@example.com'))
    has_permission = auth.s3_has_permission
    c = 'org'
    f = 'permission_test'
    tablename = 'org_permission_test'
    assertTrue = self.assertTrue
    assertFalse = self.assertFalse
    auth.s3_impersonate(None)
    permitted = has_permission('read', c=c, f=f, table=tablename)
    assertFalse(permitted)
    auth.s3_impersonate('normaluser@example.com')
    permitted = has_permission('read', c=c, f=f, table=tablename)
    assertFalse(permitted)
    s3db.pr_add_affiliation(self.org[2], user, role='TestStaff')
    auth.s3_assign_role(auth.user.id, self.editor, for_pe=self.org[2])
    permitted = has_permission('read', c=c, f=f, table=tablename, record_id=self.record1)
    assertFalse(permitted)
    permitted = has_permission('read', c=c, f=f, table=tablename, record_id=self.record2)
    assertFalse(permitted)
    permitted = has_permission('read', c=c, f=f, table=tablename, record_id=self.record3)
    assertTrue(permitted)
    permitted = has_permission('update', c=c, f=f, table=tablename, record_id=self.record1)
    assertFalse(permitted)
    permitted = has_permission('update', c=c, f=f, table=tablename, record_id=self.record2)
    assertFalse(permitted)
    permitted = has_permission('update', c=c, f=f, table=tablename, record_id=self.record3)
    assertTrue(permitted)
    s3db.pr_add_affiliation(self.org[1], self.org[2], role='TestOrgUnit')
    auth.s3_delegate_role(self.reader, self.org[0], receiver=self.org[1])
    auth.s3_impersonate('normaluser@example.com')
    permitted = has_permission('read', c=c, f=f, table=tablename, record_id=self.record1)
    assertTrue(permitted)
    permitted = has_permission('read', c=c, f=f, table=tablename, record_id=self.record2)
    assertFalse(permitted)
    permitted = has_permission('read', c=c, f=f, table=tablename, record_id=self.record3)
    assertTrue(permitted)
    permitted = has_permission('update', c=c, f=f, table=tablename, record_id=self.record1)
    assertFalse(permitted)
    permitted = has_permission('update', c=c, f=f, table=tablename, record_id=self.record2)
    assertFalse(permitted)
    permitted = has_permission('update', c=c, f=f, table=tablename, record_id=self.record3)
    assertTrue(permitted)
    auth.s3_remove_delegation(self.reader, self.org[0], receiver=self.org[1])
    s3db.pr_remove_affiliation(self.org[1], self.org[2], role='TestOrgUnit')
    s3db.pr_remove_affiliation(self.org[2], user, role='TestStaff')
    auth.s3_withdraw_role(auth.user.id, self.editor, for_pe=[])
