lundi 12 février 2018

Python SQLite3 and jsonpickle testing

I'm trying to test the following methods below in our driver.py. I'm new to Python but I've used some methods provided in the unittest library (assertEqual, assertTrue/False) to test simpler methods from different classes in the recent past.

This is some code we're given and even after reading up on SQLite3 and jsonpickle, I'm still having trouble follow the logic of what's happening and how to trigger the SUCCESS, DB_FAILURE, and FAILURE conditions to write tests.

SUCCESS = 0
DB_FAILURE = 1
FAILURE = 2

def addCompetition(uid, competition):
    """
    :param uid: user ID
    :param competition: competition to add
    """
    user = getUser(uid)
    user.addCompetition(competition)
    db = sqlite3.connect("/Project/data.db")
    cursor = db.cursor()
    compString = jsonpickle.encode(user.competitions)
    sql = 'UPDATE users
       SET competition = %s
       WHERE id = %s' % (compString, uid)
    try:
        cursor.execute(sql)
        db.commit()
        return SUCCESS
    except:
        db.rollback()
        return DB_FAILURE

def removeCompetition(uid, competition):
    """
    :param uid: user ID
    :param competition: competition to remove
    """
    user = getUser(uid)
    if(user.removeCompetition(competition)):
        db = sqlite3.connect("/Project/data.db")
        cursor = db.cursor()
        compString = jsonpickle.encode(user.competitions)
        sql = 'UPDATE users
               SET competition = %s
               WHERE id = %s' % (compString, uid)
        try:
            cursor.execute(sql)
            db.commit()
            return SUCCESS
       except:
            db.rollback()
            return DB_FAILURE
    else:
        return FAILURE

This is what I think is happening: For addCompetition, I think we're grabbing the user's ID, and adding the Competition to it (Competition is a subclass of User). Then we create and connect to data.db, create a cursor for db, and encode all the user's competitions into a JSON by using jsonpickle. Then the cursor tries to execute the SQL with the new competition, returns SUCCESS if it works, and DB_FAILURE if it doesn't.

Similarly, for removeCompetition, if the competition to be removed is successfully removed, then we connect to data.db, create cursor, make all the competitions of the user into a JSON, and try to execute again.

To trigger a SUCCESS for addCompetition, would I simply need to call: self.assertEQUAL(addCompetition(uid, comp1), 0) where comp1 is some valid competition to be added?

Aucun commentaire:

Enregistrer un commentaire