Using nf_autoid Encoding in Test Files
Summary
While we successfully implemented support for the nf_autoid encoding in test files through pytest hooks in conftest.py, it's challenging to get it working reliably due to conflicts with pytest's assertion rewriting mechanism.
Current Approach
For testing preprocessor functionality, we recommend calling preprocess_source() directly in tests to simulate what the codec would produce. This provides complete control and avoids conflicts with pytest's internals.
Example Test Pattern
from nf.codec.autoid.preprocessor import preprocess_source
def test_preprocessor_behavior():
source = """
from nf.core import Bind
from nf.core.constructs.resources import Resource
vpc: Bind = Resource(nf_type="aws_vpc")
"""
processed = preprocess_source(source)
# Verify IDs were injected
assert 'vpc = Resource(nf_type="aws_vpc", nf_id="vpc")' in processed
test_preprocessor_behavior()
Why Direct Encoding Support is Challenging
-
Pytest Assertion Rewriting: Pytest rewrites test files to provide better assertion messages. This conflicts with custom encodings.
-
Import Order: Pytest imports test modules in a specific way that makes it difficult to intercept and preprocess.
-
Module Caching: Python's import system caches modules, making it hard to ensure preprocessed versions are used.
Attempted Solutions
We tried several approaches in conftest.py:
- Custom module loader with
pytest_pycollect_makemodulehook - Temporary file generation with preprocessed content
- Disabling assertion rewriting for encoded files
While these partially work, they're fragile and can cause unexpected issues.
Recommendation
Use the direct preprocessing approach shown above for testing preprocessor functionality. This approach:
- Is explicit and easy to understand
- Works reliably with all pytest features
- Allows testing specific edge cases
- Doesn't require modifying pytest's internals
The comprehensive test suites in test_preprocessor_integration.py and test_preprocessor_autoscope.py demonstrate this approach effectively.