I'm writting a Brownie test like below:
from brownie import accounts
class Test1:
my_account = accounts\[0\]
def test_fn:
...
The test result says "my_account = accounts[0], list index out of range"
But if I put "my_account = accounts[0]" inside test_fn like below, then the test runs fine.
from brownie import accounts
class Test1:
def test_fn:
my_account = accounts\[0\]
...
Why is that? what's the pytest scope for imported variables?
Tried searching anything related to pytest variable scope, but none suit my question.
Can not reproduce your example because I do not have any accounts in both cases.
However, I think your issue is happening because this accounts
variable must be filled with values according to account management page in brownie's docs.
Class properties definition is executed during collection stage. Tests are executed after collection stage is finished. So if accounts
in your case are filled somewhere else in code (e.g. in autouse fixture or other test) it will not be accessible during pytest's collection stage.
May be you can provide some more details about your case. How are you generating this accounts in your successful case?
UPD:
According to eth-brownie
package source code using brownie test
is executing pytest
with enabled pytest-brownie
plugin like this:
pytest.main(pytest_args, ["pytest-brownie"])
So this plugin declares some hooks.
One of them is pytest_collection_finish
which is declared in PytestBrownieRunner
class. This class is used as plugin constructor during 1 thread test execution. According to pytest docs, this hook is called after all test are collected.
This hook executes following code:
if not outcome.get_result() and session.items and not brownie.network.is_connected():
brownie.network.connect(CONFIG.argv["network"])
I believe here it is adding information about your configured network including accounts.
So here is the difference:
When you try to reach accounts
during tests - code above has been already executed.
However, when you try to reach accounts
during class definition - no hooks have been executed yet, so there is no information about your network.
May be I am wrong but I assume your issue is related to order of pytest execution stages.