如果您自己製作Ansible模塊,可以試著進行sanity測試

这里将总结一下在创建自己的Ansible模块时的测试方法。在这里,我只会写关于sanity测试的方法。sanity测试是一种进行静态分析的测试。它会检查诸如PEP8是否合规,是否已加载所需模块等内容。

环境

項目バージョンOSCentOS7.5Python3.6.6Ansibledevel

2. 测试用文件

以下是用于测试Ansible模块的文档。

    • https://docs.ansible.com/ansible/latest/dev_guide/developing_modules_general.html

 

    https://docs.ansible.com/ansible/latest/dev_guide/testing_sanity.html

3. 制作完成的模块 de

为了执行测试,我创建了一个简单的模块。
以下是一个只返回指定字符串的字典的模块。

#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright: (c) 2018, sky_joker
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function
__metaclass__ = type


ANSIBLE_METADATA = {
    'metadata_version': '1.1',
    'status': ['preview'],
    'supported_by': 'community'
}


DOCUMENTATION = '''
module: output_name
short_description: module that outputs a name.
author:
    - sky_joker (@sky-joker)
version_added: 2.x
description:
    - Output the specified name.
requirements:
    - python >= 2.7
options:
    name:
        description:
            - Specify name.
        required: True
'''

EXAMPLES = '''
---
- output_name:
    name: taro
  register: r

- debug: msg="{{ r }}"
'''

from ansible.module_utils.basic import AnsibleModule


def main():
    argument_spec = dict(
        name=dict(type="str", required=True)
    )

    module = AnsibleModule(argument_spec, supports_check_mode=True)

    result = dict(changed=False)

    name = module.params['name']
    if(name):
        result['name'] = name
        module.exit_json(**result)
    else:
        module.fail_json(msg="Please specify name.")


if __name__ == "__main__":
    main()

4. 考试准备

4-1. 克隆存储库

由于测试工具位于 Ansible 存储库中,因此我们将进行克隆。

[example@localhost ~]$ git clone https://github.com/ansible/ansible.git

创建虚拟环境venv。

为了进行测试,我将安装一个模块并创建venv。

[example@localhost ~]$ cd ansible/
[example@localhost ansible]$ python36 -m venv venv

4-3. 安装必要的模块。

由于只使用requirements.txt中列出的内容是不够的,因此需要额外安装模块。
由于分开了用于sanity的模块,所以需要安装在test/runner/requirements/sanity.txt中列出的模块。

[example@localhost ansible]$ source venv/bin/activate
(venv) [example@localhost ansible]# pip install -r test/runner/requirements/sanity.txt

进行考试。

我将进行测试。
现在是目前的路径。

(venv) [example@localhost ansible]$ pwd
/home/example/ansible
(venv) [example@localhost ansible]$ ls
CODING_GUIDELINES.md  MANIFEST.in           Makefile    bin         contrib  examples  lib       packaging         setup.py       test     venv
COPYING               MODULE_GUIDELINES.md  README.rst  changelogs  docs     hacking   licenses  requirements.txt  shippable.yml  tox.ini

将在ansible目录中执行测试。
原因是ansible-test(测试工具)正在使用相对路径读取当前的lib模块。
我们将使用output_name.py尝试创建一个文件。

如果执行 env-setup ,路径将被自动设置。

(venv) [example@localhost ansible]# . hacking/env-setup

制作测试用模块。

(venv) [example@localhost ansible]# mkdir lib/ansible/modules/salf-made
(venv) [example@localhost ansible]# touch lib/ansible/modules/salf-made/__init__.py
(venv) [example@localhost ansible]$ vi lib/ansible/modules/salf-made/output_name.py
コードを貼り付け

执行测试。
由于使用的是Python 3.6,因此需要指定版本。
跳过symlinks的原因是因为存在符号链接会导致处理失败。venv文件夹下有一个名为lib64的符号链接,因此处理一定会失败。考虑到这个问题不会造成特别大的影响,我们将其禁用。

(venv) [example@localhost ansible]# ansible-test sanity --skip-test symlinks --python 3.6 lib/ansible/modules/salf-made/output_name.py
WARNING: Skipping tests disabled by default without --allow-disabled: docs-build
Sanity check using ansible-doc with Python 3.6
Sanity check using azure-requirements
Sanity check using boilerplate
Sanity check using botmeta
Sanity check using changelog
Sanity check using compile with Python 3.6
Sanity check using configure-remoting-ps1
Sanity check using empty-init
Sanity check using import with Python 3.6
Sanity check using integration-aliases
Sanity check using line-endings
Sanity check using no-assert
Sanity check using no-basestring
Sanity check using no-dict-iteritems
Sanity check using no-dict-iterkeys
Sanity check using no-dict-itervalues
Sanity check using no-get-exception
Sanity check using no-illegal-filenames
Sanity check using no-smart-quotes
Sanity check using no-tests-as-filters
Sanity check using no-underscore-variable
Sanity check using no-unicode-literals
Sanity check using pep8
Sanity check using pslint
Sanity check using pylint
Sanity check using replace-urlopen
Sanity check using required-and-default-attributes
Sanity check using rstcheck
Sanity check using sanity-docs
Sanity check using shebang
Sanity check using shellcheck
Sanity check using test-constraints
Sanity check using use-argspec-type-path
Sanity check using use-compat-six
Sanity check using validate-modules
WARNING: Cannot perform module comparison against the base branch. Base branch not detected when running locally.
Sanity check using yamllint
WARNING: Reviewing previous 2 warning(s):
WARNING: Skipping tests disabled by default without --allow-disabled: docs-build
WARNING: Cannot perform module comparison against the base branch. Base branch not detected when running locally.

如果你想对ansible-doc进行测试,可以按照以下方式操作。

(venv) [example@localhost ansible]# ansible-doc -v output_name
No config file found; using defaults
> OUTPUT_NAME    (/root/ansible/lib/ansible/modules/salf-made/output_name.py)

        Output the specified name.

OPTIONS (= is mandatory):

= name
        Specify name.



REQUIREMENTS:  python >= 2.7

AUTHOR: sky_jokerxx
        METADATA:
          status:
          - preview
          supported_by: community


EXAMPLES:
---
- output_name:
    name: taro
  register: r

- debug: msg="{{ r }}"

现在,能够进行自制Ansible模块的静态检查了。
由于没有发生错误,所以没问题 🙂
因为在官方文档中也写了使用docker的方法,所以可以结合SCM进行CI。
一旦实现了CI,我会再次尝试写关于sanity的文章。
这次我总结了几个测试中与sanity相关的内容。

6. 补充完整

您可以通过 Sanity 运行的测试可以以以下方式进行列表显示。

(venv) [example@localhost ansible]$ ansible-test sanity --list-test
WARNING: Skipping tests disabled by default without --allow-disabled: docs-build
ansible-doc
azure-requirements
boilerplate
botmeta
changelog
compile
configure-remoting-ps1
empty-init
import
integration-aliases
line-endings
no-assert
no-basestring
no-dict-iteritems
no-dict-iterkeys
no-dict-itervalues
no-get-exception
no-illegal-filenames
no-smart-quotes
no-tests-as-filters
no-underscore-variable
no-unicode-literals
pep8
pslint
pylint
replace-urlopen
required-and-default-attributes
rstcheck
sanity-docs
shebang
shellcheck
symlinks
test-constraints
use-argspec-type-path
use-compat-six
validate-modules
yamllint
WARNING: Reviewing previous 1 warning(s):
WARNING: Skipping tests disabled by default without --allow-disabled: docs-build
bannerAds