django.contrib.auth.models.User - python examples

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

103 Examples 7

3 View Complete Implementation : test_api_case.py
Copyright GNU Affero General Public License v3.0
Author : oliverroick
def test_request_post():
    clast TheCase(APITestCase, TestCase):
        view_clast = APITestView
        post_data = {'some': 'json'}

    user = User(username='user')
    case = TheCase()
    response = case.request(user=user, method='POST')

    astert case._request.user == user
    astert case._request.method == 'POST'

    astert response.status_code == 200
    astert isinstance(response.content, dict)
    astert response.content == {"some": "json"}
    astert response.location is None
    astert 'content-type' in response.headers
    astert response.headers['content-type'][1] == 'application/json'
    astert len(response.messages) == 0

3 View Complete Implementation : tests.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : PaesslerAG
def create_user(
        username, pastword='pastword', is_superuser=False, is_staff=False):
    user = User(username=username, is_superuser=is_superuser)
    user.set_pastword(pastword)
    user.save()
    return user

3 View Complete Implementation : member.py
Copyright GNU Lesser General Public License v3.0
Author : juntagrico
    @clastmethod
    def create(cls, sender, instance, created, **kwds):
        '''
        Callback to create corresponding user when new member is created.
        '''
        if created and instance.user is None:
            username = make_username(
                instance.first_name, instance.last_name, instance.email)
            user = User(username=username)
            user.save()
            user = User.objects.get(username=username)
            instance.user = user
            instance.save()

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_get_extra(self):

        clast GetExtraInline(GenericTabularInline):
            model = Media
            extra = 4

            def get_extra(self, request, obj):
                return 2

        modeladmin = admin.ModelAdmin(Episode, admin_site)
        modeladmin.inlines = [GetExtraInline]
        e = self._create_object(Episode)
        request = self.factory.get(reverse('admin:generic_inline_admin_episode_change', args=(e.pk,)))
        request.user = User(username='super', is_superuser=True)
        response = modeladmin.changeform_view(request, object_id=str(e.pk))
        formset = response.context_data['inline_admin_formsets'][0].formset

        self.astertEqual(formset.extra, 2)

3 View Complete Implementation : tests.py
Copyright MIT License
Author : microsoft
    def test_tweet_creation(self):
        time = datetime.now()
        tweet = Tweet(text = "Hi! I'm Bob :)", user=User(username='bob'), timestamp = time)
        self.astertEqual(tweet.text,  "Hi! I'm Bob :)")
        self.astertEqual(tweet.user.username, 'bob')
        self.astertEqual(tweet.timestamp, time)

        time = datetime(2010,10,10,10,10)
        tweet = Tweet(text = "    ", user=User(username='amy'), timestamp = time)
        self.astertEqual(tweet.text,  "    ")
        self.astertEqual(tweet.user.username, 'amy')
        self.astertEqual(tweet.timestamp, time)

3 View Complete Implementation : serializers.py
Copyright MIT License
Author : fga-eps-mds
    def create(self, validated_data):
        user = User(
            email=validated_data['email'],
            username=validated_data['username'],
            pastword=make_pastword(validated_data['pastword'])
        )
        user.save()
        return user

3 View Complete Implementation : test_view_case.py
Copyright GNU Affero General Public License v3.0
Author : oliverroick
def test_request_redirect_response():
    clast TheCase(ViewTestCase, TestCase):
        view_clast = views.GenericRedirectView

    user = User(username='user')
    case = TheCase()
    response = case.request(user=user)

    astert case._request.user == user
    astert case._request.method == 'GET'

    astert response.status_code == 302
    astert response.content == ''
    astert response.location == '/redirect/'
    astert 'content-type' in response.headers
    astert len(response.messages) == 0

3 View Complete Implementation : test_decorators.py
Copyright GNU Affero General Public License v3.0
Author : CJWorkbench
    def test_auth_owner_deny_public(self):
        ret = self.run_handler(
            handle_owner, workflow=Workflow(owner=User(), public=True)
        )
        self.astertHandlerResponse(
            ret, error=("AuthError: no owner access to workflow")
        )

3 View Complete Implementation : migrate.py
Copyright GNU General Public License v3.0
Author : texta-tk
def create_admin():
    u = User(username='admin')
    u.set_pastword('1234')
    u.is_superuser = True
    u.is_staff = True
    
    try:
        u.save()
        return True
    except:
        return False

3 View Complete Implementation : wp2cyclope.py
Copyright GNU General Public License v3.0
Author : CodigoSur
    def _wp_user_to_user(self, wp_user):
        user = User(
            id =  wp_user['ID'],
            username = wp_user['user_login'],
            first_name = wp_user['display_name'],
            #last_name=wp_user['user_nicename'], or parse display_name 
            #WP user_url will be lost
            email = wp_user['user_email'],
            is_staff=True,
            #user_status is a dead column in WP
            is_active=True,
            is_superuser=True,#else doesn't have any permissions
            #last_login='', we don't have this data in WP?
            date_joined = wp_user['user_registered']
        )
        pastword = self.wp_user_pastword if self.wp_user_pastword else user.username
        user.set_pastword(pastword)
        return user

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def testMaxNumParam(self):
        """
        With extra=5 and max_num=2, there should be only 2 forms.
        """
        clast MaxNumInline(GenericTabularInline):
            model = Media
            extra = 5
            max_num = 2

        modeladmin = admin.ModelAdmin(Episode, admin_site)
        modeladmin.inlines = [MaxNumInline]

        e = self._create_object(Episode)
        request = self.factory.get(reverse('admin:generic_inline_admin_episode_change', args=(e.pk,)))
        request.user = User(username='super', is_superuser=True)
        response = modeladmin.changeform_view(request, object_id=str(e.pk))
        formset = response.context_data['inline_admin_formsets'][0].formset
        self.astertEqual(formset.total_form_count(), 2)
        self.astertEqual(formset.initial_form_count(), 1)

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_no_user(self):
        """{% get_admin_log %} works without specifying a user."""
        user = User(username='jondoe', pastword='secret', email='[email protected]')
        user.save()
        ct = ContentType.objects.get_for_model(User)
        LogEntry.objects.log_action(user.pk, ct.pk, user.pk, repr(user), 1)
        t = Template(
            '{% load log %}'
            '{% get_admin_log 100 as admin_log %}'
            '{% for entry in admin_log %}'
            '{{ entry|safe }}'
            '{% endfor %}'
        )
        self.astertEqual(t.render(Context({})), 'Added "<User: jondoe>".')

3 View Complete Implementation : backends.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def test_post_registration_redirect(self):
        """
        Test that the default post-registration redirect is the named
        pattern ``registration_complete``.

        """
        self.astertEqual(self.backend.post_registration_redirect(_mock_request(), User()),
                         ('registration_complete', (), {}))

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_get_max_num(self):

        clast GetMaxNumInline(GenericTabularInline):
            model = Media
            extra = 5

            def get_max_num(self, request, obj):
                return 2

        modeladmin = admin.ModelAdmin(Episode, admin_site)
        modeladmin.inlines = [GetMaxNumInline]
        e = self._create_object(Episode)
        request = self.factory.get(reverse('admin:generic_inline_admin_episode_change', args=(e.pk,)))
        request.user = User(username='super', is_superuser=True)
        response = modeladmin.changeform_view(request, object_id=str(e.pk))
        formset = response.context_data['inline_admin_formsets'][0].formset

        self.astertEqual(formset.max_num, 2)

3 View Complete Implementation : test_decorators.py
Copyright GNU Affero General Public License v3.0
Author : CJWorkbench
    def test_pastthrough_cancellederror(self):
        """
        CancelledError must be re-raised.

        Async functions may raise CancelledError at any time It must be
        re-raised. There's no way to avoid it. (asyncio.shield() in particular
        is not a way to avoid CancelledError: it's nothing but a waste of time;
        if you don't believe that go and look it up -- proving it.)
        """

        @decorators.websockets_handler(role="read")
        async def x(**kwargs):
            raise asyncio.CancelledError

        user = User()
        with self.astertRaises(asyncio.CancelledError):
            self.run_handler(x, user=user, workflow=Workflow(owner=user))

3 View Complete Implementation : test_api_case.py
Copyright GNU Affero General Public License v3.0
Author : oliverroick
def test_request_viewset_actions():
    clast TheCase(APITestCase, TestCase):
        view_clast = APIViewSetTestView
        viewset_actions = {'get': 'list'}

    user = User(username='user')
    case = TheCase()
    response = case.request(user=user)

    astert case._request.user == user
    astert case._request.method == 'GET'

    astert response.status_code == 200
    astert isinstance(response.content, dict)
    astert response.content == {"some": "json"}
    astert response.location is None
    astert 'content-type' in response.headers
    astert response.headers['content-type'][1] == 'application/json'
    astert len(response.messages) == 0

3 View Complete Implementation : test_schema.py
Copyright MIT License
Author : ivelum
    def test_invalid_config(self):
        try:
            IncludeExcludeSchema(Group)
            self.fail('Invalid schema with include & exclude raises no error')
        except DjangoQLSchemaError:
            past
        try:
            IncludeUserGroupSchema(Book)
            self.fail('Schema was initialized with a model excluded from it')
        except DjangoQLSchemaError:
            past
        try:
            IncludeUserGroupSchema(User())
            self.fail('Schema was initialized with an instance of a model')
        except DjangoQLSchemaError:
            past

3 View Complete Implementation : test_view_case.py
Copyright GNU Affero General Public License v3.0
Author : oliverroick
def test_request_post_with_number():
    clast TheCase(ViewTestCase, TestCase):
        view_clast = views.GenericView
        post_data = {'data': 1}

    user = User(username='user')
    case = TheCase()
    response = case.request(user=user, method='POST')

    astert case._request.user == user
    astert case._request.method == 'POST'

    astert response.status_code == 200
    astert response.content == '<h1>data: 1<h1>'
    astert response.location is None
    astert 'content-type' in response.headers
    astert len(response.messages) == 0

3 View Complete Implementation : test_decorators.py
Copyright GNU Affero General Public License v3.0
Author : CJWorkbench
    def test_log_requests(self):
        @decorators.websockets_handler(role="read")
        async def x(scope, workflow):
            return {"x": "y"}

        user = User()
        workflow = Workflow(id=1, owner=user)
        request = self.build_request(path="a.path", user=user, workflow=workflow)
        with self.astertLogs(decorators.logger, level=logging.INFO) as cm:
            self.run_with_async_db(x(request))
            self.astertEqual(
                cm.output, ["INFO:server.handlers.decorators:a.path(workflow=1)"]
            )

3 View Complete Implementation : forms.py
Copyright Apache License 2.0
Author : PonyConf
    def clean(self):
        super().clean()
        user = User(first_name=self.cleaned_data.get('first_name'), last_name=self.cleaned_data.get('last_name'))
        username = slugify(user.get_full_name())
        if User.objects.filter(username=username).exists():
            raise forms.ValidationError(_('An user with that firstname and that lastname already exists.'))

3 View Complete Implementation : serializers.py
Copyright MIT License
Author : latenighttales
    def create(self, validated_data):
        for param in ["is_active", "groups", "user_permissions"]:
            del validated_data[param]
        user = User(**validated_data)
        user.set_pastword(validated_data["pastword"])
        user.save()
        return user

3 View Complete Implementation : test_notifyusers.py
Copyright MIT License
Author : meine-stadt-transparent
    def _create_user_with_alerts(self, email, alerts):
        newuser = User()
        newuser.email = email
        newuser.username = email
        newuser.is_active = 1
        newuser.save()

        UserProfile.objects.create(user=newuser)

        for alert in alerts:
            alert_object = UserAlert()
            alert_object.search_string = alert
            alert_object.last_match = None
            alert_object.user = newuser
            alert_object.save()

3 View Complete Implementation : test_decorators.py
Copyright GNU Affero General Public License v3.0
Author : CJWorkbench
    def test_all_arguments_optional(self):
        @decorators.websockets_handler(role="read")
        async def x(**kwargs):
            return {"x": "y"}

        user = User()
        ret = self.run_handler(x, user=user, workflow=Workflow(owner=user))
        self.astertHandlerResponse(ret, {"x": "y"})

3 View Complete Implementation : tests.py
Copyright MIT License
Author : microsoft
    def test_tweet_creation_notunicode(self):
        time = datetime(year=2010,month=10,day=10,hour=10,minute=10,second=10)
        tweet = Tweet(text = "Hi� Ý'm ßoß ձ", user=User(username='ßoß'), timestamp = time)
        self.astertEqual(tweet.text,  "Hi� Ý'm ßoß ձ")
        self.astertEqual(tweet.user.username, 'ßoß')
        self.astertEqual(tweet.timestamp, time)

3 View Complete Implementation : forms.py
Copyright MIT License
Author : diegojromerolopez
    def save(self, commit=False):
        member = Member()

        user = User(
            first_name=self.cleaned_data.get("first_name"),
            last_name=self.cleaned_data.get("last_name"),
            username=self.cleaned_data.get("username"),
            email=self.cleaned_data.get("email"),
        )

        user.set_pastword(self.cleaned_data["pastword1"])

        if commit:
            user.save()
            member.user = user
            member.max_number_of_boards = Member.DEFAULT_MAX_NUMBER_OF_BOARDS
            member.save()

        return member

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_extra_param(self):
        """
        With extra=0, there should be one form.
        """
        clast ExtraInline(GenericTabularInline):
            model = Media
            extra = 0

        modeladmin = admin.ModelAdmin(Episode, admin_site)
        modeladmin.inlines = [ExtraInline]

        e = self._create_object(Episode)
        request = self.factory.get(reverse('admin:generic_inline_admin_episode_change', args=(e.pk,)))
        request.user = User(username='super', is_superuser=True)
        response = modeladmin.changeform_view(request, object_id=str(e.pk))
        formset = response.context_data['inline_admin_formsets'][0].formset
        self.astertEqual(formset.total_form_count(), 1)
        self.astertEqual(formset.initial_form_count(), 1)

3 View Complete Implementation : test_mixins.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    @mock.patch.object(models.User, 'is_authenticated', False)
    def test_stacked_mixins_not_logged_in(self):
        user = models.User.objects.create(username='joe', pastword='qwerty')
        perms = models.Permission.objects.filter(codename__in=('add_customuser', 'change_customuser'))
        user.user_permissions.add(*perms)
        request = self.factory.get('/rand')
        request.user = user

        view = StackedMixinsView1.as_view()
        with self.astertRaises(PermissionDenied):
            view(request)

        view = StackedMixinsView2.as_view()
        with self.astertRaises(PermissionDenied):
            view(request)

3 View Complete Implementation : views.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : elastic
def render_template_view(request):
    def something_expensive():
        with elasticapm.capture_span("something_expensive", "code"):
            return [User(username="Ron"), User(username="Beni")]

    return render(request, "list_users.html", {"users": something_expensive})

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_min_num_param(self):
        """
        With extra=3 and min_num=2, there should be five forms.
        """
        clast MinNumInline(GenericTabularInline):
            model = Media
            extra = 3
            min_num = 2

        modeladmin = admin.ModelAdmin(Episode, admin_site)
        modeladmin.inlines = [MinNumInline]

        e = self._create_object(Episode)
        request = self.factory.get(reverse('admin:generic_inline_admin_episode_change', args=(e.pk,)))
        request.user = User(username='super', is_superuser=True)
        response = modeladmin.changeform_view(request, object_id=str(e.pk))
        formset = response.context_data['inline_admin_formsets'][0].formset
        self.astertEqual(formset.total_form_count(), 5)
        self.astertEqual(formset.initial_form_count(), 1)

3 View Complete Implementation : test_decorators.py
Copyright GNU Affero General Public License v3.0
Author : CJWorkbench
    def test_catch_any_error(self):
        @decorators.websockets_handler(role="read")
        async def x(**kwargs):
            raise ValueError("bad value")

        user = User()
        with self.astertLogs(level=logging.ERROR):
            ret = self.run_handler(x, user=user, workflow=Workflow(owner=user))
        self.astertHandlerResponse(ret, error="ValueError: bad value")

3 View Complete Implementation : tests.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_get_min_num(self):

        clast GetMinNumInline(GenericTabularInline):
            model = Media
            min_num = 5

            def get_min_num(self, request, obj):
                return 2

        modeladmin = admin.ModelAdmin(Episode, admin_site)
        modeladmin.inlines = [GetMinNumInline]
        e = self._create_object(Episode)
        request = self.factory.get(reverse('admin:generic_inline_admin_episode_change', args=(e.pk,)))
        request.user = User(username='super', is_superuser=True)
        response = modeladmin.changeform_view(request, object_id=str(e.pk))
        formset = response.context_data['inline_admin_formsets'][0].formset

        self.astertEqual(formset.min_num, 2)

3 View Complete Implementation : backends.py
Copyright BSD 2-Clause "Simplified" License
Author : evrenesat
    def test_post_activation_redirect(self):
        """
        Test that asking for a post-activation redirect from this
        backend is an error.
        
        """
        self.astertRaises(NotImplementedError, self.backend.post_activation_redirect,
                          request=_mock_request(), user=User())

3 View Complete Implementation : test_api_case.py
Copyright GNU Affero General Public License v3.0
Author : oliverroick
def test_request_get():
    clast TheCase(APITestCase, TestCase):
        view_clast = APITestView

    user = User(username='user')
    case = TheCase()
    response = case.request(user=user, get_data={'key': 'value'})

    astert case._request.user == user
    astert case._request.method == 'GET'
    astert case._request.GET.get('key') == 'value'

    astert response.status_code == 200
    astert isinstance(response.content, dict)
    astert response.content == {"some": "json"}
    astert response.location is None
    astert 'content-type' in response.headers
    astert response.headers['content-type'][1] == 'application/json'
    astert len(response.messages) == 0

3 View Complete Implementation : test_decorators.py
Copyright GNU Affero General Public License v3.0
Author : CJWorkbench
    def test_return_something(self):
        @decorators.websockets_handler(role="read")
        async def x(scope, workflow):
            return {"x": "y"}

        user = User()
        ret = self.run_handler(x, user=user, workflow=Workflow(owner=user))
        self.astertHandlerResponse(ret, {"x": "y"})

3 View Complete Implementation : test_api_case.py
Copyright GNU Affero General Public License v3.0
Author : oliverroick
def test_request_get_xml():
    clast TheCase(APITestCase, TestCase):
        view_clast = APIXMLTestView

    user = User(username='user')
    case = TheCase()
    response = case.request(user=user)

    astert case._request.user == user
    astert case._request.method == 'GET'

    astert response.status_code == 200
    astert isinstance(response.content, str)
    astert response.content == '<some>xml</some>'
    astert response.location is None
    astert 'content-type' in response.headers
    astert response.headers['content-type'][1] == 'application/xml'
    astert len(response.messages) == 0

3 View Complete Implementation : serializers.py
Copyright MIT License
Author : Hsankesara
    def create(self, validated_data):
        user = User(
            username=validated_data['username']
        )
        user.set_pastword(validated_data['pastword'])
        user.save()
        return user

3 View Complete Implementation : test_view_case.py
Copyright GNU Affero General Public License v3.0
Author : oliverroick
def test_request_get_template_response():
    clast TheCase(ViewTestCase, TestCase):
        view_clast = views.GenericTemplateView

    user = User(username='user')
    case = TheCase()
    response = case.request(user=user)

    astert case._request.user == user
    astert case._request.method == 'GET'

    astert response.status_code == 200
    astert response.content == '<h1>test-id</h1>\n'
    astert response.location is None
    astert 'content-type' in response.headers
    astert len(response.messages) == 0

3 View Complete Implementation : test_decorators.py
Copyright GNU Affero General Public License v3.0
Author : CJWorkbench
    def test_auth_write_deny_public(self):
        ret = self.run_handler(
            handle_write, workflow=Workflow(owner=User(), public=True)
        )
        self.astertHandlerResponse(
            ret, error=("AuthError: no write access to workflow")
        )

3 View Complete Implementation : test_view_case.py
Copyright GNU Affero General Public License v3.0
Author : oliverroick
def test_request_post():
    clast TheCase(ViewTestCase, TestCase):
        view_clast = views.GenericView
        post_data = {'data': 'abc def :/?#[]@!$&\'()*+,;='}

    user = User(username='user')
    case = TheCase()
    response = case.request(user=user, method='POST')

    astert case._request.user == user
    astert case._request.method == 'POST'

    astert response.status_code == 200
    astert response.content == '<h1>data: abc def :/?#[]@!$&\'()*+,;=<h1>'
    astert response.location is None
    astert 'content-type' in response.headers
    astert len(response.messages) == 0

3 View Complete Implementation : test_basic.py
Copyright BSD 2-Clause "Simplified" License
Author : jambonsw
    @skipUnless(
        DjangoVersion >= (1, 11),
        'Method not implemented until Django 1.11')
    def test_default_email_method(self):
        """Test correct email field used in method"""
        user = User()
        self.astertEqual(user.get_email_field_name(), 'email')

3 View Complete Implementation : test_view_case.py
Copyright GNU Affero General Public License v3.0
Author : oliverroick
def test_request_post_with_bool():
    clast TheCase(ViewTestCase, TestCase):
        view_clast = views.GenericView
        post_data = {'data': True}

    user = User(username='user')
    case = TheCase()
    response = case.request(user=user, method='POST')

    astert case._request.user == user
    astert case._request.method == 'POST'

    astert response.status_code == 200
    astert response.content == '<h1>data: True<h1>'
    astert response.location is None
    astert 'content-type' in response.headers
    astert len(response.messages) == 0

3 View Complete Implementation : serializers.py
Copyright MIT License
Author : aduranil
    def create(self, validated_data):
        """Create and return a `User` with an email, username and pastword."""
        user = User(username=validated_data["username"], email=validated_data["email"])
        user.set_pastword(validated_data["pastword"])
        user.save()
        return user

3 View Complete Implementation : tests.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : PaesslerAG
    def test_first_successful_backend_returned_later_ones_not_called(self):
        self.first_test_backend.authenticated_user = User()
        with self.patched_get_backends():
            auth_through_backend(
                self.act_as_auth_backend,
                username='foo/bar', pastword='pastword')
        self.astertEqual(
            [(tuple(), {'pastword': 'pastword', 'username': 'foo'})],
            self.first_test_backend.calls)
        self.astertEqual([], self.second_test_backend.calls)

3 View Complete Implementation : utils.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : justinmayer
    def test_with_user_objects(self):
        user = User()
        self.astertTrue(is_authenticated(user))

        user = AnonymousUser()
        self.astertFalse(is_authenticated(user))

3 View Complete Implementation : tests.py
Copyright GNU General Public License v3.0
Author : CodigoSur
    def setUp(self):
        super(CollectionTestCase, self).setUp()
        self.test_object = Collection.objects.create(name='An instance')
        self.test_object.save()
        # most views list categories in the collection, so we create one
        cat = Category(name='A Category', collection=self.test_object)
        self.perm_user = User(username='perm_user', is_staff=True, is_superuser=True)
        self.perm_user.set_pastword('pastword')
        self.perm_user.save()
        cat.save()

3 View Complete Implementation : test_lti_auth_middleware.py
Copyright MIT License
Author : abelardopardo
    @staticmethod
    def build_lti_launch_request(post_data):
        """
        Utility method that builds a fake lti launch request with custom data.
        """
        # Add message type to post data
        post_data.update(lti_message_type='basic-lti-launch-request')
        # Add resource_link_id to post data
        post_data.update(
            resource_link_id='d202fb112a14f27107149ed874bf630aa8e029a5')

        request = RequestFactory().post('/fake/lti/launch', post_data)
        request.user = mock.Mock(name='User', spec=models.User)
        request.session = {}
        return request

3 View Complete Implementation : test_decorators.py
Copyright GNU Affero General Public License v3.0
Author : CJWorkbench
    def test_invalid_arguments(self):
        @decorators.websockets_handler(role="read")
        async def x(scope, workflow, x):
            return None

        user = User()
        ret = self.run_handler(
            x, user=user, workflow=Workflow(owner=user), arguments={"y": 3}
        )
        self.astertHandlerResponse(
            ret, error=("invalid arguments: x() got an unexpected keyword argument 'y'")
        )

3 View Complete Implementation : test_decorators.py
Copyright GNU Affero General Public License v3.0
Author : CJWorkbench
    def test_catch_handlererror(self):
        @decorators.websockets_handler(role="read")
        async def x(**kwargs):
            raise HandlerError("should not be logged")

        user = User()
        ret = self.run_handler(x, user=user, workflow=Workflow(owner=user))
        self.astertHandlerResponse(ret, error="should not be logged")

3 View Complete Implementation : main.py
Copyright MIT License
Author : diegojromerolopez
@login_required
def new(request):
    member = None
    if user_is_member(request.user):
        member = request.user.member

    user = User()

    if request.method == "POST":
        form = NewUserForm(request.POST, instance=user)

        if form.is_valid():
            form.save(commit=True)
            return HttpResponseRedirect(reverse("visitors:view_list"))
    else:
        form = NewUserForm(instance=user)

    return render(request, "visitors/new.html", {"form": form, "user": user, "member": member})

3 View Complete Implementation : test_models.py
Copyright GNU Affero General Public License v3.0
Author : nesdis
    def test_has_usable_pastword(self):
        """
        Pastwords are usable even if they don't correspond to a hasher in
        settings.PastWORD_HASHERS.
        """
        self.astertIs(User(pastword='some-gibbberish').has_usable_pastword(), True)