Commit graph

545 commits

Author SHA1 Message Date
Adrian Likins
727ca6f436 Fix error on 'help module' in ansible-console (#19390)
If 'help xattr' for example, ansible-console would
traceback because module_docs.get_docstring() now
returns 4 values (module metadata was added)
2016-12-20 15:50:29 -05:00
Peter Sprygada
2a5a2773c8 adds new module net_command for network devices (#19468)
* new module net_command for sending a command to a network device
* adds unit test cases for module
* only works with connection=network_cli
2016-12-19 11:21:37 -05:00
Andrea Tartaglia
59227d8c31 Removed dict.iteritems() in several other files.
This is for py3 compatibility #18506
2016-12-14 08:01:45 -08:00
Adrian Likins
c693ba19f9 unit tests for playbook/conditional.py (#18586)
Start of unit tests for playbook/conditional.py
2016-12-13 14:38:16 -05:00
Adrian Likins
3efef40822 Add unit tests for playbook/helpers.py (#18709) 2016-12-13 14:36:04 -05:00
Adrian Likins
1653a77f1d add unit tests for playbook/included_file.py (#18710) 2016-12-13 14:35:27 -05:00
Adrian Likins
08a5d506bb Fix errors on 'ansible-playbook --flush-cache' (#18754)
Add a unit test, and split out the flush cache logic to
it's own method.
Fixes #18708
2016-12-13 14:35:15 -05:00
Adrian Likins
6c4f554f5a Provide slightly better msg on fact cache error (#18759)
If the configured fact_cache plugin (fact_caching config)
fails, raise a fatal error instead of failing mysteriously
later.

Fixes #18751
2016-12-13 14:34:58 -05:00
Clark Boylan
a65e34ce77 Fix synchronize retries (#18535)
* Fix synchronize retries

The synchronize module munges its task args on every invocation of
run(). This was problematic because the munged data was not fit for use
by a second pass of the synchronize module. Correct this by using a copy
of the task args on every invocation of run() so that the original args
are not affected.

Local testing using this playbook seems to confirm that things work as
expected:

  - hosts: all
  tasks:
    - delay: 2
      register: task_result
      retries: 1
      until: task_result.rc == 0
      synchronize:
        dest: /tmp/out
        mode: pull
        src: /tmp/nonexistent/

fixes #18281

* Update synchroncization fixture assertions

When we started operating on a copy of the task args the test assertions
were no longer asserting things about the munged state but of the
pristine state. Convert the copy of task args to a class member so that
it can be compared against later in testing and update the assertions to
check this munged copy.
* Shuffle objects around for cleaner testing

Attach the temporary args dict to the task rather than the action as
this makes updating the existing tests cleaner.
2016-12-12 13:33:30 -08:00
Matt Clay
5628e260f2 Relocate module unit tests. (#18812)
* Relocate module unit tests.
* Fix classification of unit test changes.
2016-12-08 11:35:20 -05:00
Matt Clay
bd7ce0696e Fix tests after repo merge. 2016-12-08 11:35:19 -05:00
Peter Sprygada
dc23667cc2 add back reverted change to network_cli (#18761)
This adds back the change to the network_cli plugin.  Ths change adds
the ensure_connect decorator to the open_shell() method to make sure
the connection is valid before trying to open a shell.

The issue was due to the addition of the decorator that will call
_connect() when there is no connection.  The _connect() method should
have been mocked in the test case.  This commit fixes the test
case as well

Change was originally reverted in c414ded69a
2016-12-05 21:42:09 -05:00
Toshio Kuratomi
5f5ea06ca4 make hash_params more robust in the face of many corner cases (#18701)
* make hash_params more robust in the face of many corner cases

Fixes #18680
Alternative fix to #18681

* add test case for role.hash_params

* Add role.hash_params test for more types

A set, a generator/iterable, and a Container that
is not Iterable.
2016-12-05 04:01:45 -08:00
Peter Sprygada
06f5bf980e adds unit test for network_cli connection plugin (#18729) 2016-12-03 20:38:41 -05:00
Adrian Likins
a1ca10f7fc Add lots of test cases to inventory/test_host.py (#17827) 2016-11-29 13:38:04 -05:00
Adrian Likins
d6e2f1846a add a unit test for playbook/base.py (#17688)
* wip: add a unit test for playbook/base.py

This commit include a failing test
TestBaseSubClass.test_attr_class_post_validate

It fails with the error:
Traceback (most recent call last):
  File "/home/adrian/src/ansible/test/units/playbook/test_base.py", line 264, in test_attr_class_post_validate
    bsc = self._base_validate(ds)
  File "/home/adrian/src/ansible/test/units/playbook/test_base.py", line 206, in _base_validate
    bsc.post_validate(templar)
  File "/home/adrian/src/ansible/lib/ansible/playbook/base.py", line 450, in post_validate
    " Error was: %s" % (name, value, attribute.isa, e), obj=self.get_ds())
AnsibleParserError: the field 'test_attr_class_post_validate' has an invalid value (<class 'units.playbook.test_base.ExampleSubClass'>), and could not be converted to an class. Error was: test_attr_class_post_validate is not a valid <class 'units.playbook.test_base.ExampleSubClass'> (got a <class 'ansible.playbook.base.BaseMeta'> instead)

* wip, test refactoring

* wip, trying to add a parent->child

* wip, fix isa=class.

the ds the base using needs an instance of the class
(ie, whats normally created by the yaml loaders)

* wip, theres no need to argue, I just dont understand parents

* stub a _preprocess_data for coverage

* cleanup, required, parent, etc
2016-11-29 10:42:25 -05:00
Adrian Likins
f0c71ad68d More test coverage for plugins/callback/__init__ (#18020) 2016-11-29 10:40:46 -05:00
Daniel Miranda
57f4a9885e Make sure include_role inherit variables from parent role (#18627)
* Make sure include_role inherit variables from parent role

Setting the parent of task blocks generated by include_role after they
have been produced is not sufficient - it means the tasks don't have the
correct dependency chain set afterwards, and therefore, don't properly
inherit variables from outer roles.

In addition to manually setting the parents, pass the dep_chain when
compiling the role, such that variables are correctly imported.

Fixes #18540.

* Add tests for include_role

* Fix include_role variable inheritance for multiple parent levels
2016-11-28 17:54:27 -05:00
Brian Coca
778c983ef9 ansible_playbook_python (#18530)
* ansible_playbook_python

fixes #18471

* fix tests

* removed dupe
2016-11-23 16:30:46 -05:00
Toshio Kuratomi
ed00741a01 Mcsalgado's change to use shlex.quote instead of pipes.quote (#18534)
* Replace pipes.quote for shlex_quote

* More migration of pipes.quote to shlex_quote

Note that we cannot yet move module code over.  Modules have six-1.4
bundled which does not have shlex_quote.  This shouldn't be a problem as
the function is still importable from pipes.quote.  It's just that this
has become an implementation detail that makes us want to import from
shlex instead.

Once we get rid of the python2.4 dependency we can update to a newer
version of bundled six module-side and then we're free to use
shlex_quote everywhere.
2016-11-17 13:18:29 -08:00
Adrian Likins
17738e6b73 Fix test_play_context fail with local config. (#17596)
If the current ansible enviroment has a config setup
that doesn't use 'smart' as the configured transport
test_play_context would fail when it assumes the
transport will be 'smart'.
2016-11-17 12:25:39 -05:00
James Cammarata
ca5b361ad8 Reworking iterator logic regarding failed states during always
Previous changes addressed a corner case, which unfortunately introduced
another bug. This patch adds a new flag to the host state (did_rescue) which
is set to true when the rescue portion of a block completes. This flag is
then checked in _check_failed_state() when the fail_state != FAILED_NONE.

This lead to the discovery of another bug - current strategies are not advancing
hosts to ITERATING_COMPLETE after doing a peek at the next task, leaving the
host state in the run_state of the final task. To address this, before gathering
the list of failed hosts in StrategyBase.run(), a final pass through the iterator
for all hosts is done to ensure each host is in its final state. This way, no
strategy derived from StrategyBase has to worry about it and it's handled.

Fixes #17983
2016-11-16 10:21:46 -06:00
Matt Clay
ac8842eee8 Fix unit test dirs to match code under test. 2016-11-10 18:59:07 -08:00
Matt Clay
8552ad6bf1 Fix docker connection unit tests.
- Use assertRaisesRegexp to make sure correct exceptions are raised.
- Set docker_command to avoid docker dependency (skips find_executable).
- Use a fake path for docker_command to make sure mock.patch is working.
2016-11-09 10:23:35 -08:00
Adrian Likins
51e3ef89a9 Add error info if tabs are found in the yaml (#18343)
If a yaml file fails to load because of tabs being used
for formatting, detect that and show a error message
with more details.
2016-11-08 11:43:08 -05:00
Matt Clay
8c270ac75f Add empty-init code-smell script. (#18406)
Also removed boilerplate from otherwise empty __init__.py files
which should not contain any code (checked by empty-init script).
2016-11-07 15:02:13 -08:00
Brian Coca
a0f27d552c File attributes (#18213)
* added attributes to base file params

* dont change attributes when none

* fixed test to deal with new attributes
2016-11-07 15:48:04 -05:00
Brian Coca
8cab33a779 skip vmware inventory when missing lib
fixes #18190
2016-11-07 15:37:59 -05:00
Adrian Likins
dd0189839e Fix bug (#18355) where encrypted inventories fail 18355 (#18373)
* Fix bug (#18355) where encrypted inventories fail

This is first part of fix for #18355
* Make DataLoader._get_file_contents return bytes

The issue #18355 is caused by a change to inventory to
stop using _get_file_contents so that it can handle text
encoding itself to better protect against harmless text
encoding errors in ini files (invalid unicode text in
comment fields).

So this makes _get_file_contents return bytes so it and other
callers can handle the to_text().

The data returned by _get_file_contents() is now a bytes object
instead of a text object. The callers of _get_file_contents() have
been updated to call to_text() themselves on the results.

Previously, the ini parser attempted to work around
ini files that potentially include non-vailid unicode
in comment lines. To do this, it stopped using
DataLoader._get_file_contents() which does the decryption of
files if vault encrypted. It didn't use that because _get_file_contents
previously did to_text() on the read data itself.

_get_file_contents() returns a bytestring now, so ini.py
can call it and still special case ini file comments when
converting to_text(). That also means encrypted inventory files
are decrypted first.

Fixes #18355
2016-11-07 10:07:26 -05:00
Matt Clay
0d46805979 Clean up shebangs for various files.
- Remove shebangs from:
  - ini files
  - unit tests
  - module_utils
  - plugins
  - module_docs_fragments
  - non-executable Makefiles
- Change non-modules from '/usr/bin/python' to '/usr/bin/env python'.
- Change '/bin/env' to '/usr/bin/env'.

Also removed main functions from unit tests (since they no longer
have a shebang) and fixed a python 3 compatibility issue with
update_bundled.py so it does not need to specify a python 2 shebang.

A script was added to check for unexpected shebangs in files.
This script is run during CI on Shippable.
2016-11-02 17:00:27 -07:00
jctanner
cb872415d1 set galaxy unit test server to None (#18298)
Prevents connections to the internet in isolated environments such as koji+mock

Fixes #18297
2016-11-02 10:25:09 -04:00
Matt Clay
37271867b1 Move amazon unit tests and apply fixes.
- Update import for relocated tests.
- Fix test to expect changed from update_tags.
- Add checks for boto3 and botocore to tests.
- Set check mode with kwarg.
- Python 3 fixes for unit tests.
- Python 2.6 fix for unit tests.
2016-10-31 20:54:36 -07:00
Matt Clay
e24588902f Move test_os_server and apply fixes.
- Add missing meta value for test_create_server
- Add .gitignore for pytest .cache directory

Exclude test_os_server from nose test runs since it was designed
for pytest. The test will work correctly when run using pytest.

This is a temporary issue, as we'll be moving to pytest soon.
2016-10-31 15:45:10 -07:00
Matt Clay
71819c0a60 Test reorganization and cleanup. (#18270)
- Correct directory name in test/README.md
- Move code-smell tests to test/sanity/code-smell
- Update code-smell.sh to use new script paths
- Add test/integration/target-prefixes.win for ansible-test
- Move module unit tests to match module directory layout
2016-10-31 12:53:11 -07:00
Steve Kuznetsov
0bc35354ce Change v2_playbook_on_start logic to positively detect legacy plugins
In order to support legacy plugins, the following two method signatures
are allowed for `CallbackBase.v2_playbook_on_start`:

def v2_playbook_on_start(self):
def v2_playbook_on_start(self, playbook):

Previously, the logic to handle this divergence checked to see if the
callback plugin being called supported an argument named `playbook`
in its `v2_playbook_on_start` method. This was fragile in a few ways:
 - if a plugin author did not use the literal `playbook` to name their
   method argument, their plugin would not be called correctly
 - if a plugin author wrapped their `v2_playbook_on_start` method and
   by doing so changed the argspec to no longer expose an argument
   with that literal name, their plugin would not be called correctly

In order to continue to support both types of callback for backwards
compatibility while making the call more robust for plugin authors,
the logic can be reversed in order to have a positive check for the old
method signature instead of a positive check for the new one.

Signed-off-by: Steve Kuznetsov <skuznets@redhat.com>
2016-10-28 10:05:58 -07:00
Matt Robinson
4ff8890ec1 Set ansible_os_family correctly under KDE neon
As neon is derived from Ubuntu, ansible_os_family should have the value
"Debian" instead of "Neon".  Add a test case for KDE neon and set
os_family correctly for it.
2016-10-27 20:28:38 +01:00
Adrian Likins
c0331d50dc Remove callback.CallbackBase._copy_result_exclude
Nothing seems to use this now.

Was added originally added in2d11cfab92f9d26448461b4bc81f466d1910a15e
but the code that used it was removed in
e02b98274b
2016-10-23 13:36:20 +02:00
Adrian Likins
6f9ca7bb83 test name TestPlayIterator->TestPlaybookExecutor 2016-10-23 02:19:04 +02:00
stephane
77868a4104 Set Suse family for openSUSE Tumbleweed & Leap
On openSUSE Tumbleweed, lsb-release -a currently reports
the distributor ID as "openSUSE Tumbleweed". On openSUSE
Leap, the distributor ID is "SUSE LINUX".

Add them to the OS_FAMILY dict as Suse family systems.

Also add an entry to TESTSETS in test_distribution_version.py
for openSUSE Tumbleweed.
2016-10-23 02:04:28 +02:00
Ssawa
8e47b9bc70 Handle 'smart' scp_if_ssh option for fetch (#18125) 2016-10-21 09:59:56 -04:00
Thilo Uttendorfer
cf0da0948d Fix uninitialized variable in deserialize method (#18037)
The bug was introduced with commit 06d4f4ad0e.
Added a simple test.
2016-10-20 22:54:16 -04:00
Thilo Uttendorfer
5ece97ae5b Fix call of wrong super class
Added a basic test
2016-10-17 14:53:03 -04:00
Brian Coca
04b86df815 updated pbrun test to match expected output 2016-10-17 14:41:23 -04:00
Adrian Likins
8bf4aa97b0 Skip test_aws.py if boto3/botocore are missing (#17814) 2016-10-13 13:19:40 -07:00
Toshio Kuratomi
9265016b95 Fix a test failure when run on a system with python-future installed. 2016-10-07 11:13:21 -07:00
Toshio Kuratomi
1efe782b46 Refactor parsing of CLI args so that we can modify them in the base class
Implement tag and skip_tag handling in the CLI() class.  Change tag and
skip_tag command line options to be accepted multiple times on the CLI
and add them together rather than overwrite.

* Make it configurable whether to merge or overwrite multiple --tags arguments
* Make the base CLI class an abstractbaseclass so we can implement
  functionality in parse() but still make subclasses implement it.
* Deprecate the overwrite feature of --tags with a message that the
  default will change in 2.4 and go away in 2.5.

* Add documentation for merge_multiple_cli_flags
* Fix galaxy search so its tags argument does not conflict with generic tags
* Unit tests and more integration tests for tags
2016-10-06 10:46:58 -04:00
Toshio Kuratomi
23305540b4 Make ini parsing slightly more robust
Prior to this commit, the ini parser would fail if the inventory was
not 100% utf-8.  This commit makes this slightly more robust by
omitting full line comments from that requirement.

Fixes #17593
2016-10-04 11:24:50 -07:00
Toshio Kuratomi
08a58ae025 Fix for run_command tests now that it returns native strings 2016-10-03 18:45:28 -07:00
Matt Davis
aa0ad073b8 bugfixes to JSON junk filter, added unit/integration tests to exercise (#17834) 2016-10-02 08:03:42 -07:00
Brian Coca
dfff608ceb dzdo prompt fix
fixed tests
dzdo has 2 paths now, with and w/o password
fixes #17838
2016-09-30 17:58:19 -04:00
jctanner
fff161f2f6 Smart mode for sftp+scp (#17813)
If the sftp fails, roll over to scp by default. This saves users
from having to know about the scp_if_ssh method when sftp is broken
on the remote host.
2016-09-29 17:44:54 -04:00
Toshio Kuratomi
efa78b4ff4 The mode that we fake from stat is checked more closely under python3.5 on El Capitan (#17794)
Python2 seems to allow any integer.  Python3.5 on Linux seems to allow
a 32 bit unsigned int.  Python3.5 on El Capitan seems to limit it to
a smaller size...  perhaps a 16 bit int.
2016-09-28 08:24:28 -07:00
Adrian Likins
bba0fb3a42 Add mnt pnts with single quote to test (16855) (#17771)
This adds some test data to test_facts.py that
includes mnt points that have a single quote in
the path.

Ala, https://github.com/ansible/ansible/issues/16855

The bug was already fixed via other changes, but this is
for regression testing.
2016-09-27 20:21:25 -07:00
Christoph
f9e49de2ef Add a test for int/float parameter type checking (#16741)
A parameter of type int should accept int and string, but not float.
A parameter of type float should accept float, int, and string.

Also reset the arguments in another test so that it runs cleanly.  This
agrees with what all the other tests are doing.
2016-09-21 20:36:14 -07:00
Matt Clay
39c5c558f8 Switch tests from sudo to become. (#17694) 2016-09-21 13:58:35 -07:00
James Cammarata
1b54d3b6dc Merge branch 'threaded_receiver' into devel 2016-09-20 09:18:26 -05:00
Toshio Kuratomi
5e9a8d9202 Fix password lookup py3 plus alikins unittest additions refactoring (#17626)
* Improve unit testing of 'password' lookup

The tests showed some UnicodeErrors for the
cases where the 'chars' param include unicode,
causing the 'getattr(string, c, c)' to fail.
So the candidate char generation code try/excepts
UnicodeErrors there now.

Some refactoring of the password.py module to make
it easier to test, and some new tests that cover more
of the password and salt generation.

* More refactoring and fixes.

* manual merge of text enc fixes from pr17475

* moving methods to module scope

* more refactoring

* A few more text encoding fixes/merges

* remove now unused code

* Add test cases and data for _gen_candidate_chars

* more test coverage for password lookup

* wip

* More text encoding fixes and test coverage

* cleanups

* reenable text_type assert

* Remove unneeded conditional in _random_password

* Add docstring for _gen_candidate_chars

* remove redundant to_text and list comphenesion

* Move set of 'chars' default in _random_password

on py2, C.DEFAULT_PASSWORD_CHARS is a regular str
type, so the assert here fails. Move setting the
default into the method and to_text(DEFAULT_PASSWORD_CHARS)
if it's needed.

* combine _random_password and _gen_password

* s/_create_password_file/_create_password_file_dir

* native strings for exception msgs

* move password to_text to _read_password_file

* move to_bytes(content) to _write_password_file

* add more test assertions about genned pw's

* Some cleanups to alikins and abadger's password lookup refactoring:

* Make DEFAULT_PASSWORD_CHARS into a text string in constants.py
  - Move this into the nonconfigurable section of constants.
* Make utils.encrypt.do_encrypt() return a text string because all the
  hashes in passlib should be returning ascii-only strings and they are
  text strings in python3.
* Make the split up of functions more sane:
   - Don't split such that conditionals have to occur in two separate functions.
   - Don't go overboard: Good to split file system manipulation from parsing
     but we don't need to do every file manipulation in a separate
     function.
  - Don't split so that creation of the password store happens in two
    parts.
  - Don't split in such a way that no decisions are made in run.
* Organize functions by when it gets called from run().
* Run all potential characters through the gen_candidate_chars function
  because it does both normalization and validation.
* docstrings for functions
* Change when we store salt slightly.  Store it whenever it was already
  present in the file as well as when encrypt is requested.  This will
  head of potential idempotence bugs where a user has two playbook tasks
  using the same password and in one they need it encrypted but in the
  other they need it plaintext.
* Reorganize tests to follow the order of the functions so it's easier
  to figure out if/where a function has been tested.
* Add tests for the functions that read and write the password file.
* Add tests of run() when the password has already been created.
* Test coverage currently at 100%
2016-09-19 11:37:57 -07:00
cinerama70
02cec7dca9 Add os_family to test_distribution_version (#17620)
As suggested in feedback on
https://github.com/ansible/ansible/pull/17575, add
os_family to test_distribution_version. Add the
correct os_family to the existing testcase data
entries.

Also add os_family to the output of
gen_distribution_version_testcase.py so any new
generated entries will contain this data.
2016-09-17 23:27:35 +02:00
James Cammarata
5a57c66e3c Moving result reading to a background thread 2016-09-17 08:12:52 -05:00
Toshio Kuratomi
8af8eec789 Merge pull request #17590 from abadger/vault-fixes
Vault fixes
2016-09-15 18:39:34 -07:00
Toshio Kuratomi
e70066a6f7 Many Cleanups to vault
* Make is_encrypted_file handle both files opened in text and binary mode
  On python3, by default files are opened in text mode.  Since we know
  the encoding of vault files (and especially the header which is the
  first set of bytes) we can decide whether the file is an encrypted
  vault file in either case.
* Fix is_encrypted_file not resetting the file position
* Update is_encrypted_file to check that all the data in the file is ascii
* For is_encrypted_file(), add start_pos and count parameters
  This allows callers to specify reading vaulttext from the middle of
  a file if necessary.
* Combine VaultLib.encrypt() and VaultLib.encrypt_bytestring()
* Change vault's is_encrypted() to take either text or byte strings and to return False if any part of the data is non-ascii.
* Remove unnecessary use of six.b
* Vault Cipher: mark a few methods as private.
* VaultAES256._is_equal throws a TypeError if given non byte strings
* Make VaultAES256 methods that don't need self staticmethods and classmethods
* Mark VaultAES and is_encrypted as deprecated
* Get rid of VaultFile (unused and feature implemented in a different way)
* Normalize variable and parameter names on plaintext, ciphertext, vaulttext
* Normalize variable and parameter names on "b_" prefix when dealing with bytes
* Test changes:
  * Remove redundant tests( both checking the same byte string)
  * Fix use of format string without format operator
  * Enable vault editor tests on python3
  * Initialize the vault_cipher for VaultAES256 testing in setUp()
  * Make assertTrue and assertFalse take the actual method calls for
    better error messages.
  * Test that non-ascii byte strings compare correctly.
  * Test that unicode strings and ints raise TypeError

* Test-specific:
  * Removed test_methods_exist().  We only have one VaultLib so the
    implementation is the assurance that the methods exist. (Can use an abc for
    this if it changes).
  * Add tests for both byte string and text string input where the API takes either.
  * Convert "assert" to unittest assert functions or add a custom message where
    that will make failures easier to debug.
  * Move instantiating the VaultLib into setUp().
2016-09-15 15:22:06 -07:00
Toshio Kuratomi
0139298786 Have unittests import mock from ansible.compat so they work on py3 without mock installed from pypi 2016-09-15 15:21:17 -07:00
James Cammarata
dfb1c0647e Revert "Move queuing tasks to a background thread"
This reverts commit b71957d6e6.
2016-09-15 17:00:06 -05:00
Matt Clay
16baef1f72 Do not use bare vars in integration tests. (#17599) 2016-09-15 17:41:54 -04:00
Toshio Kuratomi
f4cd1c6321 Fix galaxy's parsing of the command line. (#17569)
Also make the parsing of the action in both galaxy and vault more
robust.

Fixes #17534
May Fix #17563
2016-09-14 11:49:54 -07:00
Allen Sanabria
b510abce17 CloudRetry/AWSRetry backoff decorator with unit tests (#17039)
* Added aws_retry decorator function with unit tests

* Restructured the code to be used with a base class.

This base class CloudRetry can be reused by any other cloud provider.
This decorator should be used in situations, where you need to implement
a backoff algorithm and want to retry based on the status code from the
exception.

* updated documentation

* fixed tabs

* added botocore and boto3 to requirements.txt

* removed cloud.py from py24 tests, as it depends on boto3

* fix relative imports

* updated test to be 2.6 compat

* updated method name from retry to backoff

* readded lxd

* Updated default backoff from 2 seconds to 1.1s.

This will be about a total of 48 seconds in 10 tries. This is
configurable.
2016-09-13 16:46:59 -04:00
Toshio Kuratomi
4ed88512e4 Move uses of to_bytes, to_text, to_native to use the module_utils version (#17423)
We couldn't copy to_unicode, to_bytes, to_str into module_utils because
of licensing.  So once created it we had two sets of functions that did
the same things but had different implementations.  To remedy that, this
change removes the ansible.utils.unicode versions of those functions.
2016-09-06 22:54:17 -07:00
Matt Clay
94a0d2afb4 Add partially backwards compatible version of _fixup_perms. (#17427)
Also added a deprecation notice for _fixup_perms.

Resolves issue #17352 (assumes custom actions use recursive=False).
2016-09-06 16:49:59 -07:00
Will Thames
d54f5277d5 Add ksu privilege escalation (#17340)
Allow ksu privilege escalation to be used
as a standard become_method

https://web.mit.edu/kerberos/krb5-1.12/doc/user/user_commands/ksu.html
2016-09-01 16:54:31 -04:00
Tobias Wolf
c23b11d212 [Inventory] Cache the result of enumerating groups and host names
for `VariableManager._get_magic_variables()`.

This saves a lot of time re-iterating the nearly always constant global
list of groups and their members.

Generate once and cache, and invalidate cache in case `add_host:` or
`group_by:` are used.
2016-09-01 06:19:49 -05:00
Toshio Kuratomi
28227546fa Various python3 updates for module_utils: (#17345)
* Port set_*_if_different functions to python3
* Add surrogate_or_strict and surrogate_or_replace error handlers for
  to_text, to_bytes, to_native
* Set default error handler to surrogate_or_replace
* Make use of the new error handlers in the already ported code
* Move the unittests for module_utils._text as they aren't in basic.py
* Cleanup around SEQUENCETYPE.  On python2.6+ SEQUENCETYPE includes
  strings so make sure code omits those explicitly if necessary
* Allow arg_spec aliases to be other sequence types
2016-09-01 04:19:03 -07:00
James Cammarata
b71957d6e6 Move queuing tasks to a background thread 2016-08-31 13:33:01 -05:00
Toshio Kuratomi
fa804125b5 Python3 fixes and porting (#17271)
* Fix to_native call in selinux_context and selinux_default_context to
  use the error handler correctly.
* Port set_mode_if_different to work on python3
* Port atomic_move to work on python3
* Fix check_password_prompt variable which wasn't renamed properly
2016-08-29 09:11:40 -07:00
Alexander Stock
238cccf166 Fix "Text file busy" exception in atomic_move (#9526) (#17204)
tempfile.NamedTemporaryFile keeps a file handle causing os.rename() to fail with windows based vboxfs: [Errno 26] Text file busy.
Changed NamedTemporaryFile to mkstemp() and added a finally block to unlink the temp file in each and every case.
2016-08-26 07:41:17 -07:00
Toshio Kuratomi
bd68c324ce Get the ssh plugin working with python3 (#17234) 2016-08-25 10:57:55 -07:00
Toshio Kuratomi
44d979c8f5 Enable most unittests on python3 (just some vault unittests and a logging one left) (#17240)
Make some python3 fixes to make the unittests pass:

* galaxy imports
* dictionary iteration in role requirements
* swap_stdout helper for unittests
* Normalize to text string in a facts.py function
2016-08-25 07:30:03 -07:00
Adrian Likins
e396d5d508 Implement vault encrypted yaml variables. (#16274)
Make !vault-encrypted create a AnsibleVaultUnicode
yaml object that can be used as a regular string object.

This allows a playbook to include a encrypted vault
blob for the value of a yaml variable. A 'secret_password'
variable can have it's value encrypted instead of having
to vault encrypt an entire vars file.

Add __ENCRYPTED__ to the vault yaml types so
template.Template can treat it similar
to __UNSAFE__ flags.

vault.VaultLib api changes:
    - Split VaultLib.encrypt to encrypt and encrypt_bytestring

    - VaultLib.encrypt() previously accepted the plaintext data
      as either a byte string or a unicode string.
      Doing the right thing based on the input type would fail
      on py3 if given a arg of type 'bytes'. To simplify the
      API, vaultlib.encrypt() now assumes input plaintext is a
      py2 unicode or py3 str. It will encode to utf-8 then call
      the new encrypt_bytestring(). The new methods are less
      ambiguous.

    - moved VaultLib.is_encrypted logic to vault module scope
      and split to is_encrypted() and is_encrypted_file().

Add a test/unit/mock/yaml_helper.py
It has some helpers for testing parsing/yaml

Integration tests added as roles test_vault and test_vault_embedded
2016-08-23 20:03:11 -04:00
Toshio Kuratomi
a22909c226 Migrate basestring to a python3 compatible type (#17199) 2016-08-23 13:13:44 -07:00
Toshio Kuratomi
57701d7115 Give native strings to selinux library functions. (#17184)
* Give native strings to selinux library functions.

SELinux takes pathnames as native strings.  That means we need to
convert to bytes on python2 and convert to text on python3.

Fixes #17155

* Read kitchen documentation, make module_utils params more like kitchen API

* Remove none nonstring strategy and add strict
* Raise TypeError on invalid nonstring strategy

* Document to_native()

* Make unittests for testing module_utils.text
2016-08-22 16:44:13 -07:00
Adrian Likins
a4785c2691 Fix docker connection plugin version tests and py2.6 compat (#16841)
* Rm py2.7+ code in docker connection plugin

The docker connection plugin was using subprocess.check_output
which only exists in python 2.7 and later. Connection plugins
need to support python2.6 so this replaces it with Popen/communicate()

* Handle docker ver errors in docker connection

Add unit tests for DockerConnection

Fixes #16971
2016-08-22 10:39:38 -04:00
Toshio Kuratomi
d29a7c55fe Enable some basic.py tests on python3 (#17167) 2016-08-20 10:13:54 -07:00
Adrian Likins
7d41f623dd Move py34 mock_open compat to compat/test/mock (#17157)
test/units/plugins/action/test_action.py had code
for handling a bug in python 3.4's mock_open that
causes errors when reading binary data.

Moved to compat/tests/mock.py so other tests can
use it by default.
2016-08-19 18:11:24 -04:00
Toshio Kuratomi
bd31cc096a Fix facts.py for python3 (#17131)
* Fix facts.py for python3

* Update facts unittest to account for filepaths being byte strings
2016-08-18 09:36:03 -04:00
Adrian Likins
7bd57acda4 Linux mount/fs (lsblk) facts fixes and tests. (#17036)
Fixes #10779

Refactor some of the block device, mount point, and
mtab/fstab facts collection for linux for better
performance on systems with lots of block devices.

Instead of invoking 'lsblk' for every entry in mtab,
invoke it once, then map the results to mtab entries.

Change the args used for invoking 'findmnt' since the
previous combination of args conflicts, so this would
always fail on some systems depending on version.

Add test cases for facts Hardware()/Network()/Virtual() classes
__new__ method and verify they create the proper subclass based
on the platform.system() results.

Split out all the 'invoke some command and grab it's output'
bits related to linux mount paths into their own methods so
it is easier to mock them in unit tests.

Fix the DragonFly* classes that did not defined a 'platform'
class attribute. This caused FreeBSD systems to potentially
get the DragonFly* subclasses incorrectly. In practice it
didnt matter much since the DragonFly* subclasses duplicated
the FreeBSD ones. Actual DragonFly systems would end up with
the generic Hardware() etc instead of the DragonFly* classes.

Fix Hardware.__new__() on PY3, passing args to __new__
would cause "object() takes no parameters" errors. So
check for PY3 and just call __new__ without the args

See
https://hg.python.org/cpython/file/44ed0cd3dc6d/Objects/typeobject.c#l2818
for some explaination.
2016-08-17 17:58:51 -07:00
Brian Coca
b1410fa278 fixed tests to accoutn for new parameter 2016-08-16 13:11:58 -04:00
James Cammarata
c669a381d1 Don't immediately return failed for any_errors_fatal tasks
Instead of immediately returning a failed code (indicating a break in
the play execution), we internally 'or' that failure code with the result
(now an integer flag instead of a boolean) so that we can properly handle
the rescue/always portions of blocks and still remember that the break
condition was hit.

Fixes #16937
2016-08-12 14:18:50 -05:00
James Cammarata
47acf55fa9 Cache tasks by uuid in PlayIterator for O(1) lookups
Rather than repeatedly searching for tasks by uuid via iterating over
all known blocks, cache the tasks when they are added to the PlayIterator
so the lookup becomes a simple key check in a dict.
2016-08-10 12:49:19 -05:00
James Cammarata
e244895174 Avoid copying task parents in TaskExecutor
As Block.copy() is potentially expensive, avoid copying the parent
structure of tasks in TaskExecutor.
2016-08-08 15:58:46 -05:00
James Cammarata
06d4f4ad0e Move tasks/blocks to a single parent model 2016-08-08 15:58:46 -05:00
James Cammarata
d2b3b2c03e Performance improvements 2016-08-08 15:58:46 -05:00
James Cammarata
159aa26b36 FEATURE: adding variable serial batches
This feature changes the scalar value of `serial:` to a list, which
allows users to specify a list of values, so batches can be ramped
up (commonly called "canary" setups):

- hosts: all
  serial: [1, 5, 10, "100%"]
  tasks:
  ...
2016-08-04 15:04:10 -05:00
Brian Coca
e2f17f8d9b set cwd to task's basedir (#16805)
* switch cwd to basedir of task

This restores previous behaviour in pre 2.0 and allows for 'local type' plugins
and actions to have a more predictable relative path.

fixes #14489

* removed FIXME since prev commit 'fixes' this

* fix tests, now they need a loader (thanks jimi!)
2016-07-25 08:11:45 -04:00
s-hertel
93c5ec42cf Test GalaxyCLI when no actions are provided
Adds a new test for GalaxyCLI. Tests cases when:

- no actions are provided
- invalid actions are provided
- each valid action is provided

When parser() runs successfully the method returns True, creates a
SortedOptParser instance, a Galaxy instance, and updates certain class data.
2016-07-22 14:39:01 -04:00
s-hertel
671f9c3d15 Merge pull request #16783 from s-hertel/test_display_galaxy_info_fix
fixing a logic error in test_galaxy
2016-07-21 15:22:07 -04:00
s-hertel
3cb5747f54 fixing a logic error in test_galaxy 2016-07-21 15:02:19 -04:00
s-hertel
aae5e50299 Adding a test for GalaxyCLI. Tests exit_without_ignore method. 2016-07-21 13:53:44 -04:00
Christoph Dittmann
d55452d3ed Adding unit tests for role variable precedence
Originally from PR #16735
2016-07-20 10:14:44 -04:00
jctanner
238c6461f6 Add a function to check for killed processes in all strategies (#16684)
* Add a function to check for killed processes so that if any
threads are sigkilled or sigtermed, the entire playbook execution is aborted.
2016-07-14 16:37:35 -04:00
Toshio Kuratomi
c8a8f546d4 A little unittest refactoring (#16704)
A little unittest refactoring

* Add a class decorator to generate tests when using a unittest.TestCase base class
* Add a TestCase subclass with setUp() and tearDown() that sets up
  module parameter parsing
* Move test_safe_eval to use the class decorator and ModuleTestCase base
  class
* Move testing of set_mode_if_different into its own file and separate
  some test methods out so we get better errors and more coverage in
  case of errors.
* Naming convention for test cases doesn't need to duplicate information
  that's already in the file path.
2016-07-14 09:22:54 -07:00
James Cammarata
221520cbad Fixing type in 293723f (mock_handler -> mock_handler_task) 2016-07-12 17:00:29 -05:00