如何将函数和类导入conftest.py?或者如何将fixtures和类导入conftest.py?

huangapple go评论102阅读模式
英文:

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

  1. test_fixture.py(create_db)
  2. create_db()

示例2

现在想象一下,我想将额外的fixtures拆分成test_function.py文件中的函数。

test_function.py

在这里还编写了数据库类。

  1. def test_username_db():
  2. # 假设Bob存在
  3. user_db = User.query.filter_by(username='Bob').first()
  4. assert user_db != 'Bob'
  5. # 其他fixtures...

conftest.py

  1. from tests.test_function import test_username_db ...
  2. @pytest.fixture()
  3. def create_db(new_user):
  4. bind_key = "testing_app_db"
  5. # 创建数据库和数据库表
  6. db.create_all(bind_key)
  7. db.session.add(new_user)
  8. db.session.commit()
  9. # yield不像return在调用时停止。
  10. yield test_username_db()
  11. yield #其他函数
  12. db.drop_all(bind_key)

test_fixture.py

  1. test_fixture.py(create_db)
  2. create_db()

这看起来没问题,但问题是当我运行示例2中的代码时,我遇到了一个错误。以下是错误:

  1. python -m pytest
  2. ========================================================================================= test session starts ==========================================================================================
  3. platform win32 -- Python 3.10.8, pytest-7.1.2, pluggy-1.0.0
  4. rootdir: C:\Users\user\OneDrive\Desktop\flaskcodeusethis\flaskblog2
  5. collected 0 items / 1 error
  6. ================================================================================================ ERRORS ================================================================================================
  7. ____________________________________________________________________________________ ERROR collecting test session _____________________________________________________________________________________
  8. ..\..\..\..\Anaconda3\envs\py\lib\importlib\__init__.py:126: in import_module
  9. return _bootstrap._gcd_import(name[level:], package, level)
  10. <frozen importlib._bootstrap>:1050: in _gcd_import
  11. ???
  12. <frozen importlib._bootstrap>:1027: in _find_and_load
  13. ???
  14. <frozen importlib._bootstrap>:1006: in _find_and_load_unlocked
  15. ???
  16. <frozen importlib._bootstrap>:688: in _load_unlocked
  17. ???
  18. ..\..\..\..\Anaconda3\envs\py\lib\site-packages\_pytest\assertion\rewrite.py:168: in exec_module
  19. exec(co, module.__dict__)
  20. app\tests\conftest.py:13: in <module>
  21. from tests.test_password_function import app, db, UserTest, email_token_and_registration_confirmation_email
  22. E ModuleNotFoundError: No module named 'tests'
  23. ======================================================================================= short test summary info ========================================================================================
  24. ERROR - ModuleNotFoundError: No module named 'tests'
  25. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 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

在这里还编写了数据库类。

  1. import fixture
  2. @pytest.fixture
  3. def test_username_db():
  4. # 假设Bob存在
  5. user_db = User.query.filter_by(username='Bob').first()
  6. assert user_db != 'Bob'
  7. # 其他fixtures...

conftest.py

  1. from tests.test_function import test_username_db ...
  2. __all__ = ['test_username_db']
  3. @pytest.fixture()
  4. def create_db(new_user, test_username_db):
  5. bind_key = "testing_app_db"
  6. # 创建数据库和数据库表
  7. db.create_all(bind_key)
  8. db.session.add(new_user)
  9. db.session.commit()
  10. # yield不像return在调用时停止。
  11. yield test_username_db()
  12. yield #其他函数
  13. db.drop_all(bind_key)

test_fixture.py

  1. test_fixture.py(create_db)
  2. create_db()

这是示例3的确切错误。

  1. python -m pytest
  2. ================================================================= test session starts ==================================================================
  3. platform win32 -- Python 3.10.8, pytest-7.1.2, pluggy-1.0.0
  4. rootdir: C:\Users\nmyle\OneDrive\Desktop\flaskcodeusethis\flaskblog2
  5. collected 0 items / 1 error
  6. ======================================================================== ERRORS ========================================================================
  7. ____________________________________________________________ ERROR collecting test session _____________________________________________________________
  8. ..\..\..\..\Anaconda3\envs\py\lib\importlib\__init__.py:126: in import_module
  9. return _bootstrap._gcd_import(name[level:], package, level)
  10. <frozen importlib._bootstrap>:1050: in _gcd_import
  11. ???
  12. <frozen importlib._bootstrap>:1027: in _find_and_load
  13. ???
  14. <frozen importlib._bootstrap>:1006: in _find_and_load_unlocked
  15. ???
  16. <frozen importlib._bootstrap>:688: in _load_unlocked
  17. ???
  18. ..\..\..\..\Anaconda3\envs\py\lib\site-packages\_pytest\assertion\rewrite.py:168: in exec_module
  19. exec(co, module.__dict__)
  20. app\tests\conftest.py:5: in <module>
  21. from tests.functions_use_db import app, db, UserTest , email_token_and_registration_confirmation_email
  22. E ModuleNotFoundError: No module named 'tests'
  23. =============================================================== short test summary info ================================================================
  24. ERROR - ModuleNotFoundError: No module named 'tests'
  25. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 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.

  1. @pytest.fixture
  2. def test_username_db():
  3. # assume bob exists
  4. user_db = User.query.filter_by(username=&#39;Bob&#39;).first()
  5. assert user_db != &#39;Bob&#39;
  6. # other fixtures...
  7. @pytest.fixture()
  8. def create_db(new_user, test_username_db):
  9. bind_key=&quot;testing_app_db&quot;
  10. # Create the database and the database table
  11. db.create_all(bind_key)
  12. db.session.add(new_user)
  13. db.session.commit()
  14. # yield unlike return doesn&#39;t stop when called.
  15. yield test_username_db()
  16. yield other fixtures
  17. db.drop_all(bind_key)

test_fixture.py

  1. test_fixture.py(create_db)
  2. 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

  1. Also I wrote the database class here.
  2. def test_username_db():
  3. # assume bob exists
  4. user_db = User.query.filter_by(username=&#39;Bob&#39;).first()
  5. assert user_db != &#39;Bob&#39;
  6. # other fixtures...

conftest.py

  1. from tests.test_function import test_username_db ...
  2. @pytest.fixture()
  3. def create_db(new_user):
  4. bind_key=&quot;testing_app_db&quot;
  5. # Create the database and the database table
  6. db.create_all(bind_key)
  7. db.session.add(new_user)
  8. db.session.commit()
  9. # yield unlike return doesn&#39;t stop when called.
  10. yield test_username_db()
  11. yield # other functions
  12. db.drop_all(bind_key)

test_fixture.py

  1. test_fixture.py(create_db)
  2. 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

  1. python -m pytest
  2. ========================================================================================= test session starts ==========================================================================================
  3. platform win32 -- Python 3.10.8, pytest-7.1.2, pluggy-1.0.0
  4. rootdir: C:\Users\user\OneDrive\Desktop\flaskcodeusethis\flaskblog2
  5. collected 0 items / 1 error
  6. ================================================================================================ ERRORS ================================================================================================
  7. ____________________________________________________________________________________ ERROR collecting test session _____________________________________________________________________________________
  8. ..\..\..\..\Anaconda3\envs\py\lib\importlib\__init__.py:126: in import_module
  9. return _bootstrap._gcd_import(name[level:], package, level)
  10. &lt;frozen importlib._bootstrap&gt;:1050: in _gcd_import
  11. ???
  12. &lt;frozen importlib._bootstrap&gt;:1027: in _find_and_load
  13. ???
  14. &lt;frozen importlib._bootstrap&gt;:1006: in _find_and_load_unlocked
  15. ???
  16. &lt;frozen importlib._bootstrap&gt;:688: in _load_unlocked
  17. ???
  18. ..\..\..\..\Anaconda3\envs\py\lib\site-packages\_pytest\assertion\rewrite.py:168: in exec_module
  19. exec(co, module.__dict__)
  20. app\tests\conftest.py:13: in &lt;module&gt;
  21. from tests.test_password_function import app, db, UserTest, email_token_and_registration_confirmation_email
  22. E ModuleNotFoundError: No module named &#39;tests&#39;
  23. ======================================================================================= short test summary info ========================================================================================
  24. ERROR - ModuleNotFoundError: No module named &#39;tests&#39;
  25. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 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

  1. Also I wrote the database class here.
  2. import fixture
  3. @pytest.fixture
  4. def test_username_db():
  5. # assume bob exists
  6. user_db = User.query.filter_by(username=&#39;Bob&#39;).first()
  7. assert user_db != &#39;Bob&#39;
  8. # other fixtures...

conftest.py

  1. from tests.test_function import test_username_db ...
  2. __all__ = [&#39;test_username_db&#39;]
  3. @pytest.fixture()
  4. def create_db(new_user, test_username_db):
  5. bind_key=&quot;testing_app_db&quot;
  6. # Create the database and the database table
  7. db.create_all(bind_key)
  8. db.session.add(new_user)
  9. db.session.commit()
  10. # yield unlike return doesn&#39;t stop when called.
  11. yield test_username_db()
  12. yield # other functions
  13. db.drop_all(bind_key)

test_fixture.py

  1. test_fixture.py(create_db)
  2. create_db()

Here is the exact error for example 3.

  1. python -m pytest
  2. ================================================================= test session starts ==================================================================
  3. platform win32 -- Python 3.10.8, pytest-7.1.2, pluggy-1.0.0
  4. rootdir: C:\Users\nmyle\OneDrive\Desktop\flaskcodeusethis\flaskblog2
  5. collected 0 items / 1 error
  6. ======================================================================== ERRORS ========================================================================
  7. ____________________________________________________________ ERROR collecting test session _____________________________________________________________
  8. ..\..\..\..\Anaconda3\envs\py\lib\importlib\__init__.py:126: in import_module
  9. return _bootstrap._gcd_import(name[level:], package, level)
  10. &lt;frozen importlib._bootstrap&gt;:1050: in _gcd_import
  11. ???
  12. &lt;frozen importlib._bootstrap&gt;:1027: in _find_and_load
  13. ???
  14. &lt;frozen importlib._bootstrap&gt;:1006: in _find_and_load_unlocked
  15. ???
  16. &lt;frozen importlib._bootstrap&gt;:688: in _load_unlocked
  17. ???
  18. ..\..\..\..\Anaconda3\envs\py\lib\site-packages\_pytest\assertion\rewrite.py:168: in exec_module
  19. exec(co, module.__dict__)
  20. app\tests\conftest.py:5: in &lt;module&gt;
  21. from tests.functions_use_db import app, db, UserTest , email_token_and_registration_confirmation_email
  22. E ModuleNotFoundError: No module named &#39;tests&#39;
  23. =============================================================== short test summary info ================================================================
  24. ERROR - ModuleNotFoundError: No module named &#39;tests&#39;
  25. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 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

  1. yield
  2. # 在这里执行拆卸函数(不要引用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

  1. #pass your fixture name as a parameter
  2. def test_username_db(create_db):
  3. #reference your fixture in this function to call it
  4. db_usr_name = create_db(&quot;Bob&quot;)
  5. assert db_usr_name != &#39;Bob&#39;

conftest.py

  1. import pytest
  2. @pytest.fixture()
  3. def create_db():
  4. def _subfunc(new_user):
  5. #code to create your db here
  6. return db.user_name
  7. yield
  8. #do your tear down functions here (don&#39;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.

huangapple
  • 本文由 发表于 2023年4月4日 08:32:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75924656.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定