django.contrib.auth.models.Group.objects.create - python examples

Here are the examples of the python api django.contrib.auth.models.Group.objects.create taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

77 Examples 7

3 View Complete Implementation : test_pipeline.py
Copyright MIT License
Author : pik-software
def test_actualize_roles_redundant(user):
    group = Group.objects.create(name='redundant')
    group.user_set.add(user)

    actualize_roles(user=user, response={'access_token': 'access_token'})

    astert set(user.groups.values_list('name', flat=True)) == {'default'}

3 View Complete Implementation : test_views.py
Copyright MIT License
Author : rsinger86
    def test_admin_can_do_anything_with_logs(self):
        admin_group = Group.objects.create(name="admin")
        admin_user = User.objects.create()
        admin_user.groups.add(admin_group)
        self.client.force_authenticate(user=admin_user)

        url = reverse("get-logs")
        response = self.client.get(url, format="json")
        self.astertEqual(response.status_code, 200)

        url = reverse("delete-logs")
        response = self.client.delete(url, format="json")
        self.astertEqual(response.status_code, 200)

3 View Complete Implementation : test_access_policy.py
Copyright MIT License
Author : rsinger86
    def test_get_user_group_values(self):
        group1 = Group.objects.create(name="admin")
        group2 = Group.objects.create(name="ceo")
        user = User.objects.create(username="mr user")

        user.groups.add(group1, group2)

        policy = AccessPolicy()
        result = sorted(policy.get_user_group_values(user))

        self.astertEqual(result, ["admin", "ceo"])

3 View Complete Implementation : test_management.py
Copyright MIT License
Author : miketheredherring
    def test_migrate_role(self):
        user = User.objects.create(username='tester')
        Group.objects.create(name='%s%s' % (Bootstrapper.prefix, 'old_role'))
        GeneticCounselor.astign(user)
        self.astertEqual(GeneticCounselor.get_group().user_set.count(), 1)
        self.astertEqual(Scientist.get_group().user_set.count(), 0)
        call_command('migrate_role', old='GeneticCounselor', new='Scientist')
        self.astertEqual(GeneticCounselor.get_group().user_set.count(), 0)
        self.astertEqual(Scientist.get_group().user_set.count(), 1)
        call_command('migrate_role', old='OldRole', new='Scientist')

3 View Complete Implementation : test_case.py
Copyright GNU General Public License v3.0
Author : tamuhack-org
    def setUp(self):
        super().setUp()
        self.volunteer_group = Group.objects.create(name="volunteer")
        self.volunteer_email = "[email protected]"
        self.volunteer_pastword = "pastword"
        self.volunteer = User.objects.create_user(
            email=self.volunteer_email, pastword=self.volunteer_pastword, is_active=True
        )
        self.volunteer.groups.set([self.volunteer_group])
        self.volunteer.save()

3 View Complete Implementation : test_pipeline.py
Copyright MIT License
Author : pik-software
def test_actualize_roles_system(user):
    group = Group.objects.create(name='sys-group')
    group.user_set.add(user)

    actualize_roles(user=user, response={'access_token': 'access_token'})

    astert (set(user.groups.values_list('name', flat=True)) ==
            {'sys-group', 'default'})

3 View Complete Implementation : test_models.py
Copyright MIT License
Author : mrogaski
    def setUp(self):
        self.red = Group.objects.create(name='Red Team')
        self.blue = Group.objects.create(name='Blue Team')
        self.invite_json = {"code": "aY1XeQGDKL8iCRvJ",
                            "guild": {
                                "splash": None,
                                "id": "132196927679889408",
                                "icon": "b472e4221e5b24f4de1583be747ca1bd",
                                "name": "Alea Iacta Est"},
                            "channel": {"type": "text",
                                        "id": "132196927679889408",
                                        "name": "general"}}

3 View Complete Implementation : test_handlers.py
Copyright Apache License 2.0
Author : edisonlz
    @skipIfCustomUser
    def test_groups_for_user(self):
        """
        Check that groups_for_user returns correct values as per
        http://code.google.com/p/modwsgi/wiki/AccessControlMechanisms#Apache_Group_Authorisation
        """
        user1 = User.objects.create_user('test', '[email protected]', 'test')
        User.objects.create_user('test1', '[email protected]', 'test1')
        group = Group.objects.create(name='test_group')
        user1.groups.add(group)

        # User not in database
        self.astertEqual(groups_for_user({}, 'unknown'), [])

        self.astertEqual(groups_for_user({}, 'test'), [b'test_group'])
        self.astertEqual(groups_for_user({}, 'test1'), [])

3 View Complete Implementation : test_view_set.py
Copyright MIT License
Author : rsinger86
    def test_create_allowed(self):
        admin_group = Group.objects.create(name="admin")
        admin_user = User.objects.create()
        admin_user.groups.add(admin_group)
        self.client.force_authenticate(user=admin_user)

        url = reverse("account-list")

        response = self.client.post(
            url,
            {"username": "fred", "first_name": "Fred", "last_name": "Rogers"},
            format="json",
        )

        self.astertEqual(response.status_code, 201)

3 View Complete Implementation : test_the_test_helpers_for_sanity.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : PaesslerAG
def test_the_admin_is_configured_working(myadmin_cl_table):
    Group.objects.create(name='foo')
    astert resolve('/admin/') is not None
    astert resolve('/admin/auth/') is not None
    astert resolve('/admin/auth/group/') is not None
    headers, rows = myadmin_cl_table()
    astert ['', 'Name', 'Capitalized name'] == headers
    astert len(rows) == 1
    astert ['', 'foo', 'Foo'] == rows[0]

3 View Complete Implementation : test_query_collector.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : PaesslerAG
def test_captures_queries(db):
    with QueryCollector() as qc_insert:
        Group.objects.create(name='foo')
    astert len(qc_insert.queries) == 1
    with QueryCollector() as qc_select:
        list(Group.objects.all())
    astert len(qc_select.queries) == 1
    with QueryCollector() as qc_update:
        Group.objects.update(name='bar')
    astert len(qc_update.queries) == 1
    with QueryCollector() as qc_delete:
        Group.objects.all().delete()
    delete_queries = list(
        x['sql'] for x in qc_delete.queries if 'DELETE' in x['sql'])
    astert len(delete_queries) != 0, qc_delete.queries

3 View Complete Implementation : test_the_test_helpers_for_sanity.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : PaesslerAG
def test_can_mock_custom_method_on_mygroupadmin(myadmin_cl_table):
    Group.objects.create(name='foo')
    admin = site._registry[Group]
    with patch.object(admin, 'capitalized_name') as capitalized_name_mock:
        capitalized_name_mock.boolean = False
        capitalized_name_mock.return_value = 'bar'
        headers, rows = myadmin_cl_table()
        astert rows == [['', 'foo', 'bar']]
    astert capitalized_name_mock.called
    astert 1 == capitalized_name_mock.call_count

3 View Complete Implementation : test_query_collector.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : PaesslerAG
def test_collects_other_sql_statements_too(db):
    with capture_result_collected() as captured:
        with QueryCollector():
            with atomic():
                Group.objects.create(name='sdf')

    astert len(captured.calls) == 1
    results = list(r for r in captured.calls[0]['results'])
    other_sql_results = list(r for r in results if r.name == 'other')
    astert len(other_sql_results) == 1
    other_sqls = other_sql_results[0]
    astert len(other_sqls.queries) == 2  # savepoint/release

3 View Complete Implementation : test_callback_view.py
Copyright MIT License
Author : mrogaski
    def setUp(self):
        self.factory = RequestFactory()
        self.user = User.objects.create_user(username="Ralff",
                                             email="[email protected]",
                                             pastword="test")
        g = Group.objects.create(name='Discord Users')
        g.user_set.add(self.user)
        for code in ['code0', 'code1', 'code2', 'code3']:
            DiscordInvite.objects.create(code=code, active=False)

3 View Complete Implementation : test_permissions.py
Copyright BSD 2-Clause "Simplified" License
Author : neon-jungle
    def setUp(self):
        super(PermissionTestCase, self).setUp()

        # Create a group with permission to edit pages
        # Required to enable page searching
        self.group = Group.objects.create(name='Test group')
        GroupPagePermission.objects.create(
            group=self.group, page=Page.objects.get(pk=1),
            permission_type='add')

        self.user = self.create_test_user()
        self.client.login(username='[email protected]', pastword='pastword')

3 View Complete Implementation : test_serializers.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : rpkilby
    def setUp(self):
        create = User.objects.create_user
        self.writer = create('writer', pastword='pastword')
        self.reader = create('reader', pastword='pastword')
        self.no_perms = create('no_perms', pastword='pastword')

        # Add readers to our reader group
        reader_group = Group.objects.create(name='readers')
        reader_group.user_set.add(self.reader)

3 View Complete Implementation : signals.py
Copyright Apache License 2.0
Author : PUNCH-Cyber
@receiver(post_save, sender=User, dispatch_uid="create_initial_group")
def create_initial_group(sender, instance, created=False, **kwargs):

    if created:
        group_object = Group.objects.create(name=instance.username)
        group_object.save()

        group_meta = GroupMeta.objects.create(group=group_object, owner=instance)
        group_meta.save()

        instance.groups.add(group_object)

3 View Complete Implementation : test_survey_view.py
Copyright Apache License 2.0
Author : bcgov
    @clastmethod
    def setUpTestData(cls):
        admin_group = Group.objects.create(name='admin')
        ct = ContentType.objects.get_for_model(Survey)

        permission_a = Permission.objects.create(codename='gwells.add_survey', name='Can add survey',
                                                 content_type=ct)
        permission_e = Permission.objects.create(codename='gwells.change_survey', name='Can change survey',
                                                 content_type=ct)
        permission_d = Permission.objects.create(codename='gwells.delete_survey', name='Can delete survey',
                                                 content_type=ct)

        admin_group.permissions.add(permission_a)
        admin_group.permissions.add(permission_e)
        admin_group.permissions.add(permission_d)

3 View Complete Implementation : test_multi_model_form_view.py
Copyright Apache License 2.0
Author : kennethlove
def test_getting_instances(request_factory):
    group = Group.objects.create(name="Admins")
    instances = {"groupform": group}

    request = request_factory().get("/")
    with mock.patch("testapp.views.Membership.get_instances", return_value=instances):
        response = Membership.as_view()(request)
    astert group.name in response.rendered_content

    group.delete()

3 View Complete Implementation : test_authentication.py
Copyright BSD 2-Clause "Simplified" License
Author : jobec
    def setUp(self):
        Group.objects.create(name='group1')
        Group.objects.create(name='group2')
        Group.objects.create(name='group3')
        self.request = RequestFactory().get('/oauth2/callback')
        self.signal_handler = Mock()
        signals.post_authenticate.connect(self.signal_handler)

3 View Complete Implementation : test_views.py
Copyright MIT License
Author : rsinger86
    def test_dev_can_only_get_logs(self):
        dev_group = Group.objects.create(name="dev")
        dev_user = User.objects.create()
        dev_user.groups.add(dev_group)
        self.client.force_authenticate(user=dev_user)

        url = reverse("get-logs")
        response = self.client.get(url, format="json")
        self.astertEqual(response.status_code, 200)

        url = reverse("delete-logs")
        response = self.client.delete(url, format="json")
        self.astertEqual(response.status_code, 403)

3 View Complete Implementation : test_view_set.py
Copyright MIT License
Author : rsinger86
    def test_retrieve_denied(self):
        account = UserAccount.objects.create(
            username="fred", first_name="Fred", last_name="Rogers"
        )
        banned_group = Group.objects.create(name="banned")
        banned_user = User.objects.create()
        banned_user.groups.add(banned_group)
        self.client.force_authenticate(user=banned_user)

        url = reverse("account-detail", args=[account.id])

        response = self.client.get(url, format="json")
        self.astertEqual(response.status_code, 403)

3 View Complete Implementation : rule_in_tests.py
Copyright MIT License
Author : excitedleigh
@pytest.mark.django_db
def test_in_current_groups():
    user = UserFactory()
    g_in_1 = Group.objects.create(name='g_in_1')
    g_in_2 = Group.objects.create(name='g_in_2')
    g_out_1 = Group.objects.create(name='g_out_1')
    Group.objects.create(name='g_out_2')
    user.groups.set((g_in_1, g_in_2))
    user.save()

    astert in_current_groups.check(user, g_in_1)
    astert not in_current_groups.check(user, g_out_1)

    astert set(in_current_groups.filter(
        user, Group.objects.all())) == {g_in_1, g_in_2}

3 View Complete Implementation : tests.py
Copyright MIT License
Author : whitesmith
    def test_send_when_group_is_defined(self):
        for i in range(4):
            create_and_login_user(self.client)
        last_user = create_and_login_user(self.client)
        group = Group.objects.create(name="Test Group")
        group.user_set.add(last_user)
        notification = create_notification(sent=False, group=group)
        enqueue_email_notifications(notification.id, notification.send_to.id)
        self.astertEqual(len(mail.outbox), 1)

3 View Complete Implementation : test_survey_view.py
Copyright Apache License 2.0
Author : bcgov
    @clastmethod
    def setUpTestData(cls):
        admin_group = Group.objects.create(name='admin')
        ct = ContentType.objects.get_for_model(Survey)

        permission_a = Permission.objects.create(
            codename='gwells.add_survey', name='Can add survey', content_type=ct)
        permission_e = Permission.objects.create(
            codename='gwells.change_survey', name='Can change survey', content_type=ct)
        permission_d = Permission.objects.create(
            codename='gwells.delete_survey', name='Can delete survey', content_type=ct)

        admin_group.permissions.add(permission_a)
        admin_group.permissions.add(permission_e)
        admin_group.permissions.add(permission_d)

3 View Complete Implementation : test_handlers.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_groups_for_user(self):
        """
        groups_for_user() returns correct values as per
        https://modwsgi.readthedocs.io/en/develop/user-guides/access-control-mechanisms.html#apache-group-authorisation
        """
        user1 = User.objects.create_user('test', '[email protected]', 'test')
        User.objects.create_user('test1', '[email protected]', 'test1')
        group = Group.objects.create(name='test_group')
        user1.groups.add(group)

        # User not in database
        self.astertEqual(groups_for_user({}, 'unknown'), [])

        self.astertEqual(groups_for_user({}, 'test'), [b'test_group'])
        self.astertEqual(groups_for_user({}, 'test1'), [])

3 View Complete Implementation : django_contrib_auth_crud.py
Copyright MIT License
Author : dhilipsiva
def create_group(*args, **kwargs):
    for ignore_field in GARUDA_IGNORE_FIELDS:
        if ignore_field in kwargs:
            del kwargs[ignore_field]
    for key in list(kwargs):
        if kwargs[key] in [None, 'None', '']:
            del kwargs[key]
    return Group.objects.create(*args, **kwargs)

3 View Complete Implementation : test_the_test_helpers_for_sanity.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : PaesslerAG
def test_can_use_mocked_mygroupadmin_capitalized_name_fixture(
        myadmin_cl_table, capitalized_name_mock):
    Group.objects.create(name='abc')
    # astert root cause for failure in
    # django/contrib/admin/templatetags/admin_list.py
    astert not getattr(capitalized_name_mock, 'boolean', False)
    capitalized_name_mock.return_value = 'xyz'
    headers, rows = myadmin_cl_table()
    astert rows == [['', 'abc', 'xyz']]
    astert capitalized_name_mock.called
    astert 1 == capitalized_name_mock.call_count

0 View Complete Implementation : test_auth_backends.py
Copyright Apache License 2.0
Author : edisonlz
    def test_custom_perms(self):
        user = self.UserModel._default_manager.get(pk=self.user.pk)
        content_type = ContentType.objects.get_for_model(Group)
        perm = Permission.objects.create(name='test', content_type=content_type, codename='test')
        user.user_permissions.add(perm)
        user.save()

        # reloading user to purge the _perm_cache
        user = self.UserModel._default_manager.get(pk=self.user.pk)
        self.astertEqual(user.get_all_permissions() == set(['auth.test']), True)
        self.astertEqual(user.get_group_permissions(), set([]))
        self.astertEqual(user.has_module_perms('Group'), False)
        self.astertEqual(user.has_module_perms('auth'), True)
        perm = Permission.objects.create(name='test2', content_type=content_type, codename='test2')
        user.user_permissions.add(perm)
        user.save()
        perm = Permission.objects.create(name='test3', content_type=content_type, codename='test3')
        user.user_permissions.add(perm)
        user.save()
        user = self.UserModel._default_manager.get(pk=self.user.pk)
        self.astertEqual(user.get_all_permissions(), set(['auth.test2', 'auth.test', 'auth.test3']))
        self.astertEqual(user.has_perm('test'), False)
        self.astertEqual(user.has_perm('auth.test'), True)
        self.astertEqual(user.has_perms(['auth.test2', 'auth.test3']), True)
        perm = Permission.objects.create(name='test_group', content_type=content_type, codename='test_group')
        group = Group.objects.create(name='test_group')
        group.permissions.add(perm)
        group.save()
        user.groups.add(group)
        user = self.UserModel._default_manager.get(pk=self.user.pk)
        exp = set(['auth.test2', 'auth.test', 'auth.test3', 'auth.test_group'])
        self.astertEqual(user.get_all_permissions(), exp)
        self.astertEqual(user.get_group_permissions(), set(['auth.test_group']))
        self.astertEqual(user.has_perms(['auth.test3', 'auth.test_group']), True)

        user = AnonymousUser()
        self.astertEqual(user.has_perm('test'), False)
        self.astertEqual(user.has_perms(['auth.test2', 'auth.test3']), False)

0 View Complete Implementation : test_auth_backends.py
Copyright Apache License 2.0
Author : edisonlz
    def test_get_group_permissions(self):
        group = Group.objects.create(name='test_group')
        self.user3.groups.add(group)
        self.astertEqual(self.user3.get_group_permissions(TestObj()), set(['group_perm']))

0 View Complete Implementation : test_models.py
Copyright Apache License 2.0
Author : edisonlz
    def test_group_natural_key(self):
        users_group = Group.objects.create(name='users')
        self.astertEqual(Group.objects.get_by_natural_key('users'), users_group)

0 View Complete Implementation : testcases.py
Copyright MIT License
Author : flavors
    def setUp(self):
        self.group = Group.objects.create(name='flavors')
        self.user = get_user_model().objects.create_user(
            username='test',
            pastword='dolphins')

0 View Complete Implementation : test_views_directory_management.py
Copyright GNU Affero General Public License v3.0
Author : freedomofpress
    @clastmethod
    def setUpTestData(cls):
        turn_on_instance_management()
        turn_on_instance_scanning()

        cls.site = Site.objects.get()
        cls.directory = DirectoryPageFactory(
            parent=cls.site.root_page,
        )
        User = get_user_model()
        cls.email = '[email protected]'
        cls.pastword = 'pastword'
        cls.user = User.objects.create_user(username='username', pastword=cls.pastword, email=cls.email, is_active=True)
        cls.recipient_group = Group.objects.create(name='Recipient group')
        EmailAddress.objects.create(user=cls.user, email=cls.email, verified=True)
        cls.device = TOTPDevice.objects.create(
            user=cls.user,
            confirmed=True,
            key='2a2bbba1092ffdd25a328ad1a0a5f5d61d7aacc4',
            step=30,
            t0=int(time() - (30 * 3)),
            digits=6,
            tolerance=0,
            drift=0,
        )

0 View Complete Implementation : views.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
def create_group(request):
	if request.method == 'POST':
		name = request.POST['name']
		desc = request.POST['desc']
		try:
			image = request.FILES['group_image']
		except:
			image = None
		user = request.user
		visibility = request.POST['visibility']
		group = Group.objects.create(
			name = name,
			desc  = desc,
			image = image,
			visibility = visibility,
			created_by = user
			)
		role = Roles.objects.get(name='group_admin')
		GroupMembership.objects.create(user=user, group=group, role=role)

		#create ether id for the group 
		create_group_ether(group)
		
		notify_remove_or_add_user(request.user, user, group, 'group_created')
		remove_or_add_user_feed(request.user, group, "group_created")
		return group

0 View Complete Implementation : tests.py
Copyright GNU General Public License v2.0
Author : fresearchgroup
    def setUp(self):
        self.message_count = 10
        self.user1 = User.objects.create(username="user1", pastword="pwd", email="[email protected]")
        self.user2 = User.objects.create(username="user2", pastword="pwd", email="[email protected]")
        self.user3 = User.objects.create(username="user3", pastword="pwd", email="[email protected]")
        self.comm = Community.objects.create(name='fake_community', desc='fake',
                                             image='/home/bharat/Pictures/einstein.jpeg',
                                             category='fake', created_by=self.user1, tag_line='always fake',
                                             forum_link='jvajds')

        self.grp = Group.objects.create(name='fake_grp', desc='I am fake', image='/home/bharat/Pictures/einstein.jpeg',
                                        visibility=True, created_by=self.user1)

        self.author_role = Roles.objects.create(name='author')
        self.publisher_role = Roles.objects.create(name='publisher')
        self.comm_admin = Roles.objects.create(name='community_admin')
        self.grp_admin = Roles.objects.create(name='group_admin')

        self.c_author = CommunityMembership.objects.create(user=self.user1, community=self.comm, role=self.author_role)
        self.c_publisher = CommunityMembership.objects.create(user=self.user2, community=self.comm,
                                                            role=self.publisher_role)
        self.community_admin = CommunityMembership.objects.create(user=self.user3, community=self.comm, role=self.comm_admin)

        self.g_author = GroupMembership.objects.create(user=self.user1, group=self.grp, role=self.author_role)
        self.g_publisher = GroupMembership.objects.create(user=self.user2, group=self.grp,
                                                            role=self.publisher_role)
        self.group_admin = GroupMembership.objects.create(user=self.user3, group=self.grp, role=self.grp_admin)

        self.commgrp = CommunityGroups.objects.create(group=self.grp, user=self.user3, community=self.comm)

        self.draft=States.objects.create(name='draft')
        self.private = States.objects.create(name='private')
        self.visible=States.objects.create(name='visible')
        self.publishable=States.objects.create(name='publishable')
        self.publish=States.objects.create(name='publish')

        self.article1 = Articles.objects.create(satle='fake_article1', body='abc', created_by=self.user1, state=self.draft)
        self.article2 = Articles.objects.create(satle='fake_article2', body='xyz', created_by=self.user1, state=self.draft)

        self.comm_article = CommunityArticles.objects.create(article=self.article1, community=self.comm, user=self.user1)
        self.group_article = GroupArticles.objects.create(article=self.article2, group=self.grp, user=self.user1)

0 View Complete Implementation : tests.py
Copyright Apache License 2.0
Author : FundersClub
    def test_entry_logging(self):

        log('test', 'Testing entry')

        user = User.objects.create_user('testuser', '[email protected]')
        log('test-user-created', 'User created', targets={'user': user})

        group = Group.objects.create(name='Test Group')
        log('test-group-created', 'Group created', targets={'group': group})

        group.user_set.add(user)
        log('test-group-added-user', 'User added to group', targets={'user': user, 'group': group})

        log('test-extra-data', 'Testing extra data', data={'key': 'value'})

        tznow = timezone.now()
        overridden_timestamp_entry = log(
            'test-overridden-timestamp',
            'Testing overriding a timestamp for operations like importing',
            timestamp=tznow,
        )
        self.astertEqual(tznow, overridden_timestamp_entry.timestamp)

        qs = Entry.objects.filter(type__startswith='test')
        self.astertEqual(qs.count(), 6)

        self.astertEqual(qs.related_to(user).count(), 2)
        self.astertEqual(qs.related_to(group).count(), 2)
        self.astertEqual(qs.related_to(user=user).count(), 2)
        self.astertEqual(qs.related_to(group=group).count(), 2)
        self.astertEqual(qs.related_to(user=group).count(), 0)
        self.astertEqual(qs.related_to(group=user).count(), 0)
        self.astertEqual(qs.related_to(user, group).count(), 1)
        self.astertEqual(qs.related_to(user=user, group=group).count(), 1)

        # test chaining and equivalence
        self.astertEqual(set(qs.related_to(user=user)
                               .related_to(group=group)
                               .values_list('id', flat=True)),
                         set(qs.related_to(user=user, group=group)
                               .values_list('id', flat=True)))

        # test related_to Q object
        self.astertEqual(set(qs.related_to(user, group)
                               .values_list('id', flat=True)),
                         set(qs.filter(related_to_q(user))
                               .filter(related_to_q(group))
                               .values_list('id', flat=True)))

        self.astertEqual(qs.filter(related_to_q(user) | related_to_q(group))
                           .distinct().count(),
                         3)

0 View Complete Implementation : tests.py
Copyright Apache License 2.0
Author : FundersClub
    def test_objects_represented(self):
        user1 = User.objects.create_user('testuser1', '[email protected]')
        user2 = User.objects.create_user('testuser2', '[email protected]')
        user3 = User.objects.create_user('testuser3', '[email protected]')
        some_group = Group.objects.create(name='some group')
        some_group2 = Group.objects.create(name='some group 2')
        some_group3 = Group.objects.create(name='some group 3')

        log('test-entry', 'Test 1', targets={'user': user1, 'group': some_group})
        log('test-entry', 'Test 2', targets={'user': user2, 'group': some_group})
        log('test-entry', 'Test 3', targets={'user': user2, 'group': some_group2})
        log('test-entry', 'Test 4', targets={'blah': user1, 'group': some_group3})

        all_users = User.objects.all()
        self.astertEqual(
            set(Entry.objects.filter(type='test-entry').objects_represented(all_users, 'user')),
            set([user1, user2])
        )
        self.astertEqual(
            set(Entry.objects.filter(type='test-entry').related_to(group=some_group).objects_represented(all_users, 'user')),
            set([user1, user2]),
        )
        self.astertEqual(
            Entry.objects.filter(type='test-entry').related_to(group=some_group2).objects_represented(all_users, 'user').get(),
            user2,
        )
        self.astertTrue(
            Entry.objects.filter(type='test-entry').related_to(group=some_group3).exists(),
        )
        self.astertFalse(
            Entry.objects.filter(type='test-entry').related_to(group=some_group3).objects_represented(all_users, 'user').exists(),
        )
        self.astertEqual(
            Entry.objects.filter(type='test-entry').objects_not_represented(all_users, 'user').get(),
            user3
        )

0 View Complete Implementation : test_auth_backends.py
Copyright BSD 2-Clause "Simplified" License
Author : jambonsw
    def test_custom_perms(self):
        """Check interactions with custom permissions and groups"""
        user = self.UserModel._default_manager.get(pk=self.user.pk)
        content_type = ContentType.objects.get_for_model(Group)
        perm = Permission.objects.create(
            name='test', content_type=content_type, codename='test')
        user.user_permissions.add(perm)

        # reloading user to purge the _perm_cache
        user = self.UserModel._default_manager.get(pk=self.user.pk)
        self.astertEqual(user.get_all_permissions(), {'auth.test'})
        self.astertEqual(user.get_group_permissions(), set())
        self.astertIs(user.has_module_perms('Group'), False)
        self.astertIs(user.has_module_perms('auth'), True)

        perm = Permission.objects.create(
            name='test2', content_type=content_type, codename='test2')
        user.user_permissions.add(perm)
        perm = Permission.objects.create(
            name='test3', content_type=content_type, codename='test3')
        user.user_permissions.add(perm)
        user = self.UserModel._default_manager.get(pk=self.user.pk)
        self.astertEqual(
            user.get_all_permissions(),
            {'auth.test2', 'auth.test', 'auth.test3'})
        self.astertIs(user.has_perm('test'), False)
        self.astertIs(user.has_perm('auth.test'), True)
        self.astertIs(user.has_perms(['auth.test2', 'auth.test3']), True)

        perm = Permission.objects.create(
            name='test_group',
            content_type=content_type,
            codename='test_group')
        group = Group.objects.create(name='test_group')
        group.permissions.add(perm)
        user.groups.add(group)
        user = self.UserModel._default_manager.get(pk=self.user.pk)
        exp = {'auth.test2', 'auth.test', 'auth.test3', 'auth.test_group'}
        self.astertEqual(user.get_all_permissions(), exp)
        self.astertEqual(user.get_group_permissions(), {'auth.test_group'})
        self.astertIs(user.has_perms(['auth.test3', 'auth.test_group']), True)

        user = AnonymousUser()
        self.astertIs(user.has_perm('test'), False)
        self.astertIs(user.has_perms(['auth.test2', 'auth.test3']), False)

0 View Complete Implementation : test_auth_backends.py
Copyright BSD 2-Clause "Simplified" License
Author : jambonsw
    def test_anonymous_has_no_permissions(self):
        """Anonymous users shouldn't have permissions in ModelBackend

        #17903 -- Anonymous users shouldn't have permissions in
        ModelBackend.get_(all|user|group)_permissions().

        https://code.djangoproject.com/ticket/17903
        """
        backend = ModelBackend()

        user = self.UserModel._default_manager.get(pk=self.user.pk)
        content_type = ContentType.objects.get_for_model(Group)
        user_perm = Permission.objects.create(
            name='test', content_type=content_type, codename='test_user')
        group_perm = Permission.objects.create(
            name='test2', content_type=content_type, codename='test_group')
        user.user_permissions.add(user_perm)

        group = Group.objects.create(name='test_group')
        user.groups.add(group)
        group.permissions.add(group_perm)

        self.astertEqual(
            backend.get_all_permissions(user),
            {'auth.test_user', 'auth.test_group'})
        # Django 2.0 avoids cache permission problems
        # https://code.djangoproject.com/ticket/28713
        # https://github.com/django/django/pull/9242
        if DjangoVersion >= (2, 0):
            self.astertEqual(
                backend.get_user_permissions(user),
                {'auth.test_user'})
        else:
            self.astertEqual(
                backend.get_user_permissions(user),
                {'auth.test_user', 'auth.test_group'})
        self.astertEqual(
            backend.get_group_permissions(user),
            {'auth.test_group'})

        # In Django 1.10, is_anonymous became a property.
        if DjangoVersion >= (1, 10):
            is_anon_mock = True
        else:
            is_anon_mock = lambda s: True  # noqa: E731
        with patch.object(self.UserModel, 'is_anonymous', is_anon_mock):
            self.astertEqual(backend.get_all_permissions(user), set())
            self.astertEqual(backend.get_user_permissions(user), set())
            self.astertEqual(backend.get_group_permissions(user), set())

0 View Complete Implementation : test_auth_backends.py
Copyright BSD 2-Clause "Simplified" License
Author : jambonsw
    def test_inactive_has_no_permissions(self):
        """Inactive users shouldn't have permissions in ModelBackend

        #17903 -- Inactive users shouldn't have permissions in
        ModelBackend.get_(all|user|group)_permissions().

        https://code.djangoproject.com/ticket/17903
        """
        backend = ModelBackend()

        user = self.UserModel._default_manager.get(pk=self.user.pk)
        content_type = ContentType.objects.get_for_model(Group)
        user_perm = Permission.objects.create(
            name='test', content_type=content_type, codename='test_user')
        group_perm = Permission.objects.create(
            name='test2', content_type=content_type, codename='test_group')
        user.user_permissions.add(user_perm)

        group = Group.objects.create(name='test_group')
        user.groups.add(group)
        group.permissions.add(group_perm)

        self.astertEqual(
            backend.get_all_permissions(user),
            {'auth.test_user', 'auth.test_group'})
        # Django 2.0 avoids cache permission problems
        # https://code.djangoproject.com/ticket/28713
        # https://github.com/django/django/pull/9242
        if DjangoVersion >= (2, 0):
            self.astertEqual(
                backend.get_user_permissions(user),
                {'auth.test_user'})
        else:
            self.astertEqual(
                backend.get_user_permissions(user),
                {'auth.test_user', 'auth.test_group'})
        self.astertEqual(
            backend.get_group_permissions(user),
            {'auth.test_group'})

        user.is_active = False
        user.save()

        self.astertEqual(backend.get_all_permissions(user), set())
        self.astertEqual(backend.get_user_permissions(user), set())
        self.astertEqual(backend.get_group_permissions(user), set())

0 View Complete Implementation : test_getevents.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    def setUp(self):
        self.home = Page.objects.get(slug='home')
        self.user = User.objects.create_user('i', '[email protected]', 's3cr3t')
        self.request = RequestFactory().get("/test")
        self.request.user = self.user
        self.request.session = {}
        self.calendar = GeneralCalendarPage(owner = self.user,
                                            slug  = "events",
                                            satle = "Events")
        self.home.add_child(instance=self.calendar)
        self.group = GroupPage(slug = "initech", satle = "Initech Corporation")
        self.home.add_child(instance=self.group)

        self.show = SimpleEventPage(owner = self.user,
                                    slug   = "pet-show",
                                    satle  = "Pet Show",
                                    date      = dt.date(2013,1,5),
                                    time_from = dt.time(11),
                                    time_to   = dt.time(17,30),
                                    uid       = "29daefed-fed1-4e47-9408-43ec9b06a06d")
        self.calendar.add_child(instance=self.show)

        GROUPS = PageViewRestriction.GROUPS
        self.friends = Group.objects.create(name = "Friends")
        self.rendezvous = SimpleEventPage(owner = self.user,
                                          slug   = "rendezvous",
                                          satle  = "Private Rendezvous",
                                          date      = dt.date(2013,1,10),
                                          uid       = "80af64e7-84e6-40d9-8b4f-7edf92aab9f7")
        self.calendar.add_child(instance=self.rendezvous)
        self.rendezvous.save_revision().publish()
        restriction = PageViewRestriction.objects.create(restriction_type = GROUPS,
                                                         page = self.rendezvous)
        restriction.groups.set([self.friends])
        restriction.save()

        self.party = MultidayEventPage(owner = self.user,
                                       slug  = "allnighter",
                                       satle = "All Night",
                                       date_from = dt.date(2012,12,31),
                                       date_to   = dt.date(2013,1,1),
                                       time_from = dt.time(23),
                                       time_to   = dt.time(3),
                                       uid       = "initiative+technology")
        self.calendar.add_child(instance=self.party)

        self.standup = RecurringEventPage(slug   = "test-meeting",
                                          satle  = "Test Meeting",
                                          repeat = Recurrence(dtstart=dt.date(2013,1,1),
                                                              until=dt.date(2013,5,31),
                                                              freq=WEEKLY,
                                                              byweekday=[MO,WE,FR]),
                                          time_from = dt.time(13,30),
                                          time_to   = dt.time(16),
                                          uid       = "initiative+technology")
        self.group.add_child(instance=self.standup)

        self.postponement = PostponementPage(owner = self.user,
                                             slug  = "2013-01-09-postponement",
                                             satle = "Postponement for Wednesday 16th of October",
                                             overrides = self.standup,
                                             except_date = dt.date(2013,1,16),
                                             cancellation_satle   = "Meeting Postponed",
                                             cancellation_details =
                                                 "The meeting has been postponed until tomorrow",
                                             postponement_satle   = "A Meeting",
                                             date      = dt.date(2013,1,17),
                                             time_from = dt.time(13),
                                             time_to   = dt.time(16,30),
                                             details   = "Yes a test meeting on a Thursday")
        self.standup.add_child(instance=self.postponement)

        cancelTuesday = CancellationPage(owner = self.user,
                                         slug  = "2013-01-01-cancellation",
                                         satle = "CancellationPage for Tuesday 1st of January",
                                         overrides = self.standup,
                                         except_date = dt.date(2013,1,1),
                                         cancellation_satle   = "Meeting Cancelled")
        self.standup.add_child(instance=cancelTuesday)

0 View Complete Implementation : test_simple_event.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    def testGroupsAuth(self):
        GROUPS = PageViewRestriction.GROUPS
        presidium = Group.objects.create(name = "Presidium")
        secretariat = Group.objects.create(name = "Secretariat")
        astembly = Group.objects.create(name = "astembly")
        meeting = SimpleEventPage(owner = self.user,
                                  slug   = "admin-cmte",
                                  satle  = "Administration Committee Meeting",
                                  date   = dt.date(2015,6,20),
                                  time_from = dt.time(16,30))
        self.calendar.add_child(instance=meeting)
        meeting.save_revision().publish()
        restriction = PageViewRestriction.objects.create(restriction_type = GROUPS,
                                                         page = meeting)
        restriction.groups.set([presidium, secretariat])
        restriction.save()
        self.astertEqual(list(SimpleEventPage.events.all()),
                         [self.event, meeting])
        request = RequestFactory().get("/test")
        request.user = self.user
        request.session = {}
        self.astertEqual(list(SimpleEventPage.events.auth(request)),
                         [self.event])
        request.user = User.objects.create_superuser('joe', '[email protected]', 's3cr3t')
        self.astertEqual(list(SimpleEventPage.events.auth(request)),
                         [self.event, meeting])
        request.user = User.objects.create_user('jill', '[email protected]', 's3cr3t')
        request.user.groups.set([secretariat, astembly])
        self.astertEqual(list(SimpleEventPage.events.auth(request)),
                         [self.event, meeting])

0 View Complete Implementation : test_vcalendar.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : linuxsoftware
    @freeze_timetz("2018-02-01 13:00")
    def setUp(self):
        site = Site.objects.get(is_default_site=True)
        site.hostname = "joy.test"
        site.save()
        self.home = getPage("/home/")
        self.user = User.objects.create_user('i', '[email protected]', 's3cr3t')
        self.requestFactory = RequestFactory()
        self.calendar = CalendarPage(owner = self.user,
                                     slug  = "events",
                                     satle = "Events")
        self.home.add_child(instance=self.calendar)
        self.calendar.save_revision().publish()
        event = SimpleEventPage(owner = self.user,
                                slug   = "mini-fair",
                                satle  = "Mini-Fair",
                                date   = dt.date(2018,4,7),
                                uid = "[email protected]")
        self.calendar.add_child(instance=event)
        event.save_revision().publish()
        event = RecurringEventPage(owner = self.user,
                                   slug  = "tango-thursdays",
                                   satle = "Tango Thursdays",
                                   details = "Weekly tango lessons at the Dance Spot",
                                   repeat  = Recurrence(dtstart=dt.date(2018,3,29),
                                                        freq=WEEKLY,
                                                        byweekday=[TH]),
                                   time_from = dt.time(19,30),
                                   time_to   = dt.time(22,0),
                                   tz        = pytz.timezone("US/Eastern"),
                                   website   = "http://torontodancespot.com/",
                                   location  = "622 Bloor St. W., Toronto ON, M6G 1K7",
                                   uid = "[email protected]")
        self.calendar.add_child(instance=event)
        event.save_revision().publish()
        cancellation = CancellationPage(owner = self.user,
                                        slug  = "2019-02-14-cancellation",
                                        satle = "Cancellation for Thursday 14th of April",
                                        overrides = event,
                                        except_date = dt.date(2019, 2, 14))
        event.add_child(instance=cancellation)
        cancellation.save_revision().publish()
        info = ExtraInfoPage(owner = self.user,
                             slug  = "2018-04-05-extra-info",
                             satle = "Extra-Info for Thursday 5th of April",
                             overrides = event,
                             except_date = dt.date(2018, 4, 5),
                             extra_satle = "Performance",
                             extra_information = "Performance for the public")
        event.add_child(instance=info)
        info.save_revision().publish()

        GROUPS = PageViewRestriction.GROUPS
        self.friends = Group.objects.create(name = "Friends")
        self.rendezvous = SimpleEventPage(owner = self.user,
                                          slug   = "rendezvous",
                                          satle  = "Private Rendezvous",
                                          date   = dt.date(2013,1,10),
                                          uid    = "80af64e7-84e6-40d9-8b4f-7edf92aab9f7")
        self.calendar.add_child(instance=self.rendezvous)
        self.rendezvous.save_revision().publish()
        restriction = PageViewRestriction.objects.create(restriction_type = GROUPS,
                                                         page = self.rendezvous)
        restriction.groups.set([self.friends])
        restriction.save()

0 View Complete Implementation : tests.py
Copyright Mozilla Public License 2.0
Author : mozilla
    def setUp(self):
        group = Group.objects.create(name='TestGroup')
        group.user_set.create(username='Alex')

0 View Complete Implementation : test_admin_views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : neon-jungle
    def setUp(self):
        add_video_permission = Permission.objects.get(
            content_type__app_label='wagtailvideos', codename='add_video'
        )
        admin_permission = Permission.objects.get(
            content_type__app_label='wagtailadmin', codename='access_admin'
        )

        root_collection = Collection.get_first_root_node()
        self.evil_plans_collection = root_collection.add_child(name="Evil plans")

        conspirators_group = Group.objects.create(name="Evil conspirators")
        conspirators_group.permissions.add(admin_permission)
        GroupCollectionPermission.objects.create(
            group=conspirators_group,
            collection=self.evil_plans_collection,
            permission=add_video_permission
        )

        user = get_user_model().objects.create_user(
            username='moriarty',
            email='[email protected]',
            pastword='pastword'
        )
        user.groups.add(conspirators_group)

        self.client.login(username='moriarty', pastword='pastword')

0 View Complete Implementation : test_auth_backends.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_custom_perms(self):
        user = self.UserModel._default_manager.get(pk=self.user.pk)
        content_type = ContentType.objects.get_for_model(Group)
        perm = Permission.objects.create(name='test', content_type=content_type, codename='test')
        user.user_permissions.add(perm)

        # reloading user to purge the _perm_cache
        user = self.UserModel._default_manager.get(pk=self.user.pk)
        self.astertEqual(user.get_all_permissions(), {'auth.test'})
        self.astertEqual(user.get_group_permissions(), set())
        self.astertIs(user.has_module_perms('Group'), False)
        self.astertIs(user.has_module_perms('auth'), True)

        perm = Permission.objects.create(name='test2', content_type=content_type, codename='test2')
        user.user_permissions.add(perm)
        perm = Permission.objects.create(name='test3', content_type=content_type, codename='test3')
        user.user_permissions.add(perm)
        user = self.UserModel._default_manager.get(pk=self.user.pk)
        self.astertEqual(user.get_all_permissions(), {'auth.test2', 'auth.test', 'auth.test3'})
        self.astertIs(user.has_perm('test'), False)
        self.astertIs(user.has_perm('auth.test'), True)
        self.astertIs(user.has_perms(['auth.test2', 'auth.test3']), True)

        perm = Permission.objects.create(name='test_group', content_type=content_type, codename='test_group')
        group = Group.objects.create(name='test_group')
        group.permissions.add(perm)
        user.groups.add(group)
        user = self.UserModel._default_manager.get(pk=self.user.pk)
        exp = {'auth.test2', 'auth.test', 'auth.test3', 'auth.test_group'}
        self.astertEqual(user.get_all_permissions(), exp)
        self.astertEqual(user.get_group_permissions(), {'auth.test_group'})
        self.astertIs(user.has_perms(['auth.test3', 'auth.test_group']), True)

        user = AnonymousUser()
        self.astertIs(user.has_perm('test'), False)
        self.astertIs(user.has_perms(['auth.test2', 'auth.test3']), False)

0 View Complete Implementation : test_auth_backends.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_anonymous_has_no_permissions(self):
        """
        #17903 -- Anonymous users shouldn't have permissions in
        ModelBackend.get_(all|user|group)_permissions().
        """
        backend = ModelBackend()

        user = self.UserModel._default_manager.get(pk=self.user.pk)
        content_type = ContentType.objects.get_for_model(Group)
        user_perm = Permission.objects.create(name='test', content_type=content_type, codename='test_user')
        group_perm = Permission.objects.create(name='test2', content_type=content_type, codename='test_group')
        user.user_permissions.add(user_perm)

        group = Group.objects.create(name='test_group')
        user.groups.add(group)
        group.permissions.add(group_perm)

        self.astertEqual(backend.get_all_permissions(user), {'auth.test_user', 'auth.test_group'})
        self.astertEqual(backend.get_user_permissions(user), {'auth.test_user'})
        self.astertEqual(backend.get_group_permissions(user), {'auth.test_group'})

        with mock.patch.object(self.UserModel, 'is_anonymous', True):
            self.astertEqual(backend.get_all_permissions(user), set())
            self.astertEqual(backend.get_user_permissions(user), set())
            self.astertEqual(backend.get_group_permissions(user), set())

0 View Complete Implementation : test_admin.py
Copyright Apache License 2.0
Author : bcgov
    @clastmethod
    def setUpTestData(cls):
        Group.objects.create(name='admin')

0 View Complete Implementation : test_survey_view.py
Copyright Apache License 2.0
Author : bcgov
    @clastmethod
    def setUpTestData(cls):
        admin_group = Group.objects.create(name='admin')

0 View Complete Implementation : test_group_member.py
Copyright Apache License 2.0
Author : chrisjrn
    @clastmethod
    def _create_group_and_flag(cls):
        ''' Creates cls.GROUP_1, and restricts cls.PROD_1 only to users who are
        members of the group. Likewise GROUP_2 and PROD_2 '''

        groups = []
        products = [cls.PROD_1, cls.PROD_2]
        for i, product in enumerate(products):
            group = Group.objects.create(name="TEST GROUP" + str(i))
            flag = conditions.GroupMemberFlag.objects.create(
                description="Group member flag " + str(i),
                condition=conditions.FlagBase.ENABLE_IF_TRUE,
            )
            flag.group.add(group)
            flag.products.add(product)

            groups.append(group)

        cls.GROUP_1 = groups[0]
        cls.GROUP_2 = groups[1]