Merge branch '2017.7' into Issue47689-pip-state-performance

This commit is contained in:
Orlando Richards 2018-07-29 22:04:23 +01:00 committed by GitHub
commit bb5939d6ef
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
33 changed files with 949 additions and 371 deletions

View file

@ -29,13 +29,13 @@ pipeline {
parallel {
stage('salt linting') {
steps {
sh 'eval "$(pyenv init -)"; tox -e pylint-salt | tee pylint-report.xml'
sh 'eval "$(pyenv init -)"; tox -e pylint-salt $(find salt/ -name "*.py" -exec git diff --name-only "origin/$CHANGE_TARGET" "origin/$BRANCH_NAME" setup.py {} +) | tee pylint-report.xml'
archiveArtifacts artifacts: 'pylint-report.xml'
}
}
stage('test linting') {
steps {
sh 'eval "$(pyenv init -)"; tox -e pylint-tests | tee pylint-report-tests.xml'
sh 'eval "$(pyenv init -)"; tox -e pylint-tests $(find tests/ -name "*.py" -exec git diff --name-only "origin/$CHANGE_TARGET" "origin/$BRANCH_NAME" {} +) | tee pylint-report-tests.xml'
archiveArtifacts artifacts: 'pylint-report-tests.xml'
}
}
@ -49,7 +49,9 @@ pipeline {
parserName: 'PyLint',
pattern: 'pylint-report*.xml'
]],
failedTotalAll: '1',
failedTotalAll: '0',
useDeltaValues: false,
canRunOnFailed: true,
usePreviousBuildAsReference: true
])
cleanWs()

View file

@ -138,7 +138,7 @@
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="http://saltstack.com/" target="_blank"><img src="{{ pathto('_static/images/saltstack.svg', 1) }}" class="nolightbox" height="40px" width="170px"></a>
<a href="http://saltstack.com/" target="_blank"><img src="{{ pathto('_static/images/SaltStack_white.svg', 1) }}" class="nolightbox" height="40px" width="170px"></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="navbarCollapse">
@ -252,13 +252,11 @@
<p>© {{ copyright }} SaltStack. All Rights Reserved, SaltStack Inc. | <a href="http://saltstack.com/privacy-policy" target="_blank">Privacy Policy</a></p>
</div>
</div>
<div class="col-sm-6">
<!--
<a href="https://saltstack.com/saltstack-enterprise/" target="_blank"><img class="nolightbox footer-banner center" src="{{ pathto('_static/images/enterprise_ad.jpg', 1) }}"/></a>
-->
<a href="http://saltconf.com" target="_blank"><img class="nolightbox footer-banner center" src="{{ pathto('_static/images/DOCBANNER.jpg', 1) }}"/></a>
</div>
{% endif %}
</div>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 240 KiB

After

Width:  |  Height:  |  Size: 589 KiB

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 301.57 44.47"><defs><style>.cls-1{fill:#fff;}</style></defs><title>Asset 2</title><g id="Layer_2" data-name="Layer 2"><g id="Layer_1-2" data-name="Layer 1"><path class="cls-1" d="M50.63,6.05h8.79L72.58,43.24H64.15L61.7,35.6H48l-2.52,7.64H37.35Zm-.51,23.14h9.52l-4.7-14.64Z"/><path class="cls-1" d="M76.12,6.05h7.77V36.56h18.58v6.68H76.12Z"/><path class="cls-1" d="M127.07,6.05v6.58H115.94V43.24h-7.82V12.63H96.94V6.05Z"/><path class="cls-1" d="M190.53,6.05v6.58H179.41V43.24h-7.83V12.63H160.4V6.05Z"/><path class="cls-1" d="M200.41,6.05h8.8l13.16,37.19h-8.43l-2.45-7.64h-13.7l-2.52,7.64h-8.13Zm-.51,23.14h9.53l-4.7-14.64Z"/><path class="cls-1" d="M227.91,10.17a15.34,15.34,0,0,1,11.34-4.83q9.28-.2,13.71,5.87a13.46,13.46,0,0,1,2.69,6.89l-7.77.16a10.78,10.78,0,0,0-2-4A7.68,7.68,0,0,0,239.68,12a7.59,7.59,0,0,0-6.48,3.56Q230.88,19,231,25.25t2.73,9.32a7.91,7.91,0,0,0,6.49,3,7.27,7.27,0,0,0,6-2.8,11.86,11.86,0,0,0,1.84-4.35l7.72-.17a16.79,16.79,0,0,1-4.9,10,14.83,14.83,0,0,1-10.44,4q-7.94.16-12.59-4.88t-4.84-14.09Q222.85,15.56,227.91,10.17Z"/><path class="cls-1" d="M260.39,6.05H268V21.37L282.4,6.05h10.05L277.18,21.34l16.05,21.9h-10L271.78,27,268,30.8V43.24h-7.64Z"/><path class="cls-1" d="M15.65,12.47a9.05,9.05,0,0,1,4.6-1.05,10.15,10.15,0,0,1,4.63.94,5.29,5.29,0,0,1,3,4.77h7.47a11.06,11.06,0,0,0-4.4-9A16.57,16.57,0,0,0,20.79,5a23,23,0,0,0-5.14.54Z"/><path class="cls-1" d="M33.21,24.77a16.6,16.6,0,0,0-6.43-2.7l-6.53-1.54A22.45,22.45,0,0,1,15.31,19a3.18,3.18,0,0,1-1.81-3c0-.12,0-.22,0-.34H6.35c0,.3,0,.59,0,.9q0,5.47,3.76,8.05,2.22,1.54,8.15,2.85l4,.89a17.48,17.48,0,0,1,5.17,1.74A3.17,3.17,0,0,1,29,33c0,2.1-1.1,3.54-3.32,4.31a14.08,14.08,0,0,1-4.56.61c-3.13,0-5.33-.77-6.62-2.3a7.48,7.48,0,0,1-1.42-3.81H5.7a11,11,0,0,0,4.21,9.12q4.22,3.33,11.56,3.32,7.19,0,11.13-3.37a10.64,10.64,0,0,0,3.94-8.46A9.1,9.1,0,0,0,33.21,24.77Z"/><path class="cls-1" d="M137.55,12.73a9,9,0,0,1,4.6-1.05,10.18,10.18,0,0,1,4.63.94,5.33,5.33,0,0,1,3,4.77h7.47a11,11,0,0,0-4.41-9,16.54,16.54,0,0,0-10.15-3.12,23,23,0,0,0-5.14.54Z"/><path class="cls-1" d="M155.11,25a16.83,16.83,0,0,0-6.43-2.7l-6.53-1.54a21.71,21.71,0,0,1-4.94-1.54,3.17,3.17,0,0,1-1.81-3c0-.13,0-.23,0-.35h-7.19c0,.3-.05.6-.05.9,0,3.65,1.26,6.34,3.77,8.05,1.48,1,4.19,2,8.15,2.85l4,.89a17.29,17.29,0,0,1,5.16,1.74,3.16,3.16,0,0,1,1.63,2.85q0,3.15-3.32,4.32a14.39,14.39,0,0,1-4.56.6c-3.13,0-5.34-.76-6.62-2.3A7.48,7.48,0,0,1,135,32H127.6a11,11,0,0,0,4.21,9.13c2.8,2.21,6.66,3.32,11.55,3.32s8.51-1.13,11.14-3.37a10.7,10.7,0,0,0,3.94-8.47A9.1,9.1,0,0,0,155.11,25Z"/><rect class="cls-1" width="9.85" height="9.85"/><path class="cls-1" d="M299.8,40.44a.94.94,0,0,0,.16-.57,1.06,1.06,0,0,0-.08-.45.82.82,0,0,0-.24-.32,1,1,0,0,0-.38-.19,1.72,1.72,0,0,0-.52-.07h-1.2v3.4h.59V40.93h.66l.68,1.31h.63v0l-.76-1.42A1,1,0,0,0,299.8,40.44Zm-.59-.14a.52.52,0,0,1-.19.12,1.18,1.18,0,0,1-.28,0h-.61V39.32h.61a.79.79,0,0,1,.28,0,.55.55,0,0,1,.2.11.76.76,0,0,1,.12.19.85.85,0,0,1,0,.23.56.56,0,0,1,0,.23A.36.36,0,0,1,299.21,40.3Z"/><path class="cls-1" d="M298.7,37.68a2.88,2.88,0,1,0,2.87,2.87A2.88,2.88,0,0,0,298.7,37.68Zm0,5.27a2.4,2.4,0,1,1,2.39-2.4A2.41,2.41,0,0,1,298.7,43Z"/></g></g></svg>

After

Width:  |  Height:  |  Size: 3.1 KiB

View file

@ -21,11 +21,21 @@ SaltStack has its own coding style guide that informs contributors on various co
approaches. Please review the :ref:`Salt Coding Style <coding-style>` documentation
for information about Salt's particular coding patterns.
Within the :ref:`Salt Coding Style <coding-style>` documentation, there is a section
about running Salt's ``.pylintrc`` file. SaltStack recommends running the ``.pylintrc``
file on any files you are changing with your code contribution before submitting a
pull request to Salt's repository. Please see the :ref:`Linting<pylint-instructions>`
documentation for more information.
Within the :ref:`Salt Coding Style <coding-style>` documentation, there is a
section about running Salt's ``.testing.pylintrc`` file. SaltStack recommends
running the ``.testing.pylintrc`` file on any files you are changing with your
code contribution before submitting a pull request to Salt's repository. Please
see the :ref:`Linting<pylint-instructions>` documentation for more information.
.. note::
There are two pylint files in the ``salt`` directory. One is the
``.pylintrc`` file and the other is the ``.testing.pylintrc`` file. The
tests that run in Jenkins against GitHub Pull Requests use
``.testing.pylintrc``. The ``testing.pylintrc`` file is a little less
strict than the ``.pylintrc`` and is used to make it easier for contributors
to submit changes. The ``.pylintrc`` file can be used for linting, but the
``testing.pylintrc`` is the source of truth when submitting pull requests.
.. _github-pull-request:

View file

@ -22,21 +22,31 @@ improve Salt)!!
Linting
=======
Most Salt style conventions are codified in Salt's ``.pylintrc`` file. Salt's
pylint file has two dependencies: pylint_ and saltpylint_. You can install
these dependencies with ``pip``:
Most Salt style conventions are codified in Salt's ``.testing.pylintrc`` file.
Salt's pylint file has two dependencies: pylint_ and saltpylint_. You can
install these dependencies with ``pip``:
.. code-block:: bash
pip install pylint
pip install saltpylint
The ``.pylintrc`` file is found in the root of the Salt project and can be passed
as an argument to the pylint_ program as follows:
The ``.testing.pylintrc`` file is found in the root of the Salt project and can
be passed as an argument to the pylint_ program as follows:
.. code-block:: bash
pylint --rcfile=/path/to/salt/.pylintrc salt/dir/to/lint
pylint --rcfile=/path/to/salt/.testing.pylintrc salt/dir/to/lint
.. note::
There are two pylint files in the ``salt`` directory. One is the
``.pylintrc`` file and the other is the ``.testing.pylintrc`` file. The
tests that run in Jenkins against GitHub Pull Requests use
``.testing.pylintrc``. The ``testing.pylintrc`` file is a little less
strict than the ``.pylintrc`` and is used to make it easier for contributors
to submit changes. The ``.pylintrc`` file can be used for linting, but the
``testing.pylintrc`` is the source of truth when submitting pull requests.
.. _pylint: http://www.pylint.org
.. _saltpylint: https://github.com/saltstack/salt-pylint

View file

@ -130,20 +130,18 @@ If Defined ProgramFiles(x86) (
)
@echo.
@echo Copying VCRedist to Prerequisites
@echo ----------------------------------------------------------------------
:: Make sure the "prereq" directory exists
If NOT Exist "%PreDir%" mkdir "%PreDir%"
:: Set the location of the vcredist to download
If %Python%==3 (
Set Url64="http://repo.saltstack.com/windows/dependencies/64/vcredist_x64_2015.exe"
Set Url32="http://repo.saltstack.com/windows/dependencies/32/vcredist_x86_2015.exe"
:: Don't include the vcredist for Py3 installations
If %Python%==3 goto :vcredist_end
) Else (
Set Url64="http://repo.saltstack.com/windows/dependencies/64/vcredist_x64_2008_mfc.exe"
Set Url32="http://repo.saltstack.com/windows/dependencies/32/vcredist_x86_2008_mfc.exe"
)
@echo Copying VCRedist to Prerequisites
@echo ----------------------------------------------------------------------
:: Set the location of the vcredist to download
Set Url64="http://repo.saltstack.com/windows/dependencies/64/vcredist_x64_2008_mfc.exe"
Set Url32="http://repo.saltstack.com/windows/dependencies/32/vcredist_x86_2008_mfc.exe"
:: Check for 64 bit by finding the Program Files (x86) directory
If Defined ProgramFiles(x86) (
@ -153,6 +151,8 @@ If Defined ProgramFiles(x86) (
)
@echo.
:vcredist_end
:: Remove the fixed path in .exe files
@echo Removing fixed path from .exe files
@echo ----------------------------------------------------------------------

View file

@ -211,26 +211,13 @@ Section -Prerequisites
Var /Global CheckVcRedist
StrCpy $CheckVcRedist "False"
# Visual C++ 2015 redist packages
!define PY3_VC_REDIST_NAME "VC_Redist_2015"
!define PY3_VC_REDIST_X64_GUID "{50A2BC33-C9CD-3BF1-A8FF-53C10A0B183C}"
!define PY3_VC_REDIST_X86_GUID "{BBF2AC74-720C-3CB3-8291-5E34039232FA}"
# Visual C++ 2008 SP1 MFC Security Update redist packages
!define PY2_VC_REDIST_NAME "VC_Redist_2008_SP1_MFC"
!define PY2_VC_REDIST_X64_GUID "{5FCE6D76-F5DC-37AB-B2B8-22AB8CEDB1D4}"
!define PY2_VC_REDIST_X86_GUID "{9BE518E6-ECC6-35A9-88E4-87755C07200F}"
${If} ${PYTHON_VERSION} == 3
StrCpy $VcRedistName ${PY3_VC_REDIST_NAME}
${If} ${CPUARCH} == "AMD64"
StrCpy $VcRedistGuid ${PY3_VC_REDIST_X64_GUID}
${Else}
StrCpy $VcRedistGuid ${PY3_VC_REDIST_X86_GUID}
${EndIf}
StrCpy $CheckVcRedist "True"
${Else}
# VCRedist only needs to be installed for Python 2
${If} ${PYTHON_VERSION} == 2
StrCpy $VcRedistName ${PY2_VC_REDIST_NAME}
${If} ${CPUARCH} == "AMD64"

View file

@ -164,7 +164,7 @@ def salt_refs(data, ret=None):
return ret
def prep_trans_tar(opts, file_client, chunks, file_refs, pillar=None, id_=None):
def prep_trans_tar(file_client, chunks, file_refs, pillar=None, id_=None):
'''
Generate the execution package from the saltenv file refs and a low state
data structure

View file

@ -32,10 +32,10 @@ __func_alias__ = {
log = logging.getLogger(__name__)
def _ssh_state(chunks, __opts__, __context__, __pillar__, __salt__, st_kwargs,
def _ssh_state(chunks, st_kwargs,
kwargs, test=False):
'''
funciton to run a state with the given chunk via salt-ssh
Function to run a state with the given chunk via salt-ssh
'''
file_refs = salt.client.ssh.state.lowstate_file_refs(
chunks,
@ -46,7 +46,6 @@ def _ssh_state(chunks, __opts__, __context__, __pillar__, __salt__, st_kwargs,
)
# Create the tar containing the state pkg and relevant files.
trans_tar = salt.client.ssh.state.prep_trans_tar(
__opts__,
__context__['fileclient'],
chunks,
file_refs,
@ -210,7 +209,6 @@ def sls(mods, saltenv='base', test=None, exclude=None, **kwargs):
# Create the tar containing the state pkg and relevant files.
_cleanup_slsmod_low_data(chunks)
trans_tar = salt.client.ssh.state.prep_trans_tar(
__opts__,
__context__['fileclient'],
chunks,
file_refs,
@ -377,7 +375,6 @@ def low(data, **kwargs):
)
# Create the tar containing the state pkg and relevant files.
trans_tar = salt.client.ssh.state.prep_trans_tar(
__opts__,
__context__['fileclient'],
chunks,
file_refs,
@ -462,7 +459,6 @@ def high(data, **kwargs):
# Create the tar containing the state pkg and relevant files.
_cleanup_slsmod_low_data(chunks)
trans_tar = salt.client.ssh.state.prep_trans_tar(
__opts__,
__context__['fileclient'],
chunks,
file_refs,
@ -696,7 +692,6 @@ def highstate(test=None, **kwargs):
# Create the tar containing the state pkg and relevant files.
_cleanup_slsmod_low_data(chunks)
trans_tar = salt.client.ssh.state.prep_trans_tar(
__opts__,
__context__['fileclient'],
chunks,
file_refs,
@ -773,7 +768,6 @@ def top(topfn, test=None, **kwargs):
# Create the tar containing the state pkg and relevant files.
_cleanup_slsmod_low_data(chunks)
trans_tar = salt.client.ssh.state.prep_trans_tar(
__opts__,
__context__['fileclient'],
chunks,
file_refs,
@ -938,10 +932,6 @@ def sls_id(id_, mods, test=None, queue=False, **kwargs):
)
ret = _ssh_state(chunk,
__opts__,
__context__,
__pillar__,
__salt__,
st_kwargs,
kwargs,
test=test)
@ -1134,7 +1124,6 @@ def single(fun, name, test=None, **kwargs):
# Create the tar containing the state pkg and relevant files.
trans_tar = salt.client.ssh.state.prep_trans_tar(
__opts__,
__context__['fileclient'],
chunks,
file_refs,

View file

@ -101,6 +101,7 @@ def cert(name,
server=None,
owner='root',
group='root',
mode='0640',
certname=None):
'''
Obtain/renew a certificate from an ACME CA, probably Let's Encrypt.
@ -113,8 +114,9 @@ def cert(name,
:param renew: True/'force' to force a renewal, or a window of renewal before expiry in days
:param keysize: RSA key bits
:param server: API endpoint to talk to
:param owner: owner of private key
:param group: group of private key
:param owner: owner of the private key file
:param group: group of the private key file
:param mode: mode of the private key file
:param certname: Name of the certificate to save
:return: dict with 'result' True/False/None, 'comment' and certificate's expiry date ('not_after')
@ -170,27 +172,17 @@ def cert(name,
return {'result': False, 'comment': 'Certificate {0} renewal failed with:\n{1}'.format(name, res['stderr'])}
if 'no action taken' in res['stdout']:
return {'result': None,
'comment': 'No action taken on certificate {0}'.format(cert_file),
'not_after': expires(name)}
if renew:
comment = 'Certificate {0} unchanged'.format(cert_file)
elif renew:
comment = 'Certificate {0} renewed'.format(name)
else:
comment = 'Certificate {0} obtained'.format(name)
ret = {'comment': comment, 'not_after': expires(name)}
res = __salt__['file.check_perms'](_cert_file(name, 'privkey'), {}, owner, group, '0600', follow_symlinks=True)
if res is None:
ret['result'] = False
ret['comment'] += ', but setting permissions failed.'
elif not res[0].get('result', False):
ret['result'] = False
ret['comment'] += ', but setting permissions failed with \n{0}'.format(res[0]['comment'])
else:
ret['result'] = True
ret['comment'] += '.'
ret = {'comment': comment, 'not_after': expires(name), 'changes': {}, 'result': True}
ret, _ = __salt__['file.check_perms'](_cert_file(name, 'privkey'),
ret,
owner, group, mode,
follow_symlinks=True)
return ret

View file

@ -5235,7 +5235,6 @@ def _prepare_trans_tar(name, mods=None, saltenv='base', pillar=None):
refs = salt.client.ssh.state.lowstate_file_refs(chunks)
_mk_fileclient()
trans_tar = salt.client.ssh.state.prep_trans_tar(
__opts__,
__context__['cp.fileclient'],
chunks, refs, pillar, name)
return trans_tar

View file

@ -160,7 +160,11 @@ def install(pkg=None,
env.update({'SUDO_UID': uid, 'SUDO_USER': ''})
cmd = ' '.join(cmd)
result = __salt__['cmd.run_all'](cmd, python_shell=True, cwd=dir, runas=runas, env=env)
result = __salt__['cmd.run_all'](cmd,
python_shell=True,
cwd=dir,
runas=runas,
env=env)
if result['retcode'] != 0:
raise CommandExecutionError(result['stderr'])
@ -168,33 +172,9 @@ def install(pkg=None,
# npm >1.2.21 is putting the output to stderr even though retcode is 0
npm_output = result['stdout'] or result['stderr']
try:
return json.loads(npm_output)
return salt.utils.find_json(npm_output)
except ValueError:
pass
json_npm_output = _extract_json(npm_output)
return json_npm_output or npm_output
def _extract_json(npm_output):
lines = npm_output.splitlines()
log.error(lines)
# Strip all lines until JSON output starts
while lines and not lines[0].startswith('{') and not lines[0].startswith('['):
lines = lines[1:]
while lines and not lines[-1].startswith('}') and not lines[-1].startswith(']'):
lines = lines[:-1]
# macOS with fsevents includes the following line in the return
# when a new module is installed which is invalid JSON:
# [fsevents] Success: "..."
while lines and (lines[0].startswith('[fsevents]') or lines[0].startswith('Pass ')):
lines = lines[1:]
try:
return json.loads(''.join(lines))
except ValueError:
pass
return None
return npm_output
def uninstall(pkg, dir=None, runas=None, env=None):

View file

@ -7,50 +7,55 @@ powercfg.
.. code-block:: bash
# Set monitor to never turn off on Battery power
salt '*' powercfg.set_monitor_timeout 0 power=dc
# Set disk timeout to 120 minutes on AC power
salt '*' powercfg.set_disk_timeout 120 power=ac
'''
# Import Python Libs
from __future__ import absolute_import
import re
import logging
# Import Salt Libs
import salt.utils
log = logging.getLogger(__name__)
__virtualname__ = "powercfg"
__virtualname__ = 'powercfg'
def __virtual__():
'''
Only work on Windows
'''
if __grains__['os'] == 'Windows':
return __virtualname__
return (False, 'Module only works on Windows.')
if not salt.utils.is_windows():
return False, 'PowerCFG: Module only works on Windows'
return __virtualname__
def _get_current_scheme():
cmd = "powercfg /getactivescheme"
cmd = 'powercfg /getactivescheme'
out = __salt__['cmd.run'](cmd, python_shell=False)
matches = re.search(r"GUID: (.*) \(", out)
matches = re.search(r'GUID: (.*) \(', out)
return matches.groups()[0].strip()
def _get_powercfg_minute_values(scheme, guid, subguid, safe_name):
'''
Returns the AC/DC values in an array for a guid and subguid for a the given scheme
Returns the AC/DC values in an dict for a guid and subguid for a the given
scheme
'''
if scheme is None:
scheme = _get_current_scheme()
if __grains__['osrelease'] == '7':
cmd = "powercfg /q {0} {1}".format(scheme, guid)
cmd = 'powercfg /q {0} {1}'.format(scheme, guid)
else:
cmd = "powercfg /q {0} {1} {2}".format(scheme, guid, subguid)
cmd = 'powercfg /q {0} {1} {2}'.format(scheme, guid, subguid)
out = __salt__['cmd.run'](cmd, python_shell=False)
split = out.split("\r\n\r\n")
split = out.split('\r\n\r\n')
if len(split) > 1:
for s in split:
if safe_name in s or subguid in s:
@ -59,172 +64,309 @@ def _get_powercfg_minute_values(scheme, guid, subguid, safe_name):
else:
out = split[0]
raw_settings = re.findall(r"Power Setting Index: ([0-9a-fx]+)", out)
return {"ac": int(raw_settings[0], 0) / 60, "dc": int(raw_settings[1], 0) / 60}
raw_settings = re.findall(r'Power Setting Index: ([0-9a-fx]+)', out)
return {'ac': int(raw_settings[0], 0) / 60,
'dc': int(raw_settings[1], 0) / 60}
def _set_powercfg_value(scheme, sub_group, setting_guid, power, value):
'''
Sets the value of a setting with a given power (ac/dc) to
the given scheme
Sets the AC/DC values of a setting with the given power for the given scheme
'''
salt.utils.warn_until(
'Fluorine',
'This function now expects the timeout value in minutes instead of '
'seconds as stated in the documentation. This warning will be removed '
'in Salt Fluorine.')
if scheme is None:
scheme = _get_current_scheme()
cmd = "powercfg /set{0}valueindex {1} {2} {3} {4}".format(power, scheme, sub_group, setting_guid, value)
return __salt__['cmd.run'](cmd, python_shell=False)
cmd = 'powercfg /set{0}valueindex {1} {2} {3} {4}' \
''.format(power, scheme, sub_group, setting_guid, value * 60)
return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
def set_monitor_timeout(timeout, power="ac", scheme=None):
def set_monitor_timeout(timeout, power='ac', scheme=None):
'''
Set the monitor timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the monitor will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' powercfg.set_monitor_timeout 30 power=ac
timeout
The amount of time in minutes before the monitor will timeout
power
Should we set the value for AC or DC (battery)? Valid options ac,dc.
scheme
The scheme to use, leave as None to use the current.
# Sets the monitor timeout to 30 minutes
salt '*' powercfg.set_monitor_timeout 30
'''
return _set_powercfg_value(scheme, "SUB_VIDEO", "VIDEOIDLE", power, timeout)
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_VIDEO',
setting_guid='VIDEOIDLE',
power=power,
value=timeout)
def get_monitor_timeout(scheme=None):
'''
Get the current monitor timeout of the given scheme
Args:
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_monitor_timeout
scheme
The scheme to use, leave as None to use the current.
'''
return _get_powercfg_minute_values(scheme, "SUB_VIDEO", "VIDEOIDLE", "Turn off display after")
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_VIDEO',
subguid='VIDEOIDLE',
safe_name='Turn off display after')
def set_disk_timeout(timeout, power="ac", scheme=None):
def set_disk_timeout(timeout, power='ac', scheme=None):
'''
Set the disk timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the disk will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the disk timeout to 30 minutes on battery
salt '*' powercfg.set_disk_timeout 30 power=dc
timeout
The amount of time in minutes before the disk will timeout
power
Should we set the value for AC or DC (battery)? Valid options ac,dc.
scheme
The scheme to use, leave as None to use the current.
'''
return _set_powercfg_value(scheme, "SUB_DISK", "DISKIDLE", power, timeout)
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_DISK',
setting_guid='DISKIDLE',
power=power,
value=timeout)
def get_disk_timeout(scheme=None):
'''
Get the current disk timeout of the given scheme
Args:
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_disk_timeout
scheme
The scheme to use, leave as None to use the current.
'''
return _get_powercfg_minute_values(scheme, "SUB_DISK", "DISKIDLE", "Turn off hard disk after")
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_DISK',
subguid='DISKIDLE',
safe_name='Turn off hard disk after')
def set_standby_timeout(timeout, power="ac", scheme=None):
def set_standby_timeout(timeout, power='ac', scheme=None):
'''
Set the standby timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer sleeps
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
# Sets the system standby timeout to 30 minutes on Battery
salt '*' powercfg.set_standby_timeout 30 power=dc
timeout
The amount of time in minutes before the computer sleeps
power
Should we set the value for AC or DC (battery)? Valid options ac,dc.
scheme
The scheme to use, leave as None to use the current.
'''
return _set_powercfg_value(scheme, "SUB_SLEEP", "STANDBYIDLE", power, timeout)
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='STANDBYIDLE',
power=power,
value=timeout)
def get_standby_timeout(scheme=None):
'''
Get the current standby timeout of the given scheme
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_standby_timeout
scheme
The scheme to use, leave as None to use the current.
'''
return _get_powercfg_minute_values(scheme, "SUB_SLEEP", "STANDBYIDLE", "Sleep after")
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_SLEEP',
subguid='STANDBYIDLE',
safe_name='Sleep after')
def set_hibernate_timeout(timeout, power="ac", scheme=None):
def set_hibernate_timeout(timeout, power='ac', scheme=None):
'''
Set the hibernate timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the computer hibernates
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
bool: ``True`` if successful, otherwise ``False``
CLI Example:
.. code-block:: bash
salt '*' powercfg.set_hibernate_timeout 30 power=pc
timeout
The amount of time in minutes before the computer hibernates
power
Should we set the value for AC or DC (battery)? Valid options ac,dc.
scheme
The scheme to use, leave as None to use the current.
# Sets the hibernate timeout to 30 minutes on Battery
salt '*' powercfg.set_hibernate_timeout 30 power=dc
'''
return _set_powercfg_value(scheme, "SUB_SLEEP", "HIBERNATEIDLE", power, timeout)
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_SLEEP',
setting_guid='HIBERNATEIDLE',
power=power,
value=timeout)
def get_hibernate_timeout(scheme=None):
'''
Get the current hibernate timeout of the given scheme
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
Returns:
dict: A dictionary of both the AC and DC settings
CLI Example:
.. code-block:: bash
salt '*' powercfg.get_hibernate_timeout
scheme
The scheme to use, leave as None to use the current.
'''
return _get_powercfg_minute_values(scheme, "SUB_SLEEP", "HIBERNATEIDLE", "Hibernate after")
return _get_powercfg_minute_values(
scheme=scheme,
guid='SUB_SLEEP',
subguid='HIBERNATEIDLE',
safe_name='Hibernate after')

View file

@ -9,6 +9,12 @@ import salt.utils
import logging
import re
try:
import tzlocal
HAS_TZLOCAL = True
except ImportError:
HAS_TZLOCAL = False
log = logging.getLogger(__name__)
# Maybe put in a different file ... ? %-0
@ -473,6 +479,10 @@ def get_zone():
salt '*' timezone.get_zone
'''
if HAS_TZLOCAL:
return tzlocal.get_localzone().zone
log.warning('tzutil not installed. get_zone might be inaccurate')
winzone = __salt__['cmd.run'](['tzutil', '/g'], python_shell=False)
for key in LINTOWIN:
if LINTOWIN[key] == winzone:

View file

@ -171,7 +171,9 @@ def init(
start=True,
disk='default',
saltenv='base',
enable_vnc=False):
enable_vnc=False,
seed_cmd='seed.apply',
enable_qcow=False):
'''
This routine is used to create a new virtual machine. This routines takes
a number of options to determine what the newly created virtual machine
@ -193,14 +195,14 @@ def init(
on the salt fileserver, but http, https and ftp can also be used.
hypervisor
The hypervisor to use for the new virtual machine. Default is 'kvm'.
The hypervisor to use for the new virtual machine. Default is `kvm`.
host
The host to use for the new virtual machine, if this is omitted
Salt will automatically detect what host to use.
seed
Set to False to prevent Salt from seeding the new virtual machine.
Set to `False` to prevent Salt from seeding the new virtual machine.
nic
The nic profile to use, defaults to the "default" nic profile which
@ -216,6 +218,17 @@ def init(
saltenv
The Salt environment to use
enable_vnc
Whether a VNC screen is attached to resulting VM. Default is `False`.
seed_cmd
If seed is `True`, use this execution module function to seed new VM.
Default is `seed.apply`.
enable_qcow
Clone disk image as a copy-on-write qcow2 image, using downloaded
`image` as backing file.
'''
__jid_event__.fire_event({'message': 'Searching for hosts'}, 'progress')
data = query(host, quiet=True)
@ -256,25 +269,29 @@ def init(
)
try:
cmd_ret = client.cmd_iter(
host,
'virt.init',
[
name,
cpu,
mem,
image,
nic,
hypervisor,
start,
disk,
saltenv,
seed,
install,
pub_key,
priv_key,
enable_vnc,
],
timeout=600)
host,
'virt.init',
[
name,
cpu,
mem
],
timeout=600,
kwarg={
'image': image,
'nic': nic,
'hypervisor': hypervisor,
'start': start,
'disk': disk,
'saltenv': saltenv,
'seed': seed,
'install': install,
'pub_key': pub_key,
'priv_key': priv_key,
'seed_cmd': seed_cmd,
'enable_vnc': enable_vnc,
'enable_qcow': enable_qcow,
})
except SaltClientError as client_error:
# Fall through to ret error handling below
print(client_error)

View file

@ -49,6 +49,7 @@ def cert(name,
server=None,
owner='root',
group='root',
mode='0640',
certname=None):
'''
Obtain/renew a certificate from an ACME CA, probably Let's Encrypt.
@ -61,8 +62,9 @@ def cert(name,
:param renew: True/'force' to force a renewal, or a window of renewal before expiry in days
:param keysize: RSA key bits
:param server: API endpoint to talk to
:param owner: owner of private key
:param group: group of private key
:param owner: owner of the private key file
:param group: group of the private key file
:param mode: mode of the private key file
:param certname: Name of the certificate to save
'''
@ -105,7 +107,8 @@ def cert(name,
keysize=keysize,
server=server,
owner=owner,
group=group
group=group,
mode=mode
)
ret = {

View file

@ -275,9 +275,13 @@ def bootstrap(name, user=None, silent=True):
if __opts__['test']:
try:
call = __salt__['npm.install'](dir=name, runas=user, pkg=None, silent=silent, dry_run=True)
ret['result'] = None
ret['changes'] = {'old': [], 'new': call}
ret['comment'] = '{0} is set to be bootstrapped'.format(name)
if call:
ret['result'] = None
ret['changes'] = {'old': [], 'new': call}
ret['comment'] = '{0} is set to be bootstrapped'.format(name)
else:
ret['result'] = True
ret['comment'] = '{0} is already bootstrapped'.format(name)
except (CommandNotFoundError, CommandExecutionError) as err:
ret['result'] = False
ret['comment'] = 'Error Bootstrapping \'{0}\': {1}'.format(name, err)

View file

@ -8,6 +8,7 @@ powercfg.
.. code-block:: yaml
# Set timeout to 30 minutes on battery power
monitor:
powercfg.set_timeout:
- value: 30
@ -18,82 +19,131 @@ powercfg.
from __future__ import absolute_import
import logging
# Import Salt Libs
import salt.utils
log = logging.getLogger(__name__)
__virtualname__ = "powercfg"
__virtualname__ = 'powercfg'
def __virtual__():
'''
Only work on Windows
'''
if __grains__['os'] == 'Windows':
return __virtualname__
return False
if not salt.utils.is_windows():
return False, 'PowerCFG: Module only works on Windows'
return __virtualname__
def _check_or_set(check_func, set_func, value, power):
values = check_func()
if values[power] == value:
return True
else:
set_func(value, power)
return False
def set_timeout(name, value, power="ac", scheme=None):
def set_timeout(name, value, power='ac', scheme=None):
'''
Set the sleep timeouts of specific items such as disk, monitor.
Set the sleep timeouts of specific items such as disk, monitor, etc.
Args:
name (str)
The setting to change, can be one of the following:
- ``monitor``
- ``disk``
- ``standby``
- ``hibernate``
value (int):
The amount of time in minutes before the item will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Power)
- ``dc`` (Battery)
scheme (str):
The scheme to use, leave as ``None`` to use the current. Default is
``None``. This can be the GUID or the Alias for the Scheme. Known
Aliases are:
- ``SCHEME_BALANCED`` - Balanced
- ``SCHEME_MAX`` - Power saver
- ``SCHEME_MIN`` - High performance
CLI Example:
.. code-block:: yaml
# Set monitor timeout to 30 minutes on Battery
monitor:
powercfg.set_timeout:
- value: 30
- power: dc
powercfg.set_timeout:
- value: 30
- power: dc
# Set disk timeout to 10 minutes on AC Power
disk:
powercfg.set_timeout:
- value: 12
- power: ac
name
The setting to change, can be one of the following: monitor, disk, standby, hibernate
timeout
The amount of time in minutes before the item will timeout i.e the monitor
power
Should we set the value for AC or DC (battery)? Valid options ac,dc.
scheme
The scheme to use, leave as None to use the current.
powercfg.set_timeout:
- value: 10
- power: ac
'''
ret = {'name': name,
'result': True,
'comment': '',
'changes': {}}
comment = []
# Validate name values
name = name.lower()
if name not in ['monitor', 'disk', 'standby', 'hibernate']:
ret['result'] = False
ret['comment'] = '"{0}" is not a valid setting'.format(name)
log.debug(ret['comment'])
return ret
if name not in ["monitor", "disk", "standby", "hibernate"]:
ret["result"] = False
comment.append("{0} is not a valid setting".format(name))
elif power not in ["ac", "dc"]:
ret["result"] = False
comment.append("{0} is not a power type".format(power))
# Validate power values
power = power.lower()
if power not in ['ac', 'dc']:
ret['result'] = False
ret['comment'] = '"{0}" is not a power type'.format(power)
log.debug(ret['comment'])
return ret
# Get current settings
old = __salt__['powercfg.get_{0}_timeout'.format(name)](scheme=scheme)
# Check current settings
if old[power] == value:
ret['comment'] = '{0} timeout on {1} power is already set to {2}' \
''.format(name.capitalize(), power.upper(), value)
return ret
else:
check_func = __salt__["powercfg.get_{0}_timeout".format(name)]
set_func = __salt__["powercfg.set_{0}_timeout".format(name)]
ret['comment'] = '{0} timeout on {1} power will be set to {2}' \
''.format(name.capitalize(), power.upper(), value)
values = check_func(scheme=scheme)
if values[power] == value:
comment.append("{0} {1} is already set with the value {2}.".format(name, power, value))
else:
ret['changes'] = {name: {power: value}}
set_func(value, power, scheme=scheme)
# Check for test=True
if __opts__['test']:
ret['result'] = None
return ret
# Set the timeout value
__salt__['powercfg.set_{0}_timeout'.format(name)](
timeout=value,
power=power,
scheme=scheme)
# Get the setting after the change
new = __salt__['powercfg.get_{0}_timeout'.format(name)](scheme=scheme)
changes = salt.utils.compare_dicts(old, new)
if changes:
ret['changes'] = {name: changes}
ret['comment'] = '{0} timeout on {1} power set to {2}' \
''.format(name.capitalize(), power.upper(), value)
log.debug(ret['comment'])
else:
ret['changes'] = {}
ret['comment'] = 'Failed to set {0} timeout on {1} power to {2}' \
''.format(name, power.upper(), value)
log.debug(ret['comment'])
ret['result'] = False
ret['comment'] = ' '.join(comment)
return ret

View file

@ -197,11 +197,12 @@ class MacServiceModuleTest(ModuleCase):
self.assertFalse(
self.run_function('service.disabled', [SERVICE_NAME]))
self.assertTrue(self.run_function('service.stop', [SERVICE_NAME]))
self.assertTrue(self.run_function('service.disable', [SERVICE_NAME]))
self.assertTrue(
self.run_function('service.disabled', [SERVICE_NAME]))
self.assertTrue(self.run_function('service.enable', [SERVICE_NAME]))
self.assertTrue(self.run_function('service.disabled', ['spongebob']))
self.assertFalse(self.run_function('service.disabled', ['spongebob']))
def test_get_all(self):
'''

View file

@ -118,21 +118,21 @@ class ServiceModuleTest(ModuleCase):
systemd = salt.utils.systemd.booted()
# check service was not enabled
if systemd or salt.utils.is_windows():
self.assertIn('ERROR', enable)
else:
try:
self.assertFalse(enable)
except AssertionError:
self.assertIn('ERROR', enable)
# check service was not disabled
if tuple(self.run_function('grains.item', ['osrelease_info'])['osrelease_info']) == (14, 0o4) and not systemd:
# currently upstart does not have a mechanism to report if disabling a service fails if does not exist
self.assertTrue(self.run_function('service.disable', [srv_name]))
else:
if salt.utils.is_windows():
try:
disable = self.run_function('service.disable', [srv_name])
self.assertFalse(disable)
except AssertionError:
self.assertTrue('error' in disable.lower())
else:
self.assertFalse(self.run_function('service.disable', [srv_name]))
if salt.utils.is_darwin():
self.assertFalse(self.run_function('service.disabled', [srv_name]))

View file

@ -8,8 +8,19 @@ Linux and Solaris are supported
# Import python libs
from __future__ import absolute_import
try:
import tzlocal # pylint: disable=unused-import
HAS_TZLOCAL = True
except ImportError:
HAS_TZLOCAL = False
# Import Salt Testing libs
from tests.support.case import ModuleCase
from tests.support.helpers import destructiveTest
from tests.support.unit import skipIf
# Import salt libs
import salt.utils
class TimezoneLinuxModuleTest(ModuleCase):
@ -42,3 +53,44 @@ class TimezoneSolarisModuleTest(ModuleCase):
timescale = ['UTC', 'localtime']
ret = self.run_function('timezone.get_hwclock')
self.assertIn(ret, timescale)
@skipIf(not salt.utils.is_windows(), 'windows test only')
class TimezoneWindowsModuleTest(ModuleCase):
def setUp(self):
self.pre = self.run_function('timezone.get_zone')
def tearDown(self):
post = self.run_function('timezone.get_zone')
if self.pre != post:
self.run_function('timezone.set_zone', [self.pre])
def test_get_hwclock(self):
timescale = ['UTC', 'localtime']
ret = self.run_function('timezone.get_hwclock')
self.assertIn(ret, timescale)
@destructiveTest
def test_get_zone(self):
'''
test timezone.set_zone, get_zone and zone_compare
'''
zone = 'America/Inuvik' if not HAS_TZLOCAL else 'America/Denver'
# first set the zone
assert self.run_function('timezone.set_zone', [zone])
# check it set the correct zone
ret = self.run_function('timezone.get_zone')
assert zone in ret
# compare zones
assert self.run_function('timezone.zone_compare', [zone])
def test_get_offset(self):
'''
test timezone.get_offset
'''
ret = self.run_function('timezone.get_offset')
self.assertIn('-', ret)

View file

@ -0,0 +1,33 @@
# -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import
import re
# Import Salt Testing libs
from tests.support.case import ModuleCase
from tests.support.unit import skipIf
# Import Salt libs
import salt.utils
@skipIf(not salt.utils.is_windows(), 'windows test only')
class WinIPTest(ModuleCase):
'''
Tests for salt.modules.win_ip
'''
def test_get_default_gateway(self):
'''
Test getting default gateway
'''
ip = re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
ret = self.run_function('ip.get_default_gateway')
assert ip.match(ret)
def test_ip_is_enabled(self):
'''
Test ip.is_enabled
'''
assert self.run_function('ip.is_enabled', ['Ethernet'])
assert 'not found' in self.run_function('ip.is_enabled', ['doesnotexist'])

View file

@ -0,0 +1,84 @@
# -*- coding: utf-8 -*-
# Import Python libs
from __future__ import absolute_import
import os
import textwrap
# Import Salt Testing libs
from tests.support.case import ModuleCase
from tests.support.unit import skipIf
from tests.support.helpers import destructiveTest
from tests.support.runtests import RUNTIME_VARS
# Import Salt libs
import salt.utils
CURL = os.path.join(RUNTIME_VARS.FILES, 'file', 'base', 'win', 'repo-ng', 'curl.sls')
@skipIf(not salt.utils.is_windows(), 'windows test only')
class WinPKGTest(ModuleCase):
'''
Tests for salt.modules.win_pkg. There are already
some pkg execution module tests in the the test
integration.modules.test_pkg but this will be for
specific windows software respository tests while
using the win_pkg module.
'''
@destructiveTest
def test_adding_removing_pkg_sls(self):
'''
Test add and removing a new pkg sls
in the windows software repository
'''
def _check_pkg(pkgs, exists=True):
self.run_function('pkg.refresh_db')
repo_data = self.run_function('pkg.get_repo_data')
repo_cache = os.path.join(RUNTIME_VARS.TMP, 'rootdir', 'cache', 'files', 'base', 'win', 'repo-ng')
for pkg in pkgs:
if exists:
assert pkg in str(repo_data)
else:
assert pkg not in str(repo_data)
for root, dirs, files in os.walk(repo_cache):
if exists:
assert pkg + '.sls' in files
else:
assert pkg + '.sls' not in files
pkgs = ['putty', '7zip']
# check putty and 7zip are in cache and repo query
_check_pkg(pkgs)
# now add new sls
with salt.utils.fopen(CURL, 'w') as fp_:
fp_.write(textwrap.dedent('''
curl:
'7.46.0':
full_name: 'cURL'
{% if grains['cpuarch'] == 'AMD64' %}
installer: 'salt://win/repo-ng/curl/curl-7.46.0-win64.msi'
uninstaller: 'salt://win/repo-ng/curl/curl-7.46.0-win64.msi'
{% else %}
installer: 'salt://win/repo-ng/curl/curl-7.46.0-win32.msi'
uninstaller: 'salt://win/repo-ng/curl/curl-7.46.0-win32.msi'
{% endif %}
install_flags: '/qn /norestart'
uninstall_flags: '/qn /norestart'
msiexec: True
locale: en_US
reboot: False
'''))
# now check if curl is also in cache and repo query
pkgs.append('curl')
_check_pkg(pkgs)
# remove curl sls and check its not in cache and repo query
os.remove(CURL)
_check_pkg(['curl'], exists=False)
def tearDown(self):
if os.path.isfile(CURL):
os.remove(CURL)

View file

@ -86,6 +86,7 @@ class TestSaltAPIHandler(_SaltnadoIntegrationTestCase):
self.assertEqual(response.code, 302)
self.assertEqual(response.headers['Location'], '/login')
@flaky
def test_simple_local_post(self):
'''
Test a basic API of /
@ -125,6 +126,7 @@ class TestSaltAPIHandler(_SaltnadoIntegrationTestCase):
response_obj = json_loads(response.body)
self.assertEqual(response_obj['return'], ["No minions matched the target. No command was sent, no jid was assigned."])
@flaky
def test_simple_local_post_only_dictionary_request(self):
'''
Test a basic API of /
@ -258,6 +260,7 @@ class TestSaltAPIHandler(_SaltnadoIntegrationTestCase):
response_obj = json_loads(response.body)
self.assertEqual(response_obj['return'], [{}])
@flaky
def test_simple_local_post_only_dictionary_request_with_order_masters(self):
'''
Test a basic API of /

View file

@ -30,6 +30,7 @@ from tests.support.helpers import (
with_system_user_and_group,
with_tempfile,
Webserver,
destructiveTest
)
from tests.support.mixins import SaltReturnAssertsMixin
@ -668,8 +669,8 @@ class FileTest(ModuleCase, SaltReturnAssertsMixin):
This is a regression test for Issue #38914 and Issue #48230 (test=true use).
'''
name = os.path.join(TMP, 'source_hash_indifferent_case')
state_name = 'file_|-/tmp/salt-tests-tmpdir/source_hash_indifferent_case_|' \
'-/tmp/salt-tests-tmpdir/source_hash_indifferent_case_|-managed'
state_name = 'file_|-{0}_|' \
'-{0}_|-managed'.format(name)
local_path = os.path.join(FILES, 'file', 'base', 'hello_world.txt')
actual_hash = 'c98c24b677eff44860afea6f493bbaec5bb1c4cbb209c6fc2bbb47f66ff2ad31'
uppercase_hash = actual_hash.upper()
@ -3866,3 +3867,54 @@ class RemoteFileTest(ModuleCase, SaltReturnAssertsMixin):
skip_verify=True)
log.debug('ret = %s', ret)
self.assertSaltTrueReturn(ret)
WIN_TEST_FILE = 'c:/testfile'
@destructiveTest
@skipIf(not salt.utils.is_windows(), 'windows test only')
class WinFileTest(ModuleCase):
'''
Test for the file state on Windows
'''
def setUp(self):
self.run_state('file.managed', name=WIN_TEST_FILE, makedirs=True, contents='Only a test')
def tearDown(self):
self.run_state('file.absent', name=WIN_TEST_FILE)
def test_file_managed(self):
'''
Test file.managed on Windows
'''
self.assertTrue(self.run_state('file.exists', name=WIN_TEST_FILE))
def test_file_copy(self):
'''
Test file.copy on Windows
'''
ret = self.run_state('file.copy', name='c:/testfile_copy', makedirs=True, source=WIN_TEST_FILE)
self.assertTrue(ret)
def test_file_comment(self):
'''
Test file.comment on Windows
'''
self.run_state('file.comment', name=WIN_TEST_FILE, regex='^Only')
with salt.utils.fopen(WIN_TEST_FILE, 'r') as fp_:
self.assertTrue(fp_.read().startswith('#Only'))
def test_file_replace(self):
'''
Test file.replace on Windows
'''
self.run_state('file.replace', name=WIN_TEST_FILE, pattern='test', repl='testing')
with salt.utils.fopen(WIN_TEST_FILE, 'r') as fp_:
self.assertIn('testing', fp_.read())
def test_file_absent(self):
'''
Test file.absent on Windows
'''
ret = self.run_state('file.absent', name=WIN_TEST_FILE)
self.assertTrue(ret)

View file

@ -41,9 +41,19 @@ class ServiceTest(ModuleCase, SaltReturnAssertsMixin):
self.stopped = ''
self.running = '[0-9]'
self.pre_srv_enabled = True if self.service_name in self.run_function('service.get_enabled') else False
self.post_srv_disable = False
if not self.pre_srv_enabled:
self.run_function('service.enable', name=self.service_name)
self.post_srv_disable = True
if salt.utils.which(cmd_name) is None:
self.skipTest('{0} is not installed'.format(cmd_name))
def tearDown(self):
if self.post_srv_disable:
self.run_function('service.disable', name=self.service_name)
def check_service_status(self, exp_return):
'''
helper method to check status of service

View file

@ -14,6 +14,7 @@ import logging
import os
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
@ -590,8 +591,24 @@ class TestSaltProgram(six.with_metaclass(TestSaltProgramMeta, TestProgram)):
'log_dir',
'script_dir',
])
pub_port = 4505
ret_port = 4506
for port in [pub_port, ret_port]:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
connect = sock.bind(('localhost', port))
except OSError:
# these ports are already in use, use different ones
pub_port = 4606
ret_port = 4607
break
sock.close()
config_base = {
'root_dir': '{test_dir}',
'publish_port': pub_port,
'ret_port': ret_port,
}
configs = {}
config_dir = os.path.join('etc', 'salt')

View file

@ -6,6 +6,7 @@
# Import Python Libs
from __future__ import absolute_import
import json
import textwrap
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
@ -34,43 +35,87 @@ class NpmTestCase(TestCase, LoaderModuleMockMixin):
self.addCleanup(patcher.stop)
return {npm: {}}
# 'install' function tests: 1
# 'install' function tests: 4
def test_install(self):
'''
Test if it install an NPM package.
Test if it installs an NPM package.
'''
mock = MagicMock(return_value={'retcode': 1, 'stderr': 'error'})
with patch.dict(npm.__salt__, {'cmd.run_all': mock}):
self.assertRaises(CommandExecutionError, npm.install,
'coffee-script')
mock = MagicMock(return_value={'retcode': 0, 'stderr': 'error',
'stdout': '{"salt": ["SALT"]}'})
with patch.dict(npm.__salt__, {'cmd.run_all': mock}):
mock_err = MagicMock(return_value='SALT')
with patch.object(json, 'loads', mock_err):
self.assertEqual(npm.install('coffee-script'), 'SALT')
# This is at least somewhat closer to the actual output format.
mock_json_out = textwrap.dedent('''\
[
{
"salt": "SALT"
}
]''')
mock = MagicMock(return_value={'retcode': 0, 'stderr': 'error',
'stdout': '{"salt": ["SALT"]}'})
# Successful run, expected output format
mock = MagicMock(return_value={'retcode': 0, 'stderr': '',
'stdout': mock_json_out})
with patch.dict(npm.__salt__, {'cmd.run_all': mock}):
self.assertEqual(npm.install('coffee-script'),
[{u'salt': u'SALT'}])
mock_json_out_extra = textwrap.dedent('''\
Compilation output here
[bcrypt] Success: "/tmp/node_modules/bcrypt/foo" is installed via remote"
[grpc] Success: "/usr/lib/node_modules/@foo/bar" is installed via remote"
[
{
"from" : "express@",
"name" : "express",
"dependencies" : {
"escape-html" : {
"from" : "escape-html@~1.0.3",
"dependencies" : {},
"version" : "1.0.3"
}
},
"version" : "4.16.3"
}
]''')
extra_expected = [{u'dependencies':
{u'escape-html': {
u'dependencies': {},
u'from': u'escape-html@~1.0.3',
u'version': u'1.0.3'}
},
u'from': u'express@',
u'name': u'express',
u'version': u'4.16.3'}]
# Successful run, expected output format with additional leading text
mock = MagicMock(return_value={'retcode': 0, 'stderr': '',
'stdout': mock_json_out_extra})
with patch.dict(npm.__salt__, {'cmd.run_all': mock}):
self.assertEqual(npm.install('coffee-script'), extra_expected)
# Successful run, unexpected output format
mock = MagicMock(return_value={'retcode': 0, 'stderr': '',
'stdout': 'SALT'})
with patch.dict(npm.__salt__, {'cmd.run_all': mock}):
mock_err = MagicMock(side_effect=ValueError())
# When JSON isn't successfully parsed, return should equal input
with patch.object(json, 'loads', mock_err):
self.assertEqual(npm.install('coffee-script'),
'{"salt": ["SALT"]}')
self.assertEqual(npm.install('coffee-script'), 'SALT')
# 'uninstall' function tests: 1
def test_uninstall(self):
'''
Test if it uninstall an NPM package.
Test if it uninstalls an NPM package.
'''
mock = MagicMock(return_value={'retcode': 1, 'stderr': 'error'})
with patch.dict(npm.__salt__, {'cmd.run_all': mock}):
self.assertFalse(npm.uninstall('coffee-script'))
mock = MagicMock(return_value={'retcode': 0, 'stderr': 'error'})
mock = MagicMock(return_value={'retcode': 0, 'stderr': ''})
with patch.dict(npm.__salt__, {'cmd.run_all': mock}):
self.assertTrue(npm.uninstall('coffee-script'))

View file

@ -21,7 +21,7 @@ from tests.support.mock import (
@skipIf(NO_MOCK, NO_MOCK_REASON)
class PowerCfgTestCase(TestCase, LoaderModuleMockMixin):
'''
Validate the powercfg state
Validate the powercfg state
'''
def setup_loader_modules(self):
@ -40,76 +40,103 @@ class PowerCfgTestCase(TestCase, LoaderModuleMockMixin):
def test_set_monitor_timeout(self):
'''
Test to make sure we can set the monitor timeout value
Test to make sure we can set the monitor timeout value
'''
mock = MagicMock()
mock.side_effect = ["Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)", self.query_output]
mock = MagicMock(return_value=0)
mock.side_effect = [
'Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)',
self.query_output]
mock_retcode = MagicMock(return_value=0)
with patch.dict(powercfg.__salt__, {'cmd.run': mock}):
powercfg.set_monitor_timeout(0, "dc")
calls = [
call('powercfg /getactivescheme', python_shell=False),
call('powercfg /setdcvalueindex 381b4222-f694-41f0-9685-ff5bb260df2e SUB_VIDEO VIDEOIDLE 0', python_shell=False)
]
mock.assert_has_calls(calls)
with patch.dict(powercfg.__salt__, {'cmd.retcode': mock_retcode}):
powercfg.set_monitor_timeout(0, 'dc')
mock.assert_called_once_with(
'powercfg /getactivescheme',
python_shell=False)
mock_retcode.assert_called_once_with(
'powercfg /setdcvalueindex 381b4222-f694-41f0-9685-ff5bb260df2e SUB_VIDEO VIDEOIDLE 0',
python_shell=False)
def test_set_disk_timeout(self):
'''
Test to make sure we can set the disk timeout value
Test to make sure we can set the disk timeout value
'''
mock = MagicMock()
mock.side_effect = ["Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)", self.query_output]
mock.side_effect = [
'Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)',
self.query_output]
mock_retcode = MagicMock(return_value=0)
with patch.dict(powercfg.__salt__, {'cmd.run': mock}):
powercfg.set_disk_timeout(0, "dc")
calls = [
call('powercfg /getactivescheme', python_shell=False),
call('powercfg /setdcvalueindex 381b4222-f694-41f0-9685-ff5bb260df2e SUB_DISK DISKIDLE 0', python_shell=False)
]
mock.assert_has_calls(calls)
with patch.dict(powercfg.__salt__, {'cmd.retcode': mock_retcode}):
powercfg.set_disk_timeout(0, 'dc')
mock.assert_called_once_with(
'powercfg /getactivescheme',
python_shell=False)
mock_retcode.assert_called_once_with(
'powercfg /setdcvalueindex 381b4222-f694-41f0-9685-ff5bb260df2e SUB_DISK DISKIDLE 0',
python_shell=False)
def test_set_standby_timeout(self):
'''
Test to make sure we can set the standby timeout value
Test to make sure we can set the standby timeout value
'''
mock = MagicMock()
mock.side_effect = ["Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)", self.query_output]
mock = MagicMock(return_value=0)
mock.side_effect = [
'Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)',
self.query_output]
mock_retcode = MagicMock(return_value=0)
with patch.dict(powercfg.__salt__, {'cmd.run': mock}):
powercfg.set_standby_timeout(0, "dc")
calls = [
call('powercfg /getactivescheme', python_shell=False),
call('powercfg /setdcvalueindex 381b4222-f694-41f0-9685-ff5bb260df2e SUB_SLEEP STANDBYIDLE 0', python_shell=False)
]
mock.assert_has_calls(calls)
with patch.dict(powercfg.__salt__, {'cmd.retcode': mock_retcode}):
powercfg.set_standby_timeout(0, 'dc')
mock.assert_called_once_with(
'powercfg /getactivescheme',
python_shell=False)
mock_retcode.assert_called_once_with(
'powercfg /setdcvalueindex 381b4222-f694-41f0-9685-ff5bb260df2e SUB_SLEEP STANDBYIDLE 0',
python_shell=False)
def test_set_hibernate_timeout(self):
'''
Test to make sure we can set the hibernate timeout value
Test to make sure we can set the hibernate timeout value
'''
mock = MagicMock()
mock.side_effect = ["Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)", self.query_output]
mock = MagicMock(return_value=0)
mock.side_effect = [
'Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)',
self.query_output]
mock_retcode = MagicMock(return_value=0)
with patch.dict(powercfg.__salt__, {'cmd.run': mock}):
powercfg.set_hibernate_timeout(0, "dc")
calls = [
call('powercfg /getactivescheme', python_shell=False),
call('powercfg /setdcvalueindex 381b4222-f694-41f0-9685-ff5bb260df2e SUB_SLEEP HIBERNATEIDLE 0', python_shell=False)
]
mock.assert_has_calls(calls)
with patch.dict(powercfg.__salt__, {'cmd.retcode': mock_retcode}):
powercfg.set_hibernate_timeout(0, 'dc')
mock.assert_called_once_with(
'powercfg /getactivescheme',
python_shell=False)
mock_retcode.assert_called_once_with(
'powercfg /setdcvalueindex 381b4222-f694-41f0-9685-ff5bb260df2e SUB_SLEEP HIBERNATEIDLE 0',
python_shell=False)
def test_get_monitor_timeout(self):
'''
Test to make sure we can get the monitor timeout value
Test to make sure we can get the monitor timeout value
'''
mock = MagicMock()
mock.side_effect = ["Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)", self.query_output]
mock.side_effect = [
'Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)',
self.query_output]
with patch.dict(powercfg.__salt__, {'cmd.run': mock}):
ret = powercfg.get_monitor_timeout()
calls = [
call('powercfg /getactivescheme', python_shell=False),
call('powercfg /q 381b4222-f694-41f0-9685-ff5bb260df2e SUB_VIDEO VIDEOIDLE', python_shell=False)
call('powercfg /q 381b4222-f694-41f0-9685-ff5bb260df2e SUB_VIDEO VIDEOIDLE',
python_shell=False)
]
mock.assert_has_calls(calls)
@ -117,16 +144,19 @@ class PowerCfgTestCase(TestCase, LoaderModuleMockMixin):
def test_get_disk_timeout(self):
'''
Test to make sure we can get the disk timeout value
Test to make sure we can get the disk timeout value
'''
mock = MagicMock()
mock.side_effect = ["Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)", self.query_output]
mock.side_effect = [
'Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)',
self.query_output]
with patch.dict(powercfg.__salt__, {'cmd.run': mock}):
ret = powercfg.get_disk_timeout()
calls = [
call('powercfg /getactivescheme', python_shell=False),
call('powercfg /q 381b4222-f694-41f0-9685-ff5bb260df2e SUB_DISK DISKIDLE', python_shell=False)
call('powercfg /q 381b4222-f694-41f0-9685-ff5bb260df2e SUB_DISK DISKIDLE',
python_shell=False)
]
mock.assert_has_calls(calls)
@ -134,16 +164,19 @@ class PowerCfgTestCase(TestCase, LoaderModuleMockMixin):
def test_get_standby_timeout(self):
'''
Test to make sure we can get the standby timeout value
Test to make sure we can get the standby timeout value
'''
mock = MagicMock()
mock.side_effect = ["Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)", self.query_output]
mock.side_effect = [
'Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)',
self.query_output]
with patch.dict(powercfg.__salt__, {'cmd.run': mock}):
ret = powercfg.get_standby_timeout()
calls = [
call('powercfg /getactivescheme', python_shell=False),
call('powercfg /q 381b4222-f694-41f0-9685-ff5bb260df2e SUB_SLEEP STANDBYIDLE', python_shell=False)
call('powercfg /q 381b4222-f694-41f0-9685-ff5bb260df2e SUB_SLEEP STANDBYIDLE',
python_shell=False)
]
mock.assert_has_calls(calls)
@ -151,16 +184,19 @@ class PowerCfgTestCase(TestCase, LoaderModuleMockMixin):
def test_get_hibernate_timeout(self):
'''
Test to make sure we can get the hibernate timeout value
Test to make sure we can get the hibernate timeout value
'''
mock = MagicMock()
mock.side_effect = ["Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)", self.query_output]
mock.side_effect = [
'Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)',
self.query_output]
with patch.dict(powercfg.__salt__, {'cmd.run': mock}):
ret = powercfg.get_hibernate_timeout()
calls = [
call('powercfg /getactivescheme', python_shell=False),
call('powercfg /q 381b4222-f694-41f0-9685-ff5bb260df2e SUB_SLEEP HIBERNATEIDLE', python_shell=False)
call('powercfg /q 381b4222-f694-41f0-9685-ff5bb260df2e SUB_SLEEP HIBERNATEIDLE',
python_shell=False)
]
mock.assert_has_calls(calls)
@ -168,17 +204,20 @@ class PowerCfgTestCase(TestCase, LoaderModuleMockMixin):
def test_windows_7(self):
'''
Test to make sure we can get the hibernate timeout value on windows 7
Test to make sure we can get the hibernate timeout value on windows 7
'''
mock = MagicMock()
mock.side_effect = ["Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)", self.query_output]
mock.side_effect = [
'Power Scheme GUID: 381b4222-f694-41f0-9685-ff5bb260df2e (Balanced)',
self.query_output]
with patch.dict(powercfg.__salt__, {'cmd.run': mock}):
with patch.dict(powercfg.__grains__, {'osrelease': '7'}):
ret = powercfg.get_hibernate_timeout()
calls = [
call('powercfg /getactivescheme', python_shell=False),
call('powercfg /q 381b4222-f694-41f0-9685-ff5bb260df2e SUB_SLEEP', python_shell=False)
call('powercfg /q 381b4222-f694-41f0-9685-ff5bb260df2e SUB_SLEEP',
python_shell=False)
]
mock.assert_has_calls(calls)
@ -186,30 +225,29 @@ class PowerCfgTestCase(TestCase, LoaderModuleMockMixin):
def test_set_hibernate_timeout_scheme(self):
'''
Test to make sure we can set the hibernate timeout value
Test to make sure we can set the hibernate timeout value
'''
mock = MagicMock()
mock = MagicMock(return_value=0)
mock.side_effect = [self.query_output]
with patch.dict(powercfg.__salt__, {'cmd.run': mock}):
powercfg.set_hibernate_timeout(0, "dc", scheme="SCHEME_MIN")
calls = [
call('powercfg /setdcvalueindex SCHEME_MIN SUB_SLEEP HIBERNATEIDLE 0', python_shell=False)
]
mock.assert_has_calls(calls)
with patch.dict(powercfg.__salt__, {'cmd.retcode': mock}):
powercfg.set_hibernate_timeout(0, 'dc', scheme='SCHEME_MIN')
mock.assert_called_once_with(
'powercfg /setdcvalueindex SCHEME_MIN SUB_SLEEP HIBERNATEIDLE 0',
python_shell=False)
def test_get_hibernate_timeout_scheme(self):
'''
Test to make sure we can get the hibernate timeout value with a specified scheme
Test to make sure we can get the hibernate timeout value with a
specified scheme
'''
mock = MagicMock()
mock.side_effect = [self.query_output]
with patch.dict(powercfg.__salt__, {'cmd.run': mock}):
ret = powercfg.get_hibernate_timeout(scheme="SCHEME_MIN")
calls = [
call('powercfg /q SCHEME_MIN SUB_SLEEP HIBERNATEIDLE', python_shell=False)
]
mock.assert_has_calls(calls)
ret = powercfg.get_hibernate_timeout(scheme='SCHEME_MIN')
mock.assert_called_once_with(
'powercfg /q SCHEME_MIN SUB_SLEEP HIBERNATEIDLE',
python_shell=False)
self.assertEqual({'ac': 30, 'dc': 15}, ret)

View file

@ -239,6 +239,18 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin):
self.assertTrue(win_service.enabled('spongebob'))
self.assertFalse(win_service.enabled('squarepants'))
def test_enabled_with_space_in_name(self):
'''
Test to check to see if the named
service is enabled to start on boot
when have space in service name
'''
mock = MagicMock(side_effect=[{'StartType': 'Auto'},
{'StartType': 'Disabled'}])
with patch.object(win_service, 'info', mock):
self.assertTrue(win_service.enabled('spongebob test'))
self.assertFalse(win_service.enabled('squarepants test'))
def test_disabled(self):
'''
Test to check to see if the named

View file

@ -27,36 +27,71 @@ class PowerCfgTestCase(TestCase, LoaderModuleMockMixin):
def test_set_monitor(self):
'''
Test to make sure we can set the monitor timeout value
Test to make sure we can set the monitor timeout value
'''
ret = {'changes': {'monitor': {'ac': 0}}, 'comment': '', 'name': 'monitor', 'result': True}
monitor_val = {"ac": 45, "dc": 22}
with patch.dict(powercfg.__salt__, {"powercfg.get_monitor_timeout": MagicMock(return_value=monitor_val),
"powercfg.set_monitor_timeout": MagicMock(return_value=True)}):
self.assertEqual(powercfg.set_timeout("monitor", 0), ret)
ret = {
'changes': {
'monitor': {
'ac': {
'new': 0,
'old': 45
}
}
},
'comment': 'Monitor timeout on AC power set to 0',
'name': 'monitor',
'result': True}
get_monitor_side_effect = MagicMock(side_effect=[{"ac": 45, "dc": 22},
{"ac": 0, "dc": 22}])
with patch.dict(powercfg.__salt__,
{"powercfg.get_monitor_timeout": get_monitor_side_effect,
"powercfg.set_monitor_timeout": MagicMock(return_value=True)}):
with patch.dict(powercfg.__opts__, {"test": False}):
self.assertEqual(powercfg.set_timeout("monitor", 0), ret)
def test_set_monitor_already_set(self):
'''
Test to make sure we can set the monitor timeout value
Test to make sure we can set the monitor timeout value
'''
ret = {'changes': {}, 'comment': 'monitor ac is already set with the value 0.', 'name': 'monitor', 'result': True}
monitor_val = {"ac": 0, "dc": 0}
with patch.dict(powercfg.__salt__, {"powercfg.get_monitor_timeout": MagicMock(return_value=monitor_val),
"powercfg.set_monitor_timeout": MagicMock(return_value=True)}):
ret = {'changes': {},
'comment': 'Monitor timeout on AC power is already set to 0',
'name': 'monitor',
'result': True}
monitor_val = MagicMock(return_value={"ac": 0, "dc": 0})
with patch.dict(powercfg.__salt__, {"powercfg.get_monitor_timeout": monitor_val}):
self.assertEqual(powercfg.set_timeout("monitor", 0), ret)
def test_set_monitor_test_true_with_change(self):
'''
Test to make sure set monitor works correctly with test=True with
changes
'''
ret = {'changes': {},
'comment': 'Monitor timeout on AC power will be set to 0',
'name': 'monitor',
'result': None}
get_monitor_return_value = MagicMock(return_value={"ac": 45, "dc": 22})
with patch.dict(powercfg.__salt__, {"powercfg.get_monitor_timeout": get_monitor_return_value}):
with patch.dict(powercfg.__opts__, {"test": True}):
self.assertEqual(powercfg.set_timeout("monitor", 0), ret)
def test_fail_invalid_setting(self):
'''
Test to make sure we can set the monitor timeout value
Test to make sure we can set the monitor timeout value
'''
ret = {'changes': {}, 'comment': 'fakesetting is not a valid setting', 'name': 'fakesetting', 'result': False}
ret = {'changes': {},
'comment': '"fakesetting" is not a valid setting',
'name': 'fakesetting',
'result': False}
self.assertEqual(powercfg.set_timeout("fakesetting", 0), ret)
def test_fail_invalid_power(self):
'''
Test to make sure we can set the monitor timeout value
Test to make sure we can set the monitor timeout value
'''
ret = {'changes': {}, 'comment': 'fakepower is not a power type', 'name': 'monitor', 'result': False}
self.assertEqual(powercfg.set_timeout("monitor", 0, power="fakepower"), ret)
ret = {'changes': {},
'comment': '"fakepower" is not a power type',
'name': 'monitor',
'result': False}
self.assertEqual(powercfg.set_timeout("monitor", 0, power="fakepower"),
ret)

View file

@ -30,6 +30,7 @@ integration.modules.test_system
integration.modules.test_test
integration.modules.test_useradd
integration.modules.test_win_dns_client
integration.modules.test_win_pkg
integration.reactor.test_reactor
integration.renderers.test_pydsl
integration.returners.test_librato_return
@ -41,6 +42,7 @@ integration.states.test_host
integration.states.test_pip_state
integration.states.test_pkg
integration.states.test_renderers
integration.states.test_file
integration.states.test_user
integration.utils.testprogram
integration.wheel.test_client