如何测试用户是否可以显示其个人资料?

时间:2019-10-16 08:57:08

标签: python django unit-testing testing

我有一个模型UserProfile。

Use communicate() rather than .stdin.write, .stdout.read or .stderr.read to avoid deadlocks due to any of the other OS pipe buffers filling up and blocking the child process.

他的观点:

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='user', on_delete=models.CASCADE)
    city = models.CharField(max_length=100, blank=False)
    region = models.CharField(max_length=100, blank=False)
    post_code = models.CharField(max_length=100, blank=False)


    def create_profile(sender, **kwargs): #Funckja, ktora tworzy profile użytkownika
        user = kwargs["instance"]
        if kwargs["created"]:
            user_profile = UserProfile(user=user)
            user_profile.save()
    post_save.connect(create_profile, sender=User)

    def __str__(self):
        return self.user.username

问题是我想测试用户是否可以通过单击以下内容来显示其个人资料:

def user_details(request, pk):
    user = get_object_or_404(User, pk=pk)
    userprofile = user.user
    return render(request, 'user_details.html', {'userprofile': userprofile})

我不知道该怎么做。我试图这样做:

<a href="{% url 'accounts:user_details' pk=user.pk %}">Your profile</a>

但是它不起作用。

完整代码在这里:https://github.com/Incybro/DjangoShop

1 个答案:

答案 0 :(得分:0)

from django.test import TestCase
from .models import *
from django.test import Client


class UserDetailsView(TestCase):
    @classmethod
    def setUpTestData(cls):
        cls.client = Client()
        cls.user = User.objects.create(username="Test")
        # owner needs to be a class or instance attribute to access it otherwhere
        cls.owner = cls.user
        cls.user.save()

    def test_view_url_exists_at_desired_location(self):
        # you formated the response of get instead of the url string
        response = self.client.get('accounts/{}'.format(self.owner))
        self.assertEqual(response.status_code, 200)