Я пытаюсь научиться тестировать в Django, поэтому я новичок, и любое попадание приветствуется.
Итак, мне только что удалось создать пользовательскую модель, идентичную электронной почте и пароль:
class UserManager(BaseUserManager):
def create_user(self, email, first_name, last_name, password=None):
"""
Creates and saves a User with the given email,
first name and last name.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
first_name=first_name,
last_name=last_name,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, first_name, last_name, password=None):
"""
Creates and saves a superuser with the given email, date of
birth and password.
"""
user = self.create_user(
email,
password=password,
first_name=first_name,
last_name=last_name,
)
user.is_admin = True
user.save(using=self._db)
return user
class User(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
def __str__(self):
return '{} {} ID: {}'.format(self.first_name, self.last_name, self.id)
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
"Is the user a member of staff?"
# Simplest possible answer: All admins are staff
return self.is_admin
И, следуя документации Django, я зарегистрировал ее в admin.py, как показано ниже:
class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = User
fields = ('email', 'first_name', 'last_name')
def clean_password2(self):
# Check that the two password entries match
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError("Passwords don't match")
return password2
def save(self, commit=True):
# Save the provided password in hashed format
user = super().save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
Я предполагаю, что все работает нормально, но это говорит о том, что Первое, что я должен проверить (кроме домашнего просмотра), это представление регистрации, которое я определил следующим образом:
def signup(request):
form = UserCreationForm()
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
data = form.cleaned_data
user = User.objects.create(email=data['email'], first_name=data['email'], last_name=data['last_name'])
user.save()
return redirect(home)
template_name = 'signup.html'
context = {'form': form}
return render(request, template_name, context)
Итак, я написал следующий тест:
class SignUpViewTest(TestCase):
def setUp(self):
User.objects.create(
email='john.smith@example.com',
first_name='John',
last_name='Smith',
)
User.objects.create(
email='jack.sparrow@example.com',
first_name='Jack',
last_name='Sparrow',
)
def test_signup(self):
client = Client()
form = UserCreationForm()
if form.is_valid():
form.data = {
'email': 'leo.davinci@example.com',
'first_name': 'Leonardo',
'last_name': 'Da Vinci',
'password1:': 'leopass1',
'password2:': 'leopass1',
}
response = client.post(
'/signup/',
form
)
users = User.objects.all()
self.assertRedirects(response, '', status_code=302, target_status_code=200, msg_prefix='',
fetch_redirect_response=True)
self.assertEqual(
users,
'<QuerySet [<User: John Smith ID: 1>, <User: Jack Sparrow ID: 2>, <User: Leonardo Da Vinci ID: 3>]>',
)
, что не получается с выводом:
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
E
======================================================================
ERROR: test_signup (accounts.tests.SignUpViewTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\oricc\PycharmProjects\AssessmentSystem\accounts\tests.py", line 32, in te
st_signup
form
File "C:\Users\oricc\PycharmProjects\AssessmentSystem\venv\lib\site-packages\django\test
\client.py", line 526, in post
response = super().post(path, data=data, content_type=content_type, secure=secure, **e
xtra)
File "C:\Users\oricc\PycharmProjects\AssessmentSystem\venv\lib\site-packages\django\test
\client.py", line 353, in post
post_data = self._encode_data(data, content_type)
File "C:\Users\oricc\PycharmProjects\AssessmentSystem\venv\lib\site-packages\django\test
\client.py", line 312, in _encode_data
return encode_multipart(BOUNDARY, data)
File "C:\Users\oricc\PycharmProjects\AssessmentSystem\venv\lib\site-packages\django\test
\client.py", line 193, in encode_multipart
for (key, value) in data.items():
AttributeError: 'UserCreationForm' object has no attribute 'items'
----------------------------------------------------------------------
Ran 1 test in 0.003s
FAILED (errors=1)
Destroying test database for alias 'default'...
Я знаю, что этот тест, вероятно, выглядит ужасно, но я только учусь, и документация Django не очень удобна для начинающих ...
Что я делаю не так? как я могу это реализовать?
Спасибо