英文:
How Can I Write and Run a Django User Registration Unit Test Case
问题
这个错误可能是由于测试用例的命名问题引起的。请确保你的测试类的命名是正确的,应该与文件名匹配,并且在命名中使用驼峰命名法。此外,确保在测试文件中导入了需要的模块和类。
请检查以下几点:
- 测试文件的文件名应该与测试类的名称匹配,确保文件名以
.py
结尾,例如,如果你的测试类名为RegisterViewTestCase
,测试文件的名称应该是test_register_view.py
。 - 确保在测试文件的顶部导入了必要的模块和类,包括
RegistrationForm
和其他相关的模块。 - 在运行测试之前,确保你的Django项目的应用中有一个名为
account
的应用,并且在应用的tests.py
文件中定义了RegisterViewTestCase
类。
如果你已经检查了以上几点,但问题仍然存在,请提供更多关于你的项目结构和文件组织的信息,以便我能够提供更具体的帮助。
英文:
I am working on a Django Project that contain two apps; account and realestate and I have a user registration form for registration. This Registration Form is working correctly on my local machine but I want to write and run a Django Unit test for it to be sure everything is working internally well.
Below is my Registration Form code:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
# Define the user_type choices
USER_TYPE_CHOICES = (
('landlord', 'Landlord'),
('agent', 'Agent'),
('prospect', 'Prospect'),
)
# Create the registration form
class RegistrationForm(UserCreationForm):
username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control left-label'}))
password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control left-label'}))
password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control left-label'}))
user_type = forms.ChoiceField(choices=USER_TYPE_CHOICES, widget=forms.Select(attrs={'class': 'form-control left-label'}))
class Meta:
model = User
fields = ['username', 'password1', 'password2', 'user_type']
Here is my User Registration View code:
def register(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
# Create a new user object
user = form.save()
# Get the user_type value from the form
user_type = form.cleaned_data['user_type']
# Create a new object based on the user_type
if user_type == 'landlord':
Landlord.objects.create(user=user)
elif user_type == 'agent':
Agent.objects.create(user=user)
elif user_type == 'prospect':
Prospect.objects.create(user=user)
# Log the user in and redirect to the homepage
login(request, user)
return redirect('success-account')
else:
form = RegistrationForm()
context = {
'form': form,
'page_title': 'Register',
}
return render(request, 'account/register.html', context)
Here is my Unit Test Code:
from django.contrib.auth.models import User
from django.test import TestCase, Client
from django.urls import reverse
from account.forms import RegistrationForm
from realestate.models import Landlord, Agent, Prospect
class RegisterViewTestCase(TestCase):
def setUp(self):
self.client = Client()
self.url = reverse('register-account')
def test_register_view_success(self):
data = {
'username': 'testuser',
'email': 'testuser@example.com',
'password1': 'testpassword',
'password2': 'testpassword',
'user_type': 'landlord'
}
form = RegistrationForm(data)
self.assertTrue(form.is_valid())
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, 302)
self.assertRedirects(response, reverse('success-account'))
user = User.objects.get(username='testuser')
self.assertIsNotNone(user)
self.assertTrue(user.check_password('testpassword'))
landlord = Landlord.objects.get(user=user)
self.assertIsNotNone(landlord)
def test_register_view_invalid_form(self):
data = {
'username': 'testuser',
'email': 'testuser@example.com',
'password1': 'testpassword',
'password2': 'wrongpassword',
'user_type': 'landlord'
}
form = RegistrationForm(data)
self.assertFalse(form.is_valid())
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(response, 'account/register.html')
form = response.context['form']
self.assertTrue(form.has_error('password2'))
user_exists = User.objects.filter(username='testuser').exists()
self.assertFalse(user_exists)
Any time I run python manage.py test account.tests.RegisterViewTestCase on the terminal error says: ERROR: RegisterViewTestCase (unittest.loader._FailedTest), AttributeError: module 'account.tests' has no attribute 'RegisterViewTestCase'.
What could be the issue here and how can it be fixed.
答案1
得分: 1
错误提示说测试在'account'包中找不到。
你需要检查你的测试文件是否命名正确,例如:
- tests.py
或
- test_register.py
然后运行 $ ./manage.py test
进行检查。
查看 Django 文档 这里:
默认的 startapp 模板会在新应用中创建一个 tests.py 文件。如果你只有一些测试,这可能没问题,但随着测试套件的增长,你可能会想要将其重组为一个 tests 包,这样你可以将测试分成不同的子模块,如 test_models.py、test_views.py、test_forms.py 等。随意选择你喜欢的组织方案。
英文:
The error say that the test are not found within the 'account' package.
You need to check if your test file is properly named, for instance:
- tests.py
or
- test_register.py
and run $ ./manage.py test
this
check django documentation from here:
> The default startapp template creates a tests.py file in the new
> application. This might be fine if you only have a few tests, but as
> your test suite grows you’ll likely want to restructure it into a
> tests package so you can split your tests into different submodules
> such as test_models.py, test_views.py, test_forms.py, etc. Feel free
> to pick whatever organizational scheme you like.
答案2
得分: 0
确保测试文件以test_*.py开头,或者如果测试文件位于test文件夹中,请在该文件夹中创建__init__.py。
英文:
make sure that test file starts with test_*.py or if the tests file in test folder create init.py within the folder
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论