SQLAlchemyORM函数在主脚本中工作,但在Pytest中失败



使用Postgres、SQLAlchemy 1.4 ORM、Python 3.7、Pytest。

我在myproject/src/db.py中有一个脚本,它的测试位于myproject/tests/中。

db.py中,我有一个删除任何给定表的功能,它按预期工作:

async def delete_table(self, table_name):
table = self.meta.tables[table_name]
async with self.engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all(sync_engine, [table], checkfirst=True))

它被称为:asyncio.run(db.delete_table('user'))

conftest.py中,我有一个这样的固定装置:

@pytest.fixture(scope='function')
def test_drop_table():
def get_delete_tables(table_name):
return asyncio.run(DB.delete_table(table_name))
return get_delete_tables

test.py中,我这样运行测试:

@pytest.mark.parametrize('function_input, expected',
[('user', 'user'),
pytest.param('intentional failure', 'intentional failure',
marks=pytest.mark.xfail(reason='testing incorrect table name fails'))])
def test_drop_table(test_drop_table, function_input, expected):
# Drop the table
test_drop_table(function_input)

# Check that it no longer exists
with pytest.raises(KeyError) as error_info:
test_table_commits(function_input, expected)
raise KeyError
assert error_info.type is KeyError

当我运行这个测试时,我得到了这个错误:

self = <postgresdb.PostgresDb object at 0x7f4bbd87cc18>, table_name = 'user'
async def delete_table(self, table_name):
>       table = self.meta.tables[table_name]
E       KeyError: 'user'

我验证了这个表可以在主脚本中删除。然后,我重新提交该表,验证它是否存在,然后尝试在测试中删除它,但会不断收到该表不存在的KeyError,即使在检查数据库时该表确实存在。

我不确定要在代码中测试或调整什么才能让Pytest使用这个函数。我感谢任何帮助!

我认为这是第一次删除名为user的表,但pytest.mark.parametrize中的第二个输入也是名称user,因此可能是抛出错误。如果你需要测试两种不同的场景,最好有两种不同测试功能。通过这样做,您可以在with pytest.raises(KeyError) as error_info下的第二个测试函数中获得所有代码。

相关内容

最新更新