'Test merge of link table entries'

def testMergeLinkTable(self):

    assertEqual = self.assertEqual
    assertNotEqual = self.assertNotEqual
    assertTrue = self.assertTrue
    assertFalse = self.assertFalse
    db = current.db
    s3db = current.s3db
    deployment_settings = current.deployment_settings
    (org1, org2) = self.get_records()
    org1_pe_id = s3db.pr_get_pe_id(org1)
    org2_pe_id = s3db.pr_get_pe_id(org2)
    otable = s3db.org_organisation
    btable = s3db.org_organisation_branch
    branch1 = Storage(name='TestBranch1')
    branch1_id = otable.insert(**branch1)
    assertNotEqual(branch1_id, None)
    branch1.update(id=branch1_id)
    s3db.update_super(otable, branch1)
    branch1_pe_id = s3db.pr_get_pe_id(otable, branch1_id)
    assertNotEqual(branch1_pe_id, None)
    link1 = Storage(organisation_id=self.id1, branch_id=branch1_id)
    link1_id = btable.insert(**link1)
    s3db.pr_update_affiliations(btable, link1_id)
    ancestors = s3db.pr_get_ancestors(branch1_pe_id)
    assertEqual(ancestors, [str(org1_pe_id)])
    branch2 = Storage(name='TestBranch2')
    branch2_id = otable.insert(**branch2)
    assertNotEqual(branch2_id, None)
    branch2.update(id=branch2_id)
    s3db.update_super(otable, branch2)
    branch2_pe_id = s3db.pr_get_pe_id('org_organisation', branch2_id)
    assertNotEqual(branch2_pe_id, None)
    link2 = Storage(organisation_id=self.id2, branch_id=branch2_id)
    link2_id = btable.insert(**link2)
    s3db.pr_update_affiliations(btable, link2_id)
    ancestors = s3db.pr_get_ancestors(branch2_pe_id)
    assertEqual(ancestors, [str(org2_pe_id)])
    success = self.resource.merge(self.id1, self.id2)
    assertTrue(success)
    link1 = db((btable._id == link1_id)).select(limitby=(0, 1)).first()
    link2 = db((btable._id == link2_id)).select(limitby=(0, 1)).first()
    assertEqual(str(link1.organisation_id), str(self.id1))
    assertEqual(str(link2.organisation_id), str(self.id1))
    ancestors = s3db.pr_get_ancestors(branch1_pe_id)
    assertEqual(ancestors, [str(org1_pe_id)])
    ancestors = s3db.pr_get_ancestors(branch2_pe_id)
    assertEqual(ancestors, [str(org1_pe_id)])
