'Test organisation-dependent accessibility of fields'

def testSetOrgDependentFields(self):

    auth = current.auth
    s3db = current.s3db
    settings = current.deployment_settings
    table = current.s3db.pr_person_details
    s = settings.org.get('dependent_fields', None)
    settings.org.dependent_fields = {'pr_person_details.mother_name': ['Example    Root    Org']}
    auth.s3_impersonate('admin@example.com')
    check = settings.set_org_dependent_field('pr_person_details', 'mother_name')
    self.assertTrue(check)
    self.assertTrue(table.mother_name.readable)
    self.assertTrue(table.mother_name.writable)
    auth.s3_impersonate(None)
    check = settings.set_org_dependent_field('pr_person_details', 'mother_name')
    self.assertFalse(check)
    self.assertFalse(table.mother_name.readable)
    self.assertFalse(table.mother_name.writable)
    try:
        auth.override = True
        xmlstr = '\n<s3xml>\n                <resource    name="org_organisation"    uuid="ExampleRootOrg">\n                                <data    field="name">Example    Root    Org</data>\n                </resource>\n</s3xml>'
        from lxml import etree
        tree = etree.ElementTree(etree.fromstring(xmlstr))
        resource = s3db.resource('org_organisation')
        msg = resource.import_xml(tree)
        resource = s3db.resource('org_organisation', uid='ExampleRootOrg')
        org = resource.select(None, as_rows=True)[0]
        auth.override = False
        auth.s3_impersonate('normaluser@example.com')
        check = settings.set_org_dependent_field('pr_person_details', 'mother_name')
        self.assertFalse(check)
        self.assertFalse(table.mother_name.readable)
        self.assertFalse(table.mother_name.writable)
        auth.user.organisation_id = org.id
        self.assertEqual(auth.root_org(), org.id)
        check = settings.set_org_dependent_field('pr_person_details', 'mother_name')
        self.assertTrue(check)
        self.assertTrue(table.mother_name.readable)
        self.assertTrue(table.mother_name.writable)
        settings.org.dependent_fields = None
        check = settings.set_org_dependent_field('pr_person_details', 'mother_name')
        self.assertFalse(check)
        self.assertFalse(table.mother_name.readable)
        self.assertFalse(table.mother_name.writable)
    finally:
        current.db.rollback()
        auth.s3_impersonate(None)
        if s:
            settings.org.dependent_fields = s
