英文:
How do I import functions and classes into conftest.py? Or how do I import fixtures and classes into conftest.py?
问题
Here's the translated portion of your text:
example 1
conftest.py
我从conftest.py文件中开始所有的代码。这是示例1。在示例2中,我想将像def test_username_db():
这样的函数移动到一个名为test_function.py的单独文件中。然后,我想从test_function.py中导入到conftest.py中。问题是我遇到了错误。我该如何修复这个问题?
test_fixture.py
test_fixture.py(create_db)
create_db()
示例2
现在想象一下,我想将额外的fixtures拆分成test_function.py文件中的函数。
test_function.py
在这里还编写了数据库类。
def test_username_db():
# 假设Bob存在
user_db = User.query.filter_by(username='Bob').first()
assert user_db != 'Bob'
# 其他fixtures...
conftest.py
from tests.test_function import test_username_db ...
@pytest.fixture()
def create_db(new_user):
bind_key = "testing_app_db"
# 创建数据库和数据库表
db.create_all(bind_key)
db.session.add(new_user)
db.session.commit()
# yield不像return在调用时停止。
yield test_username_db()
yield #其他函数
db.drop_all(bind_key)
test_fixture.py
test_fixture.py(create_db)
create_db()
这看起来没问题,但问题是当我运行示例2中的代码时,我遇到了一个错误。以下是错误:
python -m pytest
========================================================================================= test session starts ==========================================================================================
platform win32 -- Python 3.10.8, pytest-7.1.2, pluggy-1.0.0
rootdir: C:\Users\user\OneDrive\Desktop\flaskcodeusethis\flaskblog2
collected 0 items / 1 error
================================================================================================ ERRORS ================================================================================================
____________________________________________________________________________________ ERROR collecting test session _____________________________________________________________________________________
..\..\..\..\Anaconda3\envs\py\lib\importlib\__init__.py:126: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
<frozen importlib._bootstrap>:1050: in _gcd_import
???
<frozen importlib._bootstrap>:1027: in _find_and_load
???
<frozen importlib._bootstrap>:1006: in _find_and_load_unlocked
???
<frozen importlib._bootstrap>:688: in _load_unlocked
???
..\..\..\..\Anaconda3\envs\py\lib\site-packages\_pytest\assertion\rewrite.py:168: in exec_module
exec(co, module.__dict__)
app\tests\conftest.py:13: in <module>
from tests.test_password_function import app, db, UserTest, email_token_and_registration_confirmation_email
E ModuleNotFoundError: No module named 'tests'
======================================================================================= short test summary info ========================================================================================
ERROR - ModuleNotFoundError: No module named 'tests'
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
这个错误为什么会发生?您还提到了错误中使用了def email_token_and_registration_confirmation_email()
而不是def test_username_db()
以及使用了文件test_functions_use_db.py
而不是test_function.py
。
以下是我尝试的解决方法。
我尝试将test_functions_use_db.py中的函数更改为functions_use_db.py。结果效果相同。
我还找到了这个链接https://stackoverflow.com/questions/73191533/using-conftest-py-vs-importing-fixtures-from-dedicate-modules。我尝试将一些函数和test_email_token_and_registration_confirmation_email()
fixture添加到一个文件中,但仍然遇到了非常相似的错误。
示例3
在示例3中,我不是使用函数def test_username_db()
,而是使用了一个fixture。
test_function.py
在这里还编写了数据库类。
import fixture
@pytest.fixture
def test_username_db():
# 假设Bob存在
user_db = User.query.filter_by(username='Bob').first()
assert user_db != 'Bob'
# 其他fixtures...
conftest.py
from tests.test_function import test_username_db ...
__all__ = ['test_username_db']
@pytest.fixture()
def create_db(new_user, test_username_db):
bind_key = "testing_app_db"
# 创建数据库和数据库表
db.create_all(bind_key)
db.session.add(new_user)
db.session.commit()
# yield不像return在调用时停止。
yield test_username_db()
yield #其他函数
db.drop_all(bind_key)
test_fixture.py
test_fixture.py(create_db)
create_db()
这是示例3的确切错误。
python -m pytest
================================================================= test session starts ==================================================================
platform win32 -- Python 3.10.8, pytest-7.1.2, pluggy-1.0.0
rootdir: C:\Users\nmyle\OneDrive\Desktop\flaskcodeusethis\flaskblog2
collected 0 items / 1 error
======================================================================== ERRORS ========================================================================
____________________________________________________________ ERROR collecting test session _____________________________________________________________
..\..\..\..\Anaconda3\envs\py\lib\importlib\__init__.py:126: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
<frozen importlib._bootstrap>:1050: in _gcd_import
???
<frozen importlib._bootstrap>:1027: in _find_and_load
???
<frozen importlib._bootstrap>:1006: in _find_and_load_unlocked
???
<frozen importlib._bootstrap>:688: in _load_unlocked
???
..\..\..\..\Anaconda3\envs\py\lib\site-packages\_pytest\assertion\rewrite.py:168: in exec_module
exec(co, module.__dict__)
app\tests\conftest.py:5: in <module>
from tests.functions_use_db import app, db, UserTest , email_token_and_registration_confirmation_email
E ModuleNotFoundError: No module named 'tests'
=============================================================== short test summary info ================================================================
ERROR - ModuleNotFoundError: No module named 'tests'
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
请问您还有其他问题需要解答吗?
英文:
I start off with all the code in conftest.py. This is in example 1. In example 2 I want to move a functions like def test_username_db():
into a separate file called test_function.py. Then I want to import from test_function.py into conftest.py. The problem is I am getting an error. How do I fix this?
example 1
conftest.py
Also I wrote the database class here.
@pytest.fixture
def test_username_db():
# assume bob exists
user_db = User.query.filter_by(username='Bob').first()
assert user_db != 'Bob'
# other fixtures...
@pytest.fixture()
def create_db(new_user, test_username_db):
bind_key="testing_app_db"
# Create the database and the database table
db.create_all(bind_key)
db.session.add(new_user)
db.session.commit()
# yield unlike return doesn't stop when called.
yield test_username_db()
yield other fixtures
db.drop_all(bind_key)
test_fixture.py
test_fixture.py(create_db)
create_db()
Example 2
Now imagine I want to split up the extra fixtures into functions in a file called test_function.py.
test_function.py
Also I wrote the database class here.
def test_username_db():
# assume bob exists
user_db = User.query.filter_by(username='Bob').first()
assert user_db != 'Bob'
# other fixtures...
conftest.py
from tests.test_function import test_username_db ...
@pytest.fixture()
def create_db(new_user):
bind_key="testing_app_db"
# Create the database and the database table
db.create_all(bind_key)
db.session.add(new_user)
db.session.commit()
# yield unlike return doesn't stop when called.
yield test_username_db()
yield # other functions
db.drop_all(bind_key)
test_fixture.py
test_fixture.py(create_db)
create_db()
This seems okay but the problem is when I run the code in example 2 I get an error.
Here is the error
python -m pytest
========================================================================================= test session starts ==========================================================================================
platform win32 -- Python 3.10.8, pytest-7.1.2, pluggy-1.0.0
rootdir: C:\Users\user\OneDrive\Desktop\flaskcodeusethis\flaskblog2
collected 0 items / 1 error
================================================================================================ ERRORS ================================================================================================
____________________________________________________________________________________ ERROR collecting test session _____________________________________________________________________________________
..\..\..\..\Anaconda3\envs\py\lib\importlib\__init__.py:126: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
<frozen importlib._bootstrap>:1050: in _gcd_import
???
<frozen importlib._bootstrap>:1027: in _find_and_load
???
<frozen importlib._bootstrap>:1006: in _find_and_load_unlocked
???
<frozen importlib._bootstrap>:688: in _load_unlocked
???
..\..\..\..\Anaconda3\envs\py\lib\site-packages\_pytest\assertion\rewrite.py:168: in exec_module
exec(co, module.__dict__)
app\tests\conftest.py:13: in <module>
from tests.test_password_function import app, db, UserTest, email_token_and_registration_confirmation_email
E ModuleNotFoundError: No module named 'tests'
======================================================================================= short test summary info ========================================================================================
ERROR - ModuleNotFoundError: No module named 'tests'
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
My testing folder looks like this tests folder and files .
Why is this error occurring?
Also the error I posted I am using the function def email_token_and_registration_confirmation_email():
instead of def test_username_db():
.
Also the error I posted I am using the file test_functions_use_db.py
instead of test_function.py
.
Here is what I tried.
I tried changing the functions test_functions_use_db.py to functions_use_db.py. I get the same effect.
I also found this link https://stackoverflow.com/questions/73191533/using-conftest-py-vs-importing-fixtures-from-dedicate-modules. I tried adding some functions and test_email_token_and_registration_confirmation_email()
fixture into one file and I am still getting a very similar error.
example 3
In example 3 instead of a function for def test_username_db():
I am using a fixture
test_function.py
Also I wrote the database class here.
import fixture
@pytest.fixture
def test_username_db():
# assume bob exists
user_db = User.query.filter_by(username='Bob').first()
assert user_db != 'Bob'
# other fixtures...
conftest.py
from tests.test_function import test_username_db ...
__all__ = ['test_username_db']
@pytest.fixture()
def create_db(new_user, test_username_db):
bind_key="testing_app_db"
# Create the database and the database table
db.create_all(bind_key)
db.session.add(new_user)
db.session.commit()
# yield unlike return doesn't stop when called.
yield test_username_db()
yield # other functions
db.drop_all(bind_key)
test_fixture.py
test_fixture.py(create_db)
create_db()
Here is the exact error for example 3.
python -m pytest
================================================================= test session starts ==================================================================
platform win32 -- Python 3.10.8, pytest-7.1.2, pluggy-1.0.0
rootdir: C:\Users\nmyle\OneDrive\Desktop\flaskcodeusethis\flaskblog2
collected 0 items / 1 error
======================================================================== ERRORS ========================================================================
____________________________________________________________ ERROR collecting test session _____________________________________________________________
..\..\..\..\Anaconda3\envs\py\lib\importlib\__init__.py:126: in import_module
return _bootstrap._gcd_import(name[level:], package, level)
<frozen importlib._bootstrap>:1050: in _gcd_import
???
<frozen importlib._bootstrap>:1027: in _find_and_load
???
<frozen importlib._bootstrap>:1006: in _find_and_load_unlocked
???
<frozen importlib._bootstrap>:688: in _load_unlocked
???
..\..\..\..\Anaconda3\envs\py\lib\site-packages\_pytest\assertion\rewrite.py:168: in exec_module
exec(co, module.__dict__)
app\tests\conftest.py:5: in <module>
from tests.functions_use_db import app, db, UserTest , email_token_and_registration_confirmation_email
E ModuleNotFoundError: No module named 'tests'
=============================================================== short test summary info ================================================================
ERROR - ModuleNotFoundError: No module named 'tests'
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Like stated earlier how do I fix this?
答案1
得分: 0
在第3个示例中,这可能与Pytest加载模块的方式有关。当我在conftest.py文件中引用我的测试模块时,出现了错误。我建议将用于实例化数据库的代码放在测试模块之外的另一个模块中,也许可以放在contest.py模块中。此外,我将所有的fixtures都放在了conftest模块中。因此,你的代码将类似于这样。
test_functions.py
将你的fixture名称作为参数传递
def test_username_db(create_db):
# 在这个函数中引用你的fixture以调用它
db_usr_name = create_db("Bob")
assert db_usr_name != 'Bob'
conftest.py
import pytest
@pytest.fixture()
def create_db():
def _subfunc(new_user):
# 在这里编写创建数据库的代码
return db.user_name
yield
# 在这里执行拆卸函数(不要引用test_functions.py模块中的任何函数)
关于fixtures,我在参数上使用子函数,因为似乎无法像普通函数那样在fixtures上使用参数(参见这里)。
附注:如果数据库正确地将“Bob”添加为新用户,你的测试将失败。我不知道这是否是你打算的。
英文:
Focusing on example 3, it may have something to do w/ the way Pytest loads the modules. When I reference my test module in my conftest.py file, I ran into errors. I would suggest writing the code to instantiate your database in another module other than the test module (maybe in your contest.py module). Also, I put all of my fixtures in my conftest module. So your code would look similar to this.
test_functions.py
#pass your fixture name as a parameter
def test_username_db(create_db):
#reference your fixture in this function to call it
db_usr_name = create_db("Bob")
assert db_usr_name != 'Bob'
conftest.py
import pytest
@pytest.fixture()
def create_db():
def _subfunc(new_user):
#code to create your db here
return db.user_name
yield
#do your tear down functions here (don't reference any functions in your test_functions.py module)
On fixtures, I use sub functions for parameters because it seems you can't use parameter like normal functions on fixtures (see here).
Sidenote: Your test will fail if the database correctly adds "Bob" as a new user. I don't know if that's what you intended.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论