コード例 #1
0
ファイル: test_DAOs.py プロジェクト: fnduister/LOG3430
class TestContactDAO(unittest.TestCase):
    def setUp(self):
        self.db_file = 'temp.db'
        self.contactDAO = ContactDAO(self.db_file)
        self.contactDAO.init_db()

        self.contact = Mock(first_name="fabrice",
                            last_name="ndui",
                            phone="4382747208",
                            mail="*****@*****.**",
                            updated=False,
                            updated_date=122323223232,
                            id=1222)
        self.contact1 = Mock(first_name="fabrice1",
                             last_name="ndui1",
                             phone="4382747208",
                             mail="*****@*****.**",
                             updated=False,
                             updated_date=122323223232)

    def tearDown(self):
        os.remove(self.db_file)

    def testContact(self, newContact=None):
        if newContact is not None:
            assert self.contact.first_name == newContact.first_name
            assert self.contact.last_name == newContact.last_name
            assert self.contact.phone == newContact.phone
            assert self.contact.mail == newContact.mail
            assert self.contact.updated == newContact.updated
            assert self.contact.updated_date == newContact.updated_date

    def test_when_init_db_is_called_it_should_create_table(self):
        try:
            with sqlite3.connect(self.db_file) as connection:
                cursor = connection.cursor()
                cursor.execute('SELECT * FROM contact')
        except sqlite3.OperationalError:
            self.fail("Should not have raised sqlite3.OperationalError")

    def test_when_add_is_called_it_should_return_an_autoincremented_id(self):
        assert self.contactDAO.add(self.contact) == 1, "should be 1"
        assert self.contactDAO.add(self.contact) == 2, "should be 1"
        assert self.contactDAO.add(self.contact1) == 3, "should be 3"

    def test_get_by_id_after_add_should_return_inserted_value(self):
        idContact = self.contactDAO.add(self.contact)
        newContact = self.contactDAO.get_by_id(idContact)
        self.testContact(newContact)

    def test_get_by_names_after_add_should_return_inserted_value(self):
        self.contactDAO.add(self.contact)
        newContact = self.contactDAO.get_by_names(self.contact.first_name,
                                                  self.contact.last_name)
        self.testContact(newContact)

    def test_get_by_id_with_undefined_rowid_should_return_None(self):
        self.contactDAO.add(self.contact)
        newContact = self.contactDAO.get_by_id(2)
        assert newContact == None

    def test_get_by_names_with_notexisted_contact_should_return_None(self):
        newContact = self.contactDAO.get_by_names("elie", "Rouphael")
        assert newContact == None

    def test_deactivate_contact_then_get_it_with_id_should_be_not_updated(
            self):
        id = self.contactDAO.add(self.contact)
        self.contactDAO.deactivate(id)
        self.contact.first_name = "test"
        self.contactDAO.update(self.contact)
        newContact = self.contactDAO.get_by_id(id)
        self.contact.first_name = "fabrice"
        self.testContact(self.contact)

    def test_deactivate_contact_on_undefined_id_should_return_zero(self):
        returnedvalue = self.contactDAO.deactivate(2)
        assert returnedvalue == 0

    def test_after_deleting_contact_by_id_get_it_with_id_should_return_None(
            self):
        id = self.contactDAO.add(self.contact)
        self.contactDAO.delete_by_id(id)
        newContact = self.contactDAO.get_by_id(id)
        assert newContact == None

    def test_deleting_undefined_id_should_return_zero(self):
        id = self.contactDAO.delete_by_id(1)
        assert id == 0

    def test_after_deleting_contact_by_names_get_item_with_id_should_return_None(
            self):
        id_returned = self.contactDAO.add(self.contact)
        self.contactDAO.delete_by_names("fabrice", "ndui")
        newContact = self.contactDAO.get_by_id(id_returned)
        assert newContact is None

    def test_deleting_not_existed_contact_should_return_zero(self):
        returnedValue = self.contactDAO.delete_by_names("fabrice", "ndui")
        assert returnedValue == 0


##################################################################

    def test_update_contact_should_set_the_provided_values(self):
        self.contactDAO.add(self.contact)
        self.contact.name = "barbara"
        indexModified = self.contactDAO.update(self.contact)
        updatedContact = self.contactDAO.get_by_id(self.contact.id)
        self.testContact(updatedContact)

    def test_update_contact_should_return_zero_if_id_does_not_exist(self):
        assert self.contactDAO.update(self.contact) == 0, "should return 0"

    def test_list_contacts_with_no_contacts_added_returns_empty_list(self):
        assert len(self.contactDAO.list(True)) == 0, "should return 0"
        assert len(self.contactDAO.list(False)) == 0, "should return 0"
        assert len(self.contactDAO.list()) == 0, "should return 0"

    def test_list_contacts_with_one_contact_should_return_list_with_contact(
            self):
        idContact = self.contactDAO.add(self.contact)
        contacts = self.contactDAO.list()
        assert len(contacts) == 1, "should return 1"
        self.testContact(contacts[0])

    def test_list_contacts_with_updated_False_and_all_items_updated_should_return_empty_list(
            self):
        self.contact.name = "barbara"
        self.contact.updated = True
        self.contactDAO.add(self.contact)
        assert len(self.contactDAO.list(False)) == 0, "should return 0"

    def test_list_contacts_with_updated_True_and_all_items_not_updated_should_return_empty_list(
            self):
        self.contactDAO.add(self.contact)
        assert len(self.contactDAO.list(True)) == 0, "should return 0"

    def test_list_contacts_with_all_not_updated_items_and_updated_False_should_return_all_contacts(
            self):
        self.contactDAO.add(self.contact)
        contacts = self.contactDAO.list(False)
        assert len(contacts) == 1, "should return 1"
        self.testContact(contacts[0])

    def test_list_contacts_with_all_updated_items_and_updated_True_should_return_all_contacts(
            self):
        self.contact.name = "barbara"
        self.contact.updated = True
        self.contactDAO.add(self.contact)
        contacts = self.contactDAO.list(True)
        assert len(contacts) == 1, "should return 1"
        self.testContact(contacts[0])
コード例 #2
0
class TestContactDAO(unittest.TestCase):
    def setUp(self):
        self.db_file = 'temp.db'
        self.contactDAO = ContactDAO(self.db_file)
        self.contactDAO.init_db()
        self.contact1 = Contact(6, "R", "Z", "514999666", "*****@*****.**",
                                True, 20.3)
        self.contact2 = Contact(50, "H", "P", "514999666", "*****@*****.**",
                                False, 20.3)

    def tearDown(self):
        os.remove(self.db_file)

    # fonction pour rapidement imprimer les informations d'un contact sur la console
    def printContact(self, contactToPrint):
        if contactToPrint is None:
            print("Contact is None. Cannot print")
        else:
            print(contactToPrint.first_name)
            print(contactToPrint.last_name)
            print(contactToPrint.phone)
            print(contactToPrint.mail)
            print(contactToPrint.updated)
            print(contactToPrint.updated_date)
            print(contactToPrint)

    # fonction pour rapidement comparer 2 contacts
    def areContactAttribsEqual(self, contact1=None, contact2=None):
        if contact1 is None:
            print("First contact is None (see first parameter)")
            return
        if contact2 is None:
            print("Second contact is None (see second parameter)")
            return
        self.assertEqual(
            contact1.first_name, contact2.first_name,
            "{0} not equal to {1}".format(self.contact1.first_name,
                                          self.contact2.first_name))
        self.assertEqual(
            contact1.last_name, contact2.last_name,
            "{0} not equal to {1}".format(self.contact1.last_name,
                                          self.contact2.last_name))
        self.assertEqual(
            contact1.phone, contact2.phone,
            "{0} not equal to {1}".format(self.contact1.phone,
                                          self.contact2.phone))
        self.assertEqual(
            contact1.mail, contact2.mail,
            "{0} not equal to {1}".format(self.contact1.mail,
                                          self.contact2.mail))
        self.assertEqual(
            contact1.updated, contact2.updated,
            "{0} not equal to {1}".format(self.contact1.updated,
                                          self.contact2.updated))
        self.assertEqual(
            contact1.updated_date, contact2.updated_date,
            "{0} not equal to {1}".format(self.contact1.updated_date,
                                          self.contact2.updated_date))

    def test_when_init_db_is_called_it_should_create_table(self):
        try:
            with sqlite3.connect(self.db_file) as connection:
                cursor = connection.cursor()
                cursor.execute('SELECT * FROM contact')
        except sqlite3.OperationalError:
            self.fail("Should not have raised sqlite3.OperationalError")

    # On vérifie que le nombre d'appel concorde avec la valeur de lastrowid
    def test_when_add_is_called_it_should_return_an_autoincremented_id(self):
        assert self.contactDAO.add(self.contact1) == 1, "should be 1"
        assert self.contactDAO.add(self.contact1) == 2, "should be 2"
        self.contactDAO.add(self.contact1)
        assert self.contactDAO.add(self.contact1) == 4, "should be 4"

    # On vérifie que contact1 à bel et bien été ajouté en effectuant get_by_id
    def test_get_by_id_after_add_should_return_inserted_value(self):
        self.contactDAO.add(self.contact1)
        newContact = self.contactDAO.get_by_id(1)
        self.areContactAttribsEqual(newContact, self.contact1)

    # On vérifie que le contact retourné par get_by_names retourne contact1
    def test_get_by_names_after_add_should_return_inserted_value(self):
        self.contactDAO.add(self.contact1)
        newContact = self.contactDAO.get_by_names(self.contact1.first_name,
                                                  self.contact1.last_name)
        self.areContactAttribsEqual(newContact, self.contact1)

    # On vérifie que get_by_id retourne none pour un id inexistant
    def test_get_by_id_with_undefined_rowid_should_return_None(self):
        self.contactDAO.add(self.contact1)
        newContact = self.contactDAO.get_by_id(2)
        self.assertIsNone(newContact)

    # On vérifie que get_by_names retourne none pour un contact absent de la BD
    def test_get_by_names_with_notexisted_contact_should_return_None(self):
        self.contactDAO.add(self.contact1)
        newContact = self.contactDAO.get_by_names(self.contact2.first_name,
                                                  self.contact2.last_name)
        self.assertIsNone(newContact)

    # On vérifie que Contact.updated est assigne a False suite a l'appel de deactivate sur un contact avec updated = True dans la BD
    def test_deactivate_contact_then_get_it_with_id_should_be_not_updated(
            self):
        self.contactDAO.add(self.contact1)
        self.contactDAO.deactivate(1)
        res = self.contactDAO.get_by_id(1)
        self.assertFalse(res.updated)

    # On vérifie que la valeur de retoure de deactivate sur id inexistant est 0
    def test_deactivate_contact_on_undefined_id_should_return_zero(self):
        res = self.contactDAO.deactivate(1)
        self.assertEqual(res, 0, "deactivate did not return 0 on invalid id")

    # On vérifie que get_by_id retourne none suite à une suppression avec delete_by_id pour le même id
    def test_after_deleting_contact_by_id_get_it_with_id_should_return_None(
            self):
        contactToDelete = Contact(3, "Bob", "Kump", "514-554-223",
                                  "*****@*****.**", True, 22.9)
        self.contactDAO.add(contactToDelete)
        self.contactDAO.delete_by_id(1)
        res = self.contactDAO.get_by_id(1)
        self.assertIsNone(
            res, "getting a deleted contact by id does not return None")

    # On vérifie que delete_by_id retourne 0 pour un id inexistant
    def test_deleting_undefined_id_should_return_zero(self):
        res = self.contactDAO.delete_by_id(1)
        self.assertEqual(res, 0, "undefined id deletion does not return 0")

    # On vérifie que get_by_names retourne none pour un contact supprimé par delete_by_names
    def test_after_deleting_contact_by_names_get_item_with_id_should_return_None(
            self):
        contactToDelete = Contact(3, "Bob", "Kump", "514-554-223",
                                  "*****@*****.**", True, 22.9)
        self.contactDAO.add(contactToDelete)
        self.contactDAO.delete_by_names("Bob", "Kump")
        res = self.contactDAO.get_by_id(1)
        self.assertIsNone(
            res,
            "getting by id a deleted contact by name does not return None")

    # On vérifie que delete_by_id et delete_by_names retourne 0 sur un contact inexistant
    def test_deleting_not_existed_contact_should_return_zero(self):
        res = self.contactDAO.delete_by_names("Bob", "Kump")
        self.assertEqual(
            res, 0, "deleting non existant contact by name does not return 0")
        res = self.contactDAO.delete_by_id(1)
        self.assertEqual(
            res, 0, "deleting non existant contact by id does not return 0")

    # On vérifie que contactToUpdate est écrasé par contactToCopy suite à un appel à update avec contactToCopy en paramètre
    def test_update_contact_should_set_the_provided_values(self):
        contactToUpdate = Contact(3, "Bob", "Kump", "514-554-223",
                                  "*****@*****.**", True, 22.9)
        contactToCopy = Contact(1, "John", "Dough", "450-221-998",
                                "*****@*****.**", False, 40.8)
        self.contactDAO.add(contactToUpdate)
        self.contactDAO.update(contactToCopy)
        res = self.contactDAO.get_by_names("John", "Dough")
        self.areContactAttribsEqual(contactToCopy, res)

    # On vérifie que update retourne 0 sur un contact inexistant
    def test_update_contact_should_return_zero_if_id_does_not_exist(self):
        contactToUpdate = Contact(3, "Bob", "Kump", "514-554-223",
                                  "*****@*****.**", True, 22.9)
        res = self.contactDAO.update(contactToUpdate)
        self.assertEqual(
            res, 0, "updating a non existant contact id does not return 0")

    # On vérifie que la liste retournée par list a une longueur de 0 pour une BD vide
    def test_list_contacts_with_no_contacts_added_returns_empty_list(self):
        res = self.contactDAO.list()
        self.assertEqual(
            len(res), 0,
            "list does not return an empty list on empty database")

    # On vérifie que la liste retournée par list est de longueur 1 et contient un seul contact (contactToAdd)
    def test_list_contacts_with_one_contact_should_return_list_with_contact(
            self):
        contactToAdd = Contact(3, "Bob", "Kump", "514-554-223",
                               "*****@*****.**", True, 22.9)
        self.contactDAO.add(contactToAdd)
        res = self.contactDAO.list()
        self.assertEqual(
            len(res), 1,
            "list does not return a list of count = 1 when only 1 contact is in database"
        )
        self.areContactAttribsEqual(contactToAdd, res[0])

    # On vérifie que la liste retournée par list est vide si False lui est passé en paramètre et que tous les contacts ont updated = True
    def test_list_contacts_with_updated_False_and_all_items_updated_should_return_empty_list(
            self):
        contactToAdd = Contact(3, "Bob", "Kump", "514-554-223",
                               "*****@*****.**", True, 22.9)
        self.contactDAO.add(contactToAdd)
        res = self.contactDAO.list(False)
        self.assertEqual(
            len(res), 0,
            "list does not return an empty list when all contacts are updated and list was called with update = False"
        )

    # On vérifie que la liste retournée par list est vide si True lui est passé en paramètre et que tous les contacts ont updated = False
    def test_list_contacts_with_updated_True_and_all_items_not_updated_should_return_empty_list(
            self):
        contactToAdd = Contact(3, "Bob", "Kump", "514-554-223",
                               "*****@*****.**", False, 22.9)
        self.contactDAO.add(contactToAdd)
        res = self.contactDAO.list(True)
        self.assertEqual(
            len(res), 0,
            "list does not return an empty list when all contacts are not updated and list was called with updated = True"
        )

    # On vérifie que la liste retournée par list avec False en paramètre contient tous les contacts de la BD ayant updated = False
    def test_list_contacts_with_all_not_updated_items_and_updated_False_should_return_all_contacts(
            self):
        contactToAdd = Contact(3, "Bob", "Kump", "514-554-223",
                               "*****@*****.**", False, 22.9)
        self.contactDAO.add(contactToAdd)
        res = self.contactDAO.list(False)
        self.assertEqual(
            len(res), 1,
            "list does not return all updated contacts when list was called with updated = False"
        )

    # On vérifie que la liste retournée par list avec True en paramètre contient tous les contacts de la BD ayant updated = True
    def test_list_contacts_with_all_updated_items_and_updated_True_should_return_all_contacts(
            self):
        contactToAdd = Contact(3, "Bob", "Kump", "514-554-223",
                               "*****@*****.**", True, 22.9)
        self.contactDAO.add(contactToAdd)
        res = self.contactDAO.list(True)
        self.assertEqual(
            len(res), 1,
            "list does not return all updated contacts when list was called with updated = True"
        )
コード例 #3
0
ファイル: test_DAOs.py プロジェクト: jmetais2017/LOG3430_TP
class TestContactDAO(unittest.TestCase):
    def setUp(self):
        self.db_file = 'temp.db'
        self.contactDAO = ContactDAO(self.db_file)
        self.contactDAO.init_db()

    def tearDown(self):
        os.remove(self.db_file)

    def test_when_init_db_is_called_it_should_create_table(self):
        try:
            with sqlite3.connect(self.db_file) as connection:
                cursor = connection.cursor()
                cursor.execute('SELECT * FROM contact')
        except sqlite3.OperationalError:
            self.fail("Should not have raised sqlite3.OperationalError")

    def test_when_add_is_called_it_should_return_an_autoincremented_id(self):

        #On teste diverses valeurs de l'id à créer
        for i in range(1, 10):
            #On crée le i-ème contact à ajouter
            contact = Contact(0, "Name" + str(i), "lastName" + str(i), 111 + i,
                              "mail" + str(i), True, "date")
            #On vérifie que le i-ème contact est ajouté avec un id égal à i
            self.assertEqual(self.contactDAO.add(contact), i)

    def test_get_by_id_after_add_should_return_inserted_value(self):

        #On crée un contact à ajouter
        contact = Contact(0, "Name", "lastName", 111, "mail", True, "date")
        #On ajoute ce contact au DAO, puis on récupère son id
        id = self.contactDAO.add(contact)

        #On va chercher dans le DAO le contact ayant l'id obtenu ci-dessus, et on vérifie champ par champ qu'il est égal à notre contact initial
        self.assertEqual(self.contactDAO.get_by_id(id).first_name, "Name")
        self.assertEqual(self.contactDAO.get_by_id(id).last_name, "lastName")
        self.assertEqual(self.contactDAO.get_by_id(id).phone, '111')
        self.assertEqual(self.contactDAO.get_by_id(id).mail, "mail")
        self.assertTrue(self.contactDAO.get_by_id(id).updated)
        self.assertEqual(self.contactDAO.get_by_id(id).updated_date, "date")

    def test_get_by_names_after_add_should_return_inserted_value(self):

        #On crée un contact à ajouter
        contact = Contact(0, "Name", "lastName", 111, "mail", True, "date")
        #On ajoute ce contact au DAO
        id = self.contactDAO.add(contact)

        #On va chercher dans le DAO le contact ayant les noms donnés ci-dessus, et on vérifie champ par champ qu'il est égal à notre contact initial
        self.assertEqual(
            self.contactDAO.get_by_names("Name", "lastName").id, id)
        self.assertEqual(
            self.contactDAO.get_by_names("Name", "lastName").first_name,
            "Name")
        self.assertEqual(
            self.contactDAO.get_by_names("Name", "lastName").last_name,
            "lastName")
        self.assertEqual(
            self.contactDAO.get_by_names("Name", "lastName").phone, '111')
        self.assertEqual(
            self.contactDAO.get_by_names("Name", "lastName").mail, "mail")
        self.assertTrue(
            self.contactDAO.get_by_names("Name", "lastName").updated)
        self.assertEqual(
            self.contactDAO.get_by_names("Name", "lastName").updated_date,
            "date")

    def test_get_by_id_with_undefined_rowid_should_return_None(self):

        #On tente de récupérer un contact sans en avoir ajouté au préalable
        self.assertEqual(self.contactDAO.get_by_id(1), None)

    def test_get_by_names_with_notexisted_contact_should_return_None(self):

        contact = Contact(0, "Denis", "Richard", 111, "mail", True, "date")
        id = self.contactDAO.add(contact)

        #On tente de récupérer un contact ne figurant pas dans le DAO
        self.assertEqual(self.contactDAO.get_by_names("Pierre", "Richard"),
                         None)

    def test_deactivate_contact_then_get_it_with_id_should_be_not_updated(
            self):

        #On crée un contact pour les besoins du test, puis on l'ajoute
        contact = Contact(0, "Pierre", "Richard", 111, "mail", True, "date")
        id = self.contactDAO.add(contact)

        #On désactive ce contact
        self.contactDAO.deactivate(id)
        #On tente de récupérer ce contact, puis on vérifie qu'il n'a pas été updated
        self.assertFalse(self.contactDAO.get_by_id(id).updated)

    def test_deactivate_contact_on_undefined_id_should_return_zero(self):

        #On tente de désactiver un contact sans en avoir ajouté au préalable
        self.assertEqual(self.contactDAO.deactivate(1), 0)

    def test_after_deleting_contact_by_id_get_it_with_id_should_return_None(
            self):

        #On crée un contact pour les besoins du test, puis on l'ajoute
        contact = Contact(0, "Pierre", "Richard", 111, "mail", True, "date")
        id = self.contactDAO.add(contact)

        #On supprime ce contact
        self.contactDAO.delete_by_id(id)
        #On tente de récupérer ce contact par son id
        self.assertEqual(self.contactDAO.get_by_id(id), None)

    def test_deleting_undefined_id_should_return_zero(self):

        #On tente de supprimer un contact sans en avoir ajouté au préalable
        self.assertEqual(self.contactDAO.delete_by_id(1), 0)

    #Seul test qui ne passait pas initialement
    def test_after_deleting_contact_by_names_get_item_with_id_should_return_None(
            self):

        #On crée un contact pour les besoins du test, puis on l'ajoute
        contact = Contact(0, "Pierre", "Richard", 111, "mail", True, "date")
        id = self.contactDAO.add(contact)

        #On supprime ce contact
        self.contactDAO.delete_by_names("Pierre", "Richard")
        #On tente de récupérer ce contact par son id
        self.assertEqual(self.contactDAO.get_by_id(id), None)

    def test_deleting_not_existed_contact_should_return_zero(self):

        contact = Contact(0, "Denis", "Richard", 111, "mail", True, "date")
        id = self.contactDAO.add(contact)

        #On tente de supprimer un contact ne figurant pas dans le DAO
        self.assertEqual(self.contactDAO.delete_by_names("Pierre", "Richard"),
                         0)
        self.assertEqual(self.contactDAO.delete_by_id(15), 0)

    def test_update_contact_should_set_the_provided_values(self):

        #On crée un contact pour les besoins du test, puis on l'ajoute
        contact = Contact(0, "Pierre", "Richard", 111, "mail", True, "date")
        id = self.contactDAO.add(contact)

        #On définit les valeurs pour la modification
        contact = Contact(id, "Jean", "Martin", 222, "mail2", True, "date2")
        #On met à jour le contact initial
        count = self.contactDAO.update(contact)

        #On récupère le contact modifié, puis on vérifie qu'il contient les nouvelles valeurs
        self.assertEqual(self.contactDAO.get_by_id(id).first_name, "Jean")
        self.assertEqual(self.contactDAO.get_by_id(id).last_name, "Martin")
        self.assertEqual(self.contactDAO.get_by_id(id).phone, '222')
        self.assertEqual(self.contactDAO.get_by_id(id).mail, "mail2")
        self.assertTrue(self.contactDAO.get_by_id(id).updated)
        self.assertEqual(self.contactDAO.get_by_id(id).updated_date, "date2")

    def test_update_contact_should_return_zero_if_id_does_not_exist(self):

        #On définit les valeurs pour la modification
        contact1 = Contact(1, "Jean", "Martin", 222, "mail2", True, "date2")
        contact2 = Contact(10, "Jean", "Martin", 222, "mail2", True, "date2")
        contact3 = Contact(24, "Jean", "Martin", 222, "mail2", True, "date2")

        #On tente de mettre à jour les contacts aux id spécifiés
        self.assertEqual(self.contactDAO.update(contact1), 0)
        self.assertEqual(self.contactDAO.update(contact2), 0)
        self.assertEqual(self.contactDAO.update(contact3), 0)

    def test_list_contacts_with_no_contacts_added_returns_empty_list(self):

        #On liste les contacts sans en avoir ajouté au préalable
        #On teste toutes les valeurs possibles pour l'argument "updated"
        self.assertEqual(self.contactDAO.list(), [])
        self.assertEqual(self.contactDAO.list(True), [])
        self.assertEqual(self.contactDAO.list(False), [])

    def test_list_contacts_with_one_contact_should_return_list_with_contact(
            self):

        #On crée un contact pour les besoins du test, puis on l'ajoute
        contact = Contact(0, "Pierre", "Richard", 111, "mail", True, "date")
        id = self.contactDAO.add(contact)

        #On vérifie qu'on obtient une liste de longueur 1 contenant ce contact
        self.assertEqual(len(self.contactDAO.list()), 1)
        self.assertEqual(self.contactDAO.list()[0].first_name, "Pierre")
        self.assertEqual(self.contactDAO.list()[0].last_name, "Richard")
        self.assertEqual(self.contactDAO.list()[0].phone, '111')
        self.assertEqual(self.contactDAO.list()[0].mail, "mail")
        self.assertTrue(self.contactDAO.list()[0].updated)
        self.assertEqual(self.contactDAO.list()[0].updated_date, "date")

    def test_list_contacts_with_updated_False_and_all_items_updated_should_return_empty_list(
            self):

        #On ajoute plusieurs contacts, tous avec updated = True
        for i in range(1, 10):
            contact = Contact(0, "Name" + str(i), "lastName" + str(i), 111 + i,
                              "mail" + str(i), True, "date")
            id = self.contactDAO.add(contact)

        #On vérifie que l'on ne liste aucun contact en passant False en argument
        self.assertEqual(self.contactDAO.list(False), [])

    def test_list_contacts_with_updated_True_and_all_items_not_updated_should_return_empty_list(
            self):

        #On ajoute plusieurs contacts, tous avec updated = False
        for i in range(1, 10):
            contact = Contact(0, "Name" + str(i), "lastName" + str(i), 111 + i,
                              "mail" + str(i), False, "date")
            id = self.contactDAO.add(contact)

        #On vérifie que l'on ne liste aucun contact en passant True en argument
        self.assertEqual(self.contactDAO.list(True), [])

    def test_list_contacts_with_all_not_updated_items_and_updated_False_should_return_all_contacts(
            self):

        #On ajoute 9 contacts, tous avec updated = False
        for i in range(1, 10):
            contact = Contact(0, "Name" + str(i), "lastName" + str(i), 111 + i,
                              "mail" + str(i), False, "date")
            id = self.contactDAO.add(contact)

        #On vérifie qu'on obtient une liste de longueur 9
        self.assertEqual(len(self.contactDAO.list(False)), 9)

    def test_list_contacts_with_all_updated_items_and_updated_True_should_return_all_contacts(
            self):

        #On ajoute 9 contacts, tous avec updated = True
        for i in range(1, 10):
            contact = Contact(0, "Name" + str(i), "lastName" + str(i), 111 + i,
                              "mail" + str(i), True, "date")
            id = self.contactDAO.add(contact)

        #On vérifie qu'on obtient une liste de longueur 9
        self.assertEqual(len(self.contactDAO.list(True)), 9)
コード例 #4
0
class TestContactDAO(unittest.TestCase):
    def setUp(self):
        self.db_file = 'temp.db'
        self.contactDAO = ContactDAO(self.db_file)
        self.contactDAO.init_db()

    def tearDown(self):
        os.remove(self.db_file)

    def isSameContact(self, contact1, contact2):
        return (contact1.id == contact2.id
                and contact1.first_name == contact2.first_name
                and contact1.last_name == contact2.last_name
                and contact1.phone == contact2.phone
                and contact1.mail == contact2.mail
                and contact1.updated == contact2.updated
                and contact1.updated_date == contact2.updated_date)

    def test_when_init_db_is_called_it_should_create_table(self):
        try:
            with sqlite3.connect(self.db_file) as connection:
                cursor = connection.cursor()
                cursor.execute('SELECT * FROM contact')
        except sqlite3.OperationalError:
            self.fail("Should not have raised sqlite3.OperationalError")

    def test_when_add_is_called_it_should_return_an_autoincremented_id(self):
        firstId = None
        contact1 = Contact(firstId, "testFirstName1", "testLastName1", "911",
                           "testMail1", True, "testTime1")
        firstId = self.contactDAO.add(contact1)

        SecondId = None
        contact2 = Contact(SecondId, "testFirstName2", "testLastName2", "911",
                           "testMail2", True, "testTime2")
        SecondId = self.contactDAO.add(contact2)

        self.assertTrue(SecondId == firstId + 1)

    def test_get_by_id_after_add_should_return_inserted_value(self):
        contact = Contact(None, "testFirstName", "testLastName", "911",
                          "testMail", True, "testTime")
        contact.id = self.contactDAO.add(contact)

        contactReturned = self.contactDAO.get_by_id(id=contact.id)

        self.assertTrue(self.isSameContact(contact, contactReturned))

    def test_get_by_names_after_add_should_return_inserted_value(self):
        contact = Contact(None, "testFirstName", "testLastName", "911",
                          "testMail", True, "testTime")
        contact.id = self.contactDAO.add(contact)

        contactReturned = self.contactDAO.get_by_names(
            first_name=contact.first_name, last_name=contact.last_name)

        self.assertTrue(self.isSameContact(contact, contactReturned))

    def test_get_by_id_with_undefined_rowid_should_return_None(self):
        self.assertTrue(self.contactDAO.get_by_id(None) == None)

    def test_get_by_names_with_notexisted_contact_should_return_None(self):
        self.assertTrue(self.contactDAO.get_by_names("", "") == None)

    def test_deactivate_contact_then_get_it_with_id_should_be_not_updated(
            self):
        contact = Contact(None, "testFirstName", "testLastName", "911",
                          "testMail", True, "testTime")
        contact.id = self.contactDAO.add(contact)
        self.contactDAO.deactivate(contact.id)
        self.assertTrue(not self.contactDAO.get_by_id(contact.id).updated)

    def test_deactivate_contact_on_undefined_id_should_return_zero(self):
        self.assertTrue(self.contactDAO.deactivate(None) == 0)

    def test_after_deleting_contact_by_id_get_it_with_id_should_return_None(
            self):
        contact = Contact(None, "testFirstName", "testLastName", "911",
                          "testMail", True, "testTime")
        contact.id = self.contactDAO.add(contact)
        self.contactDAO.delete_by_id(contact.id)
        self.assertTrue(self.contactDAO.get_by_id(contact.id) == None)

    def test_deleting_undefined_id_should_return_zero(self):
        self.assertTrue(self.contactDAO.delete_by_id(None) == 0)

    def test_after_deleting_contact_by_id_get_item_with_id_should_return_None(
            self):
        # FX: tested two times?
        contact = Contact(None, "testFirstName", "testLastName", "911",
                          "testMail", True, "testTime")
        contact.id = self.contactDAO.add(contact)
        self.contactDAO.delete_by_id(contact.id)
        self.assertTrue(self.contactDAO.get_by_id(contact.id) == None)

    def test_deleting_not_existed_contact_should_return_zero(self):
        self.assertTrue(self.contactDAO.delete_by_id(0) == 0)
        self.assertTrue(self.contactDAO.delete_by_names("", "") == 0)

    def test_update_contact_should_set_the_provided_values(self):
        contact = Contact(None, "testFirstName", "testLastName", "911",
                          "testMail", True, "testTime")
        contact.id = self.contactDAO.add(contact)

        newFirstName = "newFirstName"
        newLastName = "newLastName"
        newNumber = "newNumber"
        newMail = "newMail"

        contact.first_name = newFirstName
        contact.last_name = newLastName
        contact.phone = newNumber
        contact.mail = newMail

        self.contactDAO.update(contact)

        updatedContact = self.contactDAO.get_by_id(contact.id)

        self.assertTrue(self.isSameContact(contact, updatedContact))

    def test_update_contact_should_return_zero_if_id_does_not_exist(self):
        contact = Contact(None, "testName", "testName", "514", "testMail",
                          True, "testTime")
        self.assertTrue(self.contactDAO.update(contact) == 0)

    def test_list_contacts_with_no_contacts_added_returns_empty_list(self):
        self.assertTrue(self.contactDAO.list(None) == [])

    def test_list_contacts_with_one_contact_should_return_list_with_contact(
            self):
        contact = Contact(None, "testFirstName", "testLastName", "911",
                          "testMail", True, "testTime")
        contact.id = self.contactDAO.add(contact)

        contactList = self.contactDAO.list(True)

        self.assertTrue(
            len(contactList) == 1
            and self.isSameContact(contact, contactList[0]))

    def test_list_contacts_with_updated_False_and_all_items_updated_should_return_empty_list(
            self):
        contact = Contact(None, "testFirstName", "testLastName", "911",
                          "testMail", True, "testTime")
        contact.id = self.contactDAO.add(contact)
        contactList = self.contactDAO.list(False)
        self.assertTrue(len(contactList) == 0)

    def test_list_contacts_with_updated_True_and_all_items_not_updated_should_return_empty_list(
            self):
        contact = Contact(None, "testFirstName", "testLastName", "911",
                          "testMail", False, "testTime")
        contact.id = self.contactDAO.add(contact)
        contactList = self.contactDAO.list(True)
        self.assertTrue(len(contactList) == 0)

    def test_list_contacts_with_all_not_updated_items_and_updated_False_should_return_all_contacts(
            self):
        contact1 = Contact(None, "testFirstName1", "testLastName1", "testNum1",
                           "testMail1", False, "testTime1")
        contact1.id = self.contactDAO.add(contact1)
        contact2 = Contact(None, "testFirstName2", "testLastName2", "testNum2",
                           "testMail2", False, "testTime2")
        contact2.id = self.contactDAO.add(contact2)

        contactList = self.contactDAO.list(False)
        self.assertTrue(
            len(contactList) == 2
            and self.isSameContact(contact1, contactList[0])
            and self.isSameContact(contact2, contactList[1]))

    def test_list_contacts_with_all_updated_items_and_updated_True_should_return_all_contacts(
            self):
        contact1 = Contact(None, "testFirstName1", "testLastName1", "testNum1",
                           "testMail1", True, "testTime1")
        contact1.id = self.contactDAO.add(contact1)
        contact2 = Contact(None, "testFirstName2", "testLastName2", "testNum2",
                           "testMail2", True, "testTime2")
        contact2.id = self.contactDAO.add(contact2)

        contactList = self.contactDAO.list(True)
        self.assertTrue(
            len(contactList) == 2
            and self.isSameContact(contact1, contactList[0])
            and self.isSameContact(contact2, contactList[1]))