test_cli.py (2118B)
1 # File: test_cli.py 2 # Created Date: Saturday July 27th 2024 3 # Author: Steven Atkinson (steven@atkinson.mn) 4 5 import importlib 6 import os 7 from pathlib import Path 8 9 import pytest 10 11 12 def test_extensions(): 13 """ 14 Test that we can use a simple extension. 15 """ 16 # DRY: Make sure this matches the code! 17 home_path = os.environ["HOMEPATH"] if os.name == "nt" else os.environ["HOME"] 18 extensions_path = os.path.join(home_path, ".neural-amp-modeler", "extensions") 19 20 def get_name(): 21 i = 0 22 while True: 23 basename = f"test_extension_{i}.py" 24 path = Path(extensions_path, basename) 25 if not path.exists(): 26 return path 27 else: 28 i += 1 29 30 path = get_name() 31 path.parent.mkdir(parents=True, exist_ok=True) 32 33 try: 34 # Make the extension 35 # It's going to set an attribute inside nam.core. We'll know the extension worked if 36 # that attr is set. 37 attr_name = "my_test_attr" 38 attr_val = "THIS IS A TEST ATTRIBUTE I SHOULDN'T BE HERE" 39 with open(path, "w") as f: 40 f.writelines( 41 [ 42 'print("RUNNING TEST!")\n', 43 "from nam.train import core\n", 44 f'name = "{attr_name}"\n', 45 "assert not hasattr(core, name)\n" 46 f'setattr(core, name, "{attr_val}")\n', 47 ] 48 ) 49 50 # Now trigger the extension by importing the CLI module: 51 from nam import cli 52 53 # If some other test already imported this, then we need to trigger a re-load or 54 # else the extension won't get picked up! 55 importlib.reload(cli) 56 57 # Now let's have a look: 58 from nam.train import core 59 60 assert hasattr(core, attr_name) 61 assert getattr(core, attr_name) == attr_val 62 finally: 63 if path.exists(): 64 path.unlink() 65 # You might want to comment that .unlink() and uncomment this if this test isn't 66 # passing and you're struggling: 67 # pass 68 69 70 if __name__ == "__main__": 71 pytest.main()