diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py new file mode 100644 index 0000000..eb4a82d --- /dev/null +++ b/tests/unit/test_config.py @@ -0,0 +1,114 @@ +"""Tests for configuration.""" + +import os +import tempfile +from pathlib import Path + +import pytest +import yaml + +from mockapi.core.config import Config, load_config + + +class TestConfig: + """Test cases for Config.""" + + def test_default_values(self): + """Test default configuration values.""" + config = Config() + assert config.port == 8080 + assert config.host == "0.0.0.0" + assert config.delay == 0 + assert config.random_delay is False + assert config.seed == 42 + assert config.validate_requests is True + assert config.validate_responses is False + assert config.strict_validation is False + + def test_load_from_dict(self): + """Test creating config with dict values.""" + config = Config( + port=3000, + host="127.0.0.1", + delay=100, + seed=123, + ) + assert config.port == 3000 + assert config.host == "127.0.0.1" + assert config.delay == 100 + assert config.seed == 123 + + def test_to_dict(self): + """Test converting config to dictionary.""" + config = Config(port=9000, host="localhost") + d = config.to_dict() + assert d["port"] == 9000 + assert d["host"] == "localhost" + assert "delay" in d + assert "seed" in d + + def test_load_from_env(self): + """Test loading config from environment variables.""" + os.environ["MOCKAPI_PORT"] = "5000" + os.environ["MOCKAPI_HOST"] = "127.0.0.1" + os.environ["MOCKAPI_SEED"] = "999" + + config = load_config() + + assert config.port == 5000 + assert config.host == "127.0.0.1" + assert config.seed == 999 + + del os.environ["MOCKAPI_PORT"] + del os.environ["MOCKAPI_HOST"] + del os.environ["MOCKAPI_SEED"] + + def test_load_from_file(self): + """Test loading config from YAML file.""" + config_data = { + "port": 7000, + "host": "0.0.0.0", + "delay": 200, + "random_delay": True, + "seed": 456, + } + + with tempfile.NamedTemporaryFile( + mode="w", suffix=".yaml", delete=False + ) as f: + yaml.dump(config_data, f) + temp_path = f.name + + try: + config = load_config(temp_path) + assert config.port == 7000 + assert config.host == "0.0.0.0" + assert config.delay == 200 + assert config.random_delay is True + assert config.seed == 456 + finally: + os.unlink(temp_path) + + def test_env_overrides_file(self): + """Test that environment variables override file config.""" + config_data = {"port": 7000, "host": "0.0.0.0"} + + with tempfile.NamedTemporaryFile( + mode="w", suffix=".yaml", delete=False + ) as f: + yaml.dump(config_data, f) + temp_path = f.name + + os.environ["MOCKAPI_PORT"] = "9000" + + try: + config = load_config(temp_path) + assert config.port == 9000 + finally: + os.unlink(temp_path) + del os.environ["MOCKAPI_PORT"] + + def test_load_config_default_path(self): + """Test load_config with no arguments.""" + config = load_config() + assert isinstance(config, Config)