如何在Yaml文件引用其餘Yaml文件(使用python Pyyaml)

 

背景: 項目中有多個測試用例,測試用例使用yaml的配置文件,各個測試用例的yaml配置文件中有一些共有的屬性,node

把這些共有的屬性抽取出來放在一個yaml文件中,問題來了:如何在測試用例的Yaml文件引用這些共享的Yaml文件:python

 

測試用例的yaml文件:document.ymlweb

languages:
- Ruby
- Perl
- Python
websites:
YAML: yaml.org
Ruby: ruby-lang.org
Python: python.org
Perl: use.perl.org

test: !include
doc01.yml


共享的yaml文件: doc01.ymlruby

demo01:
- Ruby

 

python實現:測試

import yaml
import os


def yaml_include(loader, node):
# Get the path out of the yaml file
file_name = os.path.join(os.path.dirname(loader.name), node.value)

with file(file_name) as inputfile:
return yaml.load(inputfile)

yaml.add_constructor("!include", yaml_include)
stream = file('document.yml', 'r')
print yaml.dump(yaml.load(stream))






打印結果:

languages: [Ruby, Perl, Python]
test:
  demo01: [Ruby]
websites: {Perl: use.perl.org, Python: python.org, Ruby: ruby-lang.org, YAML: yaml.org}
相關文章
相關標籤/搜索