vendredi 12 juin 2020

Django - testing model with ManyToMany field

I'm just starting out writing tests (yes, I know!!!) for a django app I've been writing (A library). I've got a Title model which has authors as a ManyToMany field (as a book can have more than one author). This works fine in the app - I create a new title, save it, and then I can set the authors using title.authors.set([author]) - a pattern which I have used in several places and works OK (I appreciate you can't set a many to many relationship until the item in question has an id, so it's saved before and after this line.

I'm trying to set this up in a test (this is my first hour or so of trying to do testing with django, so please bear this in mind if I'm doing anything stupid) - and I've got the following to set up the title and author, but I can't find any way of adding the author to the test title:

class TitleModelTests(TestCase):
    def setUp(self):
        Author.objects.create(first_name="Darren", last_name="Jones")
        title_author = Author.objects.get(id=1)
        t1 = Title(title="Book One")
        t1.save()
        t1.authors.set([title_author])
        t1.save()


    def tearDown(self):
        pass

    def test_for_title_creation(self):
        title = Title.objects.get(id=1)
        self.assertEqual(title.media, "pbk")

    def test_for_title_author(self):
        title = Title.objects.get(id=1)
        title_author = Author.objects.get(id=1)
        self.assertEqual(title.authors, title_author)

I can't seem to find any way to set the author/s for the test title - and I've done a fair bit of looking, but can't find anything on this specifically; I'd appreciate a pointer in the right direction.

Aucun commentaire:

Enregistrer un commentaire