简体   繁体   中英

How to test if a class object was created using Pytest

I wrote a habit tracker app and used SQLAlchemy to store the data in an SQLite3 database. Now I'm writing the unit tests using Pytest for all the functions I wrote. Besides functions returning values, there are functions that create entries in the database by creating objects. Here's my object-relational mapper setup and the two main classes:

from sqlalchemy import create_engine, Column, Integer, String, ForeignKey, Date
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# Setting up SQLAlchemy to connect to the local SQLite3 database
Base = declarative_base()
engine = create_engine('sqlite:///:main:', echo=True)
Base.metadata.create_all(bind=engine)
Session = sessionmaker(bind=engine)
session = Session()

class Habit(Base):    
    __tablename__ = 'habit'
    habit_id = Column('habit_id', Integer, primary_key=True)
    name = Column('name', String, unique=True)
    periodicity = Column('periodicity', String)
    start_date = Column('start_date', Date)

class HabitEvent(Base):
    __tablename__ = 'habit_event'
    event_id = Column('event_id', Integer, primary_key=True)
    date = Column('date', Date)
    habit_id = Column('fk_habit_id', Integer, ForeignKey(Habit.habit_id))

One of the creating functions is the following:

def add_habit(name, periodicity):
    if str(periodicity) not in ['d', 'w']:
        print('Wrong periodicity. \nUse d for daily or w for weekly.')
    else:
        h = Habit()
        h.name = str(name)
        if str(periodicity) == 'd':
            h.periodicity = 'Daily'
        if str(periodicity) == 'w':
            h.periodicity = 'Weekly'
        h.start_date = datetime.date.today()
        session.add(h)
        session.commit()
        print('Habit added.')

Here's my question: Since this functions doesn't return a value which can be matched with an expected result, I don't know how to test if the object was created. The same problem occurs to me, when I want to check if all objects were deleted using the following function:

def delete_habit(habitID):    
    id_list = []
    
    id_query = session.query(Habit).all()
    for i in id_query:
        id_list.append(i.habit_id)
        
    if habitID in id_list:
        delete_id = int(habitID)
        session.query(HabitEvent).filter(
                HabitEvent.habit_id == delete_id).delete()
        session.query(Habit).filter(Habit.habit_id == delete_id).delete()
        session.commit()
        print('Habit deleted.')     
    else:
        print('Non existing Habit ID.')

If I understand correctly, you can utilize the get_habits function as part of the test for add_habit.

def test_add_habit():

    name = 'test_add_habit'
    periodicity = 'd'

    add_habit(name, periodicity)

    # not sure of the input or output from get_habits, but possibly:
    results = get_habits(name)
    assert name in results['name']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM