Exemplo n.º 1
0
    def test_edit_plugin_directly(self):
        job_opening = self.create_default_job_opening()

        # revision 1
        content_en_1 = self.plugin_values_raw['en'].format(1)
        self.create_revision(job_opening, content=content_en_1)

        self.assertEqual(len(get_for_object(job_opening)), 1)

        # revision 2
        content_en_2 = self.plugin_values_raw['en'].format(2)
        with transaction.atomic():
            language = job_opening.get_current_language()
            plugins = job_opening.content.get_plugins().filter(
                language=language)
            plugin = plugins[0].get_plugin_instance()[0]
            plugin.body = content_en_2
            plugin.save()
            aldryn_create_revision(job_opening)
        self.assertEqual(len(get_for_object(job_opening)), 2)

        with switch_language(job_opening, 'en'):
            url = job_opening.get_absolute_url()
        response = self.client.get(url)

        self.assertContains(response, content_en_2)
        self.assertNotContains(response, content_en_1)

        self.revert_to(job_opening, 1)
        job_opening = JobOpening.objects.get(pk=job_opening.pk)
        response = self.client.get(job_opening.get_absolute_url())
        self.assertContains(response, content_en_1)
        self.assertNotContains(response, content_en_2)
Exemplo n.º 2
0
    def test_job_application_revision_is_reverted(self):
        job_opening = self.create_default_job_opening()
        application = JobApplication.objects.create(
            job_opening=job_opening, **self.application_default_values)

        # revision 1
        new_values_1 = self.make_new_values(self.application_values_raw, 1)
        self.create_revision(application, **new_values_1)
        self.assertEqual(len(get_for_object(application)), 1)

        # revision 2
        new_values_2 = self.make_new_values(self.application_values_raw, 2)
        new_opening = JobOpening.objects.create(
            category=self.default_category,
            **self.make_new_values(self.opening_values_raw['en'], 2))
        new_values_2['job_opening'] = new_opening
        self.create_revision(application, **new_values_2)
        self.assertEqual(len(get_for_object(application)), 2)

        # revert to 1
        self.revert_to(application, 1)
        application = JobApplication.objects.get(pk=application.pk)
        # add initial job_opening to values list to be checked
        new_values_1['job_opening'] = job_opening
        for prop in new_values_1.keys():
            self.assertEqual(getattr(application, prop), new_values_1[prop])
Exemplo n.º 3
0
 def testCanRevertRevisionWithDeletedVersions(self):
     self.assertEqual(ReversionTestModel1.objects.count(), 2)
     self.assertEqual(ReversionTestModel2.objects.count(), 2)
     with create_revision():
         self.test11.name = "model1 instance1 version3"
         self.test11.save()
         self.test12.delete()
         self.test21.name = "model2 instance1 version3"
         self.test21.save()
         self.test22.delete()
     self.assertEqual(ReversionTestModel1.objects.count(), 1)
     self.assertEqual(ReversionTestModel2.objects.count(), 1)
     with create_revision():
         self.test11.name = "model1 instance1 version4"
         self.test11.save()
         self.test21.name = "model2 instance1 version4"
         self.test21.save()
     self.assertEqual(ReversionTestModel1.objects.count(), 1)
     self.assertEqual(ReversionTestModel2.objects.count(), 1)
     # Revert to a revision where some deletes were logged.
     get_for_object(self.test11)[1].revision.revert()
     self.assertEqual(ReversionTestModel1.objects.count(), 1)
     self.assertEqual(ReversionTestModel2.objects.count(), 1)
     self.assertEqual(ReversionTestModel1.objects.get(id=self.test11.id).name, "model1 instance1 version3")
     self.assertEqual(ReversionTestModel2.objects.get(id=self.test21.id).name, "model2 instance1 version3")
     # Revert the a revision before the deletes were logged.
     get_for_object(self.test11)[2].revision.revert()
     self.assertEqual(ReversionTestModel1.objects.count(), 2)
     self.assertEqual(ReversionTestModel2.objects.count(), 2)
Exemplo n.º 4
0
    def test_edit_plugin_directly(self):
        job_opening = self.create_default_job_opening()

        # revision 1
        content_en_1 = self.plugin_values_raw['en'].format(1)
        self.create_revision(job_opening, content=content_en_1)

        self.assertEqual(len(get_for_object(job_opening)), 1)

        # revision 2
        content_en_2 = self.plugin_values_raw['en'].format(2)
        with transaction.atomic():
            language = job_opening.get_current_language()
            plugins = job_opening.content.get_plugins().filter(
                language=language)
            plugin = plugins[0].get_plugin_instance()[0]
            plugin.body = content_en_2
            plugin.save()
            aldryn_create_revision(job_opening)
        self.assertEqual(len(get_for_object(job_opening)), 2)

        with switch_language(job_opening, 'en'):
            url = job_opening.get_absolute_url()
        response = self.client.get(url)

        self.assertContains(response, content_en_2)
        self.assertNotContains(response, content_en_1)

        self.revert_to(job_opening, 1)
        job_opening = JobOpening.objects.get(pk=job_opening.pk)
        response = self.client.get(job_opening.get_absolute_url())
        self.assertContains(response, content_en_1)
        self.assertNotContains(response, content_en_2)
Exemplo n.º 5
0
    def test_job_application_revision_is_reverted_if_fk_obj_was_deleted(self):
        job_opening = self.create_default_job_opening()
        application = JobApplication.objects.create(
            job_opening=job_opening, **self.application_default_values)

        # revision 1
        new_values_1 = self.make_new_values(self.application_values_raw, 1)
        self.create_revision(application, **new_values_1)
        self.assertEqual(len(get_for_object(application)), 1)

        # revision 2
        new_values_2 = self.make_new_values(self.application_values_raw, 2)
        new_opening = JobOpening.objects.create(
            category=self.default_category,
            **self.make_new_values(self.opening_values_raw['en'], 2))
        new_values_2['job_opening'] = new_opening
        self.create_revision(application, **new_values_2)
        self.assertEqual(len(get_for_object(application)), 2)

        # delete initial opening
        with transaction.atomic():
            job_opening.delete()

        # revert to 1
        self.revert_to(application, 1)
        application = JobApplication.objects.get(pk=application.pk)
        self.assertEqual(JobOpening.objects.all().count(), 2)
        # get restored job opening
        job_opening = JobOpening.objects.all().exclude(pk=new_opening.pk).get()
        # add initial job_opening to values list to be checked
        new_values_1['job_opening'] = job_opening
        for prop in new_values_1.keys():
            self.assertEqual(getattr(application, prop), new_values_1[prop])
Exemplo n.º 6
0
    def test_edit_plugin_directly(self):
        content1 = 'Content 1 text'
        content2 = 'Content 2 text'

        with force_language('en'):
            event = self.create_default_event()
        # revision 1
        self.create_event_revision(event, content1)

        self.assertEqual(len(get_for_object(event)), 1)

        # revision 2
        with transaction.atomic():
            plugins = event.description.get_plugins().filter(
                language=event.get_current_language())
            plugin = plugins[0].get_plugin_instance()[0]
            plugin.body = content2
            plugin.save()
            aldryn_create_revision(event)

        self.assertEqual(len(get_for_object(event)), 2)

        response = self.client.get(event.get_absolute_url())
        self.assertContains(response, content2)
        self.assertNotContains(response, content1)

        self.revert_to(event, 1)
        event = Event.objects.get(pk=event.pk)
        response = self.client.get(event.get_absolute_url())
        self.assertContains(response, content1)
        self.assertNotContains(response, content2)
Exemplo n.º 7
0
    def test_post_revision(self, expected, updates):
        self.client.login(username="******", password="******")

        post_data = {"location": 1, "time_block": 1, "time_slot": 1}

        game = Game()
        modify_game(game)
        game.user = User.objects.get(username="******")
        game.location = Location.objects.get(id=post_data["location"])
        game.time_block = TimeBlock.objects.get(id=post_data["time_block"])
        game.time_slot = TimeSlot.objects.get(id=post_data["time_slot"])
        game.last_modified = timezone.now()
        game.save()

        post_data["id"] = game.id

        self.assertEquals(len(reversion.get_for_object(game)), 0)

        post_data.update(updates)
        self.client.post(self.url, post_data)

        versions = reversion.get_for_object(game)
        self.assertEquals(len(versions), 1)
        self.assertEquals(versions[0].revision.comment,
                          "AJAX Schedule Submission - %s Changed" % expected)
Exemplo n.º 8
0
    def test_edit_plugin_directly(self):
        content1 = 'Content 1 text'
        content2 = 'Content 2 text'

        with force_language('en'):
            event = self.create_default_event()
        # revision 1
        self.create_event_revision(event, content1)

        self.assertEqual(len(get_for_object(event)), 1)

        # revision 2
        with transaction.atomic():
            plugins = event.description.get_plugins().filter(
                language=event.get_current_language())
            plugin = plugins[0].get_plugin_instance()[0]
            plugin.body = content2
            plugin.save()
            aldryn_create_revision(event)

        self.assertEqual(len(get_for_object(event)), 2)

        response = self.client.get(event.get_absolute_url())
        self.assertContains(response, content2)
        self.assertNotContains(response, content1)

        self.revert_to(event, 1)
        event = Event.objects.get(pk=event.pk)
        response = self.client.get(event.get_absolute_url())
        self.assertContains(response, content1)
        self.assertNotContains(response, content2)
Exemplo n.º 9
0
    def test_job_application_revision_is_reverted_if_fk_obj_was_deleted(self):
        job_opening = self.create_default_job_opening()
        application = JobApplication.objects.create(
            job_opening=job_opening, **self.application_default_values)

        # revision 1
        new_values_1 = self.make_new_values(self.application_values_raw, 1)
        self.create_revision(application, **new_values_1)
        self.assertEqual(len(get_for_object(application)), 1)

        # revision 2
        new_values_2 = self.make_new_values(self.application_values_raw, 2)
        new_opening = JobOpening.objects.create(
            category=self.default_category,
            **self.make_new_values(self.opening_values_raw['en'], 2))
        new_values_2['job_opening'] = new_opening
        self.create_revision(application, **new_values_2)
        self.assertEqual(len(get_for_object(application)), 2)

        # delete initial opening
        with transaction.atomic():
            job_opening.delete()

        # revert to 1
        self.revert_to(application, 1)
        application = JobApplication.objects.get(pk=application.pk)
        self.assertEqual(JobOpening.objects.all().count(), 2)
        # get restored job opening
        job_opening = JobOpening.objects.all().exclude(pk=new_opening.pk).get()
        # add initial job_opening to values list to be checked
        new_values_1['job_opening'] = job_opening
        for prop in new_values_1.keys():
            self.assertEqual(getattr(application, prop), new_values_1[prop])
Exemplo n.º 10
0
 def testCanRevertRevisionWithDeletedVersions(self):
     self.assertEqual(ReversionTestModel1.objects.count(), 2)
     self.assertEqual(ReversionTestModel2.objects.count(), 2)
     with create_revision():
         self.test11.name = "model1 instance1 version3"
         self.test11.save()
         self.test12.delete()
         self.test21.name = "model2 instance1 version3"
         self.test21.save()
         self.test22.delete()
     self.assertEqual(ReversionTestModel1.objects.count(), 1)
     self.assertEqual(ReversionTestModel2.objects.count(), 1)
     with create_revision():
         self.test11.name = "model1 instance1 version4"
         self.test11.save()
         self.test21.name = "model2 instance1 version4"
         self.test21.save()
     self.assertEqual(ReversionTestModel1.objects.count(), 1)
     self.assertEqual(ReversionTestModel2.objects.count(), 1)
     # Revert to a revision where some deletes were logged.
     get_for_object(self.test11)[1].revision.revert()
     self.assertEqual(ReversionTestModel1.objects.count(), 1)
     self.assertEqual(ReversionTestModel2.objects.count(), 1)
     self.assertEqual(
         ReversionTestModel1.objects.get(id=self.test11.id).name,
         "model1 instance1 version3")
     self.assertEqual(
         ReversionTestModel2.objects.get(id=self.test21.id).name,
         "model2 instance1 version3")
     # Revert the a revision before the deletes were logged.
     get_for_object(self.test11)[2].revision.revert()
     self.assertEqual(ReversionTestModel1.objects.count(), 2)
     self.assertEqual(ReversionTestModel2.objects.count(), 2)
Exemplo n.º 11
0
    def test_job_application_revision_is_reverted(self):
        job_opening = self.create_default_job_opening()
        application = JobApplication.objects.create(
            job_opening=job_opening, **self.application_default_values)

        # revision 1
        new_values_1 = self.make_new_values(self.application_values_raw, 1)
        self.create_revision(application, **new_values_1)
        self.assertEqual(len(get_for_object(application)), 1)

        # revision 2
        new_values_2 = self.make_new_values(self.application_values_raw, 2)
        new_opening = JobOpening.objects.create(
            category=self.default_category,
            **self.make_new_values(self.opening_values_raw['en'], 2))
        new_values_2['job_opening'] = new_opening
        self.create_revision(application, **new_values_2)
        self.assertEqual(len(get_for_object(application)), 2)

        # revert to 1
        self.revert_to(application, 1)
        application = JobApplication.objects.get(pk=application.pk)
        # add initial job_opening to values list to be checked
        new_values_1['job_opening'] = job_opening
        for prop in new_values_1.keys():
            self.assertEqual(getattr(application, prop), new_values_1[prop])
Exemplo n.º 12
0
    def test_job_application_contains_latest_values(self):
        job_opening = self.create_default_job_opening()
        application = JobApplication.objects.create(
            job_opening=job_opening, **self.application_default_values)

        # revision 1
        new_values_1 = self.make_new_values(self.application_values_raw, 1)
        self.create_revision(application, **new_values_1)
        self.assertEqual(len(get_for_object(application)), 1)

        application = JobApplication.objects.get(pk=application.pk)
        for prop in new_values_1.keys():
            self.assertEqual(getattr(application, prop), new_values_1[prop])

        # revision 2
        new_values_2 = self.make_new_values(self.application_values_raw, 2)
        new_opening = JobOpening.objects.create(
            category=self.default_category,
            **self.make_new_values(self.opening_values_raw['en'], 2))
        new_values_2['job_opening'] = new_opening
        self.create_revision(application, **new_values_2)
        self.assertEqual(len(get_for_object(application)), 2)

        application = JobApplication.objects.get(pk=application.pk)
        for prop in new_values_2.keys():
            self.assertEqual(getattr(application, prop), new_values_2[prop])
Exemplo n.º 13
0
    def test_job_application_contains_latest_values(self):
        job_opening = self.create_default_job_opening()
        application = JobApplication.objects.create(
            job_opening=job_opening,
            **self.application_default_values)

        # revision 1
        new_values_1 = self.make_new_values(self.application_values_raw, 1)
        self.create_revision(application, **new_values_1)
        self.assertEqual(len(get_for_object(application)), 1)

        application = JobApplication.objects.get(pk=application.pk)
        for prop in new_values_1.keys():
            self.assertEqual(getattr(application, prop), new_values_1[prop])

        # revision 2
        new_values_2 = self.make_new_values(self.application_values_raw, 2)
        new_opening = JobOpening.objects.create(
            category=self.default_category,
            **self.make_new_values(self.opening_values_raw['en'], 2))
        new_values_2['job_opening'] = new_opening
        self.create_revision(application, **new_values_2)
        self.assertEqual(len(get_for_object(application)), 2)

        application = JobApplication.objects.get(pk=application.pk)
        for prop in new_values_2.keys():
            self.assertEqual(getattr(application, prop), new_values_2[prop])
Exemplo n.º 14
0
    def test_page_versions(self):
        self.client.login(username="******", password="******")
        page = Page(name="Test Name", url="test-url", content="Content goes here")
        with reversion.create_revision():
            reversion.set_comment("initial")
            page.save()

        versions = reversion.get_for_object(page)
        self.assertEquals(len(versions), 1)
        self.assertEquals(versions[0].revision.comment, "initial")

        url = reverse("admin:page_page_change", args=[page.id])
        self.client.post(url, {"name": "2nd name", "url": "test-url", "content": "New content"})
        page = Page.objects.get(id=page.id)

        self.assertEquals(page.name, "2nd name")
        self.assertEquals(page.content, "New content")

        versions = map(lambda x: x, reversion.get_for_object(page))
        self.assertEquals(len(versions), 2)
        self.assertEquals(versions[0].revision.comment, "Changed name and content.")

        actual_initial = json.loads(versions[1].serialized_data)[0]
        self.assertEquals(actual_initial["fields"]["name"], "Test Name")
        self.assertEquals(actual_initial["fields"]["url"], "test-url")
        self.assertEquals(actual_initial["fields"]["content"], "Content goes here")

        actual_final = json.loads(versions[0].serialized_data)[0]
        self.assertEquals(actual_final["fields"]["name"], "2nd name")
        self.assertEquals(actual_final["fields"]["url"], "test-url")
        self.assertEquals(actual_final["fields"]["content"], "New content")
Exemplo n.º 15
0
    def test_job_opening_revision_is_created(self):
        job_opening = self.create_default_job_opening()
        self.assertEqual(len(get_for_object(job_opening)), 0)

        new_values_en_1 = self.make_new_values(self.default_job_values['en'],
                                               1)
        self.create_revision(job_opening, **new_values_en_1)
        self.assertEqual(len(get_for_object(job_opening)), 1)
Exemplo n.º 16
0
 def test_category_revision_is_created(self):
     category = JobCategory.objects.create(app_config=self.app_config,
                                           **self.category_values_raw['en'])
     self.assertEqual(len(get_for_object(category)), 0)
     new_values_en_1 = self.make_new_values(self.category_values_raw['en'],
                                            1)
     self.create_revision(category, **new_values_en_1)
     self.assertEqual(len(get_for_object(category)), 1)
Exemplo n.º 17
0
 def testCanRevertVersion(self):
     self.assertEqual(
         ReversionTestModel1.objects.get(pk=self.concrete.pk).name,
         self.proxy.name)
     get_for_object(self.proxy)[1].revert()
     self.assertEqual(
         ReversionTestModel1.objects.get(pk=self.concrete.pk).name,
         self.concrete.name)
Exemplo n.º 18
0
    def test_job_opening_revision_is_created(self):
        job_opening = self.create_default_job_opening()
        self.assertEqual(len(get_for_object(job_opening)), 0)

        new_values_en_1 = self.make_new_values(
            self.default_job_values['en'], 1)
        self.create_revision(job_opening, **new_values_en_1)
        self.assertEqual(len(get_for_object(job_opening)), 1)
Exemplo n.º 19
0
 def test_category_revision_is_created(self):
     category = JobCategory.objects.create(
         app_config=self.app_config,
         **self.category_values_raw['en'])
     self.assertEqual(len(get_for_object(category)), 0)
     new_values_en_1 = self.make_new_values(
         self.category_values_raw['en'], 1)
     self.create_revision(category, **new_values_en_1)
     self.assertEqual(len(get_for_object(category)), 1)
Exemplo n.º 20
0
    def testCanGetForObject(self):
        # Can get version for proxy model
        proxy_versions = get_for_object(self.proxy)
        self.assertEqual(len(proxy_versions), 2)
        self.assertEqual(proxy_versions[0].field_dict["name"], self.proxy.name)
        self.assertEqual(proxy_versions[1].field_dict["name"], self.concrete.name)

        # Can get the same version for concrete model
        concrete_versions = get_for_object(self.concrete)
        self.assertEqual(list(concrete_versions), list(proxy_versions))
    def setUp(self):
        super(CBViewTest, self).setUp()
        test_data = TestData(verbose=False)
        self.item1, self.item2 = test_data.create_Simple_data()

        queryset = get_for_object(self.item1)
        self.version_ids1 = queryset.values_list("pk", flat=True)
        
        queryset = get_for_object(self.item2)
        self.version_ids2 = queryset.values_list("pk", flat=True)
Exemplo n.º 22
0
 def testCanGetUnique(self):
     with create_revision():
         self.test11.save()
         self.test21.save()
     # Test a model with an int pk.
     self.assertEqual(get_for_object(self.test11).count(), 3)
     self.assertEqual(len(list(get_for_object(self.test11).get_unique())), 2)
     # Test a model with a str pk.
     self.assertEqual(get_for_object(self.test21).count(), 3)
     self.assertEqual(len(list(get_for_object(self.test21).get_unique())), 2)
Exemplo n.º 23
0
    def test_job_application_revision_is_created(self):
        job_opening = self.create_default_job_opening()
        application = JobApplication.objects.create(
            job_opening=job_opening, **self.application_default_values)
        self.assertEqual(len(get_for_object(application)), 0)

        # revision 1
        new_values_1 = self.make_new_values(self.application_values_raw, 1)
        self.create_revision(application, **new_values_1)
        self.assertEqual(len(get_for_object(application)), 1)
Exemplo n.º 24
0
 def testCanGetUniqueForObject(self):
     with create_revision():
         self.test11.save()
         self.test21.save()
     # Test a model with an int pk.
     self.assertEqual(get_for_object(self.test11).count(), 3)
     self.assertEqual(len(get_unique_for_object(self.test11)), 2)
     # Test a model with a str pk.
     self.assertEqual(get_for_object(self.test21).count(), 3)
     self.assertEqual(len(get_unique_for_object(self.test21)), 2)
Exemplo n.º 25
0
 def test_attendance_post_not_registered_revision(self):
     self.client.login(username="******", password="******")
     self.client.post(self.url, self.create_block_dict())
     registration = Registration.objects.get(user=User.objects.get(username="******"))
     reg_versions = reversion.get_for_object(registration)
     self.assertEquals(len(reg_versions), 1)
     self.assertEquals(reg_versions[0].revision.comment, "Form Submission - Initial")
     for block_reg in BlockRegistration.objects.filter(registration=registration):
         block_versions = reversion.get_for_object(block_reg)
         self.assertEquals(len(block_versions), 1)
         self.assertEquals(block_versions[0].revision, reg_versions[0].revision)
Exemplo n.º 26
0
    def testCanGetForObject(self):
        # Can get version for proxy model
        proxy_versions = get_for_object(self.proxy)
        self.assertEqual(len(proxy_versions), 2)
        self.assertEqual(proxy_versions[0].field_dict["name"], self.proxy.name)
        self.assertEqual(proxy_versions[1].field_dict["name"],
                         self.concrete.name)

        # Can get the same version for concrete model
        concrete_versions = get_for_object(self.concrete)
        self.assertEqual(list(concrete_versions), list(proxy_versions))
Exemplo n.º 27
0
    def test_job_application_revision_is_created(self):
        job_opening = self.create_default_job_opening()
        application = JobApplication.objects.create(
            job_opening=job_opening,
            **self.application_default_values)
        self.assertEqual(len(get_for_object(application)), 0)

        # revision 1
        new_values_1 = self.make_new_values(self.application_values_raw, 1)
        self.create_revision(application, **new_values_1)
        self.assertEqual(len(get_for_object(application)), 1)
Exemplo n.º 28
0
 def testReverseFollowRevertWithDelete(self):
     with create_revision():
         follow2 = TestFollowModel.objects.create(
             name = "related instance2 version 1",
             test_model_1 = self.test11,
         )
     # Test that a revert with delete works.
     follow2_pk = follow2.pk
     get_for_object(self.test11)[1].revision.revert(delete=True)
     self.assertEqual(TestFollowModel.objects.count(), 1)
     self.assertRaises(TestFollowModel.DoesNotExist, lambda: TestFollowModel.objects.get(id=follow2_pk))
Exemplo n.º 29
0
 def testCanGetForObject(self):
     # Test a model with an int pk.
     versions = get_for_object(self.test11)
     self.assertEqual(len(versions), 2)
     self.assertEqual(versions[0].field_dict["name"], "model1 instance1 version2")
     self.assertEqual(versions[1].field_dict["name"], "model1 instance1 version1")
     # Test a model with a str pk.
     versions = get_for_object(self.test21)
     self.assertEqual(len(versions), 2)
     self.assertEqual(versions[0].field_dict["name"], "model2 instance1 version2")
     self.assertEqual(versions[1].field_dict["name"], "model2 instance1 version1")
Exemplo n.º 30
0
 def testReverseFollowRevertWithDelete(self):
     with create_revision():
         follow2 = TestFollowModel.objects.create(
             name="related instance2 version 1",
             test_model_1=self.test11,
         )
     # Test that a revert with delete works.
     follow2_pk = follow2.pk
     get_for_object(self.test11)[1].revision.revert(delete=True)
     self.assertEqual(TestFollowModel.objects.count(), 1)
     self.assertRaises(TestFollowModel.DoesNotExist,
                       lambda: TestFollowModel.objects.get(id=follow2_pk))
Exemplo n.º 31
0
	def test_revert_document(self):
		document = Document.objects.get()
		versions = revisions.get_for_object(document)
		self.assertEqual(len(versions), 2)

		# second step try to revert to old version
		response = self.app.post(reverse('documents:revert'), {'id': versions[1].pk, 'url_title': document.url_title}, user=self.user, xhr=True)
		self.assertEqual(response.status_code, 200)

		versions = revisions.get_for_object(document)
		self.assertEqual(len(versions), 3)
		self.assertEqual(versions[0].object.text, "text")
		self.assertEqual(versions[0].revision.comment, 'reverted to revision "test version"')
Exemplo n.º 32
0
    def test_attendance_post_registered_revision(self):
        registration = Registration.objects.get(user=User.objects.get(username="******"))
        for block_reg in BlockRegistration.objects.filter(registration=registration):
            block_reg.attendance = BlockRegistration.ATTENDANCE_YES
            block_reg.save()

        self.client.post(self.url, self.create_block_dict())
        reg_versions = map(lambda x: x, reversion.get_for_object(registration))
        self.assertEquals(len(reg_versions), 1)
        self.assertEquals(reg_versions[0].revision.comment, "Form Submission - Update")

        for block_reg in BlockRegistration.objects.filter(registration=registration):
            block_versions = map(lambda x: x, reversion.get_for_object(block_reg))
            self.assertEquals(block_versions[0].revision, reg_versions[0].revision)
Exemplo n.º 33
0
 def testCanRevertRevision(self):
     get_for_object(self.test11)[1].revision.revert()
     self.assertEqual(
         ReversionTestModel1.objects.get(id=self.test11.pk).name,
         "model1 instance1 version1")
     self.assertEqual(
         ReversionTestModel1.objects.get(id=self.test12.pk).name,
         "model1 instance2 version1")
     self.assertEqual(
         ReversionTestModel2.objects.get(id=self.test22.pk).name,
         "model2 instance2 version1")
     self.assertEqual(
         ReversionTestModel2.objects.get(id=self.test22.pk).name,
         "model2 instance2 version1")
    def test_initial_state(self):
        self.assertTrue(reversion.is_registered(SimpleModel))

        self.assertEqual(SimpleModel.objects.count(), 2)
        self.assertEqual(SimpleModel.objects.all()[0].text, "version two")

        self.assertEqual(reversion.get_for_object(self.item1).count(), 2)
        self.assertEqual(reversion.get_for_object(self.item2).count(), 5)
        self.assertEqual(Revision.objects.all().count(), 7)
        self.assertEqual(Version.objects.all().count(), 7)

        # query.ValuesListQuerySet() -> list():
        self.assertEqual(list(self.version_ids1), [2, 1])
        self.assertEqual(list(self.version_ids2), [7, 6, 5, 4, 3])
Exemplo n.º 35
0
	def test_revert_poll_no_votes(self):
		poll = Poll.objects.get()
		self.assertTrue(poll.can_be_reverted)
		versions = revisions.get_for_object(poll)
		self.assertEqual(len(versions), 2)

		response = self.app.post(reverse('documents:revert'), {'id': versions[1].pk, 'url_title': poll.url_title}, user=self.user, xhr=True)
		self.assertEqual(response.status_code, 200)

		versions = revisions.get_for_object(poll)
		self.assertEqual(len(versions), 3)

		response = self.app.get(reverse('versions', args=[poll.url_title]), user=self.user)
		self.assertEqual(response.status_code, 200)
		self.assertNotIn('This Document can not be reverted!', response.body.decode('utf-8'))
Exemplo n.º 36
0
def test_comment_edit_versioning(john_doe_api_client, default_hearing, lookup_field):
    url = get_main_comments_url(default_hearing, lookup_field)
    response = john_doe_api_client.post(url, data={"content": "THIS SERVICE SUCKS"})
    data = get_data_from_response(response, 201)
    comment_id = data["id"]
    comment = SectionComment.objects.get(pk=comment_id)
    assert comment.content.isupper()  # Oh my, all that screaming :(
    assert not revisions.get_for_object(comment)  # No revisions
    response = john_doe_api_client.patch('%s%s/' % (url, comment_id), data={
        "content": "Never mind, it's nice :)"
    })
    data = get_data_from_response(response, 200)
    comment = SectionComment.objects.get(pk=comment_id)
    assert not comment.content.isupper()  # Screaming is gone
    assert len(revisions.get_for_object(comment)) == 1  # One old revision
Exemplo n.º 37
0
 def testCanGetForObject(self):
     # Test a model with an int pk.
     versions = get_for_object(self.test11)
     self.assertEqual(len(versions), 2)
     self.assertEqual(versions[0].field_dict["name"],
                      "model1 instance1 version2")
     self.assertEqual(versions[1].field_dict["name"],
                      "model1 instance1 version1")
     # Test a model with a str pk.
     versions = get_for_object(self.test21)
     self.assertEqual(len(versions), 2)
     self.assertEqual(versions[0].field_dict["name"],
                      "model2 instance1 version2")
     self.assertEqual(versions[1].field_dict["name"],
                      "model2 instance1 version1")
Exemplo n.º 38
0
    def test_opening_is_reverted_if_fk_object_was_deleted(self):
        opening = self.create_default_job_opening(translated=True)
        self.assertEqual(len(get_for_object(opening)), 0)

        # revision 1: en 1, de 0
        category_1 = self.default_category
        new_values_en_1 = self.make_new_values(self.opening_values_raw['en'],
                                               1)
        with switch_language(opening, 'en'):
            self.create_revision(opening, **new_values_en_1)

        # revision 2: en 1, de 1
        new_values_de_1 = self.make_new_values(self.opening_values_raw['de'],
                                               1)
        # update category
        category_2 = JobCategory.objects.create(
            app_config=self.app_config,
            **self.make_new_values(self.category_values_raw['en'], 2))
        new_values_de_1['category'] = category_2
        with switch_language(opening, 'de'):
            self.create_revision(opening, **new_values_de_1)

        # delete category_1
        with transaction.atomic():
            category_1.delete()
        self.assertEqual(JobCategory.objects.all().count(), 1)

        # revert to 1
        self.revert_to(opening, 1)
        opening = JobOpening.objects.get(pk=opening.pk)
        self.assertNotEqual(opening.category, category_2)
        self.assertEqual(JobCategory.objects.all().count(), 2)
    def test_deleted_objects(self):
        """
        for:
        https://github.com/jedie/django-reversion-compare/commit/ba22008130f4c16a32eeb900381c2d82ca6fdd9e
        https://travis-ci.org/jedie/django-reversion-compare/builds/72317520
        """
        with reversion.create_revision():
            factory1 = Factory.objects.create(name="factory one")
            car = Car.objects.create(
                name="car",
                manufacturer=factory1
            )

        with reversion.create_revision():
            factory2 = Factory.objects.create(name="factory two")
            car.manufacturer=factory2
            car.save()

        with reversion.create_revision():
            factory1.delete()

        queryset = get_for_object(car)
        version_ids = queryset.values_list("pk", flat=True)  # [3, 2]
        # print("\n", version_ids)

        # response = self.client.get("/admin/tests/car/%s/history/" % car.pk)
        # debug_response(response) # from django-tools

        response = self.client.get(
            "/admin/tests/car/%s/history/compare/" % car.pk,
            data={"version_id2":version_ids[0], "version_id1":version_ids[1]}
        )
Exemplo n.º 40
0
Arquivo: views.py Projeto: invliD/1327
def edit(request, title, new_autosaved_pages=None, initial=None):
	document = Document.objects.get(url_title=title)
	content_type = ContentType.objects.get_for_model(document)
	check_permissions(document, request.user, [document.edit_permission_name])

	# if the edit form has a formset we will initialize it here
	formset_factory = document.Form.get_formset_factory()
	formset = formset_factory(request.POST or None, instance=document) if formset_factory is not None else None

	if formset is not None:
		template_name = "{app}_edit.html".format(app=content_type.app_label)
	else:
		template_name = "documents_edit.html"

	success, form = handle_edit(request, document, formset, initial)
	__, attachment_form, __ = handle_attachment(request, document)

	if success:
		messages.success(request, _("Successfully saved changes"))
		return HttpResponseRedirect(reverse('documents:view', args=[document.url_title]))
	else:
		return render(request, template_name, {
			'document': document,
			'form': form,
			'attachment_form': attachment_form,
			'active_page': 'edit',
			'creation': (len(revisions.get_for_object(document)) == 0),
			'new_autosaved_pages': new_autosaved_pages,
			'permission_warning': permission_warning(request.user, content_type, document),
			'supported_image_types': settings.SUPPORTED_IMAGE_TYPES,
			'formset': formset,
		})
Exemplo n.º 41
0
def get_history(com, viewdate=None):
    available_versions = list(reversion.get_for_object(com).get_unique())
    available_versions.reverse()
    prev = available_versions[0]
    print(prev.revision.date_created, viewdate)
    if cmp_time(prev.revision.date_created, viewdate):
        current = True
    else:
        current = False
    history = [{'date': prev.revision.date_created, 'user': prev.revision.user, 'changes': None, 'current': current}]
    prev = prev.field_dict
    for rev in available_versions[1:]:
        changes = diff(prev, rev.field_dict)
        print(rev.revision.date_created, viewdate)
        if cmp_time(rev.revision.date_created, viewdate):
            current = True
        else:
            current = False
        if changes:
            history.append({'user': rev.revision.user, 'changes': changes, 'date': rev.revision.date_created,
                            'current': current})
        prev = rev.field_dict
    history[-1]['latest'] = True
    history.reverse()
    return history
Exemplo n.º 42
0
 def __init__(self, *args, **kwargs):
     if (kwargs.get('asset', None) is not None
             and 'asset_version_id' not in kwargs):
         asset = kwargs.get('asset')
         kwargs['asset_version_id'] = reversion.get_for_object(
             asset).last().pk
     return super(AssetSnapshot, self).__init__(*args, **kwargs)
Exemplo n.º 43
0
 def createInlineProxyObjects(self):
     # Create an instance via the admin without a child.
     response = self.client.post(
         reverse("admin:test_reversion_inlinetestparentmodelproxy_add"), {
             "name": "parent version1",
             "children-TOTAL_FORMS": "0",
             "children-INITIAL_FORMS": "0",
             "_continue": 1,
         })
     self.assertEqual(response.status_code, 302)
     parent_pk = resolve(response["Location"].replace(
         "http://testserver", "")).args[0]
     parent = InlineTestParentModelProxy.objects.get(id=parent_pk)
     # Update  instance via the admin to add a child
     response = self.client.post(
         reverse("admin:test_reversion_inlinetestparentmodelproxy_change",
                 args=(parent_pk, )), {
                     "name": "parent version2",
                     "children-TOTAL_FORMS": "1",
                     "children-INITIAL_FORMS": "0",
                     "children-0-name": "non-generic child version 1",
                     "_continue": 1,
                 })
     self.assertEqual(response.status_code, 302)
     children = InlineTestChildModelProxy.objects.filter(parent=parent_pk)
     self.assertEqual(children.count(), 1)
     # get list of versions
     version_list = get_for_object(parent)
     self.assertEqual(len(version_list), 2)
     # All done!
     return parent_pk
Exemplo n.º 44
0
    def setUp(self):
        super(OneToOneFieldTest, self).setUp()
        test_data = TestData(verbose=False)
        self.person, self.item = test_data.create_PersonIdentity_data()

        queryset = get_for_object(self.person)
        self.version_ids = queryset.values_list("pk", flat=True)
Exemplo n.º 45
0
 def test_revision_is_created_on_job_category_object_create(self):
     with transaction.atomic():
         with create_revision():
             job_category = JobCategory.objects.create(
                 app_config=self.app_config,
                 **self.category_values_raw['en'])
     self.assertEqual(len(get_for_object(job_category)), 1)
Exemplo n.º 46
0
 def test_revision_is_created_on_job_category_object_create(self):
     with transaction.atomic():
         with create_revision():
             job_category = JobCategory.objects.create(
                 app_config=self.app_config,
                 **self.category_values_raw['en'])
     self.assertEqual(len(get_for_object(job_category)), 1)
Exemplo n.º 47
0
 def testCanSaveIgnoringDuplicates(self):
     with create_revision():
         self.test11.save()
         self.test12.save()
         self.test21.save()
         self.test22.save()
         self.assertFalse(get_ignore_duplicates())
         set_ignore_duplicates(True)
         self.assertTrue(get_ignore_duplicates())
     self.assertEqual(get_for_object(self.test11).count(), 2)
     # Save a non-duplicate revision.
     with create_revision():
         self.test11.save()
         self.assertFalse(get_ignore_duplicates())
         set_ignore_duplicates(True)
     self.assertEqual(get_for_object(self.test11).count(), 3)
Exemplo n.º 48
0
 def test_revision_is_created_on_job_opening_object_created(self):
     with transaction.atomic():
         with create_revision():
             job_opening = JobOpening.objects.create(
                 category=self.default_category,
                 **self.opening_values_raw['en'])
     self.assertEqual(len(get_for_object(job_opening)), 1)
Exemplo n.º 49
0
 def test_revision_is_created_on_job_opening_object_created(self):
     with transaction.atomic():
         with create_revision():
             job_opening = JobOpening.objects.create(
                 category=self.default_category,
                 **self.opening_values_raw['en'])
     self.assertEqual(len(get_for_object(job_opening)), 1)
Exemplo n.º 50
0
def history(request, slug):
    sheet = get_object_or_404(Sheet, slug=slug)
    mark_set = SheetAPI.get_marks_for_sheet(sheet).values()
    history_items_list = []
    for marks in mark_set:
        for mark in marks:
            for revision in reversion.get_for_object(mark).all():
                history_items_list.append(revision)
    history_items_list.sort(key=lambda item: item.revision.date_created, reverse=True)

    history_items_list = [
        history_item.revision.comment + timezone.localtime(history_item.revision.date_created).strftime(
            '(%y-%m-%d %H:%m:%S)') for
        history_item in history_items_list]

    paginator = Paginator(history_items_list, 5)
    page = request.GET.get('page')
    try:
        history_items = paginator.page(page)
    except PageNotAnInteger:
        history_items = paginator.page(1)
    except EmptyPage:
        history_items = paginator.page(paginator.num_pages)

    return render(request, 'history.html', {
        'history_items': history_items
    })
Exemplo n.º 51
0
def get_marks(request, slug):
    sheet = get_object_or_404(Sheet, slug=slug)
    sheet_marks = SheetAPI.get_marks_for_sheet(sheet)
    mark_sets_json_dict = list()
    for student, students_marks in sheet_marks.items():
        marks_json_dict = list()
        for mark in students_marks:
            mark_json = mark.as_json_dict
            versions = reversion.get_for_object(mark)[:2]
            if versions.count() >= 2:
                first_revision = versions[0].revision
                second_revision = versions[1].revision
                if (
                    second_revision.user == request.user
                    and first_revision.user != second_revision.user
                    and (first_revision.date_created - second_revision.date_created).seconds < 10
                ):
                    mark_json["warning"] = True
            marks_json_dict.append(mark_json)
            if mark.user_with_lock:
                now = timezone.now()
                time_delta = now - mark.user_with_lock.profile.last_activity
                if time_delta.total_seconds() > 15:
                    mark.set_user_with_lock(None)
        mark_sets_json_dict.append(dict(student=UserAPI.as_json_dict(student, sheet), marks=marks_json_dict))
    mark_sets_json_dict = sorted(mark_sets_json_dict, key=lambda item: item["student"]["fullName"].split(" ")[1])
    return JsonResponse(mark_sets_json_dict, safe=False)
Exemplo n.º 52
0
 def testCanSaveIgnoringDuplicates(self):
     with create_revision():
         self.test11.save()
         self.test12.save()
         self.test21.save()
         self.test22.save()
         self.assertFalse(get_ignore_duplicates())
         set_ignore_duplicates(True)
         self.assertTrue(get_ignore_duplicates())
     self.assertEqual(get_for_object(self.test11).count(), 2)
     # Save a non-duplicate revision.
     with create_revision():
         self.test11.save()
         self.assertFalse(get_ignore_duplicates())
         set_ignore_duplicates(True)
     self.assertEqual(get_for_object(self.test11).count(), 3)
Exemplo n.º 53
0
    def test_opening_is_reverted_if_fk_object_was_deleted(self):
        opening = self.create_default_job_opening(translated=True)
        self.assertEqual(len(get_for_object(opening)), 0)

        # revision 1: en 1, de 0
        category_1 = self.default_category
        new_values_en_1 = self.make_new_values(self.opening_values_raw['en'], 1)
        with switch_language(opening, 'en'):
            self.create_revision(opening, **new_values_en_1)

        # revision 2: en 1, de 1
        new_values_de_1 = self.make_new_values(self.opening_values_raw['de'], 1)
        # update category
        category_2 = JobCategory.objects.create(
            app_config=self.app_config,
            **self.make_new_values(self.category_values_raw['en'], 2))
        new_values_de_1['category'] = category_2
        with switch_language(opening, 'de'):
            self.create_revision(opening, **new_values_de_1)

        # delete category_1
        with transaction.atomic():
            category_1.delete()
        self.assertEqual(JobCategory.objects.all().count(), 1)

        # revert to 1
        self.revert_to(opening, 1)
        opening = JobOpening.objects.get(pk=opening.pk)
        self.assertNotEqual(opening.category, category_2)
        self.assertEqual(JobCategory.objects.all().count(), 2)
Exemplo n.º 54
0
    def test_overrides(self):
        #   Try to render a page from a nonexistent template override
        #   and make sure it doesn't exist
        self.expect_template_error('BLAARG.NOTANACTUALTEMPLATE')

        #   Create a template override and make sure you can see it
        with reversion.create_revision():
            to = TemplateOverride(name='BLAARG.TEMPLATEOVERRIDE',
                                  content='Hello')
            to.save()
        self.assertTrue(
            self.get_response_for_template('BLAARG.TEMPLATEOVERRIDE') ==
            'Hello')

        #   Save an update to the template override and make sure you see that too
        with reversion.create_revision():
            to.content = 'Goodbye'
            to.save()
        self.assertTrue(
            self.get_response_for_template('BLAARG.TEMPLATEOVERRIDE') ==
            'Goodbye')

        #   Revert the update to the template and make sure you see the old version
        list(reversion.get_for_object(to).get_unique())[1].revert()
        self.assertTrue(
            self.get_response_for_template('BLAARG.TEMPLATEOVERRIDE') ==
            'Hello')

        #   Delete the original template override and make sure you see nothing
        TemplateOverride.objects.filter(
            name='BLAARG.TEMPLATEOVERRIDE').delete()
        self.expect_template_error('BLAARG.TEMPLATEOVERRIDE')
Exemplo n.º 55
0
 def createInlineObjects(self):
     # Create an instance via the admin without a child.
     response = self.client.post(reverse("admin:test_reversion_inlinetestparentmodel_add"), {
         "name": "parent version1",
         "children-TOTAL_FORMS": "0",
         "children-INITIAL_FORMS": "0",
         "test_reversion-inlinetestchildgenericmodel-content_type-object_id-TOTAL_FORMS": "0",
         "test_reversion-inlinetestchildgenericmodel-content_type-object_id-INITIAL_FORMS": "0",
         "_continue": 1,
         })
     self.assertEqual(response.status_code, 302)
     parent_pk = resolve(response["Location"].replace("http://testserver", "")).args[0]
     parent = InlineTestParentModel.objects.get(id=parent_pk)
     # Update  instance via the admin to add a child
     response = self.client.post(reverse("admin:test_reversion_inlinetestparentmodel_change", args=(parent_pk,)), {
         "name": "parent version1",
         "children-TOTAL_FORMS": "1",
         "children-INITIAL_FORMS": "0",
         "children-0-name": "child version 1",
         "test_reversion-inlinetestchildgenericmodel-content_type-object_id-TOTAL_FORMS": "1",
         "test_reversion-inlinetestchildgenericmodel-content_type-object_id-INITIAL_FORMS": "0",
         "test_reversion-inlinetestchildgenericmodel-content_type-object_id-0-name": "generic child version 1",
         "_continue": 1,
         })
     self.assertEqual(response.status_code, 302)
     children = InlineTestChildModel.objects.filter(parent=parent_pk)
     self.assertEqual(children.count(), 1)
     generic_children = parent.generic_children.all()
     self.assertEqual(generic_children.count(), 1)
     # get list of versions
     version_list = get_for_object(parent)
     self.assertEqual(len(version_list), 2)
Exemplo n.º 56
0
def post_revision_commit(sender, **kwargs):
    """Custom post-revision hook.

    We want to track all creations and modifications of admin. objects
    (alias, mailbox, user, domain, domain alias, etc.) so we use
    django-reversion for that.

    """
    from modoboa.lib.signals import get_request

    current_user = get_request().user.username
    logger = logging.getLogger("modoboa.admin")
    for version in kwargs["versions"]:
        if version.object is None:
            continue
        prev_revisions = reversion.get_for_object(version.object)
        if prev_revisions.count() == 1:
            action = _("added")
            level = "info"
        else:
            action = _("modified")
            level = "warning"
        message = _("%(object)s '%(name)s' %(action)s by user %(user)s") % {
            "object": unicode(version.content_type).capitalize(),
            "name": version.object_repr, "action": action,
            "user": current_user
        }
        getattr(logger, level)(message)
Exemplo n.º 57
0
    def test_it_creates_revisions_on_update(self, api_client):
        ActionFactory(name='foo', implementation='original')

        res = api_client.patch('/api/v1/action/foo/', {'implementation': 'changed'})
        assert res.status_code == 200

        action = Action.objects.all()[0]
        assert len(reversion.get_for_object(action)) == 1
Exemplo n.º 58
0
 def revert_to(self, object_with_revision, revision_number):
     """
     Revert <object with revision> to revision number.
     """
     # get by position, since reversion_id is not reliable,
     version = list(reversed(
         get_for_object(object_with_revision)))[revision_number - 1]
     version.revision.revert()
Exemplo n.º 59
0
def test_comment_edit_versioning(john_doe_api_client, default_hearing,
                                 lookup_field):
    url = get_main_comments_url(default_hearing, lookup_field)
    response = john_doe_api_client.post(url,
                                        data={"content": "THIS SERVICE SUCKS"})
    data = get_data_from_response(response, 201)
    comment_id = data["id"]
    comment = SectionComment.objects.get(pk=comment_id)
    assert comment.content.isupper()  # Oh my, all that screaming :(
    assert not revisions.get_for_object(comment)  # No revisions
    response = john_doe_api_client.patch(
        '%s%s/' % (url, comment_id),
        data={"content": "Never mind, it's nice :)"})
    data = get_data_from_response(response, 200)
    comment = SectionComment.objects.get(pk=comment_id)
    assert not comment.content.isupper()  # Screaming is gone
    assert len(revisions.get_for_object(comment)) == 1  # One old revision