In pytesting how do I create and delete the database while having assertions inbetween.I tried yield but yield will not work in new versions of pytest

Viewed 38

I could always rollback to an older pytest version but how do I do this with the newest version of pytest?

For a simple explanation

# create database
db.session.add(new_user)
db.session.commit()

# in between code that sometimes has an assertion error.

# delete database
db.session.delete(new_user) # In the try in the except block db.session.rollback()
db.session.commit() 

The problem is the in-between code. I tried a try instead of yield but the try doesn't give an assertion error. Also any alternative ideas is appreciated if someone has a better solution. I also just want to state when I run python -m pytest the code runs except the code with the function yield.

Any help is appreciated.

Here is the code below.

models.py

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    hashed_password = db.Column(db.String(128), nullable=False)
    email = db.Column(db.String(120), unique=True, nullable=False)

    confirmation_email = db.Column(db.Boolean, default=False, nullable=False) 
    reset_email_password = db.Column(db.Boolean, default=False, nullable=False)


    def __init__ (self ,username: str,  email: str, hashed_password: str, confirmation_email=False, reset_email_password=False): 
        self.username = username
        self.email = email
        self.hashed_password = hashed_password 
        self.confirmation_email = confirmation_email 
        self.reset_email_password = reset_email_password



    def create_token(self, expires_sec=1800):
        # Serializer passes in SECRET_KEY 30 min beacuse of expir_sec.
        SECRET_KEY = os.urandom(32)
        s = Serializer (SECRET_KEY, expires_sec) 
        # Creates randomly assigned token as long as less then 30 min   
    
        return s.dumps({'user_id': self.id}).decode('utf-8')
        


    

    @staticmethod
    def verify_token(token):
        # Serializer passes in SECRET_KEY
        SECRET_KEY = os.urandom(32)
        s = Serializer(SECRET_KEY)
        try:
            ''' 
            get user id by running s.loads(token).if this line works  
            If it does not work returns error and return none in the except block
            '''
            user_id = s.loads(token)['user_id']   
        except:
            # flash('That is an invalid or expired token') 
            return None 
        # why query.get? Because  "u = User.query.get(1)" gives the current user.
    return User.query.get(user_id)   

config.py

class Config(object): 
    SECRET_KEY = os.urandom(32)
    SQLALCHEMY_TRACK_MODIFICATIONS = False  
    SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URI') or \
    'sqlite:///' + os.path.join(basedir, 'app.db')
    DEBUG = True
    TESTING = False
    WTF_CSRF_ENABLED = True



class TokenPytestConfig(Config): 

    WTF_CSRF_ENABLED = False
    TESTING = True  

conftest.py

@pytest.fixture()
def new_user():
    plaintext_password = 'pojkp[kjpj[pj'
    hashed_password = bcrypt.hashpw(plaintext_password.encode('utf-8'), bcrypt.gensalt())  
    current_user = User(username='fkpr[kfkuh', hashed_password=hashed_password, email=os.environ['TESTING_EMAIL_USERNAME'],
    confirmation_email=False, reset_email_password=False)
    return current_user



token_app = create_app(TokenPytestConfig)


@pytest.fixture()
def token_client():
    # make_app_run_in_test_env = client
    return token_app.test_client()


@pytest.fixture()
def token_runner():
    return token_app.test_cli_runner()

test_routes.py

token_app = create_app(TokenPytestConfig)
token_app.app_context().push()


   
def test_verified_email(token_client, new_user):   
    ''' 
    GIVEN a Flask application configured for testing
    WHEN the "/verified_email<token>" request is (GET) Also test the token is c
    THEN check that a token works.
    '''   

    response = token_client.get("/verified_email<token>", follow_redirects=True
    assert response.status_code == 200
    with token_app.test_request_context():                   
        # Create the database and the database table
        db.create_all(token_app)
        # Insert user data
        db.session.add(new_user)
        # Commit the changes for the users
        db.session.commit()
        ''' 
        yield freezes till the functions ends. 
        This also allows you to create and delete the database 
        while putting code inbetween
        '''
        yield db.drop_all(new_user)
     
        user = User.query.filter_by(username=new_user.id).first()
        token = user.create_token()
        print(token) 
        assert token == 'ffff' # assert user?
        verify_token = User.verify_token(token)
        print(verify_token)
        assert verify_token == None 

Thanks

0 Answers
Related