global-stub
A test replaces a library function by assigning to it.
- Group
- Tests
- Runs
- On by default
- Level
- note
- Reads
- Tests
- Fix
- None: whether the code takes the function as a parameter is the author's to say
- Defends
- Resilience: the test fails only when the code is broken.
Why
The test assigns to a function or value of a module it imports, or of a built-in, which changes it for every test that runs after in the same process and is never put back.
The fix, as Ur suggests it: pass the replacement as a parameter, or patch it with the framework so it is restored.
For agents
Never replace a library function by assigning to it in a test; pass the replacement to the code under test, or use the framework's patching, which restores it.
Example
shop/files.pyimport os
def count_files(directory):
return len(os.listdir(directory))
tests/test_files.pyimport os
from shop.files import count_files
def test_counts_the_files_of_a_directory():
os.listdir = lambda directory: ["a.txt", "b.txt"]
assert count_files("/data") == 2
$ ur lint --rule global-stub
note[global-stub]: test `test_counts_the_files_of_a_directory` replaces `os.listdir` by assigning to it, which changes it for every test that runs after
--> ./tests/test_files.py:7:5 test `test_counts_the_files_of_a_directory`
= hint: pass the replacement as a parameter, or patch it with the framework so it is restored
= see: TotT: Better Stubbing in Python, Google Testing Blog (2007-01-24), https://testing.googleblog.com/2007/01/better-stubbing-in-python.html
0 clone classes and 1 test finding in 2 files
Source
TotT: Better Stubbing in Python, Google Testing Blog (2007-01-24).