I want to write a test case for a function in my views
in my Django project. I am just a beginner in this field, I have changed my settings.py
and added the below line of code to the DATABASES
dictionary, and also create a new user using MySQL shell based on this
But after I run the test it shows this error:
Failure
Traceback (most recent call last):
File "D:\ABDAL\sepanta\react\tests\test_views.py", line 26, in test_users_GET
self.assertEqual(response.status_code, 200)
AssertionError: 401 != 200
I could not understand the reason for this problem, and I have also searched for similar problems, but they did not help me. Does Django create a new database while testing the APIs? and the reason can be because of that the database is empty.
CodePudding user response:
Django always create a separate database for testing. Just so you know, the database is also always destroyed after running tests. However, you can provide a flag to keep test database. You can read more on that here
To solve your problem, you need to create a new Profile within your test (test fixtures). You will typically want to do that in the setUp
method.
NB: The profile created has nothing to do with your normal or real database and in fact you can check the id of the profile and realize it will be 1 despite having profiles in your database. That even assert to the fact that a separate database is used for testing.