M
M
Maxim2016-09-27 12:36:36
Django
Maxim, 2016-09-27 12:36:36

Problem with testing in Django?

Hello everyone, I haven’t written tests before, so the solution is most likely very simple)
there are tests themselves

class UserTestCase(TestCase):

    def setUp(self):
        self.c = Client()
        self.user = UserProfile.objects.create(
            first_name='John',
            last_name='Doy',
            username='user1',
            email='[email protected]',
            phone='+79000000001',
            code='3322',
            token="token",
            confirmed=True,
        )
        self.user.save()

and one method test
def test_user_login(self):
        qry = {
            'phone': self.user.phone,
            'code': self.user.code
        }
        res = self.c.post(
            '/login',
            json.dumps(qry),
            content_type="application/json"
        )
        data = json.loads(res.content.decode('utf-8'))
        self.assertEqual(res.status_code, 200)
        self.assertEqual(data['success'], True)
        self.assertEqual(data['token'], UserProfile.objects.get(phone=self.user.phone).token)

Here is the tested method
@csrf_exempt
def user_login(request):
    if request.method == 'POST':
        data = JSONParser().parse(request)
        phone = validate_phone(data["phone"])
        code = data["code"]
        try:
            user = UserProfile.objects.get(phone=phone, code=code)
            token = token_generator()
            user.token = token
            user.save()
            return JSONResponse({
                "token": token,
                "confirmed": user.confirmed,
                "success": True,
                "first_name": user.first_name,
                "last_name": user.last_name,
                "photo": user.photo,

            })
        except UserProfile.DoesNotExist:
            return JSONResponse({
                "token": None,
                "success": False,
                "message": "wrong phone number or confirmation code"
            })

The whole chip with the database, as far as I understood, was trying to get the debugger
-> try:
(Pdb) !user = UserProfile.objects.get(phone=phone)
*** api.models.DoesNotExist: UserProfile matching query does not exist.

What am I doing wrong?
The test fails because it cannot get data from the database.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2016-09-28
@maximkv25

I found the reason, the function phone = validate_phone(data["phone"])removes + and therefore the number was compared without +
There will be a skill in working with someone else's code)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question