'Django Testing error Object of type is not JSON serializable
I am testing an api and have some trouble when testing for objects with ForeignKeys.
This is what a test that fails looks like:
test_models.py
class GameroundViewTests(APITestCase):
def setUp(self):
self.client = APIClient()
self.user = CustomUser.objects.create(username="carina")
self.gametype = Gametype.objects.create(name="NewGame", rounds=5, round_duration=60, enabled=True)
self.gamesession = Gamesession.objects.create(user=self.user, gametype=self.gametype, created=datetime.now())
self.gameround_data = {'gamesession': self.gamesession}
self.response = self.client.get('http://localhost:8000/api/gameround',
self.gameround_data,
format="json")
def test_get(self):
self.client = APIClient()
response = self.client.get('http://localhost:8000/api/gameround')
self.assertEqual(response.status_code, 200)
# self.assertEqual(len(self.response.data), len(Gameround.objects.all().order_by('?').first()))
def test_post(self):
self.client = APIClient()
# response = self.client.get('http://localhost:8000/api/gameround')
data = {
'id': 1,
'user': self.user,
'gamesession': self.gamesession,
'created': datetime.now(),
'score': 0,
}
response = self.client.post('http://localhost:8000/api/gameround', data=data, format='json')
self.assertEqual(response.status_code, 201)
I am getting the error: GameroundViewTests::test_post - TypeError: Object of type CustomUser is not JSON serializable
If I change my test_post to:
def test_post(self):
self.client = APIClient()
self.client.get('http://localhost:8000/artigo_api/gameround')
user = {'username': self.user.id}
gamesession = {"gamesession": self.gamesession.id}
data = {
'id': 1,
'user': user,
'gamesession': gamesession,
'created': datetime.now(),
'score': 0,
}
self.assertEqual(Gameround.objects.count(), 0)
response = self.client.post('http://localhost:8000/artigo_api/gameround', data=data, format='json')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(Gameround.objects.count(), 1)
gameround = Gameround.objects.all().first()
for field_name in data.keys():
self.assertEqual(getattr(gameround, field_name), data[field_name])
I am getting the error: GameroundViewTests::test_post - KeyError: 'gamesessions'
What can I do to get rid of this and for the test_post to pass?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
