jeudi 8 avril 2021

TESTING a Django View

I am very new to testing, this is my first set of tests. I have followed few tutorials on how to go about testing and while the testing that I have made for models and URLs work perfectly, my views testing are not working properly. I have looked at some answers for similar questions on Stack but can't find a reason why this would not work.

This is my View function:

@csrf_exempt
@login_required
def profile(request, username):

    user = request.user
    profilepic = ProfilePic.objects.filter(user=user).first()
    username = User.objects.filter(username=username).first()
    usr = username
    following = FollowedCrypto.objects.filter(user=user.id)
    cryptos = []
    
    for i in following:
        cryptos.append(i.cryptocurrency)

    return render(request, "PlanetCrypton/profile.html", {
        "following":following,
        "user": user,
        "usr" : username,
        "profilepic":profilepic,
        "crypto": cryptos,
        })

and this is my test for it:

def test_profile(self):

        c = Client()    

        user_b = User.objects.create(username="Fred", password="fred")
        user_b.save()    
   
        profilepic = ProfilePic()   
        profilepic.user = user_b 
        profilepic.profile_pic = SimpleUploadedFile(name='test_image.jpg', 
        content=open("/Users/michelangelo/Desktop/FP1/static/images/Jaguar.jpg", 'rb').read(), 
        content_type='image/jpeg')
        profilepic.save()

        followedcryptos = FollowedCrypto()
        followedcryptos.user = user_b
        followedcryptos.cryptocurrency = "bitcoin"
        followedcryptos.save()

        l1 = []
        l2 = []

        l1.append(followedcryptos)
        l2.append(followedcryptos.cryptocurrency)

        data = {
        
            "following": l1,
            "user": user_b,
            "usr" : user_b.username,
            "profilepic": profilepic,
            "crypto": l2

        }
    
        response = c.get(f"/profile/{user_b.username}", data, follow=True)

        self.assertEquals(response.status_code, 200)

instead of using l1 and l2 to pass the data, I have also directly tried by writing the values as strings or sourcing them as objects but nothing, I still anyway get at the end a 404 for the assertion. Can anyone tell me where I am making a mistake?

Thanks!!

Aucun commentaire:

Enregistrer un commentaire