1
0
mirror of https://github.com/ansible/mazer.git synced 2026-02-05 12:45:17 +01:00

Removes init command (#146)

This commit is contained in:
Chris Houseknecht
2018-09-25 13:11:18 -04:00
committed by GitHub
parent 1137e880c7
commit 2e2b9ebd4e
77 changed files with 15 additions and 866 deletions

View File

@@ -1,65 +0,0 @@
import logging
import os
import re
import shutil
from jinja2 import Environment, FileSystemLoader
log = logging.getLogger(__name__)
def init(role_name,
init_path,
role_path,
force,
role_skeleton_path,
skeleton_ignore_expressions,
role_type,
display_callback=None):
# FIXME(akl): role_skeleton stuff should probably be a module or two and a few classes instead of inline here
# role_skeleton ends mostly being a list of file paths to copy
inject_data = dict(
role_name=role_name,
)
import pprint
log.debug('inject_data: %s', pprint.pformat(inject_data))
if not os.path.exists(role_path):
os.makedirs(role_path)
role_skeleton = os.path.expanduser(role_skeleton_path)
log.debug('role_skeleton: %s', role_skeleton)
skeleton_ignore_re = [re.compile(x) for x in skeleton_ignore_expressions]
template_env = Environment(loader=FileSystemLoader(role_skeleton))
for root, dirs, files in os.walk(role_skeleton, topdown=True):
rel_root = os.path.relpath(root, role_skeleton)
in_templates_dir = rel_root.split(os.sep, 1)[0] == 'templates'
dirs[:] = [d for d in dirs if not any(r.match(d) for r in skeleton_ignore_re)]
for f in files:
filename, ext = os.path.splitext(f)
if any(r.match(os.path.join(rel_root, f)) for r in skeleton_ignore_re):
continue
elif ext == ".j2" and not in_templates_dir:
src_template = os.path.join(rel_root, f)
dest_file = os.path.join(role_path, rel_root, filename)
template_env.get_template(src_template).stream(inject_data).dump(dest_file)
else:
f_rel_path = os.path.relpath(os.path.join(root, f), role_skeleton)
log.debug('copying %s to %s',
os.path.join(root, f), os.path.join(role_path, f_rel_path))
shutil.copyfile(os.path.join(root, f), os.path.join(role_path, f_rel_path))
for d in dirs:
dir_path = os.path.join(role_path, rel_root, d)
if not os.path.exists(dir_path):
os.makedirs(dir_path)
display_callback("- %s was created successfully" % role_name)
return 0

View File

@@ -31,7 +31,6 @@ from ansible_galaxy_cli import cli
from ansible_galaxy_cli import __version__ as galaxy_cli_version
from ansible_galaxy.actions import build
from ansible_galaxy.actions import info
from ansible_galaxy.actions import init
from ansible_galaxy.actions import install
from ansible_galaxy.actions import list as list_action
from ansible_galaxy.actions import remove
@@ -75,7 +74,7 @@ def get_config_path_from_env():
class GalaxyCLI(cli.CLI):
SKIP_INFO_KEYS = ("name", "description", "readme_html", "related", "summary_fields", "average_aw_composite", "average_aw_score", "url")
VALID_ACTIONS = ("build", "info", "init", "install", "list", "remove", "version")
VALID_ACTIONS = ("build", "info", "install", "list", "remove", "version")
VALID_ACTION_ALIASES = {'content-install': 'install'}
def __init__(self, args):
@@ -95,17 +94,6 @@ class GalaxyCLI(cli.CLI):
if self.action == "info":
self.parser.set_usage("usage: %prog info [options] repo_name[,version]")
elif self.action == "init":
self.parser.set_usage("usage: %prog init [options] collection name")
self.parser.add_option('-p', '--path', dest='init_path', default="./",
help='The path in which the collection will be created. Defaults to the current working directory.')
self.parser.add_option('-t', '--type', dest='artifact_type', action='store', default='collection',
choices=['apb', 'collection', 'role'],
help="Initialize using an alternate format. Valid types include: 'apb', 'collection' and 'role'.")
self.parser.add_option('--skeleton', dest='skeleton', default=None,
help='The path to a skeleton that the new collection should be based upon.')
elif self.action == "install":
self.parser.set_usage("usage: %prog install [options] [-r FILE | repo_name(s)[,version] | scm+repo_url[,version] | tar_file(s)]")
self.parser.add_option('-g', '--global', dest='global_install', action='store_true',
@@ -127,17 +115,17 @@ class GalaxyCLI(cli.CLI):
self.parser.set_usage("usage: %prog version")
# options that apply to more than one action
if self.action in ['init', 'info']:
if self.action in ("info",):
self.parser.add_option('--offline', dest='offline', default=False, action='store_true', help="Prevent Mazer from calling the galaxy API.")
if self.action not in ("init", "version"):
if self.action not in ("version",):
# NOTE: while the option type=str, the default is a list, and the
# callback will set the value to a list.
self.parser.add_option('-C', '--content-path', dest='content_path',
help='The path to the directory containing your Galaxy content. The default is the content_path configured in your'
'mazer.yml file (~/.ansible/content, if not configured)', type='str')
if self.action in ("init", "install"):
if self.action in ("install",):
self.parser.add_option('-f', '--force', dest='force', action='store_true', default=False, help='Force overwriting an existing collection')
def parse(self):
@@ -239,43 +227,6 @@ class GalaxyCLI(cli.CLI):
build_context,
display_callback=self.display)
def execute_init(self):
"""
Create a skeleton collection
"""
init_path = self.options.init_path
force = self.options.force
skeleton_path = self.options.skeleton
type_path = self.options.artifact_type
skeleton_ignore = ['^.*/.gitkeep$']
artifact_name = self.args.pop(0).strip() if self.args else None
if not artifact_name:
raise cli_exceptions.CliOptionsError("- no collection name specified for init")
artifact_path = os.path.join(init_path, artifact_name)
if os.path.exists(artifact_path):
if os.path.isfile(artifact_path):
raise cli_exceptions.GalaxyCliError("- the path %s already exists, but is a file - aborting" % artifact_path)
elif not force:
raise cli_exceptions.GalaxyCliError("- the directory %s already exists."
"Use --force to overwrite the existing directory." % artifact_path)
if not skeleton_path:
this_dir, _ = os.path.split(__file__)
skeleton_path = os.path.join(this_dir, '../', 'data/skeleton', type_path)
self.log.debug('skeleton_path: %s', skeleton_path)
return init.init(artifact_name,
init_path,
artifact_path,
force,
skeleton_path,
skeleton_ignore,
self.options.artifact_type,
display_callback=self.display)
def execute_info(self):
"""
Display detailed information about an installed collection, as well as info available from the Galaxy API.

View File

@@ -1,25 +0,0 @@
---
services: docker
sudo: required
language: python
python:
- '2.7'
env:
- OPENSHIFT_VERSION=v3.9.0
- KUBERNETES_VERSION=v1.9.0
script:
# Configure test values
- export apb_name=APB_NAME
# Download test shim.
- wget -O ${PWD}/apb-test.sh https://raw.githubusercontent.com/ansibleplaybookbundle/apb-test-shim/master/apb-test.sh
- chmod +x ${PWD}/apb-test.sh
# Run tests.
- ${PWD}/apb-test.sh
# Uncomment to allow travis to notify galaxy
# notifications:
# webhooks: https://galaxy.ansible.com/api/v1/notifications/

View File

@@ -1,8 +0,0 @@
FROM ansibleplaybookbundle/apb-base
LABEL "com.redhat.apb.spec"=\
COPY playbooks /opt/apb/actions
COPY . /opt/ansible/roles/{{ role_name }}
RUN chmod -R g=u /opt/{ansible,apb}
USER apb

View File

@@ -1,21 +0,0 @@
DOCKERHOST = DOCKERHOST
DOCKERORG = DOCKERORG
IMAGENAME = {{ role_name }}
TAG = latest
USER=$(shell id -u)
PWD=$(shell pwd)
build_and_push: apb_build docker_push apb_push
.PHONY: apb_build
apb_build:
docker run --rm --privileged -v $(PWD):/mnt:z -v $(HOME)/.kube:/.kube -v /var/run/docker.sock:/var/run/docker.sock -u $(USER) docker.io/ansibleplaybookbundle/apb-tools:latest prepare
docker build -t $(DOCKERHOST)/$(DOCKERORG)/$(IMAGENAME):$(TAG) .
.PHONY: docker_push
docker_push:
docker push $(DOCKERHOST)/$(DOCKERORG)/$(IMAGENAME):$(TAG)
.PHONY: apb_push
apb_push:
docker run --rm --privileged -v $(PWD):/mnt:z -v $(HOME)/.kube:/.kube -v /var/run/docker.sock:/var/run/docker.sock -u $(USER) docker.io/ansibleplaybookbundle/apb-tools:latest push

View File

@@ -1,31 +0,0 @@
# {{ role_name }}
A brief description of the APB goes here.
## Requirements
Any pre-requisites that may not be covered by Ansible itself or the role should be mentioned here. For instance, if the role uses the EC2 module, it may be a good idea to mention in this section that the boto package is required.
## APB Variables
A description of the settable variables for this APB should go here, including any variables that are in defaults/main.yml, vars/main.yml, apb.yml, and any variables that can/should be set via parameters to the role. Any variables that are read from other roles and/or the global scope (i.e. hostvars, group vars, etc.) should be mentioned here as well.
## Dependencies
A list of other APBs/roles hosted on Galaxy should go here, plus any details in regards to parameters that may need to be set for other roles, or variables that are used from other roles.
## Example Playbook
Including an example of how to use your APB (for instance, with variables passed in as parameters) is always nice for users too:
- hosts: servers
roles:
- { role: username.rolename, x: 42 }
## License
Apache-2.0
## Author Information
An optional section for the role authors to include contact information, or a website (HTML is not allowed).

View File

@@ -1,13 +0,0 @@
version: '1.0.0'
name: {{ role_name }}
description: {{ description }}
bindable: False
async: optional
metadata:
displayName: {{ role_name }}
plans:
- name: default
description: This default plan deploys {{ role_name }}
free: True
metadata: {}
parameters: []

View File

@@ -1,2 +0,0 @@
---
# defaults file for {{ role_name }}

View File

@@ -1,2 +0,0 @@
---
# handlers file for {{ role_name }}

View File

@@ -1,67 +0,0 @@
metadata_format_version: 2.0
galaxy_info:
author: Your name
description: A description of the APB
company: Your company
# Override the Galaxy role name
# role_name: {{ role_name }}
# If the issue tracker for your role is not on github, uncomment the
# next line and provide a value
# issue_tracker_url: 'http://example.com/issue/tracker'
# Provide a valid short identifier from the SPDX license list https://spdx.org/licenses/
# Examples include:
# - BSD-2-Clause-FreeBSD
# - MIT
# - GPL-2.0-only
# - GPL-3.0-or-later
# - Apache-2.0
# - CC-BY-4.0
license: Apache-2.0
min_ansible_version: 2.4
# If this a Container Enabled role, provide the minimum Ansible Container version.
# min_ansible_container_version:
# Provide a list of supported platforms, and for each platform a list of versions.
# If you don't wish to enumerate all versions for a particular platform, use 'all'.
# To view available platforms and versions (or releases), visit:
# https://galaxy.ansible.com/api/v1/platforms/
#
# Examples include:
#
# platforms:
# - name: Fedora
# versions:
# - all
# - name: Ubuntu
# versions:
# - artful
# - bionic
# - cuttlefish
platforms:
# Provide an optional list of supported cloud platforms. For a list of valid
# cloud platforms, visit: https://galaxy.ansible.com/api/v1/cloud_platforms/
#
# cloud_platforms:
# - amazon
# - azure
# - gce
# List tags for your role here, one per line. A tag is a keyword that describes
# and categorizes the role. Users find roles by searching for tags.
#
# NOTE: A tag is limited to a single word comprised of alphanumeric characters.
# Maximum 20 tags per role.
galaxy_tags:
- apb
# List your role dependencies here, one per line. Be sure to remove the '[]',
# if you add dependencies to this list.
dependencies: []

View File

@@ -1,8 +0,0 @@
- name: {{ role_name }} playbook to deprovision the application
hosts: localhost
gather_facts: false
connection: local
vars:
apb_action: deprovision
roles:
- role: {{ role_name }}

View File

@@ -1,8 +0,0 @@
- name: {{ role_name }} playbook to provision the application
hosts: localhost
gather_facts: false
connection: local
vars:
apb_action: provision
roles:
- role: {{ role_name }}

View File

@@ -1,2 +0,0 @@
---
# tasks file for {{ role_name }}

View File

@@ -1,2 +0,0 @@
[defaults]
inventory=./inventory

View File

@@ -1,3 +0,0 @@
localhost

View File

@@ -1,8 +0,0 @@
---
- hosts: localhost
gather_facts: no
connection: local
tasks:
# Add tasks and assertions for testing the service here.

View File

@@ -1,3 +0,0 @@
---
# vars file for {{ role_name }}

View File

@@ -1,29 +0,0 @@
---
language: python
python: "2.7"
# Use the new container infrastructure
sudo: false
# Install ansible
addons:
apt:
packages:
- python-pip
install:
# Install ansible
- pip install ansible
# Check ansible version
- ansible --version
# Create ansible.cfg with correct roles_path
- printf '[defaults]\nroles_path=../' >ansible.cfg
script:
# Basic role syntax check
- ansible-playbook tests/test.yml -i tests/inventory --syntax-check
notifications:
webhooks: https://galaxy.ansible.com/api/v1/notifications/

View File

@@ -1,31 +0,0 @@
# {{ role_name }}
A brief description of the role goes here.
## Requirements
Any pre-requisites that may not be covered by Ansible itself or the role should be mentioned here. For instance, if the role uses the EC2 module, it may be a good idea to mention in this section that the boto package is required.
## Role Variables
A description of the settable variables for this role should go here, including any variables that are in defaults/main.yml, vars/main.yml, and any variables that can/should be set via parameters to the role. Any variables that are read from other roles and/or the global scope (ie. hostvars, group vars, etc.) should be mentioned here as well.
## Dependencies
A list of other roles hosted on Galaxy should go here, plus any details in regards to parameters that may need to be set for other roles, or variables that are used from other roles.
## Example Playbook
Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too:
- hosts: servers
roles:
- { role: username.rolename, x: 42 }
## License
Apache-2.0
## Author Information
An optional section for the role authors to include contact information, or a website (HTML is not allowed).

View File

@@ -1,2 +0,0 @@
---
# defaults file for {{ role_name }}

View File

@@ -1,2 +0,0 @@
---
# handlers file for {{ role_name }}

View File

@@ -1,66 +0,0 @@
metadata_format_version: 2.0
galaxy_info:
author: Your name
description: A description of the role
company: Your company
# Override the Galaxy role name
# role_name: {{ role_name }}
# If the issue tracker for your role is not on github, uncomment the
# next line and provide a value
# issue_tracker_url: 'http://example.com/issue/tracker'
# Provide a valid short identifier from the SPDX license list https://spdx.org/licenses/
# Examples include:
# - BSD-2-Clause-FreeBSD
# - MIT
# - GPL-2.0-only
# - GPL-3.0-or-later
# - Apache-2.0
# - CC-BY-4.0
license: Apache-2.0
min_ansible_version: 2.4
# If this a Container Enabled role, provide the minimum Ansible Container version.
# min_ansible_container_version:
# Provide a list of supported platforms, and for each platform a list of versions.
# If you don't wish to enumerate all versions for a particular platform, use 'all'.
# To view available platforms and versions (or releases), visit:
# https://galaxy.ansible.com/api/v1/platforms/
#
# Examples include:
#
# platforms:
# - name: Fedora
# versions:
# - all
# - name: Ubuntu
# versions:
# - artful
# - bionic
# - cuttlefish
platforms:
# Provide an optional list of supported cloud platforms. For a list of valid
# cloud platforms, visit: https://galaxy.ansible.com/api/v1/cloud_platforms/
#
# cloud_platforms:
# - amazon
# - azure
# - gce
# List tags for your role here, one per line. A tag is a keyword that describes
# and categorizes the role. Users find roles by searching for tags. Be sure to
# remove the '[]', if you add tags to this list.
#
# NOTE: A tag is limited to a single word comprised of alphanumeric characters.
# Maximum 20 tags per role.
galaxy_tags: []
# List your role dependencies here, one per line. Be sure to remove the '[]',
# if you add dependencies to this list.
dependencies: []

View File

@@ -1,2 +0,0 @@
---
# tasks file for {{ role_name }}

View File

@@ -1,2 +0,0 @@
localhost

View File

@@ -1,5 +0,0 @@
---
- hosts: localhost
remote_user: root
roles:
- {{ role_name }}

View File

@@ -1,2 +0,0 @@
---
# vars file for {{ role_name }}

View File

@@ -1,40 +0,0 @@
import logging
import pytest
from ansible_galaxy.actions import init
log = logging.getLogger(__name__)
def display_callback(msg, **kwargs):
log.debug(msg)
role_types = \
[
'default',
'apb',
]
@pytest.fixture(scope='module',
params=role_types)
def role_type(request):
yield request.param
def test_init(tmpdir, role_type):
role_name = 'test-role'
init_path = tmpdir.mkdir('init_path')
role_path = init_path.join(role_name).strpath
role_skeleton_path = tmpdir.mkdir('role_skeleton').strpath
skeleton_ignore_expressions = []
ret = init.init(role_name,
init_path,
role_path,
False, # force
role_skeleton_path,
skeleton_ignore_expressions,
role_type,
display_callback=display_callback)
assert ret == 0

Binary file not shown.

View File

@@ -1,29 +0,0 @@
---
language: python
python: "2.7"
# Use the new container infrastructure
sudo: false
# Install ansible
addons:
apt:
packages:
- python-pip
install:
# Install ansible
- pip install ansible
# Check ansible version
- ansible --version
# Create ansible.cfg with correct roles_path
- printf '[defaults]\nroles_path=../' >ansible.cfg
script:
# Basic role syntax check
- ansible-playbook tests/test.yml -i tests/inventory --syntax-check
notifications:
webhooks: https://galaxy.ansible.com/api/v1/notifications/

View File

@@ -1,38 +0,0 @@
Role Name
=========
A brief description of the role goes here.
Requirements
------------
Any pre-requisites that may not be covered by Ansible itself or the role should be mentioned here. For instance, if the role uses the EC2 module, it may be a good idea to mention in this section that the boto package is required.
Role Variables
--------------
A description of the settable variables for this role should go here, including any variables that are in defaults/main.yml, vars/main.yml, and any variables that can/should be set via parameters to the role. Any variables that are read from other roles and/or the global scope (ie. hostvars, group vars, etc.) should be mentioned here as well.
Dependencies
------------
A list of other roles hosted on Galaxy should go here, plus any details in regards to parameters that may need to be set for other roles, or variables that are used from other roles.
Example Playbook
----------------
Including an example of how to use your role (for instance, with variables passed in as parameters) is always nice for users too:
- hosts: servers
roles:
- { role: username.rolename, x: 42 }
License
-------
BSD
Author Information
------------------
An optional section for the role authors to include contact information, or a website (HTML is not allowed).

View File

@@ -1,2 +0,0 @@
---
# defaults file for {{ role_name }}

View File

@@ -1,2 +0,0 @@
---
# handlers file for {{ role_name }}

View File

@@ -1 +0,0 @@
localhost

View File

@@ -1,60 +0,0 @@
galaxy_info:
role_name: {{ role_name }}
author: {{ author }}
description: {{ description }}
company: {{ company }}
# If the issue tracker for your role is not on github, uncomment the
# next line and provide a value
# issue_tracker_url: {{ issue_tracker_url }}
# Some suggested licenses:
# - BSD (default)
# - MIT
# - GPLv2
# - GPLv3
# - Apache
# - CC-BY
license: {{ license }}
min_ansible_version: {{ min_ansible_version }}
# Optionally specify the branch Galaxy will use when accessing the GitHub
# repo for this role. During role install, if no tags are available,
# Galaxy will use this branch. During import Galaxy will access files on
# this branch. If travis integration is configured, only notification for this
# branch will be accepted. Otherwise, in all cases, the repo's default branch
# (usually master) will be used.
#github_branch:
#
# platforms is a list of platforms, and each platform has a name and a list of versions.
#
# platforms:
# - name: Fedora
# versions:
# - all
# - 25
# - name: SomePlatform
# versions:
# - all
# - 1.0
# - 7
# - 99.99
galaxy_tags: []
# List tags for your role here, one per line. A tag is
# a keyword that describes and categorizes the role.
# Users find roles by searching for tags. Be sure to
# remove the '[]' above if you add tags to this list.
#
# NOTE: A tag is limited to a single word comprised of
# alphanumeric characters. Maximum 20 tags per role.
dependencies: []
# List your role dependencies here, one per line.
# Be sure to remove the '[]' above if you add dependencies
# to this list.
{%- for dependency in dependencies %}
#- {{ dependency }}
{%- endfor %}

View File

@@ -1,2 +0,0 @@
---
# tasks file for {{ role_name }}

View File

@@ -1,2 +0,0 @@
[defaults]
test_key = {{ test_variable }}

View File

@@ -1,2 +0,0 @@
[defaults]
test_key = {{ test_variable }}

View File

@@ -1,5 +0,0 @@
---
- hosts: localhost
remote_user: root
roles:
- {{ role_name }}

View File

@@ -1,2 +0,0 @@
---
# vars file for {{ role_name }}

View File

@@ -33,7 +33,6 @@ except ImportError:
import unittest
from mock import call, patch
import yaml
# FIXME: shouldn't need to patch object directly
@@ -66,21 +65,19 @@ class TestGalaxy(unittest.TestCase):
if os.path.exists("./delete_me"):
shutil.rmtree("./delete_me")
# creating framework for a role
gc = GalaxyCLI(args=["ansible-galaxy", "init", "--offline", "delete_me", "--type", "role"])
gc.parse()
gc.run()
archive_path = os.path.dirname(os.path.abspath(__file__))
archive_path = os.path.join(archive_path, 'data', 'delete_me.tar.gz')
tar = tarfile.open(archive_path, 'r:gz')
tar.extractall(path=".")
cls.role_dir = "./delete_me"
cls.role_name = "unittest.delete_me"
# add a meta/main.yml
test_dir = os.path.join(cls.role_dir, 'meta')
ensure_dir(test_dir)
fd = open(os.path.join(cls.role_dir, 'meta/main.yml'), 'w')
with open(os.path.join(cls.role_dir, 'meta/main.yml'), 'w') as fd:
fd.write('galaxy_info: {}\ndependencies: {}')
fd.write('galaxy_info: {}\ndependencies: {}')
fd.close()
# making a temp dir for role installation
cls.role_path = os.path.join(tempfile.mkdtemp(), "roles")
@@ -92,16 +89,12 @@ class TestGalaxy(unittest.TestCase):
# creating a temp file with installation requirements
cls.role_req = './delete_me_requirements.yml'
fd = open(cls.role_req, "w")
dep_lines = ["- 'src': '%s'\n" % cls.role_tar,
" 'name': '%s'\n" % cls.role_name,
" 'path': '%s'\n" % cls.role_path]
log.debug('dep_lines: %s', dep_lines)
for dep_line in dep_lines:
fd.write(dep_line)
fd.close()
with open(cls.role_req, 'w') as fd:
for dep_line in dep_lines:
fd.write(dep_line)
@classmethod
def makeTar(cls, output_file, source_dir):
@@ -110,7 +103,7 @@ class TestGalaxy(unittest.TestCase):
try:
tar = tarfile.open(output_file, "w:gz")
tar.add(source_dir, arcname=os.path.basename(source_dir))
except AttributeError: # tarfile obj. has no attribute __exit__ prior to python 2. 7
except AttributeError: # tarfile obj. has no attribute __exit__ prior to python 2.7
pass
finally: # ensuring closure of tarfile obj
tar.close()
@@ -131,10 +124,6 @@ class TestGalaxy(unittest.TestCase):
def setUp(self):
self.default_args = ['ansible-galaxy']
def test_init(self):
galaxy_cli = GalaxyCLI(args=self.default_args)
self.assertTrue(isinstance(galaxy_cli, GalaxyCLI))
def test_run(self):
''' verifies that the GalaxyCLI object's api is created and that execute() is called. '''
gc = GalaxyCLI(args=["ansible-galaxy", "install", "--ignore-errors", "imaginary_role"])
@@ -200,14 +189,13 @@ class TestGalaxy(unittest.TestCase):
# self.assertIsInstance(galaxycli_obj.galaxy, ansible_galaxy.models.context.GalaxyContext)
formatted_call = {
'info': 'usage: %prog info [options] repo_name[,version]',
'init': 'usage: %prog init [options] collection name',
'install': 'usage: %prog install [options] [-r FILE | repo_name(s)[,version] | scm+repo_url[,version] | tar_file(s)]',
'list': 'usage: %prog list [repo_name]',
'remove': 'usage: %prog remove repo1 repo2 ...',
'version': 'usage: %prog version',
}
first_call = 'usage: %prog [build|info|init|install|list|remove|version] [--help] [options] ...'
first_call = 'usage: %prog [build|info|install|list|remove|version] [--help] [options] ...'
second_call = formatted_call[action]
calls = [call(first_call), call(second_call)]
mocked_usage.assert_has_calls(calls)
@@ -228,13 +216,6 @@ class TestGalaxy(unittest.TestCase):
self.run_parse_common(gc, "info")
self.assertEqual(gc.options.offline, False)
def test_parse_init(self):
''' testing the options parser when the action 'init' is given '''
gc = GalaxyCLI(args=["ansible-galaxy", "init"])
self.run_parse_common(gc, "init")
self.assertEqual(gc.options.offline, False)
self.assertEqual(gc.options.force, False)
def test_parse_install(self):
''' testing the options parser when the action 'install' is given '''
gc = GalaxyCLI(args=["ansible-galaxy", "install"])
@@ -261,191 +242,3 @@ class TestGalaxy(unittest.TestCase):
gc = GalaxyCLI(args=["ansible-galaxy", "version"])
self.run_parse_common(gc, "version")
self.assertEqual(gc.options.verbosity, 0)
class ValidRoleTests(object):
expected_role_dirs = ('defaults', 'files', 'handlers', 'meta', 'tasks', 'templates', 'vars', 'tests')
# FIXME: there is some oddness with class attributes and setUpClass methods modifying them. Something
# to sort out when these get updated to pytest
@classmethod
def setup_class(cls):
log.debug('setup_class container')
log.debug('cls.content_type: %s', cls.content_type)
if not cls.content_type:
cls.content_type = 'role'
content_type_dir = cls.content_type
this_dir, _ = os.path.split(__file__)
_role_skeleton_path = os.path.join(this_dir, '../../../', 'ansible_galaxy_cli/data/', 'skeleton', content_type_dir)
log.debug('normpath(_role_skeleton_path): %s', os.path.normpath(_role_skeleton_path))
cls.setUpRole('delete_me_%s' % cls.content_type,
skeleton_path=_role_skeleton_path,
galaxy_args=['--type=%s' % cls.content_type,
'--skeleton=%s' % _role_skeleton_path])
@classmethod
def setUpRole(cls, role_name, skeleton_path, galaxy_args=None):
if galaxy_args is None:
galaxy_args = []
log.debug('skeleton_path arg: %s', skeleton_path)
# TODO: mock out role_skeleton path instead of always testing
# with --role-skeleton path to avoid issues like
# https://github.com/ansible/galaxy-cli/issues/20
cls.role_skeleton_path = skeleton_path
if '--skeleton' not in galaxy_args:
galaxy_args += ['--skeleton', skeleton_path]
log.debug('role_skeleton_path: %s', cls.role_skeleton_path)
# Make temp directory for testing
cls.test_dir = tempfile.mkdtemp()
ensure_dir(cls.test_dir)
log.debug('test_dir: %s', cls.test_dir)
cls.role_dir = os.path.join(cls.test_dir, role_name)
cls.role_name = role_name
log.debug('role_dir: %s', cls.role_dir)
log.debug('role_name: %s', cls.role_name)
# create role using default skeleton
gc_args = ['ansible-galaxy', 'init', '-c', '--offline'] + galaxy_args + ['--path', cls.test_dir, cls.role_name]
log.debug('gc_args: %s', gc_args)
gc = GalaxyCLI(args=gc_args)
gc.parse()
gc.run()
cls.gc = gc
if skeleton_path is None:
cls.role_skeleton_path = gc.galaxy.default_role_skeleton_path
@classmethod
def tearDownClass(cls):
if not os.path.isdir(cls.test_dir):
return
log.debug('deleting %s', cls.test_dir)
shutil.rmtree(cls.test_dir)
def test_metadata(self):
with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf:
metadata = yaml.safe_load(mf)
self.assertIn('galaxy_info', metadata, msg='unable to find galaxy_info in metadata')
self.assertIn('dependencies', metadata, msg='unable to find dependencies in metadata')
def test_readme(self):
readme_path = os.path.join(self.role_dir, 'README.md')
self.assertTrue(os.path.exists(readme_path), msg='Readme doesn\'t exist')
def test_main_ymls(self):
need_main_ymls = set(self.expected_role_dirs) - set(['meta', 'tests', 'files', 'templates'])
for d in need_main_ymls:
main_yml = os.path.join(self.role_dir, d, 'main.yml')
self.assertTrue(os.path.exists(main_yml), 'the main_yml path: %s does not exist' % main_yml)
expected_string = "---\n# {0} file for {1}".format(d, self.role_name)
log.debug('opening %s', main_yml)
with open(main_yml, 'r') as f:
self.assertEqual(expected_string, f.read().strip())
def test_role_dirs(self):
for d in self.expected_role_dirs:
self.assertTrue(os.path.isdir(os.path.join(self.role_dir, d)), msg="Expected role subdirectory {0} doesn't exist".format(d))
def test_travis_yml(self):
with open(os.path.join(self.role_dir, '.travis.yml'), 'r') as f:
contents = f.read()
with open(os.path.join(self.role_skeleton_path, '.travis.yml'), 'r') as f:
expected_contents = f.read()
self.assertEqual(expected_contents, contents, msg='.travis.yml does not match expected')
def test_test_yml(self):
with open(os.path.join(self.role_dir, 'tests', 'test.yml'), 'r') as f:
test_playbook = yaml.safe_load(f)
self.assertEqual(len(test_playbook), 1)
self.assertEqual(test_playbook[0]['hosts'], 'localhost')
self.assertEqual(test_playbook[0]['remote_user'], 'root')
self.assertListEqual(test_playbook[0]['roles'], [self.role_name], msg='The list of roles included in the test play doesn\'t match')
class TestGalaxyInitDefault(unittest.TestCase, ValidRoleTests):
content_type = 'role'
# @classmethod
# def setup_class(cls):
# cls.setUpRole(role_name='delete_me', skeleton_path=cls._test_role_skeleton_path)
def test_metadata_contents(self):
with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf:
metadata = yaml.safe_load(mf)
self.assertEqual(metadata.get('galaxy_info', dict()).get('author'), 'Your name', msg='author was not set properly in metadata')
class TestGalaxyInitAPB(unittest.TestCase, ValidRoleTests):
content_type = 'apb'
def test_metadata_apb_tag(self):
meta_to_read = os.path.join(self.role_dir, 'meta', 'main.yml')
log.debug('meta_to_read: %s', meta_to_read)
with open(meta_to_read, 'r') as mf:
metadata = yaml.safe_load(mf)
self.assertIn('apb', metadata.get('galaxy_info', dict()).get('galaxy_tags', []), msg='apb tag not set in role metadata')
def test_metadata_contents(self):
with open(os.path.join(self.role_dir, 'meta', 'main.yml'), 'r') as mf:
metadata = yaml.safe_load(mf)
self.assertEqual(metadata.get('galaxy_info', dict()).get('author'), 'Your name', msg='author was not set properly in metadata')
def test_apb_yml(self):
self.assertTrue(os.path.exists(os.path.join(self.role_dir, 'apb.yml')), msg='apb.yml was not created')
def test_test_yml(self):
playbook_path_to_read = os.path.join(self.role_dir, 'tests', 'test.yml')
log.debug('playbook_path_to_read: %s', playbook_path_to_read)
with open(playbook_path_to_read, 'r') as f:
test_playbook = yaml.safe_load(f)
log.debug('test_playbook: %s', test_playbook)
self.assertEqual(len(test_playbook), 1)
self.assertEqual(test_playbook[0]['hosts'], 'localhost')
self.assertEqual(test_playbook[0]['connection'], 'local')
self.assertFalse(test_playbook[0]['gather_facts'])
self.assertIsNone(test_playbook[0]['tasks'], msg='We\'re expecting an unset list of tasks in test.yml')
class TestGalaxyInitSkeleton(unittest.TestCase, ValidRoleTests):
content_type = 'role'
@classmethod
def setup_class(cls):
_test_role_skeleton_path = os.path.join(os.path.split(__file__)[0], 'data/role_skeleton')
log.debug('_test_role_sp: %s', _test_role_skeleton_path)
log.debug('normpath(_test_role_skeleton_path): %s', os.path.normpath(_test_role_skeleton_path))
cls.setUpRole('delete_me_skeleton', skeleton_path=_test_role_skeleton_path)
def test_empty_files_dir(self):
files_dir = os.path.join(self.role_dir, 'files')
self.assertTrue(os.path.isdir(files_dir))
self.assertListEqual(os.listdir(files_dir), [], msg='we expect the files directory to be empty, is ignore working?')
def test_template_ignore_jinja(self):
test_conf_j2 = os.path.join(self.role_dir, 'templates', 'test.conf.j2')
self.assertTrue(os.path.exists(test_conf_j2), msg="The test.conf.j2 template doesn't seem to exist, is it being rendered as test.conf?")
with open(test_conf_j2, 'r') as f:
contents = f.read()
expected_contents = '[defaults]\ntest_key = {{ test_variable }}'
self.assertEqual(expected_contents, contents.strip(), msg="test.conf.j2 doesn't contain what it should, is it being rendered?")
def test_template_ignore_jinja_subfolder(self):
test_conf_j2 = os.path.join(self.role_dir, 'templates', 'subfolder', 'test.conf.j2')
self.assertTrue(os.path.exists(test_conf_j2), msg="The test.conf.j2 template doesn't seem to exist, is it being rendered as test.conf?")
with open(test_conf_j2, 'r') as f:
contents = f.read()
expected_contents = '[defaults]\ntest_key = {{ test_variable }}'
self.assertEqual(expected_contents, contents.strip(), msg="test.conf.j2 doesn't contain what it should, is it being rendered?")
def test_template_ignore_similar_folder(self):
self.assertTrue(os.path.exists(os.path.join(self.role_dir, 'templates_extra', 'templates.txt')))
def test_skeleton_option(self):
self.assertEquals(self.role_skeleton_path, self.gc.options.skeleton, msg='Skeleton path was not parsed properly from the command line')