Pyramid/ Sqlalchemy - IntegrityError during tests

109 views Asked by At

I am doing pytest on a basic data insertion method in a table 'search', which is connected to table 'user' using foreign key. I have also created test data in the json format.I have created a fixture for setting up for database for testing named conftest.py.

The code is crashing before getting to the function which adds the searches to database

conftest.py

@pytest.fixture
def dbsession(app, tm):
    #a sqlalchemy.orm.session.Session object connected to the database.
    #The session is scoped to the tm fixture. Any changes made will be aborted at the end of the test.
    session_factory = app.registry['dbsession_factory']
    return models.get_tm_session(session_factory, tm)

@pytest.fixture
def setup_db(dbsession):
    here = os.getcwd()
    with open(f'{here}/tests/data/test_data.json') as j_data:
        json_data = json.loads(j_data.read())
        for s in json_data["searches"]:
            s["created_at"] = datetime.strptime(s["created_at"], "%Y-%m-%d %H:%M:%S")
            s["updated_at"] = datetime.strptime(s["updated_at"], "%Y-%m-%d %H:%M:%S")
            search = Search(**s)
            dbsession.add(search)

        
        for u in json_data["users"]:
            u["created_at"] = datetime.strptime(u["created_at"], "%Y-%m-%d %H:%M:%S")
            u["updated_at"] = datetime.strptime(u["updated_at"], "%Y-%m-%d %H:%M:%S")
            user = User(**u)
            dbsession.add(user)
            
    dbsession.flush()
    return None

test-data.json

{
    "searches":[
      {    
        "query_text": "This is an amazing text",
        "id_type_query": 1,
        "number_of_results": 40,
        "created_at": "2022-08-29 15:01:10",
        "updated_at": "2022-08-29 15:01:10",
        "id_user" : 1
      },
      {
        "query_text": "This is an amazing text 2222",
        "id_type_query": 1,
        "number_of_results": 70,
        "created_at": "2022-08-29 15:01:10",
        "updated_at": "2022-08-29 15:01:10",
        "id_user" : 2
      }
    ],
    "users":[
        {
          "username": "vivek",
          "created_at": "2022-08-29 15:01:10",
          "updated_at": "2022-08-29 16:01:10"
        },
        {  
          "username": "oliver",
          "created_at": "2022-08-29 15:01:10",
          "updated_at": "2022-08-29 16:01:10"
        }
      ]
}

Despite the user "vivek" is present in the json data for testing, the test doesn't find it and gives the below error.

ERROR : sqlalchemy.exc.IntegrityError: (psycopg2.errors.ForeignKeyViolation) insert or update on table "search" violates foreign key constraint "fk_search_id_user_user" E DETAIL: Key (id_user)=(1) is not present in table "user".

0

There are 0 answers