Python pytest夹具从外部范围[pylint]重新定义名称
我正在学习pytest,我用pylint编写代码。 但派林仍然抱怨:Python pytest夹具从外部范围[pylint]重新定义名称,python,pytest,pylint,fixture,Python,Pytest,Pylint,Fixture,我正在学习pytest,我用pylint编写代码。 但派林仍然抱怨: W0621:从外部作用域(第%s行)重新定义名称%r 对于pytest中的以下示例: # test_wallet.py @pytest.fixture def my_wallet(): '''Returns a Wallet instance with a zero balance''' return Wallet() @pytest.mark.parametrize("earned,spent,expec
W0621:从外部作用域(第%s行)重新定义名称%r
对于pytest中的以下示例:
# test_wallet.py
@pytest.fixture
def my_wallet():
'''Returns a Wallet instance with a zero balance'''
return Wallet()
@pytest.mark.parametrize("earned,spent,expected", [
(30, 10, 20),
(20, 2, 18),
])
def test_transactions(my_wallet, earned, spent, expected):
my_wallet.add_cash(earned)
my_wallet.spend_cash(spent)
assert my_wallet.balance == expected
从外部范围重新定义名称my_wallet
我找到了一种解决方法,可以在夹具名称中添加前缀:\u我的钱包
如果我想将装置与函数保存在同一个文件中,那么最佳做法是什么
pylint
检查测试有一个插件试图修复一些问题,但错误
W0621
尚未修复。我刚刚在测试文件中禁用了该规则:
#pylint:disable=重新定义的外部名称
#^^^^这个
导入pytest
@pytest.fixture
定义我的钱包()
''返回余额为零的钱包实例''
归还钱包()
@pytest.mark.parametize(“挣的、花的、预期的”[
(30, 10, 20),
(20, 2, 18),
])
def测试交易(我的钱包、收入、支出、预期):
我的钱包。添加现金(已赚)
我的钱包。花现金(已用)
断言我的钱包。余额==预期值
对于@pytest.fixture
来说:
如果在定义夹具的同一模块中使用夹具,则
夹具的函数名将被
请求夹具;解决这一问题的一种方法是命名
功能夹具
然后使用
@pytest.fixture(名称=“”)
因此,该解决方案与选项1类似,只是pytest作者为fixture函数建议了一个更具描述性的名称。因此,替换这两条线
@pytest.fixture
def my_wallet():
与:
文档中的描述还提示了另一种解决方案,即将夹具移动到conftest.py
中,使其与使用夹具的测试代码不在同一模块中。此位置对于在测试模块之间共享夹具也很有用。在def中为夹具和夹具前缀添加名称参数
@pytest.fixture(name="my_wallet")
def fixture_wallet():
'''Returns a Wallet instance with a zero balance.'''
return Wallet()
@pytest.mark.parametrize("earned, spent, expected", [
(30, 10, 20),
(20, 2, 18),
])
def test_transactions(my_wallet, earned, spent, expected):
my_wallet.add_cash(earned)
my_wallet.spend_cash(spent)
assert my_wallet.balance == expected
这个插件不是在pytest对pylint警告进行pytest时出错,而不是在测试代码中抑制pylint警告吗?是的,pluging@insysion链接到运行pylint作为pytest的一部分,与修复pytest常用夹具上的pylint错误消息无关。这应该是有效的答案。这是到相关pytest的更新链接
@pytest.fixture(name="my_wallet")
def fixture_wallet():
'''Returns a Wallet instance with a zero balance.'''
return Wallet()
@pytest.mark.parametrize("earned, spent, expected", [
(30, 10, 20),
(20, 2, 18),
])
def test_transactions(my_wallet, earned, spent, expected):
my_wallet.add_cash(earned)
my_wallet.spend_cash(spent)
assert my_wallet.balance == expected