如何解决如何在测试期间使用 CustomUser(AbstractUser) 类而不是默认 AbstractUser 来运行 Django 测试以获得正确的外键分配?
我在“帐户”应用程序中有一个 CustomUser 模型,它覆盖了 Django 的默认 auth.User:
class CustomUser(AbstractUser):
age = PositiveIntegerField(null=True,blank=True)
user_type = CharField(max_length=8,null=False,choices=[('customer','Customer'),('owner','Owner')])
另一个应用“电子商务”,其模型产品(为简洁起见而缩写)带有指向上面 CustomUser 字段的外键:
class Product(Model):
name = CharField(max_length=255,blank=False)
[...]
seller = ForeignKey(CustomUser,on_delete=CASCADE,related_name='products')
当我创建新产品时,我在模型上使用 form_valid() 函数根据 Django 通过 CreateView 使用的请求来设置用户。这在我在浏览器中工作时有效,但在我尝试通过测试脚本验证我的 ProductCreateView 时无效:
views.py
class ProductCreateView(CreateView):
model = Product
[...]
def form_valid(self,form):
form.instance.seller = self.request.user
return super().form_valid(form)
test.py
def test_product_create_view(self):
response = self.client.post(
reverse('ecommerce_post_product'),{
'name': 'newProduct','price': 2.99,'category': 'newCategory','quantity': 100,'shipping': 'standard',}) # error happens here
self.assertEqual(response.status_code,302) # test does not reach this line
当我运行我的测试时,这个测试总是抛出一个错误声明,ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7fbce54f0040>>": "Product.seller" must be a "CustomUser" instance."
我尝试使用一行 self.client.user = self.user
传入我在 TestCase 的“setUp()”函数中定义的 self.user,但它继续抛出错误。
如何让我的测试通过 CustomUser 而不是它在运行脚本时使用的 AnonymousUser?
解决方法
您收到 AnonymousUser
,因为在您访问视图时没有用户登录。在您的 setUp()
中,创建用户并确保正确散列密码。然后使用凭据调用 client.login
:
def setUp(self):
self.user = CustomUser.objects.create(username='testUser',email='test@email.com',password='')
self.user.set_password('secret')
self.user.save()
...
self.client = Client()
self.client.login(username='testUser',password='secret')
您可以阅读有关这些变化的更多信息here
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。