我正在浏览代码库并注意到以下导入模块的样式
import torch.nn as nn
在我个人的工作中,我一直使用以下方法
from torch import nn
这两种导入方式有什么区别吗?
我在 Firefox 76.0 版中启用了暗模式并安装了暗阅读器扩展。该扩展程序允许网页变暗。这些更改不会影响已在 Firefox 中打开的任何 PDF。
我采用test_tmp.py了https://docs.python.org/3/library/unittest.mock.html#patch-multiple
from unittest.mock import DEFAULT, MagicMock, patch
thing = object()
other = object()
@patch.multiple('__main__', thing=DEFAULT, other=DEFAULT)
def test_function(thing, other):
print(f'thing={thing}')
print(f'other={other}')
assert isinstance(thing, MagicMock)
assert isinstance(other, MagicMock)
test_function()
Run Code Online (Sandbox Code Playgroud)
它与 python 一起运行
python test_tmp.py
thing=<MagicMock name='thing' id='4355085552'>
other=<MagicMock name='other' id='4355243312'>
Run Code Online (Sandbox Code Playgroud)
但它不适用于 pytest 并出现类似错误
pytest test_tmp.py
============================================================================================================= test session starts =============================================================================================================
platform darwin -- Python 3.8.2, pytest-5.4.3, py-1.9.0, pluggy-0.13.1
rootdir: /private/tmp
collected 0 items / 1 error
=================================================================================================================== ERRORS ====================================================================================================================
________________________________________________________________________________________________________ ERROR collecting test_tmp.py _________________________________________________________________________________________________________
test_tmp.py:13: in <module>
test_function() …Run Code Online (Sandbox Code Playgroud) 我尝试使用 pytest-xdist 在我的硒网格上并行运行 pytest。在使用 pytest-xdist 之前,我在所有测试开始使用 pytest_sessionstart 挂钩之前执行了一次设置。它工作得很好。这将是第一个运行的事情,在它完成之前不会开始任何测试。一旦我尝试使用 pytest-xdist,所有会话范围的挂钩(例如 pytest_sessionstart 和 pytest_sessionfinish)都会被执行多次。我不明白或做错了什么?
在我的装饰器上使用后@patch它不再起作用了。我想要进行一个会失败并引发异常的调用,以便我可以检查我的装饰器是否捕获了此异常,并且正在调用某个函数。
模拟do_sth_in_db并让它引发异常是很容易的部分,但是在模拟这个方法之后,它不再被修饰 - 所以即使它引发异常,也不会发生任何事情,因为它不再有块try/except。
TLDR:我想把 @decorator 放回我的模拟函数上。
我的.py
from my_decorator import transaction
class MyClass():
@transaction
def do_sth_in_db(self):
print('Did something in DB')
Run Code Online (Sandbox Code Playgroud)
my_decorator.py
import functools
def rollback_func():
print('666 rollback fun called')
def push_to_db_func():
print('777 I have changed database')
def transaction(func):
functools.wraps(func)
def wrapper(*args,**kwargs):
try:
func(*args, **kwargs)
push_to_db_func()
print('worked')
except Exception:
rollback_func()
print('not worked, did rollback')
return wrapper
Run Code Online (Sandbox Code Playgroud)
测试.py
import unittest
from mock import Mock, patch, MagicMock
from my import MyClass
from my_decorator import transaction
class …Run Code Online (Sandbox Code Playgroud) 我使用 pytest 和 pytest-xdist 来测试 django 应用程序,当我运行时py.test -n 1出现错误:
Test session starts (platform: linux2, Python 2.7.12, pytest 2.9.2, pytest-sugar 0.7.1)
django settings: icbase.settings (from ini file)
rootdir: /home/xsy/icgoo_git/datacenter3, inifile: pytest.ini
plugins: sugar-0.7.1, xdist-1.15.0, cov-2.3.1, django-2.9.1
gw0 okINTERNALERROR> Traceback (most recent call last):
INTERNALERROR> File "/home/xsy/.virtualenvs/dc3/lib/python2.7/site-packages/_pytest/main.py", line 94, in wrap_session
INTERNALERROR> session.exitstatus = doit(config, session) or 0
INTERNALERROR> File "/home/xsy/.virtualenvs/dc3/lib/python2.7/site-packages/_pytest/main.py", line 125, in _main
INTERNALERROR> config.hook.pytest_runtestloop(session=session)
INTERNALERROR> File "/home/xsy/.virtualenvs/dc3/lib/python2.7/site-packages/_pytest/vendored_packages/pluggy.py", line 724, in __call__
INTERNALERROR> return self._hookexec(self, self._nonwrappers + self._wrappers, …Run Code Online (Sandbox Code Playgroud) 当我运行 python 的覆盖率时,我总是需要__init__.py在测试子目录中有一个空文件来获取运行测试的覆盖率。这是 python2 软件包的要求,但不是 python3 的要求。为了重现,我执行了以下操作(先决条件是 python3、pip3 和 brew):
运行以下终端命令:
pip3 install coverage
Run Code Online (Sandbox Code Playgroud)创建以下目录结构:
example\
example.py
tests\
test_example.py
Run Code Online (Sandbox Code Playgroud)示例.py:
#!/usr/bin/env python3
class Example:
value = 3
def update(self):
self.value = 4
Run Code Online (Sandbox Code Playgroud)
测试示例.py:
#!/usr/bin/env python3
import unittest
from example.example import Example
class TestExample(unittest.TestCase):
def test_example(self):
example_object = Example()
self.assertEqual(3, example_object.value)
example_object.update()
self.assertEqual(4, example_object.value)
Run Code Online (Sandbox Code Playgroud)
运行以下终端命令:
coverage run --branch -m unittest discover -s . && coverage report
Run Code Online (Sandbox Code Playgroud)我应该得到:Ran 1 test in x.yz seconds,但我总是得到Ran 0 tests in x.yz …
我有一个函数和一个测试
def foo(a):
return bar(a)
@pytest.mark.parametrize(
'number',
[1,2,3]
)
@pytest.mark.dependency
def test_foo(number):
assert foo(number) > SOME_CONST # Simplistic example, real case is more nuanced
Run Code Online (Sandbox Code Playgroud)
我正在使用 pytest 和 pytest_dependency 模块。foo是许多其他测试中使用的函数。我有一个函数,我想依赖它test_foo,下面的代码不起作用:
@pytest.mark.dependency(depends=['test_foo'])
@pytest.mark.parametrize(
'param',
itertools.permutations(['a','b','c','d','e'],2),
ids=repr,
)
def test_bar(param):
...
important_result = foo(param)
...
Run Code Online (Sandbox Code Playgroud)
理论上来说,如果test_foo失败,那么test_bar就会被跳过。但是,当我参数化 时,无论 的结果如何,都会跳过 的test_bar每个实例化。test_bartest_foo
澄清一下,此代码按预期工作(未跳过 test_bar):
@pytest.mark.dependency(depends=['test_foo'])
def test_bar():
param = some_fnc(['a', 'b'])
...
important_result = foo(param)
...
Run Code Online (Sandbox Code Playgroud) Replacing crashed worker gw0
INTERNALERROR> Traceback (most recent call last):
INTERNALERROR> File "/usr/local/lib/python3.7/site-packages/_pytest/main.py", line 191, in wrap_session
INTERNALERROR> session.exitstatus = doit(config, session) or 0
INTERNALERROR> File "/usr/local/lib/python3.7/site-packages/_pytest/main.py", line 246, in _main
INTERNALERROR> config.hook.pytest_collection(session=session)
INTERNALERROR> File "/Users/Library/Python/3.7/lib/python/site-packages/pluggy/hooks.py", line 286, in __call__
INTERNALERROR> return self._hookexec(self, self.get_hookimpls(), kwargs)
INTERNALERROR> File "/Users/Library/Python/3.7/lib/python/site-packages/pluggy/manager.py", line 93, in _hookexec
INTERNALERROR> return self._inner_hookexec(hook, methods, kwargs)
INTERNALERROR> File "/Users/Library/Python/3.7/lib/python/site-packages/pluggy/manager.py", line 87, in <lambda>
INTERNALERROR> firstresult=hook.spec.opts.get("firstresult") if hook.spec else False,
INTERNALERROR> File "/Users/Library/Python/3.7/lib/python/site-packages/pluggy/callers.py", line 208, in _multicall
INTERNALERROR> return outcome.get_result() …Run Code Online (Sandbox Code Playgroud) 我的测试脚本如下
@pytest.fixture(scope="Module", Autouse="True")
def setup_test():
....................
yield
............
def test_1()
...............
def test_2()
...............
def test_3()
...............
Run Code Online (Sandbox Code Playgroud)
顺序脚本执行工作正常。(第一个测试设置 -> Test1 -> Test2 ->Test3 -> Tear down)使用 pytest。
如何并行运行脚本执行,例如:- 第一个测试设置 -> 并行所有测试用例 -> 拆除?
如果我在 pytest 执行中使用 -n 选项,它甚至会在设置部分完成之前并行触发所有测试,并在所有测试用例之后执行拆卸部分。
我尝试提供--dist=load选项,将安装和拆卸放入conftest文件等中。在我的情况下没有任何效果。
pytest ×6
python ×6
pytest-xdist ×3
python-3.x ×3
xdist ×2
coverage.py ×1
django ×1
exception ×1
firefox ×1
import ×1
init ×1
mocking ×1
pdf ×1
python-mock ×1
unit-testing ×1