如何编写并运行Django用户注册单元测试用例

huangapple go评论97阅读模式
英文:

How Can I Write and Run a Django User Registration Unit Test Case

问题

这个错误可能是由于测试用例的命名问题引起的。请确保你的测试类的命名是正确的,应该与文件名匹配,并且在命名中使用驼峰命名法。此外,确保在测试文件中导入了需要的模块和类。

请检查以下几点:

  1. 测试文件的文件名应该与测试类的名称匹配,确保文件名以.py结尾,例如,如果你的测试类名为RegisterViewTestCase,测试文件的名称应该是test_register_view.py
  2. 确保在测试文件的顶部导入了必要的模块和类,包括RegistrationForm和其他相关的模块。
  3. 在运行测试之前,确保你的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:

  1. from django import forms
  2. from django.contrib.auth.forms import UserCreationForm
  3. from django.contrib.auth.models import User
  4. # Define the user_type choices
  5. USER_TYPE_CHOICES = (
  6. ('landlord', 'Landlord'),
  7. ('agent', 'Agent'),
  8. ('prospect', 'Prospect'),
  9. )
  10. # Create the registration form
  11. class RegistrationForm(UserCreationForm):
  12. username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control left-label'}))
  13. password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control left-label'}))
  14. password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control left-label'}))
  15. user_type = forms.ChoiceField(choices=USER_TYPE_CHOICES, widget=forms.Select(attrs={'class': 'form-control left-label'}))
  16. class Meta:
  17. model = User
  18. fields = ['username', 'password1', 'password2', 'user_type']

Here is my User Registration View code:

  1. def register(request):
  2. if request.method == 'POST':
  3. form = RegistrationForm(request.POST)
  4. if form.is_valid():
  5. # Create a new user object
  6. user = form.save()
  7. # Get the user_type value from the form
  8. user_type = form.cleaned_data['user_type']
  9. # Create a new object based on the user_type
  10. if user_type == 'landlord':
  11. Landlord.objects.create(user=user)
  12. elif user_type == 'agent':
  13. Agent.objects.create(user=user)
  14. elif user_type == 'prospect':
  15. Prospect.objects.create(user=user)
  16. # Log the user in and redirect to the homepage
  17. login(request, user)
  18. return redirect('success-account')
  19. else:
  20. form = RegistrationForm()
  21. context = {
  22. 'form': form,
  23. 'page_title': 'Register',
  24. }
  25. return render(request, 'account/register.html', context)

Here is my Unit Test Code:

  1. from django.contrib.auth.models import User
  2. from django.test import TestCase, Client
  3. from django.urls import reverse
  4. from account.forms import RegistrationForm
  5. from realestate.models import Landlord, Agent, Prospect
  6. class RegisterViewTestCase(TestCase):
  7. def setUp(self):
  8. self.client = Client()
  9. self.url = reverse('register-account')
  10. def test_register_view_success(self):
  11. data = {
  12. 'username': 'testuser',
  13. 'email': 'testuser@example.com',
  14. 'password1': 'testpassword',
  15. 'password2': 'testpassword',
  16. 'user_type': 'landlord'
  17. }
  18. form = RegistrationForm(data)
  19. self.assertTrue(form.is_valid())
  20. response = self.client.post(self.url, data)
  21. self.assertEqual(response.status_code, 302)
  22. self.assertRedirects(response, reverse('success-account'))
  23. user = User.objects.get(username='testuser')
  24. self.assertIsNotNone(user)
  25. self.assertTrue(user.check_password('testpassword'))
  26. landlord = Landlord.objects.get(user=user)
  27. self.assertIsNotNone(landlord)
  28. def test_register_view_invalid_form(self):
  29. data = {
  30. 'username': 'testuser',
  31. 'email': 'testuser@example.com',
  32. 'password1': 'testpassword',
  33. 'password2': 'wrongpassword',
  34. 'user_type': 'landlord'
  35. }
  36. form = RegistrationForm(data)
  37. self.assertFalse(form.is_valid())
  38. response = self.client.post(self.url, data)
  39. self.assertEqual(response.status_code, 200)
  40. self.assertTemplateUsed(response, 'account/register.html')
  41. form = response.context['form']
  42. self.assertTrue(form.has_error('password2'))
  43. user_exists = User.objects.filter(username='testuser').exists()
  44. 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

huangapple
  • 本文由 发表于 2023年5月11日 16:20:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76225517.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定