-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
How can I use global variables through tests? #3118
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
for each function you set it back to 100 in the setup, then increment it by 1 so its doing exactly what you told it to |
Every time a fixture is requested in a test ( Fixtures are meant to avoid using global variables in the first place, they are meant to provide resources to test functions that are isolated and particular for each test. You can update your code as follows: import pytest
pytest.global_variable_1 = 100
def test_1():
pytest.global_variable_1 +=1
print(pytest.global_variable_1)
def test_2():
pytest.global_variable_1 +=1
print(pytest.global_variable_1)
def test_3():
pytest.global_variable_1 +=1
print(pytest.global_variable_1) This will behave like you expect it to. Disclaimer: using global variables in general (and in testing in particular) is generally a bad idea(tm); if you look it up you will find dozens of posts/articles explaining why this is bad in general. |
Thank u! |
@nicoddemus I just ran into this problem and I have a question on the declarations of variables in pytest like this... For example, if I am running several modules in a pytest session, can tests on other modules access this variable? And if they can, is there a way of making this variable global only for the module? Thanks in advance! |
For all session (for all tests in file) |
Yeah, right... But what if my session is composed by several different files? Would every test in every file have access to that variable? Or only the tests on the file that I declared this variable have access to it? |
I think it will be applied for all .py file. But, not sure at 100%, just try and you will know^) |
Thanks for your help @UANEMESIS ... I tested this declaration in different files containing tests and it I concluded that when using a declaration like So I guess that this declaration is indeed dangerous to use. That is why people consider using this as a bad practice. |
``
This seems to be deprecated now, isn't it ? @RonnyPfannschmidt @nicoddemus |
For the entire session, but there's nothing special about
Not sure I understand the question, what do you mean by "this" in this context? |
In my example:
Global variable pytest.global_variable works only in test_1. output:
101
101
101
What do I wrong in?
The text was updated successfully, but these errors were encountered: