Heesung Yang

[Python] pytest 팁

임시 파일 사용하기

  • config_manager.py

    import json
    
    class ConfigManager:
        def __init__(self, file_path):
            with open(file_path, 'r') as f:
                config = json.load(f)
    
                for k, v in config.items():
                    setattr(self, k, v)
    
  • test_config_manager.py

    import json
    import pytest
    
    @pytest.fixture(scope="session")
    def config_file(tmp_path_factory):
        config = {
            "setting": 1,
        }
        dir = tmp_path_factory.mktemp("config")
        config_file = dir / "config_file.json"
        with open(config_file, "w") as f:
            json.dump(config, f)
    
        return config_file
    
    def test_load_migrated_config(config_file):
        config = ConfigManager(file_path=config_file)
        assert config.setting == 1
    

디버깅 모드로 실행하기

  • test_config_manager.py

    import json
    import pytest
    def test_load_migrated_config(config_file):
        pytest.set_trace()       # 추가. 이 부분부터 한 단계씩 진행하며 디버깅 가능
        config = ConfigManager(file_path=config_file)
        assert config.setting == 1