Ejemplo n.º 1
0
    def test_model_listener_turn_off(self):
        """
        Simple model listener construction.
        Tests that the signals will not be fired when auto_on = False
        """
        ml = ModelListener()
        ml.name = "test_listener"
        ml.app = "example_app"
        ml.model = "Dummy"
        ml.active = True
        ml.post_save_handler = "example.example_app.tests.fake_functions.fake"
        ml.post_delete_handler = "example.example_app.tests.fake_functions.fake"
        ml.auto_on = True
        ml.save()

        self.assertTrue(ml._is_method_valid(ml.post_save_handler))
        self.assertTrue(ml._is_method_valid(ml.post_delete_handler))

        dummy = mommy.make_one(Dummy)
        dummy.save()

        self.assertTrue(ModelListenerTestCase.fired)

        ml._stop_listening()
        ModelListenerTestCase.fired = False

        dummy2 = mommy.make_one(Dummy)

        self.assertFalse(ModelListenerTestCase.fired)

        ml._stop_listening()
Ejemplo n.º 2
0
    def gerarTemplate(self):
        "gera um template com filtro coerentes"
        from Avaliacao.Questao.models import Questao

#    Avaliação ->
#    1 -> q1
#    2 -> C, Facil
#    3 -> Facil, C.Malloc
        #prepara a avaliacao
        self.templateAvaliacao = TemplateAvaliacao(titulo="Avaliacao Teste Filtros",turma=self.turma,ativa=True)
        self.templateAvaliacao.data_inicio = datetime.datetime.now() - datetime.timedelta(hours=3)
        self.templateAvaliacao.data_termino = datetime.datetime.now() + datetime.timedelta(hours=5)
        self.templateAvaliacao.save()
        #prepara os filtros
        #são 3 questoes na avaliacao

        tipos = TipoQuestao.objects.filter(tipo__in = ["C", "Facil"] )
        fq1 = mommy.make_one(FiltroQuestao,templateAvaliacao=self.templateAvaliacao,questaoExata=Questao.objects.get(pk=1),tipo=tipos)
        fq1.save()

        tipos = TipoQuestao.objects.filter(tipo__in = ["C", "Facil"] )
        fq2 = mommy.make_one(FiltroQuestao,templateAvaliacao=self.templateAvaliacao,questaoExata=None,tipo=tipos)
        fq2.save()

        tipos = TipoQuestao.objects.filter(tipo__in = ["Facil","Malloc"] )
        fq3 = mommy.make_one(FiltroQuestao,templateAvaliacao=self.templateAvaliacao,questaoExata=None,tipo=tipos)
        fq3.save()
Ejemplo n.º 3
0
 def test_make_path(self):
     page = mommy.make_one(WikiPage, title='p1')
     page2 = mommy.make_one(WikiPage, title='p2', parent_page=page)
     pages = WikiPage.make_path('p1/p2/p3')
     assert page.id == pages[0].id
     assert page2.id == pages[1].id
     assert len(pages) == 2
Ejemplo n.º 4
0
def create_setup(self):
    self.campaign_one = mommy.make_one('catamidb.Campaign')

    self.deployment_one = mommy.make_one(
        'catamidb.GenericDeployment',
        start_position=Point(12.4604, 43.9420),
        end_position=Point(12.4604,43.9420),
        transect_shape=Polygon(((0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (0.0, 0.0))),
        campaign=self.campaign_one)

    self.deployment_two = mommy.make_one(
        'catamidb.GenericDeployment',
        start_position=Point(12.4604, 43.9420),
        end_position=Point(12.4604, 43.9420),
        transect_shape=Polygon(((0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (0.0, 0.0))),
        campaign=self.campaign_one)

    #self.image_list = ['/live/test/test2.jpg', '/live/test/test1.jpg']
    self.mock_image_one = mommy.make_recipe('projects.genericImage1', deployment=self.deployment_one)
    self.mock_image_two = mommy.make_recipe('projects.genericImage2', deployment=self.deployment_two)

    self.camera_one = mommy.make_one('catamidb.GenericCamera', image=self.mock_image_one)
    self.camera_two = mommy.make_one('catamidb.GenericCamera', image=self.mock_image_two)

    self.mock_image_list = []

    for i in xrange(20):
        mock_image = mommy.make_recipe('projects.genericImage1', deployment=self.deployment_one, date_time=datetime.now())
        self.mock_image_list.append(mock_image)
Ejemplo n.º 5
0
    def test_model_listener_stop(self):
        """
        Tests that stopping the signal will not fire the events
        """
        ml = ModelListener()
        ml.name = "test_listener"
        ml.app = "example_app"
        ml.model = "Dummy"
        ml.active = True
        ml.post_save_handler = "example.example_app.tests.fake_functions.fake"
        ml.post_delete_handler = "example.example_app.tests.fake_functions.fake"
        ml.auto_on = True
        ml.save()

        ModelListenerTestCase.fired = False

        self.assertTrue(ml._is_method_valid(ml.post_save_handler))
        self.assertTrue(ml._is_method_valid(ml.post_delete_handler))

        ml._stop_listening()

        dummy = mommy.make_one(Dummy)
        dummy.save()

        self.assertFalse(ModelListenerTestCase.fired)

        ml._start_listening()
        ModelListenerTestCase.fired = False

        dummy2 = mommy.make_one(Dummy)

        self.assertTrue(ModelListenerTestCase.fired)

        ml._stop_listening()
Ejemplo n.º 6
0
    def setUp(self):
        #Tastypie stuff
        super(TestDeploymentResource, self).setUp()

        self.bob_api_client = TestApiClient()
        self.bill_api_client = TestApiClient()
        self.anon_api_client = TestApiClient()

        # Create a user bob.
        self.user_bob_username = '******'
        self.user_bob_password = '******'
        self.user_bob = User.objects.create_user(self.user_bob_username,
                                                 '*****@*****.**',
                                                 self.user_bob_password)

        # Create a user bob.
        self.user_bill_username = '******'
        self.user_bill_password = '******'
        self.user_bill = User.objects.create_user(self.user_bill_username,
                                                  '*****@*****.**',
                                                  self.user_bill_password)

        self.bob_api_client.client.login(username='******', password='******')
        self.bill_api_client.client.login(username='******', password='******')

        #assign users to the Public group
        public_group, created = Group.objects.get_or_create(name='Public')
        self.user_bob.groups.add(public_group)
        self.user_bill.groups.add(public_group)
        guardian.utils.get_anonymous_user().groups.add(public_group)

        #make a couple of campaigns and save
        self.campaign_bobs = mommy.make_one('catamidb.Campaign', id=1)
        self.campaign_bills = mommy.make_one('catamidb.Campaign', id=2)

        #make a deployments
        self.deployment_bobs = mommy.make_recipe('catamidb.Deployment1',
                                                 id=1,
                                                 campaign=self.campaign_bobs)
        self.deployment_bills = mommy.make_recipe('catamidb.Deployment2',
                                                  id=2,
                                                  campaign=self.campaign_bills)

        #assign this one to bob
        authorization.apply_campaign_permissions(
            self.user_bob, self.campaign_bobs)

        #assign this one to bill
        authorization.apply_campaign_permissions(self.user_bill,
                                                 self.campaign_bills)

        #the API url for deployments
        self.deployment_url = '/api/dev/deployment/'

        #some post data for testing deployment creation
        self.post_data = {
            'type': 'AUV',
            'operator': 'XXX',
        }
Ejemplo n.º 7
0
    def test_create_two_penguins_in_love(self):
        from model_mommy import mommy
        from model_mommy.models import Penguin

        male = mommy.make_one(Penguin)
        female = mommy.make_one(Penguin, partner=male)
        self.assertEqual(male, female.partner)
        self.assertEqual(male.mate, female)
Ejemplo n.º 8
0
    def setUp(self):
        # Tastypie stuff
        super(TestCameraResource, self).setUp()

        self.bob_api_client = TestApiClient()
        self.bill_api_client = TestApiClient()
        self.anon_api_client = TestApiClient()

        # Create a user bob.
        self.user_bob_username = "******"
        self.user_bob_password = "******"
        self.user_bob = User.objects.create_user(self.user_bob_username, "*****@*****.**", self.user_bob_password)

        # Create a user bob.
        self.user_bill_username = "******"
        self.user_bill_password = "******"
        self.user_bill = User.objects.create_user(
            self.user_bill_username, "*****@*****.**", self.user_bill_password
        )

        self.bob_api_client.client.login(username="******", password="******")
        self.bill_api_client.client.login(username="******", password="******")

        # assign users to the Public group
        public_group, created = Group.objects.get_or_create(name="Public")
        self.user_bob.groups.add(public_group)
        self.user_bill.groups.add(public_group)
        guardian.utils.get_anonymous_user().groups.add(public_group)

        # make a couple of campaigns and save
        self.campaign_bobs = mommy.make_one("catamidb.Campaign", id=1)
        self.campaign_bills = mommy.make_one("catamidb.Campaign", id=2)

        # make a deployments
        self.deployment_bobs = mommy.make_recipe("catamidb.Deployment1", id=1, campaign=self.campaign_bobs)
        self.deployment_bills = mommy.make_recipe("catamidb.Deployment2", id=2, campaign=self.campaign_bills)

        # make images
        self.image_bobs = mommy.make_recipe("catamidb.Image1", id=1, deployment=self.deployment_bobs)

        self.image_bills = mommy.make_recipe("catamidb.Image2", id=2, deployment=self.deployment_bills)

        # make cameras
        self.camera_bobs = mommy.make_one("catamidb.Camera", id=1, image=self.image_bobs)
        self.camera_bills = mommy.make_one("catamidb.Camera", id=2, image=self.image_bills)

        # assign this one to bob
        authorization.apply_campaign_permissions(self.user_bob, self.campaign_bobs)

        # assign this one to bill
        authorization.apply_campaign_permissions(self.user_bill, self.campaign_bills)

        # the API url for deployments
        self.camera_url = "/api/dev/camera/"

        # some post data for testing camera creation
        self.post_data = []
Ejemplo n.º 9
0
    def setUp(self):
        #Tastypie stuff
        super(TestCampaignResource, self).setUp()

        self.bob_api_client = TestApiClient()
        self.bill_api_client = TestApiClient()
        self.anon_api_client = TestApiClient()

        # Create a user bob.
        self.user_bob_username = '******'
        self.user_bob_password = '******'
        self.user_bob = User.objects.create_user(self.user_bob_username,
                                                 '*****@*****.**',
                                                 self.user_bob_password)

        # Create a user bob.
        self.user_bill_username = '******'
        self.user_bill_password = '******'
        self.user_bill = User.objects.create_user(self.user_bill_username,
                                                  '*****@*****.**',
                                                  self.user_bill_password)

        self.bob_api_client.client.login(username='******', password='******')
        self.bill_api_client.client.login(username='******', password='******')

        #assign users to the Public group
        public_group, created = Group.objects.get_or_create(name='Public')
        self.user_bob.groups.add(public_group)
        self.user_bill.groups.add(public_group)
        guardian.utils.get_anonymous_user().groups.add(public_group)

        #make a couple of campaigns and save
        self.campaign_bobs = mommy.make_one('catamidb.Campaign', id=1)
        self.campaign_bills = mommy.make_one('catamidb.Campaign', id=2)

        #assign this one to bob
        authorization.apply_campaign_permissions(
            self.user_bob, self.campaign_bobs)

        #assign this one to bill
        authorization.apply_campaign_permissions(
            self.user_bill, self.campaign_bills)

        #the API url for campaigns
        self.campaign_url = '/api/dev/campaign/'

        #some post data for testing campaign creation
        self.post_data = {
            'short_name': 'Blah',
            'description': 'Blah',
            'associated_researchers': 'Blah',
            'associated_publications': 'Blah',
            'associated_research_grant': 'Blah',
            'date_start': '2012-05-01',
            'date_end': '2012-05-01',
            'contact_person': 'Blah',
        }
Ejemplo n.º 10
0
 def setUp(self):
     mommy.make_one(Chapter)
     self.ontem = date.today() - timedelta(days=1)
     old = mommy.make_one(Chapter)
     old.day = self.ontem
     old.save()
     old = mommy.make_one(Chapter)
     old.day = self.ontem
     old.save()
Ejemplo n.º 11
0
    def setUp(self):
        # Tastypie stuff
        super(TestCampaignResource, self).setUp()

        self.bob_api_client = TestApiClient()
        self.bill_api_client = TestApiClient()
        self.anon_api_client = TestApiClient()

        # Create a user bob.
        self.user_bob_username = "******"
        self.user_bob_password = "******"
        self.user_bob = User.objects.create_user(self.user_bob_username, "*****@*****.**", self.user_bob_password)

        # Create a user bob.
        self.user_bill_username = "******"
        self.user_bill_password = "******"
        self.user_bill = User.objects.create_user(
            self.user_bill_username, "*****@*****.**", self.user_bill_password
        )

        self.bob_api_client.client.login(username="******", password="******")
        self.bill_api_client.client.login(username="******", password="******")

        # assign users to the Public group
        public_group, created = Group.objects.get_or_create(name="Public")
        self.user_bob.groups.add(public_group)
        self.user_bill.groups.add(public_group)
        guardian.utils.get_anonymous_user().groups.add(public_group)

        # make a couple of campaigns and save
        self.campaign_bobs = mommy.make_one("catamidb.Campaign")
        self.campaign_bills = mommy.make_one("catamidb.Campaign")

        # assign this one to bob
        authorization.apply_campaign_permissions(self.user_bob, self.campaign_bobs)

        # assign this one to bill
        authorization.apply_campaign_permissions(self.user_bill, self.campaign_bills)

        # the API url for campaigns
        self.campaign_url = "/api/dev/campaign/"

        # some post data for testing campaign creation
        self.post_data = {
            "short_name": "Blah",
            "description": "Blah",
            "associated_researchers": "Blah",
            "associated_publications": "Blah",
            "associated_research_grant": "Blah",
            "date_start": "2012-05-01",
            "date_end": "2012-05-01",
            "contact_person": "Blah",
        }
Ejemplo n.º 12
0
def create_setup(self):
    self.campaign_one = mommy.make_one('catamidb.Campaign', id=1)

    self.deployment_one = mommy.make_one('catamidb.Deployment',
            start_position=Point(12.4604, 43.9420),
            end_position=Point(12.4604, 43.9420),
            transect_shape=Polygon(((0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (0.0, 0.0))),
            id=1,
            campaign=self.campaign_one
        )
    self.deployment_two = mommy.make_one('catamidb.Deployment',
            start_position=Point(12.4604, 43.9420),
            end_position=Point(12.4604, 43.9420),
            transect_shape=Polygon(((0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (0.0, 0.0))),
            id=1,
            campaign=self.campaign_one
        )

    self.pose_one = mommy.make_one('catamidb.Pose',
            position=Point(12.4, 23.5),
            id=1,
            deployment=self.deployment_one
        )
    self.pose_two = mommy.make_one('catamidb.Pose',
            position=Point(12.4, 23.5),
            id=2,
            deployment=self.deployment_two
        )

    self.camera_one = mommy.make_one('catamidb.Camera',
            deployment=self.deployment_one,
            id=1,
        )
    self.camera_two = mommy.make_one('catamidb.Camera',
            deployment=self.deployment_two,
            id=1,
        )

    self.image_list = ['/live/test/test2.jpg', '/live/test/test1.jpg']
    self.mock_image_one = mommy.make_one('catamidb.Image',
            pose=self.pose_one,
            camera=self.camera_one,
            web_location=self.image_list[0],
            pk=1
        )
    self.mock_image_two = mommy.make_one('catamidb.Image',
            pose=self.pose_two,
            camera=self.camera_two,
            web_location=self.image_list[1],
            pk=2
        )

    image_objects = Image.objects.all()
    for image in image_objects:
        self.djt.image_primary_keys.append(image.pk)
Ejemplo n.º 13
0
    def test_camera_operations_as_authorised_users(self):
        # create a campaign & deployment that ONLY bill can see
        bills_campaign = mommy.make_one('catamidb.Campaign', id=3, short_name='cp_3')
        bills_deployment = mommy.make_recipe('catamidb.Deployment3', id=3,
                                             campaign=bills_campaign)
        assign('view_campaign', self.user_bill, bills_campaign)

        #make exclusive image for bill and assign this image to camera to image
        self.image_bill_exc = mommy.make_recipe(
            'catamidb.Image3',
            id=3,             
            deployment=bills_deployment) #IMPORTANT camera checks campaign which has reference to deployment. Image has reference to deployment and camera

        #make exclusive camera for bill
        self.camera_bill_exc = mommy.make_one(
            'catamidb.Camera',
            id=3,
            image=self.image_bill_exc)

        # check that bill can see via the API
        response = self.bill_api_client.get(self.camera_url, format='json')
        self.assertValidJSONResponse(response)
        self.assertEqual(len(self.deserialize(response)['objects']), 3)

        # check that bill can get to the object itself
        response = self.bill_api_client.get(self.camera_url + "3/",
                                            format='json')
        self.assertValidJSONResponse(response)

        # check that bob can not see - now we know tastypie API has correct
        # permission validation
        response = self.bob_api_client.get(self.camera_url, format='json')       
        self.assertValidJSONResponse(response)
        self.assertEqual(len(self.deserialize(response)['objects']), 2)

        # check bob can NOT get to the hidden object
        response = self.bob_api_client.get(self.camera_url + "3/",
                                           format='json')
        self.assertHttpUnauthorized(response)

        #check that anonymous can see public ones as well
        response = self.anon_api_client.get(self.camera_url, format='json')
        self.assertValidJSONResponse(response)
        self.assertEqual(len(self.deserialize(response)['objects']), 2)

        #check anonymous can NOT get to the hidden object
        response = self.anon_api_client.get(self.camera_url + "3/",
                                            format='json')
        self.assertHttpUnauthorized(response)
Ejemplo n.º 14
0
    def test_image_measurement_operations_as_authorised_users(self):
        # create a campaign & deployment that ONLY bill can see
        bills_campaign = mommy.make_one('catamidb.Campaign', id=3)
        bills_deployment = mommy.make_recipe('catamidb.auvdeployment', id=3,
                                             campaign=bills_campaign)
        bills_pose = mommy.make_recipe('catamidb.pose3', id=3,
                                       deployment=bills_deployment)
        bills_camera = mommy.make_one('catamidb.Camera', id=3,
                                      deployment=bills_deployment)
        bills_image = mommy.make_one('catamidb.Image', id=3, pose=bills_pose,
                                     camera=bills_camera)
        bills_image_measurement = mommy.make_one(
            'catamidb.ScientificImageMeasurement', id=3, image=bills_image)
        assign('view_campaign', self.user_bill, bills_campaign)

        # check that bill can see via the API
        response = self.bill_api_client.get(self.image_measurement_url,
                                            format='json')
        self.assertValidJSONResponse(response)
        self.assertEqual(len(self.deserialize(response)['objects']), 3)

        # check that bill can get to the object itself
        response = self.bill_api_client.get(self.image_measurement_url + "3/",
                                            format='json')
        self.assertValidJSONResponse(response)

        # check that bob can not see - now we know tastypie API has correct
        # permission validation
        response = self.bob_api_client.get(self.image_measurement_url,
                                           format='json')

        self.assertValidJSONResponse(response)
        self.assertEqual(len(self.deserialize(response)['objects']), 2)

        # check bob can NOT get to the hidden object
        response = self.bob_api_client.get(self.image_measurement_url + "3/",
                                           format='json')
        self.assertHttpUnauthorized(response)

        #check that anonymous can see public ones as well
        response = self.anon_api_client.get(self.image_measurement_url,
                                            format='json')
        self.assertValidJSONResponse(response)
        self.assertEqual(len(self.deserialize(response)['objects']), 2)

        #check anonymous can NOT get to the hidden object
        response = self.anon_api_client.get(self.image_measurement_url + "3/",
                                            format='json')
        self.assertHttpUnauthorized(response)
Ejemplo n.º 15
0
 def test_render_template(self):
     """make sure render do not fail"""
     for i in xrange(5):
         mommy.make_one(User)
     
     template = Template(self._template_content())
     
     dummy_request = DummyRequest()
     setattr(dummy_request, 'user', self.user)
     context = {
         'users': User.objects.all(),
         'request': dummy_request,
     }
     
     template.render(Context(context))
Ejemplo n.º 16
0
    def test_list_templatesAvaliacao_aluno(self):
        " verifica se o metodo list_templatesAvaliacao_aluno retorna todos os templates corretamente "

        templates_list_espected= []
        for turma_num in xrange(1,3):
            turma = mommy.make_one(Turma,nome="Teste%s"%str(turma_num),sigla="tst%s"%str(turma_num))
            if turma_num == 1:
                turma.alunos.add(self.aluno)

            for template_num in xrange(1,3):
                templateAvaliacao = TemplateAvaliacao(titulo="Avaliacao Teste %s"%str(template_num),turma=turma,ativa=True)
                templateAvaliacao.data_inicio = datetime.datetime.now()
                templateAvaliacao.data_termino = datetime.datetime.now() + datetime.timedelta(hours=2)
                templateAvaliacao.save()
                for filtro in xrange(1,11):
                    self.gerarFiltroQuestao(filtro,templateAvaliacao)

                if turma_num == 1 and template_num != 1:
                    templates_list_espected.append(templateAvaliacao)

                if template_num == 1:
                    templateAvaliacao.gerarAvaliacao(self.aluno)

        templates_list = TemplateAvaliacao.objects.list_templatesAvaliacao_aluno(self.aluno)
        print "lista"
        print templates_list
        for template in templates_list:
            self.assertIn(template,templates_list_espected)

        for template in templates_list_espected:
            self.assertIn(template,templates_list)
Ejemplo n.º 17
0
    def test_make_one_should_create_one_object(self):
        from model_mommy import mommy
        from model_mommy.models import Kid

        kid = mommy.make_one(Kid)
        self.assertTrue(isinstance(kid, Kid))
        self.assertEqual(Kid.objects.all().count(), 1)
Ejemplo n.º 18
0
 def gerarFiltroQuestaoParaTemplate(self,num_tipos,template):
     """gera filtros de questao para um determinado template,
     considerando que vai pegar todos os tipos que tem pk <= num_tipos"""
     tipos_pai = TipoQuestao.objects.filter( tipo__in = ["tipo%s"%str(j) for j in xrange(1,num_tipos+1)] )
     #tipos = TipoQuestao.objects.filter(pk__lte=num_tipos)
     filtro = mommy.make_one(FiltroQuestao,templateAvaliacao=template,questaoExata=None,tipo=tipos_pai)
     return filtro
Ejemplo n.º 19
0
    def gerar_Questoes(self):
        """gera questoes mocked com tipo variando
        """
        import random

        from Avaliacao.Questao.models import Questao
        for i in xrange(1,31):
            #:basicamente quando i=1 -> mod = 1; i = 10 -> mod = 10; i = 11 -> mod = 1; i=20 -> mod = 10
            mod =  i%10
            if mod == 0:
                mod = 10

            #:retorna basicamente tipos de questao que tem PK < i(nunca ultrapassando 10)

            tipos_pai = TipoQuestao.objects.filter( tipo__in = ["tipo%s"%str(j) for j in xrange(1,mod+1)] )
            tipos_escolhidos = []
            for tipo_pai in tipos_pai:
                tipos_filho_e_proprio=tipo_pai.get_descendants(include_self=True)
                rand_tipo = random.randint(0, tipos_filho_e_proprio.__len__()-1)
                tipos_escolhidos.append( tipos_filho_e_proprio[rand_tipo] )

            questao = mommy.make_one(Questao,tipo=tipos_escolhidos,titulo="questao%s"%str(i))
            #forcando verificada, ja que estas questoes sao mocks e nao seriam verificadas automaticamente.
            #por que se fossem iriam dar erro no arquivo fonte.
            questao.verificada=True
            questao.save(verificar=False)
            print "q=%s i=%s mod=%s"%(questao.id,i,mod)
Ejemplo n.º 20
0
    def test_create_many_to_many(self):
        from model_mommy import mommy
        from model_mommy.models import Store

        store = mommy.make_one(Store)
        self.assertEqual(store.employees.count(), 0)
        self.assertEqual(store.customers.count(), 0)
Ejemplo n.º 21
0
    def test_campaigns_operations_as_authorised_users(self):
        # create a campaign that only bill can see
        bills_campaign = mommy.make_one('catamidb.Campaign', id=3)
        assign('view_campaign', self.user_bill, bills_campaign)

        # check that bill can see via the API
        response = self.bill_api_client.get(self.campaign_url, format='json')
        self.assertValidJSONResponse(response)
        self.assertEqual(len(self.deserialize(response)['objects']), 3)

        # check that bill can get to the object itself
        response = self.bill_api_client.get(self.campaign_url + "3/",
                                            format='json')
        self.assertValidJSONResponse(response)

        # check that bob can not see - now we know tastypie API has correct
        # permission validation
        response = self.bob_api_client.get(self.campaign_url, format='json')
        self.assertValidJSONResponse(response)
        self.assertEqual(len(self.deserialize(response)['objects']), 2)

        # check bob can NOT get to the hidden object
        response = self.bob_api_client.get(self.campaign_url + "3/",
                                           format='json')
        self.assertHttpUnauthorized(response)

        #check that anonymous can see public ones as well
        response = self.anon_api_client.get(self.campaign_url, format='json')
        self.assertValidJSONResponse(response)
        self.assertEqual(len(self.deserialize(response)['objects']), 2)

        #check anonymous can NOT get to the hidden object
        response = self.anon_api_client.get(self.campaign_url + "3/",
                                            format='json')
        self.assertHttpUnauthorized(response)
Ejemplo n.º 22
0
    def test_create_many_to_many_with_set_default_quantity(self):

        mommy.MAX_MANY_QUANTITY = 2

        store = mommy.make_one(Store)
        self.assertEqual(store.employees.count(), 2)
        self.assertEqual(store.customers.count(), 2)
Ejemplo n.º 23
0
 def test_view_article_custom_template(self):
     # Check that we are do not using the PrivateArticle anymore
     klass = get_article_class()
     article = mommy.make_one(klass, publication=klass.PUBLISHED, template="standard.html")
     response = self.client.get(article.get_absolute_url())
     self.assertTemplateUsed(response, "standard.html")
     self.assertEqual(200, response.status_code)
Ejemplo n.º 24
0
    def test_create_model_with_slugfield(self):
        from model_mommy import mommy
        from model_mommy.models import DummySlugModel

        dummy_slug_model = mommy.make_one(DummySlugModel)
        self.assertTrue(
            isinstance(dummy_slug_model.slug_field, basestring))
Ejemplo n.º 25
0
 def test_render_template_not_logged(self):
     """render for anonymous"""
     self.client.logout()
     for i in xrange(5):
         mommy.make_one(User)
     
     template = Template(self._template_content())
     
     dummy_request = DummyRequest()
     setattr(dummy_request, 'user', AnonymousUser())
     context = {
         'users': User.objects.all(),
         'request': dummy_request,
     }
     
     template.render(Context(context))
Ejemplo n.º 26
0
    def test_if_data_for_slugfield_is_slug_text(self):
        from model_mommy.models import DummySlugModel
        from model_mommy import mommy

        dummy_slug_model = mommy.make_one(DummySlugModel)
        self.assertTrue(
            self.is_slug(dummy_slug_model.slug_field))
    def test_filling_DecimalField_with_random_decimal(self):
        self.dummy_decimal_model = mommy.make_one(DummyDecimalModel)
        decimal_field = DummyDecimalModel._meta.get_field('decimal_field')

        self.assertTrue(isinstance(decimal_field, DecimalField))
        self.assertTrue(isinstance(self.dummy_decimal_model.decimal_field,
                                   Decimal))
Ejemplo n.º 28
0
 def test_list(self):
     """view list"""
     logged_user = self.user
     faved_users = [mommy.make_one(User, username='******'.format(i)) for i in xrange(5)]
     not_faved_users = [mommy.make_one(User, username='******'.format(i)) for i in xrange(5)]
     
     user_ct = ContentType.objects.get_for_model(User)
     for user in faved_users:
         Favorite.objects.create(user=logged_user, content_type=user_ct, object_id=user.id)
     
     response = self.client.get(reverse('users_favorites_list'))
     self.assertEqual(200, response.status_code)
     for user in faved_users:
         self.assertContains(response, user)
     for user in not_faved_users:
         self.assertNotContains(response, user)
Ejemplo n.º 29
0
    def test_image_operations_as_authorised_users(self):
        # create a campaign & deployment that ONLY bill can see
        bills_campaign = mommy.make_one("catamidb.Campaign", id=3, short_name="cp__1")
        bills_deployment = mommy.make_recipe("catamidb.Deployment3", id=3, campaign=bills_campaign)
        bills_image = mommy.make_recipe("catamidb.Image3", id=3, deployment=bills_deployment)
        assign("view_campaign", self.user_bill, bills_campaign)

        # check that bill can see via the API
        response = self.bill_api_client.get(self.image_url, format="json")
        self.assertValidJSONResponse(response)
        self.assertEqual(len(self.deserialize(response)["objects"]), 3)

        # check that bill can get to the object itself
        response = self.bill_api_client.get(self.image_url + "3/", format="json")
        self.assertValidJSONResponse(response)

        # check that bob can not see - now we know tastypie API has correct
        # permission validation
        response = self.bob_api_client.get(self.image_url, format="json")
        self.assertValidJSONResponse(response)
        self.assertEqual(len(self.deserialize(response)["objects"]), 2)

        # check bob can NOT get to the hidden object
        response = self.bob_api_client.get(self.image_url + "3/", format="json")
        self.assertHttpUnauthorized(response)

        # check that anonymous can see public ones as well
        response = self.anon_api_client.get(self.image_url, format="json")
        self.assertValidJSONResponse(response)
        self.assertEqual(len(self.deserialize(response)["objects"]), 2)

        # check anonymous can NOT get to the hidden object
        response = self.anon_api_client.get(self.image_url + "3/", format="json")
        self.assertHttpUnauthorized(response)
Ejemplo n.º 30
0
 def test_accept_model_as_string(self):
     person = mommy.make_one('model_mommy.person')
     self.assertTrue(isinstance(person, Person))
     person = mommy.prepare_one('model_mommy.Person')
     self.assertTrue(isinstance(person, Person))
     people = mommy.make_many('model_mommy.person')
     [self.assertTrue(isinstance(person, Person)) for person in people]
Ejemplo n.º 31
0
 def test_make_one_should_create_one_object(self):
     """
     make_one method is deprecated, so this test must be removed when the
     method is removed
     """
     person = mommy.make_one(Person)
     self.assertIsInstance(person, Person)
     self.assertTrue(Person.objects.filter(id=person.id))
Ejemplo n.º 32
0
 def setUp(self):
     self.course = mommy.make_one(Course)
     self.data = {
         'course': self.course.id,
         'position': 1,
         'title': 'Task 1',
         'description': 'Easy task',
         'test_code': 'return True'
     }
Ejemplo n.º 33
0
 def setUp(self):
     self.task = mommy.make_one(
         Task,
         test_code=u'return True',
         filename=u'dummy.txt',
         file_content=u'hello world',
     )
     self.url = reverse('core:submit', args=[self.task.uuid])
     self.data = {'sourcecode': u'print "Hello World,"'}
     self.cookie_name = self.task.course.slug + '-locals'
Ejemplo n.º 34
0
    def test_filling_file_field(self):
        self.dummy = mommy.make_one(DummyFileFieldModel)
        field = DummyFileFieldModel._meta.get_field('file_field')
        self.assertIsInstance(field, FileField)
        import time
        path = "/tmp/%s/mock_file.txt" % time.strftime('%Y/%m/%d')

        from django import VERSION
        if VERSION[1] >= 4:
            self.assertEqual(self.dummy.file_field.path, path)
Ejemplo n.º 35
0
 def test_skip_fields_with_default(self):
     dummy = mommy.make_one(DummyDefaultFieldsModel)
     self.assertEqual(dummy.default_char_field, 'default')
     self.assertEqual(dummy.default_text_field, 'default')
     self.assertEqual(dummy.default_int_field, 123)
     self.assertEqual(dummy.default_float_field, 123.0)
     self.assertEqual(dummy.default_date_field, '2011-01-01')
     self.assertEqual(dummy.default_date_time_field, '2011-01-01')
     self.assertEqual(dummy.default_time_field, '00:00:00')
     self.assertEqual(dummy.default_decimal_field, Decimal('0'))
     self.assertEqual(dummy.default_email_field, '*****@*****.**')
     self.assertEqual(dummy.default_slug_field, 'a-slug')
Ejemplo n.º 36
0
    def setUp(self):
        self.compadmin_login = {
            REDIRECT_FIELD_NAME: '/admin/infos/',
            LOGIN_FORM_KEY: 1,
            'username': '******',
            'password': '******',
        }

        # start with a blank slate
        self.competition = Competition.objects.all()[0] # grab any competition
        self.step = self.competition.competitionstep_set.all()[0] # grab a step
        self.c = mommy.make_one(Candidate,
                                competition=self.competition,
                                groups=[])
        self.c2 = mommy.make_one(Candidate,
                                 competition=self.competition,
                                 groups=[])
        self.cja = mommy.make_one(CandidateJuryAllocation,
                                  candidate=self.c,
                                  step=self.step,
                                  jury_members=[])
        self.cja2 = mommy.make_one(CandidateJuryAllocation,
                                   candidate=self.c2,
                                   step=self.step,
                                   jury_members=[])
        self.j1 = mommy.make_one(JuryMember,
                                 competitions=[self.competition],
                                 groups=[])
        self.j2 = mommy.make_one(JuryMember,
                                 competitions=[self.competition],
                                 groups=[])
Ejemplo n.º 37
0
    def test_create_many_to_many(self):

        store = mommy.make_one(Store)
        self.assertEqual(store.employees.count(), 5)
        self.assertEqual(store.customers.count(), 5)
Ejemplo n.º 38
0
 def test_slideshare_link(self):
     m = mommy.make_one(Member,
                        slideshare="pluck",
                        photo="ricks_sunshine.png")
     m.slideshare_link() | should | equal_to(
         "http://www.slideshare.net/pluck")
Ejemplo n.º 39
0
 def test_github_link(self):
     m = mommy.make_one(Member, github="pluck", photo="ricks_sunshine.png")
     m.github_link() | should | equal_to("http://github.com/pluck")
Ejemplo n.º 40
0
    def test_filling_DecimalField_with_random_decimal(self):
        self.dummy_decimal_model = mommy.make_one(DummyDecimalModel)
        decimal_field = DummyDecimalModel._meta.get_field('decimal_field')

        self.assertIsInstance(decimal_field, DecimalField)
        self.assertIsInstance(self.dummy_decimal_model.decimal_field, Decimal)
Ejemplo n.º 41
0
 def test_twitter_link(self):
     m = mommy.make_one(Member, twitter="pluck", photo="ricks_sunshine.png")
     m.twitter_link() | should | equal_to("http://twitter.com/pluck")
Ejemplo n.º 42
0
 def setUp(self):
     self.course = mommy.make_one(Course)
     mommy.make_many(Task, course=self.course)
     self.url = self.course.get_absolute_url()
Ejemplo n.º 43
0
 def test_skip_null(self):
     dummy = mommy.make_one(DummyNullFieldsModel)
     self.assertEqual(dummy.null_foreign_key, None)
     self.assertEqual(dummy.null_integer_field, None)
Ejemplo n.º 44
0
 def test_create_model_with_generic_relation(self):
     dummy = mommy.make_one(DummyGenericRelationModel)
     self.assertTrue(isinstance(dummy, DummyGenericRelationModel))
Ejemplo n.º 45
0
    def test_create_one_to_one(self):
        lonely_person = mommy.make_one(LonelyPerson)

        self.assertEquals(LonelyPerson.objects.all().count(), 1)
        self.assertTrue(isinstance(lonely_person.only_friend, Person))
        self.assertEquals(Person.objects.all().count(), 1)
Ejemplo n.º 46
0
def exist_a_member(step):
    for member in step.hashes:
        mommy.make_one(Member, name=member.get('name'), site=None, lattes=None, photo=None)
Ejemplo n.º 47
0
 def setUp(self):
     self.dummy_int_model = mommy.make_one(DummyIntModel)
Ejemplo n.º 48
0
 def setUp(self):
     self.dummy_positive_int_model = mommy.make_one(DummyPositiveIntModel)
Ejemplo n.º 49
0
 def test_filling_content_type_field(self):
     dummy = mommy.make_one(DummyGenericForeignKeyModel)
     self.assertIsInstance(dummy.content_type, ContentType)
Ejemplo n.º 50
0
 def test_filling_EmailField(self):
     obj = mommy.make_one(DummyEmailModel)
     field = DummyEmailModel._meta.get_field('email_field')
     self.assertIsInstance(field, EmailField)
     self.assertIsInstance(obj.email_field, basestring)
Ejemplo n.º 51
0
 def test_dependent_models_with_ForeignKey(self):
     dog = mommy.make_one(Dog)
     self.assertTrue(isinstance(dog.owner, Person))
Ejemplo n.º 52
0
    def test_make_one_should_create_one_object(self):
        person = mommy.make_one(Person)
        self.assertTrue(isinstance(person, Person))

        # makes sure it is the person we created
        self.assertTrue(Person.objects.filter(id=person.id))
Ejemplo n.º 53
0
 def test_skip_blank(self):
     dummy = mommy.make_one(DummyBlankFieldsModel)
     self.assertEqual(dummy.blank_char_field, '')
     self.assertEqual(dummy.blank_text_field, '')
Ejemplo n.º 54
0
 def test_unsupported_model_raises_an_explanatory_exception(self):
     try:
         mommy.make_one(UnsupportedModel)
         self.fail("Should have raised a TypeError")
     except TypeError, e:
         self.assertTrue('not supported' in repr(e))
Ejemplo n.º 55
0
def member_started_participation_on_project(step, member_name, project_name):
    member_obj = Member.objects.get(name=member_name)
    project_obj = Project.objects.get(name=project_name)
    mommy.make_one(Participation, member=member_obj, project=project_obj)
Ejemplo n.º 56
0
 def test_create_many_to_many_with_set_default_quantity(self):
     store = mommy.make_one(Store)
     self.assertEqual(store.employees.count(), mommy.MAX_MANY_QUANTITY)
     self.assertEqual(store.customers.count(), mommy.MAX_MANY_QUANTITY)
Ejemplo n.º 57
0
 def setUp(self):
     self.person = mommy.make_one(Person)
Ejemplo n.º 58
0
 def test_filling_FloatField_with_a_random_float(self):
     self.dummy_numbers_model = mommy.make_one(DummyNumbersModel)
     float_field = DummyNumbersModel._meta.get_field('float_field')
     self.assertIsInstance(float_field, FloatField)
     self.assertIsInstance(self.dummy_numbers_model.float_field, float)
Ejemplo n.º 59
0
 def test_simple_creating_person_with_parameters(self):
     kid = mommy.make_one(Person, happy=True, age=10, name='Mike')
     self.assertEqual(kid.age, 10)
     self.assertEqual(kid.happy, True)
     self.assertEqual(kid.name, 'Mike')
Ejemplo n.º 60
0
def given_exist_a_project(step):
    for project in step.hashes:
        mommy.make_one(Project, name=project.get('name'), logo=None)