Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to stop Pytest from executing the non test python file?

I have written a Python script that connects to a SQLite3 database and creates a table. I’ve created another python file to perform some testing using Pytest. For some reason, whenever I run the test file, the code in the main file seems to get executed too and a table is created. I assume Pytest will only execute python files with the word test in the beginning or the end of the file name. Not sure what’s happening here.

My py1.py file

import sqlite3


# Create sqlite3 table
def create_table(table_name):
    try:
        print('Creating table in db')
        conn = sqlite3.connect('lite.db')
        cur = conn.cursor()
        cur.execute("CREATE TABLE IF NOT EXISTS " + table_name + " (Id INTEGER)")
        conn.commit()
        conn.close()
        print('Table successfully created')
    except Exception as e:
        print(e)

db_table_name = 'my_temp_table'

create_table(db_table_name)

If I run this file, an empty table called my_temp_table is created as expected.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Now I dropped the my_temp_table table and tried running the below test_py1.py file using Pytest:

from py1 import create_table

def test_function():
    assert true

The expected behaviour is for it to say 1 test passed, which it does, but along with that it’s also creating a table called my_temp_table, which indicates the py1.py is also being run by Pytest. I’m not sure what is triggering this.

>Solution :

Adding this at the end of your py1.py file should solve the problem.

if __name__ == '__main__':
    db_table_name = 'my_temp_table'
    create_table(db_table_name)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading