def testUsersRawCreation(self):
     u = User(username="******", hashedID="123452", email="*****@*****.**")
     u2 = User(username="******",
               hashedID="123452",
               email="*****@*****.**")
     u.save()
     U = User.objects.filter(username="******").get()
     self.assertEqual(u.username, U.username)
     self.assertNotEqual(u2.username, U.username)
     U = User.objects.filter(username="******")
     self.assertEqual(0, U.count())
     u2.save()
     U = User.objects.filter(username="******")
     self.assertEqual(1, U.count())
示例#2
0
 def basic(self, email="*****@*****.**", commit=False):
     username = email.split("@")[0]
     user = User(username=username, email=email)
     if commit:
         Profile.objects.create(user=user)
         user.save()
     return user
示例#3
0
def test_update_leaderboard_game(status_mock):
    game = game_factory.basic()
    snakes = snake_factory.basic(n=8, commit=True)
    user_snakes = [UserSnake(snake=s, user=User()) for s in snakes]
    for s in user_snakes:
        s.save()
        UserSnakeLeaderboard.objects.get_or_create(user_snake=s)

    game.engine_id = str(uuid.uuid4())
    game.snakes = [{'id': snake.id, 'name': snake.name, 'url': snake.url} for snake in snakes]
    game.is_leaderboard_game = True
    game.create()
    game_snakes = GameSnake.objects.filter(game_id=game.id)

    snakes_dict = {snake.id: {'death': 'starvation', 'turn': random.randint(1, 100)} for snake in game_snakes}
    snakes_dict[game_snakes[0].id]['death'] = ''
    snakes_dict[game_snakes[0].id]['turn'] = 125
    snakes_dict[game_snakes[1].id]['turn'] = 125

    status_mock.return_value = {
        'status': Game.Status.COMPLETE,
        'turn': 125,
        'snakes': snakes_dict
    }

    GameStatusJob().run()

    lb = UserSnakeLeaderboard.objects.all()[0]
    assert lb.mu is not None
    assert lb.sigma is not None
示例#4
0
    def create(self, validated_data):
        password2 = validated_data.pop('password2')
        user = User(**validated_data)
        user.set_password(validated_data['password'])
        user.save()

        return user
示例#5
0
 def create(self, validated_data):
     try:
         user = User.objects.filter(email=validated_data.get('email')).get()
         if user.is_active:
             raise CustomException(ErrorCode.account_has_exist)
     except User.DoesNotExist:
         user = User(
             email=validated_data.get('email'),
             username=validated_data.get('username'),
             gender=validated_data.get('gender'),
             birthday=validated_data.get('birthday'),
             company=validated_data.get('company', None),
         )
         user.set_password(validated_data.get('password'))
         user.save()
     return user
示例#6
0
def test_update_leaderboard_game(run_mock, status_mock):

    run_mock.return_value = str(uuid.uuid4())

    snakes = snake_factory.basic(n=4, commit=True)
    user_snakes = [UserSnake(snake=s, user=User()) for s in snakes]
    for s in user_snakes:
        s.save()
        UserSnakeLeaderboard.objects.get_or_create(user_snake=s)

    MatchStarter().run()

    game_snakes = GameSnake.objects.all()

    snakes_dict = {
        snake.id: {
            'death': 'starvation',
            'turn': random.randint(1, 100)
        }
        for snake in game_snakes
    }
    snakes_dict[game_snakes[0].id]['death'] = ''
    snakes_dict[game_snakes[0].id]['turn'] = 125
    snakes_dict[game_snakes[1].id]['turn'] = 125

    status_mock.return_value = {
        'status': Game.Status.COMPLETE,
        'turn': 125,
        'snakes': snakes_dict
    }

    GameStatusJob().run()

    lb = UserSnakeLeaderboard.objects.all()[0]
    assert lb.mu is not None
    assert lb.sigma is not None

    result = LeaderboardResult.objects.get(snake=lb)
    assert result is not None
    assert result.mu_change is not None
    assert result.sigma_change is not None
示例#7
0
    def create(self, validated_data: OrderedDict) -> User:
        """ Creates new User instance when calling serializer.save() method.

        Parameters:
        ----------
        validated_data:
            Serializer property created while user_serializer.is_valid() method
            calling.

        Returns:
        ----------
            User instance.
        """

        user_instance = User(
            name=validated_data["name"],
            username=validated_data["name"],
            email=validated_data["email"],
        )
        user_instance.set_password(validated_data["password"])
        user_instance.save()

        return user_instance
示例#8
0
 def basic(self, email="*****@*****.**", commit=False):
     username = email.split("@")[0]
     user = User(username=username, email=email)
     if commit:
         user.save()
     return user
示例#9
0
def register(request):
    log = logging.getLogger(__name__)

    if request.user.is_authenticated:
        messages.error(
            request, _('Registrering av ny konto krever at du er logget ut.'))
        return HttpResponseRedirect('/')
    else:
        if request.method == 'POST':
            form = RegisterForm(request.POST)
            if form.is_valid():
                cleaned = form.cleaned_data

                # Create user
                user = User(
                    username=cleaned['username'],
                    first_name=cleaned['first_name'].title(),
                    last_name=cleaned['last_name'].title(),
                )
                # Set remaining fields
                user.phone_number = cleaned['phone']
                user.address = cleaned['address'].title()
                user.zip_code = cleaned['zip_code']
                # Store password properly
                user.set_password(cleaned['password'])
                # Users need to be manually activated
                user.is_active = False
                user.save()

                # Set email address
                email = Email(
                    user=user,
                    email=cleaned['email'].lower(),
                )
                email.primary = True
                email.save()

                # Create the registration token
                token = uuid.uuid4().hex

                try:
                    rt = RegisterToken(user=user,
                                       email=email.email,
                                       token=token)
                    rt.save()
                    log.info('Successfully registered token for %s' %
                             request.user)
                except IntegrityError as ie:
                    log.error('Failed to register token for "%s" due to "%s"' %
                              (request.user, ie))

                email_context = {}
                verify_url = reverse('auth_verify', args=(token, ))
                email_context['verify_url'] = request.build_absolute_uri(
                    verify_url)

                message = render_to_string('auth/email/welcome_tpl.txt',
                                           email_context)

                try:
                    send_mail(_('Verifiser din konto'), message,
                              settings.DEFAULT_FROM_EMAIL, [
                                  email.email,
                              ])
                except SMTPException:
                    messages.error(
                        request,
                        'Det oppstod en kritisk feil, epostadressen er ugyldig!'
                    )
                    return redirect('home')

                messages.success(
                    request,
                    _('Registreringen var vellykket. Se tilsendt epost for verifiseringsinstrukser.'
                      ))

                return HttpResponseRedirect('/')
            else:
                form = RegisterForm(request.POST, auto_id=True)
        else:
            form = RegisterForm()

        return render(request, 'auth/register.html', {
            'form': form,
        })
示例#10
0
def register(request):
    log = logging.getLogger(__name__)

    if request.user.is_authenticated:
        messages.error(
            request, _("Registrering av ny konto krever at du er logget ut."))
        return HttpResponseRedirect("/")
    else:
        if request.method == "POST":
            form = RegisterForm(request.POST)
            if form.is_valid():
                cleaned = form.cleaned_data

                # Create user
                user = User(
                    username=cleaned["username"],
                    first_name=cleaned["first_name"].title(),
                    last_name=cleaned["last_name"].title(),
                )
                # Set remaining fields
                user.phone_number = cleaned["phone"]
                user.address = cleaned["address"].title()
                user.zip_code = cleaned["zip_code"]
                # Store password properly
                user.set_password(cleaned["password"])
                # Users need to be manually activated
                user.is_active = False
                user.save()

                # Set email address
                email = Email(user=user, email=cleaned["email"].lower())
                email.primary = True
                email.save()

                # Create the registration token
                token = uuid.uuid4().hex

                try:
                    rt = RegisterToken(user=user,
                                       email=email.email,
                                       token=token)
                    rt.save()
                    log.info("Successfully registered token for %s" %
                             request.user)
                except IntegrityError as ie:
                    log.error('Failed to register token for "%s" due to "%s"' %
                              (request.user, ie))

                email_context = {}
                verify_url = reverse("auth_verify", args=(token, ))
                email_context["verify_url"] = request.build_absolute_uri(
                    verify_url)

                message = render_to_string("auth/email/welcome_tpl.txt",
                                           email_context)

                try:
                    send_mail(
                        _("Verifiser din konto"),
                        message,
                        settings.DEFAULT_FROM_EMAIL,
                        [email.email],
                    )
                except SMTPException:
                    messages.error(
                        request,
                        "Det oppstod en kritisk feil, epostadressen er ugyldig!",
                    )
                    return redirect("home")

                messages.success(
                    request,
                    _("Registreringen var vellykket. Se tilsendt epost for verifiseringsinstrukser."
                      ),
                )

                return HttpResponseRedirect("/")
            else:
                form = RegisterForm(request.POST, auto_id=True)
        else:
            form = RegisterForm()

        return render(request, "auth/register.html", {"form": form})
示例#11
0
 def test_cant_create_duplicate(self):
     User.objects.create_user(username='******', password='******')
     with self.assertRaises(ValidationError):
         user = User(username='******', password='******')
         user.full_clean()
示例#12
0
 def test_add_user_wrong_email(self):
     with self.assertRaises(Exception):
         user = User(username='******',
                     email='testuser_at_somemail.com',
                     password='******')
         user.full_clean()
示例#13
0
 def test_add_user_with_all_fields(self):
     user = User(username='******',
                 email='*****@*****.**',
                 password='******')
     user.full_clean()
     user.save()