简单的配置管理器,可以很好地进行测试
config的Python项目详细描述
简单的配置管理器,很好地进行测试。
基本用法
从pypi安装:
pip install configy
尽可能早地指定配置指令:
importconfigytry:# Every option is optional, fill in as makes sense.configy.load_config(conf='the_configuration.yaml',# The default config file if not specified as an ENV varenv='CONFIGY_FILE',# The ENV var to look for a config filedefaults='defaults.yaml',# The defaults that is always loaded.data={'manual':'defaults'},# Manually provided defaults loadedcase_sensitive=True# Case Sensitive by default)exceptconfigy.ConfigyErrorase:# Report config load error to user
给定示例yaml配置文件:
Something:value:The Valuenumber:42bool1:1bool2:FALSEbool3:y
然后使用它:
>>>fromconfigyimportconfig>>>config.Something.value'The Value'
如果您尝试访问任何未定义的配置值,将出现异常:
>>>config.Something.otherTraceback(mostrecentcalllast):File"<stdin>",line1,in<module>KeyError:'other'
config对象只是一个字典,因此您也可以将其用作常规字典:
>>>config['Something']['value']'The Value'>>>config.Something.get('other','default value')'default value'
帮助函数
由于无法保证配置文件中的值的类型(yaml将所有内容都视为文本),因此需要手动进行类型转换。
对于int和float,这很简单:
>>>int(config.Something.number)42>>float(config.Something.number)42.0
对于布尔值来说,这有点复杂,因为布尔值可以用许多不同的符号表示。你也不能完全控制使用的符号。为此,我们提供了一个to_bool()helper函数。
它不敏感地处理案例
- True
- 'y'、'yes'、'1'、't'、'true'
- False
- 'n'、'no'、'0'、'f'、'false'
任何其他操作都将使用提供的默认值(默认值为false)
>>>fromconfigyimportconfig,to_bool>>>to_bool(config.Something.bool1)True>>>to_bool(config.Something.bool2)False>>>to_bool(config.Something.bool1)True>>>to_bool(config.Something.number)False>>>to_bool(config.Something.number,True)True>>>to_bool(config.Something.number,None)None
如何重载测试设置
在测试过程中,人们经常希望覆盖一些配置来测试特定的东西。 configy支持此用例。
fromconfigyimportconfig,testconfig@testconfig.override_config({'Something':{'other':'I now exist',},'Extra':'defined',})deftest_override():# Existing values still work as per usualassertconfig.Something.value=='The Value'# New valuesassertconfig.Something.other=='I now exist'assertconfig.Extra=='defined'
还可以定义要使用的配置:
@testconfig.load_config(conf='test_config.yaml')deftest_load_config():assertconfig.testvalue=='test result'
您还可以定义为该测试加载的整个配置:
@testconfig.load_config(data={'testvalue':'test result',})deftest_load_config_data():assertconfig.testvalue=='test result'
所有的测试装饰器都将在方法、类和函数级别上工作。