I am doing some test in Django. I use fixtures to pre load some data and test API POST. In my POST, I want to link some data by foreign key. The test behavior is odd. I need to place a for loop in order for it to succeed.
Here's my example for my fixtures:
[
{
"model": "apps.track",
"pk": 1,
"fields": {
"name": "Love Song # 1",
"album": null
}
},
{
"model": "apps.track",
"pk": 2,
"fields": {
"name": "Love Song # 2",
"album": null
}
}
]
Here's my test:
class TestPost(TestCase):
fixtures = ['fixtures/sample']
def setUp(self):
self.album = {
'name': 'Love Songs Album',
'tracks': [
{'id': 1},
{'id': 2}
]
}
def test_post(self):
c = Client()
response = c.post(
'/admin/login/', {'username': 'admin', 'password': 'passwordpassword'})
response = c.post('/apps/albums/',
data=json.dumps(self.album),
content_type='application/json')
album = Album.objects.latest('id')
tracks = Track.objects.filter(album=album).all()
self.assertEqual(tracks[0].id, 1)
self.assertEqual(tracks[1].id, 2)
The test fails and only finds tracks id=2
but not tracks id=1
. However when I add a for loop
before the test assertions, the test succeeds.
Here's the magic for loop
:
for track in tracks:
print("TRACK", track.id)
I want to know if there is any reason behind this.