Пример #1
0
 def setUp(self):
     self.tag = Tag(name='test')
     self.tag.save()
     self.user = User.objects.create_user(username='******', email='*****@*****.**')
     self.user.save()
     self.petition = Petition(title='test petition', description='This is a test petition', author=self.user,created_at=timezone.now(),status=1, expires=timezone.now()+timedelta(days=30))
     self.petition.save()
     self.user.profile.petitions_signed.add(self.petition)
Пример #2
0
    def test_list(self):
        petition = Petition(author=self.get_user(), **PETITION)
        petition.save()

        self.client.logout()
        response = self.client.get(reverse('petition-list'))
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        response_data = json.loads(response.content.decode())
        self.assertTrue(isinstance(response_data["results"][0]["author"],
                                   dict))
Пример #3
0
    def test_detail(self):
        self.client.logout()
        petition = Petition(author=self.get_user(), **PETITION)
        petition.save()

        response = self.client.get(
            reverse('petition-detail', args=[petition.id]))
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        response_data = json.loads(response.content.decode())
        self.assertTrue(isinstance(response_data["author"],
                                   dict))  # author is nested object
Пример #4
0
    def test_detail(self):
        self.client.force_authenticate(self.get_staff_user())
        petition = Petition(author=self.get_staff_user(), **PETITION)
        petition.save()

        response = self.client.get(
            reverse('user-detail', args=[self.get_staff_user().id]))
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        response_data = json.loads(response.content.decode())
        self.assertTrue(isinstance(response_data["petitions"][0],
                                   dict))  # petition list consists of objects
        self.assertTrue("author" not in response_data["petitions"]
                        [0])  # petition should not contain author because
Пример #5
0
async def test_websocket_consumer_get(django_user_model):
    username = '******'
    email = '*****@*****.**'
    password = '******'
    django_user_model.objects.create(username=username,
                                     password=password,
                                     email=email)

    user = django_user_model.objects.get(username=username)

    Profile.objects.all().delete()
    Profile.objects.create(user=user,
                           full_name=username,
                           notifications=Notifications.objects.create())
    # Remove all petitions
    Petition.objects.all().delete()

    # Create Tag
    tag = Tag(name='TestTag')
    tag.save()

    pet = Petition(title='Test petition',
                   description='This is a test petition',
                   author=user,
                   created_at=timezone.now(),
                   status=0,
                   expires=timezone.now() + timedelta(days=30))
    pet.save()
    pet.tags.add(tag)
    pet.save()

    communicator = AuthWebsocketCommunicator(PetitionConsumer,
                                             "/ws/",
                                             user=user)

    connected, subprotocol = await communicator.connect()

    assert connected

    await communicator.send_json_to({"command": "get", "id": 45})
    response = await communicator.receive_json_from()
    assert response == {"command": "get", "petition": False}
    """
    dump = serialize_petitions([pet], user)
    await communicator.send_json_to({"command": "get", "id": pet.id})

    response = await communicator.receive_json_from()
    assert response == {"command": "get", "petition": dump}
    """
    await communicator.disconnect()
Пример #6
0
 def setUp(self):
     self.client = Client()
     self.factory = RequestFactory()
     self.superUser = User.objects.create_user(username='******',
                                               email='txu1267',
                                               is_staff=True)
     self.superUser.set_password('test')
     self.superUser.save()
     self.superUser2 = User.objects.create_user(username='******',
                                                email='txu1266',
                                                is_superuser=True)
     self.superUser2.set_password('test')
     self.superUser2.save()
     self.user = User.objects.create_user(username='******',
                                          email='axu7254')
     self.user2 = User.objects.create_user(username='******',
                                           email='cxl1234')
     self.user3 = User.objects.create_user(username='******',
                                           email='abc4321')
     self.tag = Tag(name='Test')
     self.tag.save()
     self.petition = Petition(title='Test petition',
                              description='This is a test petition',
                              author=self.user,
                              created_at=timezone.now(),
                              status=0,
                              expires=timezone.now() + timedelta(days=30))
     self.petition.save()
     self.petition.tags.add(self.tag)
     self.petitionPublished = Petition(
         title='Test petition Published',
         description='This is a test petition Published',
         author=self.user2,
         created_at=timezone.now(),
         status=1,
         expires=timezone.now() + timedelta(days=30))
     self.petitionPublished.save()
Пример #7
0
def petition_create(request):
    """
    Endpoint for creating a new petition.
    This requires the user be signed in.
    Note: This endpoint returns the ID of the petition
          created, in order for JavaScript to redirect
          to the correct petition.
    """
    # Build the user reference.
    user = request.user

    new_user_petitions = user.profile.petitions_created.filter(Q(status=0))
    if new_user_petitions.count() > 0:
        return HttpResponse(new_user_petitions.first().id)

    last_petition = Petition.objects.all().last()

    # Create a new blank petition.
    date = timezone.now()
    new_petition = Petition(
        title=PETITION_DEFAULT_TITLE,
        description=PETITION_DEFAULT_BODY,
        author=user,
        signatures=0,
        created_at=date,
        expires=date + timedelta(days=30),
        in_progress=False,
        id=last_petition.id + 1 if last_petition is not None else 0
    )
    new_petition.save()

    # Add the petition's ID to the user's created petitions list.
    petition_id = new_petition.id
    user.profile.petitions_created.add(petition_id)

    # Auto-sign the author to the petition.
    user.profile.petitions_signed.add(new_petition)
    user.save()
    new_petition.last_signed = timezone.now()
    new_petition.signatures = F('signatures') + 1
    new_petition.save()

    logger.info(
        "user " + user.email + " created a new petition called " + new_petition.title + " ID: " + str(new_petition.id))

    # Return the petition's ID to be used to redirect the user to the new petition.
    return HttpResponse(str(petition_id))
Пример #8
0
 def get_petition(cls):
     if not hasattr(cls, "_petition"):
         user = cls.get_users()[0]
         cls._petition = Petition(author=user, **PETITION)
         cls._petition.save()
     return cls._petition
Пример #9
0
    def generate_petitions(self, users, expired, unpub, removed, review, sigs,
                           num_petitions, resp):
        petitionlst = []
        self.stdout.write('Generating Petition objects')
        text = Text('en')
        try:
            with transaction.atomic():
                for x in range(0, num_petitions):
                    # Generate/Grab data
                    num_sentences = random.randint(1, 6)
                    title = text.sentence()[0:80]
                    description = text.text(num_sentences)
                    author = random.choice(users)
                    if sigs:
                        signatures = sigs.pop()
                    else:
                        signatures = random.randint(1, len(users))
                    created_at = timezone.now() - timedelta(
                        days=random.randint(0, 10))
                    status = 1
                    expires = created_at + timedelta(days=30)
                    last_signed = created_at + timedelta(
                        days=random.randint(0, 10))
                    petition = Petition()
                    if expired > 0:
                        created_at = timezone.now() - timedelta(days=31)
                        expires = created_at + timedelta(days=30)
                        last_signed = created_at + timedelta(
                            days=random.randint(1, 30))
                        expired -= 1
                    elif unpub > 0:
                        status = 0
                        unpub -= 1
                    elif removed > 0:
                        status = 2
                        removed -= 1
                    elif review > 0:
                        status = 3
                        review -= 1

                    petition.author = author
                    petition.title = title
                    petition.description = description
                    petition.signatures = signatures
                    petition.created_at = created_at
                    petition.status = status
                    petition.expires = expires
                    petition.last_signed = last_signed
                    if resp > 0:
                        petition.has_response = True
                        resp -= 1

                    petition.save()
                    petitionlst.append(petition)
            self.stdout.write(
                self.style.SUCCESS('Successfully created %s Petition objects' %
                                   num_petitions))
            return petitionlst
        except Exception as e:
            self.stdout.write(
                self.style.ERROR(
                    'Failed to generate %s Petition objects\n %s' %
                    (len(users), e)))
            print(traceback.format_exc())
            return None