Пример #1
0
 def setUp(self):
     # Every test needs a client.
     User.objects.all().delete()
     self.user_smb = User.objects.create_user('somebody__else',
                                              '*****@*****.**',
                                              'somebody__else')
     self.user_smb.is_staff = True
     self.user_smb.save()
     self.user = User.objects.create_user('new_unittest',
                                          '*****@*****.**',
                                          'new_test_password')
     init_user_group('w3af_webui')
     call_command('set_role_for_user', 'new_unittest')
     self.user.is_staff = True
     self.user.is_superuser = True
     self.user.save()
     self.client = Client()
     self.client.login(username=self.user.username,
                       password='******')
     self.profile = any_model(ScanProfile, user=self.user)
     self.target = any_model(Target, user=self.user)
     self.not_mine_target = any_model(Target, user=self.user_smb)
     self.scan_task = any_model(
         ScanTask,
         user=self.user,
         status=settings.TASK_STATUS['free'],
         target=self.target,
         last_updated='0',
     )
     self.scan = Scan.objects.create(
         scan_task=self.scan_task,
         data='test',
     )
    def test_fk_referencing_self(self):
        self_referencing = any_model(SelfReferencingModel)
        self.assertTrue(self_referencing.parent is None)

        root = any_model(SelfReferencingModel)
        child = any_model(SelfReferencingModel, parent=root)
        self.assertEqual(type(child.parent), SelfReferencingModel)
Пример #3
0
 def setUp(self):
     User.objects.all().delete()
     # Every test needs a client.
     self.user = User.objects.create_user('new_unittest1',
                                          '*****@*****.**',
                                          'new_test_password')
     self.user.save()
     self.client = Client()
     self.client.login(username='******',
                       password='******')
     self.profile = any_model(ScanProfile)
     self.target = any_model(Target)
     self.scan_task = any_model(
         ScanTask,
         status=settings.TASK_STATUS['free'],
         target=self.target,
         last_updated='0',
     )
     self.scan = Scan.objects.create(
         scan_task=self.scan_task,
         user=self.user,
     )
     self.vuln = any_model(
         Vulnerability,
         scan=self.scan,
     )
     # Every test needs access to the request factory.
     self.factory = RequestFactory()
Пример #4
0
 def setUp(self):
     self.range_contains = any_model(IpRange,
                                     start_ip=3568355840,
                                     end_ip=3568355843)
     self.range_not_contains = any_model(IpRange,
                                         start_ip=3568355844,
                                         end_ip=3568355851)
    def test_fk_referencing_self(self):
        self_referencing = any_model(SelfReferencingModel)
        self.assertTrue(self_referencing.parent is None)

        root = any_model(SelfReferencingModel)
        child = any_model(SelfReferencingModel, parent=root)
        self.assertEqual(type(child.parent), SelfReferencingModel)
Пример #6
0
 def setUp(self):
     # Every test needs a client.
     User.objects.all().delete()
     self.user_smb = User.objects.create_user('somebody__else', '*****@*****.**',
                                              'somebody__else')
     self.user_smb.is_staff = True
     self.user_smb.save()
     self.user = User.objects.create_user('new_unittest', '*****@*****.**',
                                          'new_test_password')
     init_user_group('w3af_webui')
     call_command('set_role_for_user',
                  'new_unittest')
     self.user.is_staff = True
     self.user.is_superuser = True
     self.user.save()
     self.client = Client()
     self.client.login(username=self.user.username,
                       password='******')
     self.profile = any_model(ScanProfile, user=self.user)
     self.target = any_model(Target, user=self.user)
     self.not_mine_target = any_model(Target, user=self.user_smb)
     self.scan_task = any_model(ScanTask,
                                user=self.user,
                                status=settings.TASK_STATUS['free'],
                                target=self.target,
                                last_updated='0',
                                )
     self.scan = Scan.objects.create(scan_task=self.scan_task,
                                     data='test',
                                     )
 def test_short_generic_fk_creation(self):
     content_object = any_model(RelatedContentModel)
     related_object = any_model(ModelWithGenericRelation,
                                content_object=content_object)
     self.assertEqual(related_object.content_object, content_object)
     self.assertEqual(related_object.content_type, ContentType.objects.get_for_model(
         RelatedContentModel))
     self.assertEqual(related_object.object_id, content_object.id)
 def test_short_generic_fk_creation(self):
     content_object = any_model(RelatedContentModel)
     related_object = any_model(ModelWithGenericRelation,
                                content_object=content_object)
     self.assertEqual(related_object.content_object, content_object)
     self.assertEqual(related_object.content_type, ContentType.objects.get_for_model(
         RelatedContentModel))
     self.assertEqual(related_object.object_id, content_object.id)
Пример #9
0
    def setUp(self):
        self.factory = RequestFactory()
        self.question_user = User.objects.create_user(
            username='******', email='*****@*****.**', password='******')

        self.answer_user = User.objects.create_user(
            username='******', email='*****@*****.**', password='******')
        self.question = any_model(Question, pk=1, author=self.question_user)
        self.answer = any_model(Answer, pk=1, author=self.question_user, question=self.question)
Пример #10
0
 def test_get_profile(self):
     scan_profile = any_model(ScanProfile)
     any_model(ProfilesTasks,
               scan_task=self.scan_task,
               scan_profile=scan_profile)
     (profile_name, xml_report) = get_profile(self.scan_task, '/var/tmp',
                                              'test.html')
     #check that this file exist
     self.assertTrue(os.access(profile_name, os.F_OK))
Пример #11
0
 def test_set_task_status_free(self):
     scan_task = any_model(ScanTask, status=settings.TASK_STATUS['lock'],)
     scan = any_model(Scan, scan_task=scan_task,
                     status=settings.SCAN_STATUS['in_process'],
                     start=datetime.now(),
                     pid=1)
     self.assertEqual(scan_task.status, settings.TASK_STATUS['lock'])
     scan.set_task_status_free()
     self.assertEqual(scan_task.status, settings.TASK_STATUS['free'])
Пример #12
0
 def test_get_profile(self):
     scan_profile = any_model(ScanProfile)
     any_model(ProfilesTasks,
               scan_task=self.scan_task,
               scan_profile=scan_profile)
     (profile_name, xml_report) = get_profile(self.scan_task,
                                              '/var/tmp',
                                              'test.html')
     #check that this file exist
     self.assertTrue(os.access(profile_name, os.F_OK))
Пример #13
0
 def setUp(self):
     # Every test needs a client.
     self.user = User.objects.create_user('new_unittest',
                                          '*****@*****.**',
                                          'new_test_password')
     self.user.save()
     self.target = any_model(Target, user=self.user)
     self.scan_task = any_model(ScanTask,
                                user=self.user,
                                status=settings.TASK_STATUS['free'],
                                target=self.target,
                                last_updated='0',)
     self.scan = any_model(Scan, scan_task=self.scan_task, data='test')
Пример #14
0
    def test_relations(self):
        self.country = any_model(Country)
        self.region = any_model(Region, country=self.country)
        self.city = any_model(City, region=self.region)
        range = any_model(IpRange,
                          start_ip=struct.unpack('!L', socket.inet_aton('43.123.56.0'))[0],
                          end_ip=struct.unpack('!L', socket.inet_aton('43.123.56.255'))[0],
                          city=self.city, region=self.region, country=self.country)

        ip_range = IpRange.objects.by_ip('43.123.56.12')
        self.assertEqual(ip_range.city, self.city)
        self.assertEqual(ip_range.city.region, self.region)
        self.assertEqual(ip_range.city.region.country, self.country)
Пример #15
0
 def test_set_task_status_free(self):
     scan_task = any_model(
         ScanTask,
         status=settings.TASK_STATUS['lock'],
     )
     scan = any_model(Scan,
                      scan_task=scan_task,
                      status=settings.SCAN_STATUS['in_process'],
                      start=datetime.now(),
                      pid=1)
     self.assertEqual(scan_task.status, settings.TASK_STATUS['lock'])
     scan.set_task_status_free()
     self.assertEqual(scan_task.status, settings.TASK_STATUS['free'])
Пример #16
0
 def setUp(self):
     # Every test needs a client.
     self.user = User.objects.create_user('new_unittest',
                                          '*****@*****.**',
                                          'new_test_password')
     self.user.save()
     self.target = any_model(Target, user=self.user)
     self.scan_task = any_model(
         ScanTask,
         user=self.user,
         status=settings.TASK_STATUS['free'],
         target=self.target,
         last_updated='0',
     )
     self.scan = any_model(Scan, scan_task=self.scan_task, data='test')
Пример #17
0
 def setUp(self):
     Scan.objects.all().delete()
     user = User.objects.create_user('svetleo', '*****@*****.**', '!')
     user.save()
     self.target = any_model(Target)
     self.scan_task = any_model(ScanTask,
                                user=user,
                                status=settings.TASK_STATUS['free'],
                                target=self.target,
                                last_updated='0',
                                cron="",)
     self.scan = Scan.objects.create(
                             scan_task=self.scan_task,
                             data='test',
                             status=settings.SCAN_STATUS['in_process'])
Пример #18
0
    def test_oneto_one_autocreate(self):
        result = any_model(ModelWithOneToOneField)
        self.assertEqual(type(result), ModelWithOneToOneField)
        self.assertTrue(result.name is not None)

        self.assertEqual(type(result.related), OneToOneRelated)
        self.assertTrue(result.related.name is not None)
Пример #19
0
 def setUp(self):
     self.scan_task = any_model(
         ScanTask,
         status=settings.TASK_STATUS['free'],
         last_updated='0',
     )
     self.scan_task.save()
Пример #20
0
def any_user(password=None, permissions=None, groups=None, **kwargs):
    """
    Shortcut for creating Users

    Permissions could be a list of permission names

    If not specified, creates active, non superuser and non staff user
    """
    permissions = permissions or []
    groups = groups or []
    is_active = kwargs.pop('is_active', True)
    is_superuser = kwargs.pop('is_superuser', False)
    is_staff = kwargs.pop('is_staff', False)

    user = any_model(User, is_active=is_active, is_superuser=is_superuser,
                     is_staff=is_staff, **kwargs)

    for group_name in groups:
        group = Group.objects.get(name=group_name)
        user.groups.add(group)

    for permission_name in permissions:
        app_label, codename = permission_name.split('.')
        permission = Permission.objects.get(
            content_type__app_label=app_label,
            codename=codename)
        user.user_permissions.add(permission)

    if password:
        user.set_password(password)

    user.save()
    return user
    def test_fk_relation_autocreate(self):
        result = any_model(BaseModel)

        self.assertEqual(type(result), BaseModel)

        self.assertEqual(type(result.related), RelatedModel)
        self.assertTrue(result.related.name is not None)
Пример #22
0
    def setUp(self):
        self.client = Client()
        self.url = '/set_location/'
        self.location = any_model(MyCustomLocation)

        self.location_model_patcher = patch.object(settings, 'GEOIP_LOCATION_MODEL', 'test_app.models.MyCustomLocation')
        self.location_model = self.location_model_patcher.start()
Пример #23
0
def any_user(password=None, permissions=[], groups=[], **kwargs):
    """
    Shortcut for creating Users

    Permissions could be a list of permission names

    If not specified, creates active, non superuser
    and non staff user
    """

    is_active = kwargs.pop('is_active', True)
    is_superuser = kwargs.pop('is_superuser', False)
    is_staff = kwargs.pop('is_staff', False)

    user = any_model(User, is_active = is_active, is_superuser = is_superuser,
                     is_staff = is_staff, **kwargs)

    for group_name in groups :
        group = Group.objects.get(name=group_name)
        user.groups.add(group)

    for permission_name in permissions:
        app_label, codename = permission_name.split('.')
        permission = Permission.objects.get(
            content_type__app_label=app_label,
            codename=codename)
        user.user_permissions.add(permission)

    if password:
        user.set_password(password)

    user.save()
    return user
    def test_oneto_one_autocreate(self):
        result = any_model(ModelWithOneToOneField)
        self.assertEqual(type(result), ModelWithOneToOneField)
        self.assertTrue(result.name is not None)

        self.assertEqual(type(result.related), OneToOneRelated)
        self.assertTrue(result.related.name is not None)
    def test_add_friends_tag_request_sent(self):
        '''
        Test to run add_friends_tag when user's sent request
        '''
        # prepare environ
        any_model(FriendshipRequest, from_user = self.user1, to_user = self.user2, accepted = False)

        # testing code
        t = Template('{% load friends_tags %} {% add_to_friends user2 user1 %}')
        rendered = t.render(Context({
            'user1' : self.user1,
            'user2' : self.user2
        }))

        # checking section
        self.assertRegexpMatches(rendered, 'Cancel')
    def test_fk_relation_autocreate(self):
        result = any_model(BaseModel)

        self.assertEqual(type(result), BaseModel)

        self.assertEqual(type(result.related), RelatedModel)
        self.assertTrue(result.related.name is not None)
Пример #27
0
    def test_relations(self):
        self.country = any_model(Country)
        self.region = any_model(Region, country=self.country)
        self.city = any_model(City, region=self.region)
        range = any_model(
            IpRange,
            start_ip=struct.unpack('!L', socket.inet_aton('43.123.56.0'))[0],
            end_ip=struct.unpack('!L', socket.inet_aton('43.123.56.255'))[0],
            city=self.city,
            region=self.region,
            country=self.country)

        ip_range = IpRange.objects.by_ip('43.123.56.12')
        self.assertEqual(ip_range.city, self.city)
        self.assertEqual(ip_range.city.region, self.region)
        self.assertEqual(ip_range.city.region.country, self.country)
Пример #28
0
 def test_foreignkey_constraint_succeed(self):
     result = any_model(
         ModelWithConstraintOnForeignKey,
         on_delete=models.CASCADE,
     )
     self.assertTrue(
         result.timestamp.start_time <= result.timestamp.end_time, )
Пример #29
0
 def setUp(self):
     Scan.objects.all().delete()
     user = User.objects.create_user('svetleo', '*****@*****.**', '!')
     user.save()
     self.target = any_model(Target)
     self.scan_task = any_model(
         ScanTask,
         user=user,
         status=settings.TASK_STATUS['free'],
         target=self.target,
         last_updated='0',
         cron="",
     )
     self.scan = Scan.objects.create(
         scan_task=self.scan_task,
         data='test',
         status=settings.SCAN_STATUS['in_process'])
    def test_created_model_with_custom_field(self):
        model = any_model(ModelWithCustomField)

        self.assertEqual(type(model), ModelWithCustomField)
        self.assertEqual(len(model._meta.fields), len(ModelWithCustomField._meta.local_fields))

        self.assertTrue(model.slug)
        self.assertTrue(isinstance(model.slug, six.string_types))
Пример #31
0
 def test_unlock_task(self, mock_kill_process):
     '''test for scan task delay'''
     scan_task = any_model(
         ScanTask,
         status=settings.TASK_STATUS['lock'],
     )
     scan = any_model(Scan,
                      scan_task=scan_task,
                      status=settings.SCAN_STATUS['in_process'],
                      start=datetime.now(),
                      pid=1)
     message = 'from tests'
     mock_kill_process.return_value = True
     ################################################
     self.assertFalse(mock_kill_process.called)
     self.assertEqual(scan.status, settings.SCAN_STATUS['in_process'])
     self.assertEqual(scan_task.status, settings.TASK_STATUS['lock'])
     # call unlock_task mothod
     result = scan.unlock_task(message)
     self.assertTrue(mock_kill_process.called)
     self.assertTrue(result)
     self.assertEqual(scan_task.status, settings.TASK_STATUS['free'])
     self.assertEqual(scan.status, settings.SCAN_STATUS['fail'])
     self.assertEqual(scan.result_message, message)
     ################################################
     scan_done = any_model(Scan,
                           scan_task=scan_task,
                           status=settings.SCAN_STATUS['done'],
                           start=datetime.now())
     self.assertEqual(scan_done.status, settings.SCAN_STATUS['done'],
                      'done status before call')
     result = scan_done.unlock_task(message)
     self.assertFalse(result,
                      'невозмозно завершить просесс со статусом done')
     self.assertEqual(scan_done.status, settings.SCAN_STATUS['done'],
                      'done status after call')
     ################################################
     scan_fail = any_model(Scan,
                           scan_task=scan_task,
                           status=settings.SCAN_STATUS['fail'],
                           start=datetime.now())
     self.assertEqual(scan_fail.status, settings.SCAN_STATUS['fail'])
     result = scan_fail.unlock_task(message)
     self.assertFalse(result,
                      'невозмозно завершить просесс со статусом fail')
     self.assertEqual(scan_fail.status, settings.SCAN_STATUS['fail'])
    def test_created_model_with_custom_field(self):
        model = any_model(ModelWithCustomField)

        self.assertEqual(type(model), ModelWithCustomField)
        self.assertEqual(len(model._meta.fields), len(ModelWithCustomField._meta.local_fields))

        self.assertTrue(model.slug)
        self.assertTrue(isinstance(model.slug, basestring))
Пример #33
0
 def setUp(self):
     PeriodicTask.objects.all().delete()
     self.task, created = PeriodicTask.objects.get_or_create(
                     name='test',
                     task='w3af_webui.tasks.test_task',
                     )
     self.scan_task = any_model(ScanTask,
                        last_updated='0',)
Пример #34
0
 def test_process_response_ok(self, mock, mock_location_set):
     mock.return_value = None
     base_response = HttpResponse()
     self.get_location_mock.return_value = mycity = any_model(City)
     self.middleware.process_request(self.request)
     self.middleware.process_response(self.request, base_response)
     mock.assert_called_once_with(request=self.request, response=base_response)
     # workaround simplelazyobject
     self.assertEqual(str(mycity), str(mock_location_set.call_args[1]["location"]))
    def test_friendship_request_accept(self):
        '''
        Test to accept friendship request
        '''
        # prepare environ
        any_model(FriendshipRequest, from_user = self.user2, to_user = self.user1)
        any_model(FriendshipRequest, from_user = self.user1, to_user = self.user2)

        # call testing code
        self.call_testing_code()

        # checking section
        # users must be friends now
        self.assertEqual(
            Friendship.objects.are_friends(
                self.user1,
                self.user2
            ),
            True,
            "F**k!!! User1 and User2 aren't friends."
        )

        # there isn't unacceptable request now
        self.assertEqual(
            FriendshipRequest.objects.filter(
                from_user=self.user2,
                to_user=self.user1,
                accepted=False
            ).count(),
            0,
            "F**k!!! There is unaccepted request from user2 to user1"
        )

        # there's one accepted request now
        self.assertEqual(
            FriendshipRequest.objects.filter(
                from_user=self.user2,
                to_user=self.user1,
                accepted=True
            ).count(),
            1,
            'F**k!!! There isn\'t accepted request from user2 to user1'
        )
Пример #36
0
 def setUp(self):
     PeriodicTask.objects.all().delete()
     self.task, created = PeriodicTask.objects.get_or_create(
         name='test',
         task='w3af_webui.tasks.test_task',
     )
     self.scan_task = any_model(
         ScanTask,
         last_updated='0',
     )
    def test_model_creation_succeed(self):
        result = any_model(SimpleModel)

        self.assertEqual(type(result), SimpleModel)
        self.assertEqual(len(result._meta.fields), len(SimpleModel._meta.local_fields))

        for field, original_field in zip(result._meta.fields, SimpleModel._meta.local_fields):
            value = getattr(result, field.name)
            if field.name != 'null_boolead_field':
                self.assertTrue(value is not None, "%s is uninitialized" % field.name)
            self.assertTrue(isinstance(field, original_field.__class__), "%s has correct field type" % field.name)
Пример #38
0
def any_model_with_defaults(cls, **attrs):
    """Use model-provided defaults"""

    for field in cls._meta.fields:
        default = field.default
        if default is not NOT_PROVIDED:
            if isfunction(default) or ismethod(default):
                # for stuff like default=datetime.now
                default = default()
            attrs.setdefault(field.name, default)

    return any_model(cls, **attrs)
Пример #39
0
 def test_create_scan(self):
     '''test for scan task delay'''
     scan_task = any_model(ScanTask,
                           status=settings.TASK_STATUS['free'],
                           last_updated='0')
     self.assertEqual(0, Scan.objects.count())
     scan = scan_task.create_scan(self.user)
     self.assertEqual(1, Scan.objects.count())
     self.assertEqual(scan_task.status, settings.TASK_STATUS['lock'])
     self.assertNotEqual(scan_task.last_updated, '0')
     self.assertEqual(scan.scan_task, scan_task)
     self.assertNotEqual(scan.start, '0')
    def test_model_creation_succeed(self):
        result = any_model(SimpleModel)

        self.assertEqual(type(result), SimpleModel)
        self.assertEqual(len(result._meta.fields),
                         len(SimpleModel._meta.local_fields))

        for field, original_field in zip(result._meta.fields,
                                         SimpleModel._meta.local_fields):
            value = getattr(result, field.name)
            if field.name != 'null_boolead_field':
                self.assertTrue(value is not None,
                                "%s is uninitialized" % field.name)
            self.assertTrue(isinstance(field, original_field.__class__),
                            "%s has correct field type" % field.name)
Пример #41
0
def any_model_with_defaults(cls, **attrs):
    """Use model-provided defaults"""

    for field in cls._meta.fields:
        default = field.default
        if default is not NOT_PROVIDED:
            if callable(default):
                # for stuff like default=datetime.now
                default = default()
            if isinstance(field, (ForeignKey, OneToOneField)):
                Model = compat.get_remote_field_model(field)
                if not isinstance(default, Model):
                    try:
                        default = Model.objects.get(pk=default)
                    except Model.DoesNotExist:
                        pass
            attrs.setdefault(field.name, default)

    return any_model(cls, **attrs)
Пример #42
0
def any_model_with_defaults(cls, **attrs):
    """Use model-provided defaults"""

    for field in cls._meta.fields:
        default = field.default
        if default is not NOT_PROVIDED:
            if isfunction(default) or ismethod(default):
                # for stuff like default=datetime.now
                default = default()
            if isinstance(field, (ForeignKey, OneToOneField)):
                if django.VERSION >= (1, 9):
                    Model = field.target_field.model
                else:
                    Model = field.related_field.model
                if not isinstance(default, Model):
                    try:
                        default = Model.objects.get(pk=default)
                    except Model.DoesNotExist:
                        pass
            attrs.setdefault(field.name, default)

    return any_model(cls, **attrs)
Пример #43
0
 def test_send_mail_notify(self):
     # Empty the test outbox
     mail.outbox = []
     # scan without vulnerabilities
     result = send_mail_only_bad.notify(self.user,
                                        self.scan.scan_task.target,
                                        self.scan.id)
     self.assertEqual(
         len(mail.outbox), 0,
         'Should not send notification about scan without vulnerabilities')
     self.assertTrue(result, 'Should return True if error was not happend')
     vulnerability = any_model(
         Vulnerability,
         scan=self.scan,
     )
     # scan without vulnerabilities
     result = send_mail_only_bad.notify(self.user,
                                        self.scan.scan_task.target,
                                        self.scan.id)
     self.assertEqual(
         len(mail.outbox), 1,
         'Should send notification about scan with vulnerabilities')
     self.assertTrue(result)
Пример #44
0
 def test_qobject_specification(self):
     result = any_model(RelatedToQObject, related=Q(pk=self.related.pk))
     self.assertEqual(self.related, result.related)
Пример #45
0
 def setUp(self):
     self.related = any_model(QObjectRelated)
Пример #46
0
 def test_created_value_pass_validation(self):
     result = any_model(ModelWithValidatedField)
     validate_even(result.even_field)
 def _test_create_related_redefied(self):
     result = any_model(RelatedToRedefined)
     self.assertEqual(result.related.name, 'test')
 def test_redefined_creation_partial_specification(self):
     result = any_model(Redefined, name="test2")
     self.assertEqual(result.name, 'test2')
 def test_redefined_creation(self):
     result = any_model(Redefined)
     self.assertEqual(result.name, 'test')