def setUpTestData(cls):
        batch_num = 0
        section_num = 0
        voter_num = 0
        party_num = 0
        position_num = 0
        candidate_num = 0
        num_elections = 2
        voters = list()
        positions = dict()
        for i in range(num_elections):
            election = Election.objects.create(name='Election {}'.format(i))
            positions[str(election.name)] = list()

            num_batches = 2
            for j in range(num_batches):
                batch = Batch.objects.create(year=batch_num, election=election)
                batch_num += 1

                num_sections = 2 if j == 0 else 1
                for k in range(num_sections):
                    section = Section.objects.create(
                        section_name=str(section_num)
                    )
                    section_num += 1

                    num_students = 2
                    for l in range(num_students):
                        voter = User.objects.create(
                            username='user{}'.format(voter_num),
                            first_name=str(voter_num),
                            last_name=str(voter_num),
                            type=UserType.VOTER
                        )
                        voter.set_password('voter')
                        voter.save()
                        voter_num += 1

                        VoterProfile.objects.create(
                            user=voter,
                            batch=batch,
                            section=section
                        )

                        voters.append(voter)

            num_positions = 3
            for i in range(num_positions):
                position = CandidatePosition.objects.create(
                    position_name='Position {}'.format(position_num),
                    election=election
                )

                positions[str(election.name)].append(position)

                position_num += 1

            num_parties = 3
            for j in range(num_parties):
                party = CandidateParty.objects.create(
                    party_name='Party {}'.format(party_num),
                    election=election
                )
                party_num += 1

                if j != 2:  # Let every third party have no candidates.
                    num_positions = 3
                    for k in range(num_positions):
                        position = positions[str(election.name)][k]

                        candidate = Candidate.objects.create(
                            user=voters[candidate_num],
                            party=party,
                            position=position,
                            election=election
                        )

                        Vote.objects.create(
                            user=voters[candidate_num],
                            candidate=candidate,
                            election=election
                        )

                        candidate_num += 1

        # Let's give one candidate an additional vote to really make sure that
        # we all got the correct number of votes.
        Vote.objects.create(
            user=voters[0],
            # NOTE: The voter in voter[1] is a Position 1 candidate of
            #       Party 1, where the voter in voter[0] is a member.
            candidate=Candidate.objects.get(user=voters[1]),
            election=Election.objects.get(name='Election 0')
        )

        _admin = User.objects.create(username='admin', type=UserType.ADMIN)
        _admin.set_password('root')
        _admin.save()
def testProvenanceFolder(self):
        """
        Test folder provenance, including turning off and on the provenance
        handling of folders.
        """
        folder1 = self.folder1
        user = self.admin

        # check that the first version of the folder provenance exists
        self._checkProvenance(None, folder1, 1, user, 'creation',
                              resource='folder')
        # Edit the folder and check again
        params1 = {'name': 'Renamed folder', 'description': 'New description'}
        resp = self.request(path='/folder/%s' % folder1['_id'],
                            method='PUT', user=user, params=params1)
        self.assertStatusOk(resp)
        params1['lowerName'] = params1['name'].lower()
        self._checkProvenance(None, folder1, 2, user, 'update',
                              {'new': params1}, resource='folder')

        # Turn off folder provenance and make sure asking for it fails
        self.model('setting').set(
            constants.PluginSettings.PROVENANCE_RESOURCES, 'setting')
        resp = self._getProvenance(folder1, user, resource='folder',
                                   checkOk=False)
        self.assertStatus(resp, 400)
        # While folder provenance is off, create a second folder and edit the
        # first folder
        params2 = {'name': 'Renamed Again', 'description': 'Description 2'}
        resp = self.request(path='/folder/%s' % folder1['_id'],
                            method='PUT', user=user, params=params2)
        self.assertStatusOk(resp)
        params2['lowerName'] = params2['name'].lower()

        folder2 = {
            'parent': self.coll1,
            'parentType': 'collection',
            'name': 'Private test folder',
            'creator': self.admin
        }
        folder2 = self.model('folder').createFolder(**folder2)
        # Turn back on folder provenance and check that it didn't record the
        # changes we made.
        self.model('setting').set(
            constants.PluginSettings.PROVENANCE_RESOURCES, 'folder,setting')
        self._checkProvenance(None, folder1, 2, user, 'update',
                              {'new': params1}, resource='folder')
        # Changing folder1 again should now show this change, and the old value
        # should show the gap in the data
        params3 = {'name': 'Renamed C', 'description': 'Description 3'}
        resp = self.request(path='/folder/%s' % folder1['_id'],
                            method='PUT', user=user, params=params3)
        self.assertStatusOk(resp)
        params3['lowerName'] = params3['name'].lower()
        self._checkProvenance(None, folder1, 3, user, 'update',
                              {'old': params2, 'new': params3},
                              resource='folder')
        # The new folder should have no provenance
        resp = self._getProvenance(folder2, user, resource='folder')
        self.assertEqual(resp.json['resourceId'], str(folder2['_id']))
        self.assertIsNone(resp.json['provenance'])
        # Edit the new folder; it should show the unknown history followed by
        # the edit
        params4 = {'description': 'Folder 2 Description'}
        resp = self.request(path='/folder/%s' % folder2['_id'],
                            method='PUT', user=user, params=params4)
        self.assertStatusOk(resp)
        resp = self._getProvenance(folder2, user, 1, resource='folder')
        self._checkProvenance(resp, folder2, 1, user, 'unknownHistory',
                              resource='folder')
        self._checkProvenance(None, folder2, 2, user, 'update',
                              {'new': params4}, resource='folder')
        # We should also see the initial history using negative indexing
        resp = self._getProvenance(folder2, user, -2, resource='folder')
        self._checkProvenance(resp, folder2, 1, user, 'unknownHistory',
                              resource='folder')
        # We should be able to get the entire history using 'all'
        resp = self._getProvenance(folder2, user, 'all', resource='folder')
        self.assertEqual(resp.json['resourceId'], str(folder2['_id']))
        self.assertEqual(len(resp.json['provenance']), 2)
        self.assertEqual(resp.json['provenance'][0]['eventType'],
                         'unknownHistory')
        self.assertEqual(resp.json['provenance'][1]['eventType'], 'update')
        # We should get an error if we ask for a nonsense version
        resp = self._getProvenance(folder2, user, 'not_a_version',
                                   resource='folder', checkOk=False)
        self.assertStatus(resp, 400)