Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions pytest_django/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,11 +291,12 @@ def admin_user(db, django_user_model, django_username_field):
try:
user = UserModel._default_manager.get(**{username_field: username})
except UserModel.DoesNotExist:
extra_fields = {}
if username_field not in ("username", "email"):
extra_fields[username_field] = "admin"
user = UserModel._default_manager.create_superuser(
username, "admin@example.com", "password", **extra_fields
**{
username_field: username,
"email": "admin@example.com",
"password": "password",
Comment on lines +296 to +298
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In case username_field is email, it should override the email below, so should come after it (even though the values are the same, but just for good measure).

Suggested change
username_field: username,
"email": "admin@example.com",
"password": "password",
"email": "admin@example.com",
"password": "password",
username_field: username,

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for taking the time to review! I will add the requested changes and push again.

}
)
return user

Expand All @@ -306,7 +307,7 @@ def admin_client(db, admin_user):
from django.test.client import Client

client = Client()
client.login(username=admin_user.username, password="password")
client.login(username=admin_user.get_username(), password="password")
return client


Expand Down
2 changes: 1 addition & 1 deletion pytest_django/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ def _get_boolean_value(x, name, default=None):
except KeyError:
raise ValueError(
"{} is not a valid value for {}. "
"It must be one of {}." % (x, name, ", ".join(possible_values.keys()))
"It must be one of {}.".format(x, name, ", ".join(possible_values.keys()))
)


Expand Down
45 changes: 32 additions & 13 deletions tests/test_fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -503,15 +503,40 @@ def test_with_live_server(live_server):
def test_custom_user_model(django_testdir, username_field):
django_testdir.create_app_file(
"""
from django.contrib.auth.models import AbstractUser
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models

class MyCustomUser(AbstractUser):
class MyCustomUserManager(BaseUserManager):
def create_user(self, {username_field}, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
user = self.model({username_field}={username_field}, **extra_fields)
user.set_password(password)
user.save()
return user

def create_superuser(self, {username_field}, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
return self.create_user(
{username_field}={username_field},
password=password,
**extra_fields
)

class MyCustomUser(AbstractBaseUser, PermissionsMixin):
email = models.EmailField(max_length=254, unique=True)
identifier = models.CharField(unique=True, max_length=100)
is_staff = models.BooleanField(
'staff status',
default=False,
help_text='Designates whether the user can log into this admin site.'
)

USERNAME_FIELD = '%s'
"""
% (username_field),
objects = MyCustomUserManager()

USERNAME_FIELD = '{username_field}'
""".format(username_field=username_field),
"models.py",
)
django_testdir.create_app_file(
Expand Down Expand Up @@ -573,19 +598,13 @@ class Migration(migrations.Migration):
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(null=True, verbose_name='last login', blank=True)),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, max_length=30, validators=[django.core.validators.RegexValidator(r'^[\\w.@+-]+$', 'Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.', 'invalid')], help_text='Required. 30 characters or fewer. Letters, digits and @/./+/-/_ only.', unique=True, verbose_name='username')),
('first_name', models.CharField(max_length=30, verbose_name='first name', blank=True)),
('last_name', models.CharField(max_length=30, verbose_name='last name', blank=True)),
('email', models.EmailField(max_length=254, verbose_name='email address', blank=True)),
('email', models.EmailField(error_messages={'unique': 'A user with that email address already exists.'}, max_length=254, unique=True, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('identifier', models.CharField(unique=True, max_length=100)),
('groups', models.ManyToManyField(related_query_name='user', related_name='user_set', to='auth.Group', blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', verbose_name='groups')),
('user_permissions', models.ManyToManyField(related_query_name='user', related_name='user_set', to='auth.Permission', blank=True, help_text='Specific permissions for this user.', verbose_name='user permissions')),
],
options={
'abstract': False,
'verbose_name': 'user',
'verbose_name_plural': 'users',
},
Expand All @@ -597,7 +616,7 @@ class Migration(migrations.Migration):
)

result = django_testdir.runpytest_subprocess("-s")
result.stdout.fnmatch_lines(["* 1 passed in*"])
result.stdout.fnmatch_lines(["* 1 passed*"])
assert result.ret == 0


Expand Down