From 6abb43d2dfc362643989ed9a856ae38cf9d4c61e Mon Sep 17 00:00:00 2001 From: Pedro Algarvio Date: Tue, 3 Aug 2021 07:25:24 +0100 Subject: [PATCH] Upgrade to black 21.7b0 --- .pre-commit-config.yaml | 18 +- doc/_ext/saltdomain.py | 14 +- doc/ref/modules/index.rst | 2 +- doc/ref/renderers/index.rst | 2 +- doc/topics/cloud/cloud.rst | 4 +- .../development/conventions/formulas.rst | 2 +- doc/topics/event/events.rst | 2 +- doc/topics/releases/2017.7.0.rst | 4 +- doc/topics/releases/2019.2.0.rst | 2 +- .../troubleshooting/yaml_idiosyncrasies.rst | 26 +- doc/topics/tutorials/http.rst | 12 +- .../tutorials/jinja_to_execution_module.rst | 2 +- pkg/rpm/build.py | 2 +- salt/beacons/smartos_vmadm.py | 3 +- salt/beacons/watchdog.py | 2 +- salt/cache/etcd_cache.py | 3 +- salt/cache/mysql_cache.py | 6 +- salt/cli/spm.py | 4 +- salt/client/mixins.py | 4 +- salt/client/ssh/__init__.py | 6 +- salt/client/ssh/shell.py | 4 +- salt/client/ssh/ssh_py_shim.py | 10 +- salt/client/ssh/state.py | 2 +- salt/cloud/__init__.py | 2 +- salt/cloud/cli.py | 52 +- salt/cloud/clouds/aliyun.py | 4 +- salt/cloud/clouds/azurearm.py | 65 +- salt/cloud/clouds/clc.py | 61 +- salt/cloud/clouds/cloudstack.py | 4 +- salt/cloud/clouds/digitalocean.py | 40 +- salt/cloud/clouds/ec2.py | 21 +- salt/cloud/clouds/gogrid.py | 4 +- salt/cloud/clouds/hetzner.py | 23 +- salt/cloud/clouds/joyent.py | 18 +- salt/cloud/clouds/libvirt.py | 6 +- salt/cloud/clouds/linode.py | 53 +- salt/cloud/clouds/msazure.py | 74 +- salt/cloud/clouds/oneandone.py | 4 +- salt/cloud/clouds/opennebula.py | 4 +- salt/cloud/clouds/packet.py | 4 +- salt/cloud/clouds/parallels.py | 10 +- salt/cloud/clouds/proxmox.py | 18 +- salt/cloud/clouds/pyrax.py | 6 +- salt/cloud/clouds/qingcloud.py | 4 +- salt/cloud/clouds/saltify.py | 6 +- salt/cloud/clouds/scaleway.py | 44 +- salt/cloud/clouds/softlayer.py | 4 +- salt/cloud/clouds/softlayer_hw.py | 4 +- salt/cloud/clouds/tencentcloud.py | 4 +- salt/cloud/clouds/vagrant.py | 8 +- salt/cloud/clouds/virtualbox.py | 8 +- salt/cloud/clouds/vmware.py | 28 +- salt/cloud/clouds/vultrpy.py | 31 +- salt/cloud/clouds/xen.py | 4 +- salt/cloud/libcloudfuncs.py | 15 +- salt/daemons/masterapi.py | 10 +- salt/engines/slack.py | 22 +- salt/exceptions.py | 3 +- salt/grains/zfs.py | 4 +- salt/loader/__init__.py | 45 +- salt/loader/lazy.py | 3 +- salt/log/setup.py | 9 +- salt/master.py | 15 +- salt/minion.py | 20 +- salt/modules/artifactory.py | 184 +-- salt/modules/at.py | 7 +- salt/modules/augeas_cfg.py | 9 +- salt/modules/bamboohr.py | 5 +- salt/modules/beacons.py | 21 +- salt/modules/bigip.py | 24 +- salt/modules/boto_cloudfront.py | 52 +- salt/modules/boto_datapipeline.py | 11 +- salt/modules/boto_route53.py | 33 +- salt/modules/boto_s3.py | 15 +- salt/modules/boto_sqs.py | 14 +- salt/modules/boto_vpc.py | 22 +- salt/modules/chronos.py | 7 +- salt/modules/cimc.py | 6 +- salt/modules/ciscoconfparse_mod.py | 7 +- salt/modules/cron.py | 12 +- salt/modules/debian_service.py | 16 +- salt/modules/djangomod.py | 5 +- salt/modules/dockermod.py | 13 +- salt/modules/file.py | 26 +- salt/modules/gcp_addon.py | 6 +- salt/modules/genesis.py | 39 +- salt/modules/glusterfs.py | 10 +- salt/modules/hadoop.py | 14 +- salt/modules/incron.py | 8 +- salt/modules/influxdbmod.py | 2 +- salt/modules/inspectlib/collector.py | 12 +- salt/modules/jboss7.py | 26 +- salt/modules/junos.py | 7 +- salt/modules/k8s.py | 22 +- salt/modules/linux_ip.py | 5 +- salt/modules/logadm.py | 5 +- salt/modules/lxc.py | 28 +- salt/modules/lxd.py | 1250 +++++++++-------- salt/modules/mac_assistive.py | 15 +- salt/modules/mac_power.py | 42 +- salt/modules/mac_system.py | 33 +- salt/modules/marathon.py | 12 +- salt/modules/napalm_mod.py | 4 +- salt/modules/napalm_network.py | 3 +- salt/modules/network.py | 29 +- salt/modules/nexus.py | 236 ++-- salt/modules/nilrt_ip.py | 14 +- salt/modules/pagerduty_util.py | 18 +- salt/modules/panos.py | 13 +- salt/modules/pdbedit.py | 6 +- salt/modules/postfix.py | 18 +- salt/modules/postgres.py | 4 +- salt/modules/proxy.py | 3 +- salt/modules/purefa.py | 2 +- salt/modules/purefb.py | 2 +- salt/modules/qemu_img.py | 3 +- salt/modules/qemu_nbd.py | 6 +- salt/modules/rallydev.py | 5 +- salt/modules/rbac_solaris.py | 9 +- salt/modules/rpmbuild_pkgbuild.py | 6 +- salt/modules/rsync.py | 90 +- salt/modules/saltcheck.py | 4 +- salt/modules/schedule.py | 21 +- salt/modules/slack_notify.py | 8 +- salt/modules/smartos_imgadm.py | 12 +- salt/modules/solaris_fmadm.py | 4 +- salt/modules/splunk.py | 3 +- salt/modules/state.py | 9 +- salt/modules/status.py | 5 +- salt/modules/supervisord.py | 36 +- salt/modules/tls.py | 22 +- salt/modules/tomcat.py | 8 +- salt/modules/twilio_notify.py | 3 +- salt/modules/vagrant.py | 2 +- salt/modules/vboxmanage.py | 3 +- salt/modules/vsphere.py | 24 +- salt/modules/win_lgpo.py | 129 +- salt/modules/win_pkg.py | 7 +- salt/modules/win_wua.py | 14 +- salt/modules/zfs.py | 98 +- salt/modules/zk_concurrency.py | 7 +- salt/modules/zoneadm.py | 6 +- salt/modules/zonecfg.py | 59 +- salt/modules/zpool.py | 122 +- salt/netapi/rest_tornado/saltnado.py | 3 +- .../rest_tornado/saltnado_websockets.py | 4 +- salt/output/__init__.py | 3 +- salt/pillar/__init__.py | 20 +- salt/pillar/hg_pillar.py | 2 +- salt/pillar/mysql.py | 4 +- salt/pillar/postgres.py | 4 +- salt/pillar/vmware_pillar.py | 6 +- salt/platform/win.py | 8 +- salt/proxy/chronos.py | 7 +- salt/proxy/cimc.py | 6 +- salt/proxy/marathon.py | 7 +- salt/returners/__init__.py | 16 +- salt/returners/couchbase_return.py | 8 +- salt/returners/elasticsearch_return.py | 3 +- salt/returners/etcd_return.py | 8 +- salt/returners/kafka_return.py | 4 +- salt/returners/splunk.py | 6 +- salt/runners/bgp.py | 14 +- salt/runners/manage.py | 7 +- salt/runners/net.py | 12 +- salt/runners/spacewalk.py | 36 +- salt/scripts.py | 7 +- salt/sdb/sqlite3.py | 3 +- salt/sdb/tism.py | 4 +- salt/spm/__init__.py | 6 +- salt/spm/pkgfiles/local.py | 6 +- salt/state.py | 22 +- salt/states/aptpkg.py | 4 +- salt/states/archive.py | 17 +- salt/states/at.py | 27 +- salt/states/azurearm_network.py | 5 +- salt/states/boto_apigateway.py | 33 +- salt/states/boto_cloudfront.py | 46 +- salt/states/boto_cognitoidentity.py | 40 +- salt/states/boto_datapipeline.py | 44 +- salt/states/boto_dynamodb.py | 7 +- salt/states/boto_ec2.py | 33 +- salt/states/boto_elasticsearch_domain.py | 10 +- salt/states/boto_rds.py | 7 +- salt/states/boto_s3.py | 19 +- salt/states/boto_sqs.py | 68 +- salt/states/boto_vpc.py | 21 +- salt/states/chronos_job.py | 13 +- salt/states/cloud.py | 19 +- salt/states/docker_container.py | 14 +- salt/states/docker_network.py | 7 +- salt/states/ethtool.py | 14 +- salt/states/file.py | 101 +- salt/states/gpg.py | 21 +- salt/states/grafana4_org.py | 7 +- salt/states/grains.py | 7 +- salt/states/influxdb_user.py | 7 +- salt/states/kapacitor.py | 5 +- salt/states/ldap.py | 4 +- salt/states/loop.py | 14 +- salt/states/lvs_service.py | 5 +- salt/states/lxd_container.py | 8 +- salt/states/marathon_app.py | 7 +- salt/states/modjk_worker.py | 7 +- salt/states/msteams.py | 5 +- salt/states/mysql_database.py | 8 +- salt/states/mysql_grants.py | 14 +- salt/states/network.py | 21 +- salt/states/nftables.py | 21 +- salt/states/pagerduty.py | 5 +- salt/states/panos.py | 26 +- salt/states/pdbedit.py | 3 +- salt/states/pip_state.py | 6 +- salt/states/pkg.py | 322 ++--- salt/states/ports.py | 7 +- salt/states/postgres_schema.py | 7 +- salt/states/saltmod.py | 6 +- salt/states/selinux.py | 24 +- salt/states/service.py | 5 +- salt/states/smartos.py | 3 +- salt/states/smtp.py | 5 +- salt/states/ssh_auth.py | 7 +- salt/states/trafficserver.py | 5 +- salt/states/user.py | 7 +- salt/states/win_network.py | 21 +- salt/states/xmpp.py | 14 +- salt/states/zabbix_action.py | 12 +- salt/states/zabbix_template.py | 18 +- salt/states/zabbix_usermacro.py | 12 +- salt/states/zabbix_valuemap.py | 6 +- salt/states/zfs.py | 60 +- salt/states/zone.py | 83 +- salt/states/zpool.py | 4 +- salt/transport/client.py | 15 +- salt/transport/ipc.py | 14 +- salt/transport/tcp.py | 33 +- salt/transport/zeromq.py | 49 +- salt/utils/asynchronous.py | 3 +- salt/utils/aws.py | 12 +- salt/utils/azurearm.py | 3 +- salt/utils/boto3mod.py | 3 +- salt/utils/cloud.py | 28 +- salt/utils/configcomparer.py | 10 +- salt/utils/configparser.py | 5 +- salt/utils/context.py | 4 +- salt/utils/decorators/jinja.py | 18 +- salt/utils/dictdiffer.py | 56 +- salt/utils/dns.py | 52 +- salt/utils/entrypoints.py | 3 +- salt/utils/event.py | 4 +- salt/utils/functools.py | 6 +- salt/utils/gitfs.py | 10 +- salt/utils/github.py | 7 +- salt/utils/http.py | 5 +- salt/utils/job.py | 2 +- salt/utils/minions.py | 2 +- salt/utils/napalm.py | 6 +- salt/utils/network.py | 16 +- salt/utils/odict.py | 2 +- salt/utils/openstack/nova.py | 4 +- salt/utils/parsers.py | 4 +- salt/utils/pkg/win.py | 56 +- salt/utils/platform.py | 8 +- salt/utils/process.py | 5 +- salt/utils/pycrypto.py | 6 +- salt/utils/schedule.py | 28 +- salt/utils/timed_subprocess.py | 3 +- salt/utils/vault.py | 6 +- salt/utils/vmware.py | 4 +- salt/utils/win_osinfo.py | 5 +- salt/utils/win_runas.py | 14 +- salt/utils/zfs.py | 10 +- salt/version.py | 4 +- salt/wheel/__init__.py | 3 +- salt/wheel/config.py | 5 +- scripts/suse/zypper/plugins/commit/zyppnotify | 2 +- tests/conftest.py | 11 +- tests/integration/cli/test_batch.py | 6 +- tests/integration/client/test_kwarg.py | 5 +- tests/integration/client/test_standard.py | 46 +- tests/integration/client/test_syndic.py | 8 +- tests/integration/modules/test_cp.py | 12 +- tests/integration/modules/test_git.py | 15 +- tests/integration/modules/test_mine.py | 12 +- tests/integration/modules/test_mysql.py | 18 +- tests/integration/modules/test_pip.py | 9 +- tests/integration/modules/test_pkg.py | 6 +- tests/integration/modules/test_test.py | 15 +- tests/integration/modules/test_tls.py | 42 +- .../netapi/rest_cherrypy/test_app_pam.py | 2 +- .../netapi/rest_tornado/test_app.py | 6 +- tests/integration/netapi/test_client.py | 3 +- tests/integration/runners/test_nacl.py | 78 +- .../runners/test_runner_returns.py | 5 +- tests/integration/states/test_beacon.py | 3 +- .../integration/states/test_docker_network.py | 27 +- tests/integration/states/test_file.py | 126 +- tests/integration/states/test_git.py | 22 +- .../integration/states/test_lxd_container.py | 40 +- tests/integration/states/test_lxd_image.py | 5 +- tests/integration/states/test_lxd_profile.py | 11 +- tests/integration/states/test_mysql_grants.py | 6 +- tests/integration/states/test_pip_state.py | 16 +- tests/integration/states/test_pkg.py | 46 +- tests/integration/states/test_x509.py | 6 +- tests/integration/utils/test_smb.py | 3 +- tests/minionswarm.py | 4 +- tests/pytests/conftest.py | 3 +- .../functional/modules/test_saltutil.py | 3 +- .../functional/states/rabbitmq/conftest.py | 3 +- .../states/test_docker_container.py | 123 +- tests/pytests/functional/states/test_user.py | 10 +- .../states/win_lgpo/test_rights_assignment.py | 18 +- .../functional/transport/ipc/test_client.py | 7 +- .../transport/ipc/test_subscriber.py | 7 +- .../functional/transport/server/conftest.py | 6 +- .../integration/logging/test_jid_logging.py | 6 +- .../modules/saltutil/test_pillar.py | 10 +- .../pytests/integration/modules/test_mysql.py | 20 +- .../modules/test_rpmbuild_pkgbuild.py | 6 +- .../integration/modules/test_sysmod.py | 12 +- tests/pytests/integration/states/test_file.py | 6 +- .../pytests/integration/states/test_mysql.py | 18 +- .../integration/utils/test_templates.py | 4 +- tests/pytests/scenarios/compat/conftest.py | 10 +- .../scenarios/compat/test_with_versions.py | 12 +- tests/pytests/scenarios/setup/test_install.py | 8 +- tests/pytests/unit/beacons/test_swapusage.py | 7 +- tests/pytests/unit/client/ssh/test_shell.py | 3 +- .../pytests/unit/cloud/clouds/test_hetzner.py | 30 +- tests/pytests/unit/cloud/clouds/test_xen.py | 8 +- tests/pytests/unit/grains/test_core.py | 31 +- tests/pytests/unit/loader/test_lazy.py | 12 +- .../pytests/unit/modules/state/test_state.py | 132 +- .../pytests/unit/modules/test_alternatives.py | 15 +- .../pytests/unit/modules/test_ansiblegate.py | 3 +- tests/pytests/unit/modules/test_aptpkg.py | 13 +- tests/pytests/unit/modules/test_archive.py | 3 +- tests/pytests/unit/modules/test_cmdmod.py | 6 +- tests/pytests/unit/modules/test_gpg.py | 8 +- tests/pytests/unit/modules/test_mysql.py | 31 +- tests/pytests/unit/modules/test_pkgng.py | 62 +- tests/pytests/unit/modules/test_rabbitmq.py | 4 +- .../pytests/unit/modules/test_restartcheck.py | 14 +- .../unit/modules/test_solaris_shadow.py | 10 +- .../unit/modules/test_solarisipspkg.py | 9 +- tests/pytests/unit/modules/test_yumpkg.py | 39 +- tests/pytests/unit/modules/test_zypperpkg.py | 6 +- .../pytests/unit/modules/virt/test_domain.py | 3 +- .../pytests/unit/modules/virt/test_network.py | 15 +- tests/pytests/unit/output/test_highstate.py | 3 +- .../pytests/unit/states/mysql/test_grants.py | 3 +- tests/pytests/unit/states/mysql/test_query.py | 7 +- tests/pytests/unit/states/mysql/test_user.py | 6 +- .../unit/states/postgresql/test_language.py | 3 +- tests/pytests/unit/states/test_archive.py | 3 +- tests/pytests/unit/states/test_boto_asg.py | 3 +- .../unit/states/test_boto_cloudwatch_event.py | 4 +- .../states/test_boto_elasticsearch_domain.py | 4 +- tests/pytests/unit/states/test_boto_iot.py | 4 +- tests/pytests/unit/states/test_boto_sqs.py | 14 +- tests/pytests/unit/states/test_btrfs.py | 5 +- tests/pytests/unit/states/test_cloud.py | 8 +- .../pytests/unit/states/test_docker_volume.py | 16 +- tests/pytests/unit/states/test_drac.py | 3 +- tests/pytests/unit/states/test_event.py | 4 +- tests/pytests/unit/states/test_host.py | 27 +- tests/pytests/unit/states/test_lvm.py | 6 +- .../pytests/unit/states/test_mac_keychain.py | 4 +- tests/pytests/unit/states/test_pkg.py | 48 +- tests/pytests/unit/states/test_service.py | 5 +- tests/pytests/unit/states/test_slack.py | 12 +- tests/pytests/unit/states/test_user.py | 3 +- tests/pytests/unit/states/test_win_network.py | 5 +- .../pytests/unit/states/test_win_powercfg.py | 3 +- tests/pytests/unit/states/test_zfs.py | 12 +- tests/pytests/unit/states/test_zpool.py | 10 +- tests/pytests/unit/states/virt/test_domain.py | 18 +- tests/pytests/unit/test_version.py | 3 +- tests/pytests/unit/transport/test_tcp.py | 3 +- tests/pytests/unit/transport/test_zeromq.py | 4 +- tests/pytests/unit/utils/test_cloud.py | 96 +- tests/pytests/unit/utils/test_stringutils.py | 125 +- tests/pytests/unit/utils/test_versions.py | 12 +- .../pytests/unit/utils/test_win_functions.py | 2 +- tests/saltsh.py | 5 +- tests/support/case.py | 4 +- tests/support/gitfs.py | 16 +- tests/support/helpers.py | 6 +- tests/support/pytest/loader.py | 16 +- tests/unit/beacons/test_journald.py | 2 +- tests/unit/beacons/test_salt_monitor.py | 17 +- tests/unit/beacons/test_telegram_bot_msg.py | 13 +- tests/unit/client/test_ssh.py | 3 +- tests/unit/cloud/clouds/test_digitalocean.py | 4 +- tests/unit/cloud/clouds/test_openstack.py | 3 +- tests/unit/cloud/clouds/test_proxmox.py | 8 +- tests/unit/fileserver/test_gitfs.py | 4 +- tests/unit/modules/nxos/nxos_n36k.py | 2 +- tests/unit/modules/nxos/nxos_n3k.py | 2 +- tests/unit/modules/nxos/nxos_n5k.py | 2 +- tests/unit/modules/nxos/nxos_n7k.py | 2 +- tests/unit/modules/nxos/nxos_n93k.py | 2 +- tests/unit/modules/nxos/nxos_n93klxc.py | 2 +- tests/unit/modules/nxos/nxos_n95k.py | 2 +- tests/unit/modules/nxos/nxos_platform.py | 14 +- tests/unit/modules/test_artifactory.py | 3 +- tests/unit/modules/test_at.py | 2 +- tests/unit/modules/test_bluez_bluetooth.py | 30 +- .../unit/modules/test_boto3_elasticsearch.py | 16 +- .../modules/test_boto_cloudwatch_event.py | 8 +- tests/unit/modules/test_boto_route53.py | 41 +- tests/unit/modules/test_boto_vpc.py | 24 +- tests/unit/modules/test_dockermod.py | 22 +- tests/unit/modules/test_file.py | 220 ++- tests/unit/modules/test_freebsd_sysctl.py | 6 +- tests/unit/modules/test_glusterfs.py | 18 +- tests/unit/modules/test_helm.py | 13 +- tests/unit/modules/test_hosts.py | 7 +- tests/unit/modules/test_influxdb08mod.py | 10 +- tests/unit/modules/test_k8s.py | 4 +- tests/unit/modules/test_kubeadm.py | 36 +- tests/unit/modules/test_kubernetesmod.py | 6 +- tests/unit/modules/test_mac_keychain.py | 16 +- tests/unit/modules/test_macdefaults.py | 14 +- tests/unit/modules/test_macpackage.py | 34 +- tests/unit/modules/test_mandrill.py | 3 +- tests/unit/modules/test_nova.py | 4 +- tests/unit/modules/test_nxos.py | 120 +- tests/unit/modules/test_nxos_upgrade.py | 46 +- tests/unit/modules/test_pillar.py | 6 +- tests/unit/modules/test_pip.py | 222 ++- tests/unit/modules/test_pkg_resource.py | 46 +- tests/unit/modules/test_proxy.py | 42 +- tests/unit/modules/test_reg.py | 7 +- tests/unit/modules/test_rh_ip.py | 26 +- tests/unit/modules/test_saltcloudmod.py | 4 +- tests/unit/modules/test_systemd_service.py | 8 +- tests/unit/modules/test_timezone.py | 4 +- tests/unit/modules/test_tuned.py | 3 +- tests/unit/modules/test_virt.py | 163 ++- tests/unit/modules/test_virtualenv_mod.py | 7 +- tests/unit/modules/test_win_certutil.py | 8 +- tests/unit/modules/test_win_dism.py | 34 +- tests/unit/modules/test_win_file.py | 2 +- tests/unit/modules/test_win_license.py | 14 +- tests/unit/modules/test_win_pkg.py | 18 +- tests/unit/modules/test_win_service.py | 52 +- tests/unit/modules/test_win_system.py | 58 +- tests/unit/modules/test_xapi_virt.py | 72 +- tests/unit/modules/test_xml.py | 10 +- tests/unit/modules/test_zcbuildout.py | 3 +- tests/unit/netapi/test_rest_tornado.py | 12 +- tests/unit/pillar/test_pepa.py | 12 +- tests/unit/proxy/test_nxos.py | 64 +- tests/unit/renderers/test_aws_kms.py | 8 +- tests/unit/renderers/test_gpg.py | 3 +- tests/unit/sdb/test_etcd_db.py | 6 +- tests/unit/sdb/test_vault.py | 6 +- tests/unit/states/test_file.py | 14 +- tests/unit/states/test_git.py | 4 +- tests/unit/states/test_group.py | 6 +- tests/unit/states/test_hg.py | 14 +- tests/unit/states/test_iptables.py | 18 +- tests/unit/states/test_kubernetes.py | 67 +- tests/unit/states/test_ldap.py | 14 +- tests/unit/states/test_module.py | 13 +- tests/unit/states/test_network.py | 18 +- tests/unit/states/test_saltmod.py | 6 +- tests/unit/states/test_virt.py | 6 +- tests/unit/states/test_virtualenv_mod.py | 4 +- tests/unit/test_auth.py | 12 +- tests/unit/test_loader.py | 5 +- tests/unit/test_minion.py | 3 +- tests/unit/test_pillar.py | 4 +- tests/unit/test_proxy_minion.py | 4 +- tests/unit/tokens/test_localfs.py | 21 +- tests/unit/transport/test_ipc.py | 6 +- tests/unit/transport/test_tcp.py | 6 +- tests/unit/utils/test_args.py | 15 +- tests/unit/utils/test_configcomparer.py | 44 +- tests/unit/utils/test_configparser.py | 4 +- tests/unit/utils/test_context.py | 39 +- tests/unit/utils/test_data.py | 14 +- tests/unit/utils/test_dns.py | 21 +- tests/unit/utils/test_dockermod.py | 79 +- tests/unit/utils/test_event.py | 7 +- tests/unit/utils/test_jinja.py | 24 +- tests/unit/utils/test_mac_utils.py | 5 +- tests/unit/utils/test_msgpack.py | 8 +- tests/unit/utils/test_process.py | 3 +- tests/unit/utils/test_pycrypto.py | 11 +- tests/unit/utils/test_reactor.py | 4 +- tests/unit/utils/test_schema.py | 2 +- tests/unit/utils/test_templates.py | 33 +- tests/unit/utils/test_thin.py | 28 +- tests/unit/utils/test_vmware.py | 3 +- tests/unit/utils/test_vt.py | 22 +- tests/unit/utils/test_win_functions.py | 2 +- tests/unit/utils/test_win_reg.py | 6 +- tests/unit/utils/test_zfs.py | 6 +- 501 files changed, 6800 insertions(+), 3586 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e6b2f5eec81..5e3ad7b6ce5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1134,7 +1134,7 @@ repos: )$ - repo: https://github.com/psf/black - rev: 19.10b0 + rev: 21.7b0 hooks: - id: black # This tells pre-commit not to pass files to black. @@ -1146,6 +1146,14 @@ repos: tests/kitchen/.* )$ + - repo: https://github.com/asottile/blacken-docs + rev: v1.10.0 + hooks: + - id: blacken-docs + args: [--skip-errors] + files: ^doc/.*\.rst + additional_dependencies: [black==21.7b0] + - repo: https://github.com/myint/rstcheck # This, for now, is meant to run when locally committing code and will be disabled(skipped) when we run pre-commit # against all codebase to avoid MASSIVE code churn. This way, we do it in smaller chunks, a few at a time. @@ -1155,14 +1163,6 @@ repos: name: Check reST files using rstcheck args: [--report=warning] additional_dependencies: [sphinx] - - - repo: https://github.com/asottile/blacken-docs - rev: v1.7.0 - hooks: - - id: blacken-docs - args: [--skip-errors] - files: ^doc/.*\.rst - additional_dependencies: [black==19.10b0] # <---- Code Formatting -------------------------------------------------------------------------------------------- # ----- Security --------------------------------------------------------------------------------------------------> diff --git a/doc/_ext/saltdomain.py b/doc/_ext/saltdomain.py index 9a3bca5fd6f..03db0f1905d 100644 --- a/doc/_ext/saltdomain.py +++ b/doc/_ext/saltdomain.py @@ -222,7 +222,7 @@ class State(Directive): indextext = "{1} ({0}-formula)".format(formula, statename) inode = addnodes.index( - entries=[("single", indextext, "module-{}".format(statename), ""),] + entries=[("single", indextext, "module-{}".format(statename), "")] ) return [targetnode, inode] @@ -244,9 +244,7 @@ class SaltDomain(python_domain.PythonDomain): data_version = 2 object_types = python_domain.PythonDomain.object_types - object_types.update( - {"state": ObjType(_("state"), "state"),} - ) + object_types.update({"state": ObjType(_("state"), "state")}) directives = python_domain.PythonDomain.directives directives.update( @@ -260,14 +258,10 @@ class SaltDomain(python_domain.PythonDomain): ) roles = python_domain.PythonDomain.roles - roles.update( - {"formula": SLSXRefRole(),} - ) + roles.update({"formula": SLSXRefRole()}) initial_data = python_domain.PythonDomain.initial_data - initial_data.update( - {"formulas": {},} - ) + initial_data.update({"formulas": {}}) indices = [ SaltModuleIndex, diff --git a/doc/ref/modules/index.rst b/doc/ref/modules/index.rst index 8d17a005525..59f7c003aaa 100644 --- a/doc/ref/modules/index.rst +++ b/doc/ref/modules/index.rst @@ -92,7 +92,7 @@ included libraries. def is_ok(person): - """ Checks whether a person is really a lumberjack """ + """Checks whether a person is really a lumberjack""" return sleep.all_night(person) and work.all_day(person) Then, create the zip: diff --git a/doc/ref/renderers/index.rst b/doc/ref/renderers/index.rst index 71a541a20cb..fb95e65e9c8 100644 --- a/doc/ref/renderers/index.rst +++ b/doc/ref/renderers/index.rst @@ -82,7 +82,7 @@ to install a package: """ return { "include": ["python"], - "python-foo": {"pkg.installed": [{"version": "1.5-1.el7"},]}, + "python-foo": {"pkg.installed": [{"version": "1.5-1.el7"}]}, } This would be equivalent to the following: diff --git a/doc/topics/cloud/cloud.rst b/doc/topics/cloud/cloud.rst index ffebf995973..bfb7aff6bdc 100644 --- a/doc/topics/cloud/cloud.rst +++ b/doc/topics/cloud/cloud.rst @@ -306,7 +306,7 @@ general, the following code can be used as-is: Return a list of the VMs that are on the provider, with select fields """ return salt.utils.cloud.list_nodes_select( - list_nodes_full("function"), __opts__["query.selection"], call, + list_nodes_full("function"), __opts__["query.selection"], call ) However, depending on the cloud provider, additional variables may be required. @@ -324,7 +324,7 @@ appropriately: conn = get_conn() # pylint: disable=E0602 return salt.utils.cloud.list_nodes_select( - list_nodes_full(conn, "function"), __opts__["query.selection"], call, + list_nodes_full(conn, "function"), __opts__["query.selection"], call ) This function is normally called with the ``-S`` option: diff --git a/doc/topics/development/conventions/formulas.rst b/doc/topics/development/conventions/formulas.rst index 0e5a492fa86..8fc28cb3e45 100644 --- a/doc/topics/development/conventions/formulas.rst +++ b/doc/topics/development/conventions/formulas.rst @@ -666,7 +666,7 @@ example is a state tree of two sls files, one simple and one complicated. return { "set_roles_grains": { - "grains.present": [{"name": "roles"}, {"value": list(list_of_roles)},], + "grains.present": [{"name": "roles"}, {"value": list(list_of_roles)}], }, } diff --git a/doc/topics/event/events.rst b/doc/topics/event/events.rst index 21a4329039c..238d10bfa05 100644 --- a/doc/topics/event/events.rst +++ b/doc/topics/event/events.rst @@ -232,7 +232,7 @@ easily done using the normal cross-calling syntax: # do something! __salt__["event.send"]( "myco/my_custom_module/finished", - {"finished": True, "message": "The something is finished!",}, + {"finished": True, "message": "The something is finished!"}, ) From Custom Python Scripts diff --git a/doc/topics/releases/2017.7.0.rst b/doc/topics/releases/2017.7.0.rst index d81270dd863..9b8fa3881bc 100644 --- a/doc/topics/releases/2017.7.0.rst +++ b/doc/topics/releases/2017.7.0.rst @@ -316,11 +316,11 @@ structure to include job meta data such as ``retcode``. This is useful at the Python API: -.. code-block:: python +.. code-block:: pycon >>> import salt.client >>> client = salt.client.LocalClient() - >>> client.cmd('*', 'cmd.run', ['return 1'], full_return=True) + >>> client.cmd("*", "cmd.run", ["return 1"], full_return=True) {'jerry': {'jid': '20170520151213898053', 'ret': '', 'retcode': 1}} As well as from salt-api: diff --git a/doc/topics/releases/2019.2.0.rst b/doc/topics/releases/2019.2.0.rst index 1d3db429653..efc5d1920a7 100644 --- a/doc/topics/releases/2019.2.0.rst +++ b/doc/topics/releases/2019.2.0.rst @@ -959,7 +959,7 @@ their code to use ``tgt_type``. >>> import salt.client >>> local = salt.client.LocalClient() - >>> local.cmd('*', 'cmd.run', ['whoami'], tgt_type='glob') + >>> local.cmd("*", "cmd.run", ["whoami"], tgt_type="glob") {'jerry': 'root'} Minion Configuration Deprecated Option diff --git a/doc/topics/troubleshooting/yaml_idiosyncrasies.rst b/doc/topics/troubleshooting/yaml_idiosyncrasies.rst index 26fe9894812..2f4e2aab3f1 100644 --- a/doc/topics/troubleshooting/yaml_idiosyncrasies.rst +++ b/doc/topics/troubleshooting/yaml_idiosyncrasies.rst @@ -86,18 +86,22 @@ deeply-nested dict can be declared with curly braces: Here is a more concrete example of how YAML actually handles these indentations, using the Python interpreter on the command line: -.. code-block:: python +.. code-block:: pycon >>> import yaml - >>> yaml.safe_load('''mystate: + >>> yaml.safe_load( + ... """mystate: ... file.managed: ... - context: - ... some: var''') + ... some: var""" + ... ) {'mystate': {'file.managed': [{'context': {'some': 'var'}}]}} - >>> yaml.safe_load('''mystate: + >>> yaml.safe_load( + ... """mystate: ... file.managed: ... - context: - ... some: var''') + ... some: var""" + ... ) {'mystate': {'file.managed': [{'some': 'var', 'context': None}]}} Note that in the second example, ``some`` is added as another key in the same @@ -367,10 +371,10 @@ string, it should be surrounded by quotes. `More information here`_. Here's an example: -.. code-block:: python +.. code-block:: pycon >>> import yaml - >>> yaml.safe_load('2013_05_10') + >>> yaml.safe_load("2013_05_10") 20130510 >>> yaml.safe_load('"2013_05_10"') '2013_05_10' @@ -385,10 +389,10 @@ functionality. If values such as these are needed in a salt YAML file (specifically a configuration file), they should be formatted with surrounding strings to force YAML to serialize them as strings: -.. code-block:: python +.. code-block:: pycon >>> import yaml - >>> yaml.safe_load('2014-01-20 14:23:23') + >>> yaml.safe_load("2014-01-20 14:23:23") datetime.datetime(2014, 1, 20, 14, 23, 23) >>> yaml.safe_load('"2014-01-20 14:23:23"') '2014-01-20 14:23:23' @@ -400,10 +404,10 @@ is a real one). Thus, for example, if a minion were to have an ID of date was out of range. The workaround is the same, surround the offending string with quotes: -.. code-block:: python +.. code-block:: pycon >>> import yaml - >>> yaml.safe_load('4017-16-20') + >>> yaml.safe_load("4017-16-20") Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.7/site-packages/yaml/__init__.py", line 93, in safe_load diff --git a/doc/topics/tutorials/http.rst b/doc/topics/tutorials/http.rst index 54a2e1e8856..33230654e1c 100644 --- a/doc/topics/tutorials/http.rst +++ b/doc/topics/tutorials/http.rst @@ -181,9 +181,7 @@ password may be passed in as ``username`` and ``password``, respectively. .. code-block:: python - salt.utils.http.query( - "http://example.com", username="larry", password="5700g3543v4r", - ) + salt.utils.http.query("http://example.com", username="larry", password="5700g3543v4r") Cookies and Sessions ```````````````````` @@ -327,9 +325,7 @@ debugging purposes, SSL verification can be turned off. .. code-block:: python - salt.utils.http.query( - "https://example.com", verify_ssl=False, - ) + salt.utils.http.query("https://example.com", verify_ssl=False) CA Bundles ~~~~~~~~~~ @@ -343,9 +339,7 @@ using the ``ca_bundle`` variable. .. code-block:: python - salt.utils.http.query( - "https://example.com", ca_bundle="/path/to/ca_bundle.pem", - ) + salt.utils.http.query("https://example.com", ca_bundle="/path/to/ca_bundle.pem") Updating CA Bundles ``````````````````` diff --git a/doc/topics/tutorials/jinja_to_execution_module.rst b/doc/topics/tutorials/jinja_to_execution_module.rst index 27c54d75271..25fa66ad89c 100644 --- a/doc/topics/tutorials/jinja_to_execution_module.rst +++ b/doc/topics/tutorials/jinja_to_execution_module.rst @@ -122,7 +122,7 @@ Note how the module encapsulates all of the logic around finding the storage ser ] colo = __pillar__.get("inventory", {}).get("colo", "Unknown") - return __pillar__.get("storage_servers", {}).get(colo, ["unknown",]) + return __pillar__.get("storage_servers", {}).get(colo, ["unknown"]) def ip(): diff --git a/pkg/rpm/build.py b/pkg/rpm/build.py index f2e5a826963..c2f6e38b0c8 100755 --- a/pkg/rpm/build.py +++ b/pkg/rpm/build.py @@ -8,7 +8,7 @@ from os.path import abspath, dirname, join from shutil import copy from subprocess import check_call -parser = argparse.ArgumentParser(description="Build salt rpms",) +parser = argparse.ArgumentParser(description="Build salt rpms") parser.add_argument( "buildid", help="The build id to use i.e. the bit after the salt version in the package name", diff --git a/salt/beacons/smartos_vmadm.py b/salt/beacons/smartos_vmadm.py index 155b5b81071..a71e5765788 100644 --- a/salt/beacons/smartos_vmadm.py +++ b/salt/beacons/smartos_vmadm.py @@ -66,7 +66,8 @@ def beacon(config): # NOTE: lookup current images current_vms = __salt__["vmadm.list"]( - keyed=True, order="uuid,state,alias,hostname,dns_domain", + keyed=True, + order="uuid,state,alias,hostname,dns_domain", ) # NOTE: apply configuration diff --git a/salt/beacons/watchdog.py b/salt/beacons/watchdog.py index 3644026f951..7b6eced6afa 100644 --- a/salt/beacons/watchdog.py +++ b/salt/beacons/watchdog.py @@ -19,7 +19,7 @@ except ImportError: HAS_WATCHDOG = False class FileSystemEventHandler: - """ A dummy class to make the import work """ + """A dummy class to make the import work""" def __init__(self): pass diff --git a/salt/cache/etcd_cache.py b/salt/cache/etcd_cache.py index 30a91f1376f..8b877bf354c 100644 --- a/salt/cache/etcd_cache.py +++ b/salt/cache/etcd_cache.py @@ -92,8 +92,7 @@ def __virtual__(): def _init_client(): - """Setup client and init datastore. - """ + """Setup client and init datastore.""" global client, path_prefix if client is not None: return diff --git a/salt/cache/mysql_cache.py b/salt/cache/mysql_cache.py index 1c183d16c03..e07260a9c03 100644 --- a/salt/cache/mysql_cache.py +++ b/salt/cache/mysql_cache.py @@ -127,7 +127,8 @@ def _create_table(): # warning on CREATE TABLE query = """SELECT COUNT(TABLE_NAME) FROM information_schema.tables WHERE table_schema = '{}' AND table_name = '{}'""".format( - _mysql_kwargs["db"], _table_name, + _mysql_kwargs["db"], + _table_name, ) cur, _ = run_query(client, query) r = cur.fetchone() @@ -149,8 +150,7 @@ def _create_table(): def _init_client(): - """Initialize connection and create table if needed - """ + """Initialize connection and create table if needed""" if client is not None: return diff --git a/salt/cli/spm.py b/salt/cli/spm.py index c3409c396de..92c882ae2fb 100644 --- a/salt/cli/spm.py +++ b/salt/cli/spm.py @@ -29,7 +29,9 @@ class SPM(parsers.SPMParser): self.config["spm_cache_dir"], ] verify_env( - v_dirs, self.config["user"], root_dir=self.config["root_dir"], + v_dirs, + self.config["user"], + root_dir=self.config["root_dir"], ) verify_log(self.config) client = salt.spm.SPMClient(ui, self.config) diff --git a/salt/client/mixins.py b/salt/client/mixins.py index 0aecf704c28..55190ce0a9f 100644 --- a/salt/client/mixins.py +++ b/salt/client/mixins.py @@ -409,7 +409,9 @@ class SyncClientMixin: data["return"] = str(ex) else: data["return"] = "Exception occurred in {} {}: {}".format( - self.client, fun, traceback.format_exc(), + self.client, + fun, + traceback.format_exc(), ) data["success"] = False diff --git a/salt/client/ssh/__init__.py b/salt/client/ssh/__init__.py index c8349ce8d06..590af96a553 100644 --- a/salt/client/ssh/__init__.py +++ b/salt/client/ssh/__init__.py @@ -1016,7 +1016,8 @@ class Single: Deploy salt-thin """ self.shell.send( - self.thin, os.path.join(self.thin_dir, "salt-thin.tgz"), + self.thin, + os.path.join(self.thin_dir, "salt-thin.tgz"), ) self.deploy_ext() return True @@ -1027,7 +1028,8 @@ class Single: """ if self.mods.get("file"): self.shell.send( - self.mods["file"], os.path.join(self.thin_dir, "salt-ext_mods.tgz"), + self.mods["file"], + os.path.join(self.thin_dir, "salt-ext_mods.tgz"), ) return True diff --git a/salt/client/ssh/shell.py b/salt/client/ssh/shell.py index fc39279213e..0fd86a7443c 100644 --- a/salt/client/ssh/shell.py +++ b/salt/client/ssh/shell.py @@ -272,7 +272,9 @@ class Shell: """ try: proc = salt.utils.nb_popen.NonBlockingPopen( - self._split_cmd(cmd), stderr=subprocess.PIPE, stdout=subprocess.PIPE, + self._split_cmd(cmd), + stderr=subprocess.PIPE, + stdout=subprocess.PIPE, ) while True: time.sleep(0.1) diff --git a/salt/client/ssh/ssh_py_shim.py b/salt/client/ssh/ssh_py_shim.py index 0261c1c2b4d..871667afee3 100644 --- a/salt/client/ssh/ssh_py_shim.py +++ b/salt/client/ssh/ssh_py_shim.py @@ -47,7 +47,7 @@ ARGS = None def get_system_encoding(): """ - Get system encoding. Most of this code is a part of salt/__init__.py + Get system encoding. Most of this code is a part of salt/__init__.py """ # This is the most trustworthy source of the system encoding, though, if # salt is being imported after being daemonized, this information is lost @@ -215,7 +215,13 @@ def reset_time(path=".", amt=None): fname = os.path.join(path, fname) if os.path.isdir(fname): reset_time(fname, amt=amt) - os.utime(fname, (amt, amt,)) + os.utime( + fname, + ( + amt, + amt, + ), + ) def get_executable(): diff --git a/salt/client/ssh/state.py b/salt/client/ssh/state.py index 79b5b5a030e..06a3f6be2fb 100644 --- a/salt/client/ssh/state.py +++ b/salt/client/ssh/state.py @@ -246,7 +246,7 @@ def prep_trans_tar( fn = filename[ len(file_client.get_cachedir(cache_dest)) : ].strip("/") - tgt = os.path.join(env_root, short, fn,) + tgt = os.path.join(env_root, short, fn) tgt_dir = os.path.dirname(tgt) if not os.path.isdir(tgt_dir): os.makedirs(tgt_dir) diff --git a/salt/cloud/__init__.py b/salt/cloud/__init__.py index 9c9fe8fabd7..2fb49c63ef0 100644 --- a/salt/cloud/__init__.py +++ b/salt/cloud/__init__.py @@ -1975,7 +1975,7 @@ class Map(Cloud): break log.warning( - "%r already exists, removing from the create map.", name, + "%r already exists, removing from the create map.", name ) if "existing" not in ret: diff --git a/salt/cloud/cli.py b/salt/cloud/cli.py index 7db264fa2bb..49f73ffba4e 100644 --- a/salt/cloud/cli.py +++ b/salt/cloud/cli.py @@ -104,70 +104,56 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser): if self.selected_query_option is not None: if self.selected_query_option == "list_providers": - # pylint: disable=broad-except try: ret = mapper.provider_list() - except (SaltCloudException, Exception,) as exc: + except Exception as exc: # pylint: disable=broad-except msg = "There was an error listing providers: {0}" self.handle_exception(msg, exc) - # pylint: enable=broad-except elif self.selected_query_option == "list_profiles": provider = self.options.list_profiles - # pylint: disable=broad-except try: ret = mapper.profile_list(provider) - except (SaltCloudException, Exception,) as exc: + except Exception as exc: # pylint: disable=broad-except msg = "There was an error listing profiles: {0}" self.handle_exception(msg, exc) - # pylint: enable=broad-except elif self.config.get("map", None): log.info("Applying map from '%s'.", self.config["map"]) - # pylint: disable=broad-except try: ret = mapper.interpolated_map(query=self.selected_query_option) - except (SaltCloudException, Exception,) as exc: + except Exception as exc: # pylint: disable=broad-except msg = "There was an error with a custom map: {0}" self.handle_exception(msg, exc) - # pylint: enable=broad-except else: - # pylint: disable=broad-except try: ret = mapper.map_providers_parallel( query=self.selected_query_option ) - except (SaltCloudException, Exception,) as exc: + except Exception as exc: # pylint: disable=broad-except msg = "There was an error with a map: {0}" self.handle_exception(msg, exc) - # pylint: enable=broad-except elif self.options.list_locations is not None: - # pylint: disable=broad-except try: ret = mapper.location_list(self.options.list_locations) - except (SaltCloudException, Exception,) as exc: + except Exception as exc: # pylint: disable=broad-except msg = "There was an error listing locations: {0}" self.handle_exception(msg, exc) - # pylint: enable=broad-except elif self.options.list_images is not None: - # pylint: disable=broad-except try: ret = mapper.image_list(self.options.list_images) - except (SaltCloudException, Exception,) as exc: + except Exception as exc: # pylint: disable=broad-except msg = "There was an error listing images: {0}" self.handle_exception(msg, exc) - # pylint: enable=broad-except elif self.options.list_sizes is not None: - # pylint: disable=broad-except try: ret = mapper.size_list(self.options.list_sizes) - except (SaltCloudException, Exception,) as exc: + except Exception as exc: # pylint: disable=broad-except msg = "There was an error listing sizes: {0}" self.handle_exception(msg, exc) - # pylint: enable=broad-except elif self.options.destroy and ( self.config.get("names", None) or self.config.get("map", None) @@ -204,14 +190,12 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser): for name in vms: msg += " {}\n".format(name) names.add(name) - # pylint: disable=broad-except try: if self.print_confirm(msg): ret = mapper.destroy(names, cached=True) - except (SaltCloudException, Exception,) as exc: + except Exception as exc: # pylint: disable=broad-except msg = "There was an error destroying machines: {0}" self.handle_exception(msg, exc) - # pylint: enable=broad-except elif self.options.action and ( self.config.get("names", None) or self.config.get("map", None) @@ -242,14 +226,12 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser): machines.append(name) names = machines - # pylint: disable=broad-except try: if self.print_confirm(msg): ret = mapper.do_action(names, kwargs) - except (SaltCloudException, Exception,) as exc: + except Exception as exc: # pylint: disable=broad-except msg = "There was an error actioning machines: {0}" self.handle_exception(msg, exc) - # pylint: enable=broad-except elif self.options.function: kwargs = {} @@ -266,24 +248,20 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser): "as kwargs. Ex: image=ami-54cf5c3d. Remaining " "arguments: {}".format(args) ) - # pylint: disable=broad-except try: ret = mapper.do_function( self.function_provider, self.function_name, kwargs ) - except (SaltCloudException, Exception,) as exc: + except Exception as exc: # pylint: disable=broad-except msg = "There was an error running the function: {0}" self.handle_exception(msg, exc) - # pylint: enable=broad-except elif self.options.profile and self.config.get("names", False): - # pylint: disable=broad-except try: ret = mapper.run_profile(self.options.profile, self.config.get("names")) - except (SaltCloudException, Exception,) as exc: + except Exception as exc: # pylint: disable=broad-except msg = "There was a profile error: {0}" self.handle_exception(msg, exc) - # pylint: enable=broad-except elif self.options.set_password: username = self.credential_username @@ -295,7 +273,6 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser): if not mapper.rendered_map: sys.stderr.write("No nodes defined in this map") self.exit(salt.defaults.exitcodes.EX_GENERIC) - # pylint: disable=broad-except try: ret = {} run_map = True @@ -354,10 +331,9 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser): msg = "Already running." ret[name] = {"Message": msg} - except (SaltCloudException, Exception,) as exc: + except Exception as exc: # pylint: disable=broad-except msg = "There was a query error: {0}" self.handle_exception(msg, exc) - # pylint: enable=broad-except elif self.options.bootstrap: host = self.options.bootstrap @@ -386,13 +362,11 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser): ) ) - # pylint: disable=broad-except try: ret = salt.utils.cloud.bootstrap(vm_, self.config) - except (SaltCloudException, Exception,) as exc: + except Exception as exc: # pylint: disable=broad-except msg = "There was an error bootstrapping the minion: {0}" self.handle_exception(msg, exc) - # pylint: enable=broad-except else: self.error("Nothing was done. Using the proper arguments?") diff --git a/salt/cloud/clouds/aliyun.py b/salt/cloud/clouds/aliyun.py index cb1f4a1a792..633b026c122 100644 --- a/salt/cloud/clouds/aliyun.py +++ b/salt/cloud/clouds/aliyun.py @@ -364,7 +364,9 @@ def list_nodes_select(call=None): Return a list of the VMs that are on the provider, with select fields """ return salt.utils.cloud.list_nodes_select( - list_nodes_full("function"), __opts__["query.selection"], call, + list_nodes_full("function"), + __opts__["query.selection"], + call, ) diff --git a/salt/cloud/clouds/azurearm.py b/salt/cloud/clouds/azurearm.py index d9306805528..4873010d18a 100644 --- a/salt/cloud/clouds/azurearm.py +++ b/salt/cloud/clouds/azurearm.py @@ -222,7 +222,9 @@ def get_configured_provider(): for combo in key_combos: provider = config.is_provider_configured( - __opts__, _get_active_provider_name() or __virtualname__, combo, + __opts__, + _get_active_provider_name() or __virtualname__, + combo, ) if provider: @@ -352,12 +354,15 @@ def avail_images(call=None): data = {} try: offers = compconn.virtual_machine_images.list_offers( - location=region, publisher_name=publisher, + location=region, + publisher_name=publisher, ) for offer_obj in offers: offer = offer_obj.as_dict() skus = compconn.virtual_machine_images.list_skus( - location=region, publisher_name=publisher, offer=offer["name"], + location=region, + publisher_name=publisher, + offer=offer["name"], ) for sku_obj in skus: sku = sku_obj.as_dict() @@ -370,7 +375,12 @@ def avail_images(call=None): for version_obj in results: version = version_obj.as_dict() name = "|".join( - (publisher, offer["name"], sku["name"], version["name"],) + ( + publisher, + offer["name"], + sku["name"], + version["name"], + ) ) data[name] = { "publisher": publisher, @@ -593,14 +603,16 @@ def delete_interface(call=None, kwargs=None): # pylint: disable=unused-argument ips = [] iface = netconn.network_interfaces.get( - kwargs["resource_group"], kwargs["iface_name"], + kwargs["resource_group"], + kwargs["iface_name"], ) iface_name = iface.name for ip_ in iface.ip_configurations: ips.append(ip_.name) poller = netconn.network_interfaces.delete( - kwargs["resource_group"], kwargs["iface_name"], + kwargs["resource_group"], + kwargs["iface_name"], ) poller.wait() @@ -735,7 +747,9 @@ def create_network_interface(call=None, kwargs=None): for pool in be_pools: try: lbbep_data = netconn.load_balancer_backend_address_pools.get( - kwargs["resource_group"], load_bal, pool, + kwargs["resource_group"], + load_bal, + pool, ) pool_ids.append({"id": lbbep_data.as_dict()["id"]}) except CloudError as exc: @@ -768,7 +782,8 @@ def create_network_interface(call=None, kwargs=None): while True: try: pub_ip_data = netconn.public_ip_addresses.get( - kwargs["resource_group"], pub_ip_name, + kwargs["resource_group"], + pub_ip_name, ) if pub_ip_data.ip_address: # pylint: disable=no-member ip_kwargs["public_ip_address"] = PublicIPAddress( @@ -942,7 +957,9 @@ def request_instance(vm_): key_data=ssh_publickeyfile_contents, path="/home/{}/.ssh/authorized_keys".format(vm_username), ) - sshconfiguration = SshConfiguration(public_keys=[sshpublickey],) + sshconfiguration = SshConfiguration( + public_keys=[sshpublickey], + ) linuxconfiguration = LinuxConfiguration( disable_password_authentication=disable_password_authentication, ssh=sshconfiguration, @@ -1074,7 +1091,10 @@ def request_instance(vm_): if "|" in vm_["image"]: img_pub, img_off, img_sku, img_ver = vm_["image"].split("|") img_ref = ImageReference( - publisher=img_pub, offer=img_off, sku=img_sku, version=img_ver, + publisher=img_pub, + offer=img_off, + sku=img_sku, + version=img_ver, ) elif vm_["image"].startswith("/subscriptions"): img_ref = ImageReference(id=vm_["image"]) @@ -1088,7 +1108,9 @@ def request_instance(vm_): name=disk_name, vhd=VirtualHardDisk( uri="https://{}.blob.{}/vhds/{}.vhd".format( - vm_["storage_account"], storage_endpoint_suffix, disk_name, + vm_["storage_account"], + storage_endpoint_suffix, + disk_name, ), ), os_type=os_type, @@ -1105,7 +1127,10 @@ def request_instance(vm_): if "|" in vm_["image"]: img_pub, img_off, img_sku, img_ver = vm_["image"].split("|") img_ref = ImageReference( - publisher=img_pub, offer=img_off, sku=img_sku, version=img_ver, + publisher=img_pub, + offer=img_off, + sku=img_sku, + version=img_ver, ) elif vm_["image"].startswith("/subscriptions"): img_ref = ImageReference(id=vm_["image"]) @@ -1192,7 +1217,9 @@ def request_instance(vm_): vm_size=getattr(VirtualMachineSizeTypes, vm_["size"].lower()), ), storage_profile=StorageProfile( - os_disk=os_disk, data_disks=data_disks, image_reference=img_ref, + os_disk=os_disk, + data_disks=data_disks, + image_reference=img_ref, ), os_profile=OSProfile( admin_username=vm_username, computer_name=vm_["name"], **os_kwargs @@ -1298,7 +1325,10 @@ def create(vm_): try: data = salt.utils.cloud.wait_for_ip( _query_node_data, - update_args=(vm_["name"], vm_["bootstrap_interface"],), + update_args=( + vm_["name"], + vm_["bootstrap_interface"], + ), timeout=config.get_cloud_config_value( "wait_for_ip_timeout", vm_, __opts__, default=10 * 60 ), @@ -1648,7 +1678,9 @@ def delete_managed_disk(call=None, kwargs=None): # pylint: disable=unused-argum compconn.disks.delete(kwargs["resource_group"], kwargs["blob"]) except Exception as exc: # pylint: disable=broad-except log.error( - "Error deleting managed disk %s - %s", kwargs.get("blob"), str(exc), + "Error deleting managed disk %s - %s", + kwargs.get("blob"), + str(exc), ) return False @@ -1947,7 +1979,8 @@ def start(name, call=None): ret = vm_result.as_dict() except CloudError as exc: salt.utils.azurearm.log_cloud_error( - "compute", "Error attempting to start {}: {}".format(name, exc.message), + "compute", + "Error attempting to start {}: {}".format(name, exc.message), ) ret = {"error": exc.message} diff --git a/salt/cloud/clouds/clc.py b/salt/cloud/clouds/clc.py index 9b853395388..5ea5dfacb21 100644 --- a/salt/cloud/clouds/clc.py +++ b/salt/cloud/clouds/clc.py @@ -119,7 +119,12 @@ def get_configured_provider(): return config.is_provider_configured( __opts__, _get_active_provider_name() or __virtualname__, - ("token", "token_pass", "user", "password",), + ( + "token", + "token_pass", + "user", + "password", + ), ) @@ -331,32 +336,68 @@ def create(vm_): __opts__, _get_active_provider_name() or __virtualname__, ("token",) ) group = config.get_cloud_config_value( - "group", vm_, __opts__, search_global=False, default=None, + "group", + vm_, + __opts__, + search_global=False, + default=None, ) name = vm_["name"] description = config.get_cloud_config_value( - "description", vm_, __opts__, search_global=False, default=None, + "description", + vm_, + __opts__, + search_global=False, + default=None, ) ram = config.get_cloud_config_value( - "ram", vm_, __opts__, search_global=False, default=None, + "ram", + vm_, + __opts__, + search_global=False, + default=None, ) backup_level = config.get_cloud_config_value( - "backup_level", vm_, __opts__, search_global=False, default=None, + "backup_level", + vm_, + __opts__, + search_global=False, + default=None, ) template = config.get_cloud_config_value( - "template", vm_, __opts__, search_global=False, default=None, + "template", + vm_, + __opts__, + search_global=False, + default=None, ) password = config.get_cloud_config_value( - "password", vm_, __opts__, search_global=False, default=None, + "password", + vm_, + __opts__, + search_global=False, + default=None, ) cpu = config.get_cloud_config_value( - "cpu", vm_, __opts__, search_global=False, default=None, + "cpu", + vm_, + __opts__, + search_global=False, + default=None, ) network = config.get_cloud_config_value( - "network", vm_, __opts__, search_global=False, default=None, + "network", + vm_, + __opts__, + search_global=False, + default=None, ) location = config.get_cloud_config_value( - "location", vm_, __opts__, search_global=False, default=None, + "location", + vm_, + __opts__, + search_global=False, + default=None, ) if len(name) > 6: name = name[0:6] diff --git a/salt/cloud/clouds/cloudstack.py b/salt/cloud/clouds/cloudstack.py index f7afe38f576..628cf077262 100644 --- a/salt/cloud/clouds/cloudstack.py +++ b/salt/cloud/clouds/cloudstack.py @@ -172,7 +172,7 @@ def get_location(conn, vm_): # Default to Dallas if not otherwise set loc = config.get_cloud_config_value("location", vm_, __opts__, default=2) for location in locations: - if str(loc) in (str(location.id), str(location.name),): + if str(loc) in (str(location.id), str(location.name)): return location @@ -270,7 +270,7 @@ def get_project(conn, vm_): return False for project in projects: - if str(projid) in (str(project.id), str(project.name),): + if str(projid) in (str(project.id), str(project.name)): return project log.warning("Couldn't find project %s in projects", projid) diff --git a/salt/cloud/clouds/digitalocean.py b/salt/cloud/clouds/digitalocean.py index 5316dc750af..20e69536174 100644 --- a/salt/cloud/clouds/digitalocean.py +++ b/salt/cloud/clouds/digitalocean.py @@ -197,7 +197,9 @@ def list_nodes_select(call=None): Return a list of the VMs that are on the provider, with select fields """ return salt.utils.cloud.list_nodes_select( - list_nodes_full("function"), __opts__["query.selection"], call, + list_nodes_full("function"), + __opts__["query.selection"], + call, ) @@ -353,7 +355,11 @@ def create(vm_): ) private_networking = config.get_cloud_config_value( - "private_networking", vm_, __opts__, search_global=False, default=None, + "private_networking", + vm_, + __opts__, + search_global=False, + default=None, ) if private_networking is not None: @@ -370,7 +376,11 @@ def create(vm_): ) backups_enabled = config.get_cloud_config_value( - "backups_enabled", vm_, __opts__, search_global=False, default=None, + "backups_enabled", + vm_, + __opts__, + search_global=False, + default=None, ) if backups_enabled is not None: @@ -379,7 +389,11 @@ def create(vm_): kwargs["backups"] = backups_enabled ipv6 = config.get_cloud_config_value( - "ipv6", vm_, __opts__, search_global=False, default=None, + "ipv6", + vm_, + __opts__, + search_global=False, + default=None, ) if ipv6 is not None: @@ -388,7 +402,11 @@ def create(vm_): kwargs["ipv6"] = ipv6 monitoring = config.get_cloud_config_value( - "monitoring", vm_, __opts__, search_global=False, default=None, + "monitoring", + vm_, + __opts__, + search_global=False, + default=None, ) if monitoring is not None: @@ -413,7 +431,11 @@ def create(vm_): log.exception("Failed to read userdata from %s: %s", userdata_file, exc) create_dns_record = config.get_cloud_config_value( - "create_dns_record", vm_, __opts__, search_global=False, default=None, + "create_dns_record", + vm_, + __opts__, + search_global=False, + default=None, ) if create_dns_record: @@ -701,7 +723,8 @@ def list_keypairs(call=None): while fetch: items = query( - method="account/keys", command="?page=" + str(page) + "&per_page=100", + method="account/keys", + command="?page=" + str(page) + "&per_page=100", ) for key_pair in items["ssh_keys"]: @@ -1031,7 +1054,8 @@ def list_floating_ips(call=None): while fetch: items = query( - method="floating_ips", command="?page=" + str(page) + "&per_page=200", + method="floating_ips", + command="?page=" + str(page) + "&per_page=200", ) for floating_ip in items["floating_ips"]: diff --git a/salt/cloud/clouds/ec2.py b/salt/cloud/clouds/ec2.py index 07ef9695e92..cb55d85cbdd 100644 --- a/salt/cloud/clouds/ec2.py +++ b/salt/cloud/clouds/ec2.py @@ -2335,7 +2335,11 @@ def query_instance(vm_=None, call=None): def wait_for_instance( - vm_=None, data=None, ip_address=None, display_ssh_output=True, call=None, + vm_=None, + data=None, + ip_address=None, + display_ssh_output=True, + call=None, ): """ Wait for an instance upon creation from the EC2 API, to become available @@ -3707,7 +3711,9 @@ def list_nodes_select(call=None): Return a list of the VMs that are on the provider, with select fields """ return salt.utils.cloud.list_nodes_select( - list_nodes_full(get_location()), __opts__["query.selection"], call, + list_nodes_full(get_location()), + __opts__["query.selection"], + call, ) @@ -4813,7 +4819,11 @@ def describe_snapshots(kwargs=None, call=None): def get_console_output( - name=None, location=None, instance_id=None, call=None, kwargs=None, + name=None, + location=None, + instance_id=None, + call=None, + kwargs=None, ): """ Show the console output from the instance. @@ -4862,7 +4872,10 @@ def get_console_output( def get_password_data( - name=None, kwargs=None, instance_id=None, call=None, + name=None, + kwargs=None, + instance_id=None, + call=None, ): """ Return password data for a Windows instance. diff --git a/salt/cloud/clouds/gogrid.py b/salt/cloud/clouds/gogrid.py index 71f2f448e41..d73577f225d 100644 --- a/salt/cloud/clouds/gogrid.py +++ b/salt/cloud/clouds/gogrid.py @@ -270,7 +270,9 @@ def list_nodes_select(call=None): salt-cloud -S """ return salt.utils.cloud.list_nodes_select( - list_nodes_full("function"), __opts__["query.selection"], call, + list_nodes_full("function"), + __opts__["query.selection"], + call, ) diff --git a/salt/cloud/clouds/hetzner.py b/salt/cloud/clouds/hetzner.py index 239a3d862eb..a5a9a6d1c55 100644 --- a/salt/cloud/clouds/hetzner.py +++ b/salt/cloud/clouds/hetzner.py @@ -59,7 +59,9 @@ def get_configured_provider(): Return the first configured instance. """ return config.is_provider_configured( - __opts__, __active_provider_name__ or __virtualname__, ("key",), + __opts__, + __active_provider_name__ or __virtualname__, + ("key",), ) @@ -68,7 +70,8 @@ def get_dependencies(): Warn if dependencies aren't met. """ return config.check_driver_dependencies( - __active_provider_name__ or __virtualname__, {"hcloud": HAS_HCLOUD}, + __active_provider_name__ or __virtualname__, + {"hcloud": HAS_HCLOUD}, ) @@ -222,7 +225,9 @@ def show_instance(name, call=None): node = {} __utils__["cloud.cache_node"]( - node, __active_provider_name__ or __virtualname__, __opts__, + node, + __active_provider_name__ or __virtualname__, + __opts__, ) return node @@ -268,7 +273,9 @@ def create(vm_): "starting create", "salt/cloud/{}/creating".format(vm_["name"]), args=__utils__["cloud.filter_event"]( - "creating", vm_, ["name", "profile", "provider", "driver"], + "creating", + vm_, + ["name", "profile", "provider", "driver"], ), sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -348,7 +355,9 @@ def create(vm_): "created instance", "salt/cloud/{}/created".format(vm_["name"]), args=__utils__["cloud.filter_event"]( - "created", vm_, ["name", "profile", "provider", "driver"], + "created", + vm_, + ["name", "profile", "provider", "driver"], ), sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -503,7 +512,9 @@ def destroy(name, call=None): if __opts__.get("update_cachedir", False) is True: __utils__["cloud.delete_minion_cachedir"]( - name, __active_provider_name__.split(":")[0], __opts__, + name, + __active_provider_name__.split(":")[0], + __opts__, ) return {"Destroyed": "{} was destroyed.".format(name)} diff --git a/salt/cloud/clouds/joyent.py b/salt/cloud/clouds/joyent.py index 56872e08643..151c1626d93 100644 --- a/salt/cloud/clouds/joyent.py +++ b/salt/cloud/clouds/joyent.py @@ -864,7 +864,9 @@ def list_nodes_select(call=None): Return a list of the VMs that are on the provider, with select fields """ return salt.utils.cloud.list_nodes_select( - list_nodes_full("function"), __opts__["query.selection"], call, + list_nodes_full("function"), + __opts__["query.selection"], + call, ) @@ -989,7 +991,10 @@ def show_key(kwargs=None, call=None): log.error("A keyname is required.") return False - rcode, data = query(command="my/keys/{}".format(kwargs["keyname"]), method="GET",) + rcode, data = query( + command="my/keys/{}".format(kwargs["keyname"]), + method="GET", + ) return {"keys": {data["name"]: data["key"]}} @@ -1028,7 +1033,11 @@ def import_key(kwargs=None, call=None): send_data = {"name": kwargs["keyname"], "key": kwargs["key"]} kwargs["data"] = salt.utils.json.dumps(send_data) - rcode, data = query(command="my/keys", method="POST", data=kwargs["data"],) + rcode, data = query( + command="my/keys", + method="POST", + data=kwargs["data"], + ) log.debug(pprint.pformat(data)) return {"keys": {data["name"]: data["key"]}} @@ -1055,7 +1064,8 @@ def delete_key(kwargs=None, call=None): return False rcode, data = query( - command="my/keys/{}".format(kwargs["keyname"]), method="DELETE", + command="my/keys/{}".format(kwargs["keyname"]), + method="DELETE", ) return data diff --git a/salt/cloud/clouds/libvirt.py b/salt/cloud/clouds/libvirt.py index 192d726bca1..b14fc64cb55 100644 --- a/salt/cloud/clouds/libvirt.py +++ b/salt/cloud/clouds/libvirt.py @@ -233,7 +233,11 @@ def list_nodes_select(call=None): raise SaltCloudSystemExit("query.selection not found in /etc/salt/cloud") # TODO: somewhat doubt the implementation of cloud.list_nodes_select - return salt.utils.cloud.list_nodes_select(list_nodes_full(), selection, call,) + return salt.utils.cloud.list_nodes_select( + list_nodes_full(), + selection, + call, + ) def to_ip_addr_type(addr_type): diff --git a/salt/cloud/clouds/linode.py b/salt/cloud/clouds/linode.py index 7ff88486d49..636daed3abb 100644 --- a/salt/cloud/clouds/linode.py +++ b/salt/cloud/clouds/linode.py @@ -179,7 +179,7 @@ def get_configured_provider(): return config.is_provider_configured( __opts__, _get_active_provider_name() or __virtualname__, - ("apikey", "password",), + ("apikey", "password"), ) @@ -400,82 +400,82 @@ def _warn_for_api_v3(): class LinodeAPI: @abc.abstractmethod def avail_images(self): - """ avail_images implementation """ + """avail_images implementation""" @abc.abstractmethod def avail_locations(self): - """ avail_locations implementation """ + """avail_locations implementation""" @abc.abstractmethod def avail_sizes(self): - """ avail_sizes implementation """ + """avail_sizes implementation""" @abc.abstractmethod def boot(self, name=None, kwargs=None): - """ boot implementation """ + """boot implementation""" @abc.abstractmethod def clone(self, kwargs=None): - """ clone implementation """ + """clone implementation""" @abc.abstractmethod def create_config(self, kwargs=None): - """ create_config implementation """ + """create_config implementation""" @abc.abstractmethod def create(self, vm_): - """ create implementation """ + """create implementation""" @abc.abstractmethod def destroy(self, name): - """ destroy implementation """ + """destroy implementation""" @abc.abstractmethod def get_config_id(self, kwargs=None): - """ get_config_id implementation """ + """get_config_id implementation""" @abc.abstractmethod def list_nodes(self): - """ list_nodes implementation """ + """list_nodes implementation""" @abc.abstractmethod def list_nodes_full(self): - """ list_nodes_full implementation """ + """list_nodes_full implementation""" @abc.abstractmethod def list_nodes_min(self): - """ list_nodes_min implementation """ + """list_nodes_min implementation""" @abc.abstractmethod def reboot(self, name): - """ reboot implementation """ + """reboot implementation""" @abc.abstractmethod def show_instance(self, name): - """ show_instance implementation """ + """show_instance implementation""" @abc.abstractmethod def show_pricing(self, kwargs=None): - """ show_pricing implementation """ + """show_pricing implementation""" @abc.abstractmethod def start(self, name): - """ start implementation """ + """start implementation""" @abc.abstractmethod def stop(self, name): - """ stop implementation """ + """stop implementation""" @abc.abstractmethod def _get_linode_by_name(self, name): - """ _get_linode_by_name implementation """ + """_get_linode_by_name implementation""" @abc.abstractmethod def _get_linode_by_id(self, linode_id): - """ _get_linode_by_id implementation """ + """_get_linode_by_id implementation""" def get_plan_id(self, kwargs=None): - """ get_plan_id implementation """ + """get_plan_id implementation""" raise SaltCloudSystemExit( "The get_plan_id is not supported by this api_version." ) @@ -495,7 +495,9 @@ class LinodeAPI: def list_nodes_select(self, call): return __utils__["cloud.list_nodes_select"]( - self.list_nodes_full(), __opts__["query.selection"], call, + self.list_nodes_full(), + __opts__["query.selection"], + call, ) @@ -1016,7 +1018,12 @@ class LinodeAPIv4(LinodeAPI): return (public, private) def _poll( - self, description, getter, condition, timeout=None, poll_interval=None, + self, + description, + getter, + condition, + timeout=None, + poll_interval=None, ): """ Return true in handler to signal complete. diff --git a/salt/cloud/clouds/msazure.py b/salt/cloud/clouds/msazure.py index 7dc445f1510..8a063101ea9 100644 --- a/salt/cloud/clouds/msazure.py +++ b/salt/cloud/clouds/msazure.py @@ -394,7 +394,9 @@ def list_nodes_select(conn=None, call=None): conn = get_conn() return salt.utils.cloud.list_nodes_select( - list_nodes_full(conn, "function"), __opts__["query.selection"], call, + list_nodes_full(conn, "function"), + __opts__["query.selection"], + call, ) @@ -487,7 +489,10 @@ def create(vm_): ) ssh_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint( - name="SSH", protocol="TCP", port=ssh_port, local_port=22, + name="SSH", + protocol="TCP", + port=ssh_port, + local_port=22, ) network_config = azure.servicemanagement.ConfigurationSet() @@ -506,7 +511,10 @@ def create(vm_): smb_port = vm_["smb_port"] smb_endpoint = azure.servicemanagement.ConfigurationSetInputEndpoint( - name="SMB", protocol="TCP", port=smb_port, local_port=smb_port, + name="SMB", + protocol="TCP", + port=smb_port, + local_port=smb_port, ) network_config.input_endpoints.input_endpoints.append(smb_endpoint) @@ -805,7 +813,9 @@ def create_attach_volumes(name, kwargs, call=None, wait_to_finish=True): # If attach is None then everything is fine if attach: msg = "{} attached to {} (aka {})".format( - volume_dict["volume_name"], kwargs["role_name"], name, + volume_dict["volume_name"], + kwargs["role_name"], + name, ) log.info(msg) ret.append(msg) @@ -1190,7 +1200,9 @@ def show_storage(kwargs=None, conn=None, call=None): if "name" not in kwargs: raise SaltCloudSystemExit('A name must be specified as "name"') - data = conn.get_storage_account_properties(kwargs["name"],) + data = conn.get_storage_account_properties( + kwargs["name"], + ) return object_to_dict(data) @@ -1225,7 +1237,9 @@ def show_storage_keys(kwargs=None, conn=None, call=None): raise SaltCloudSystemExit('A name must be specified as "name"') try: - data = conn.get_storage_account_keys(kwargs["name"],) + data = conn.get_storage_account_keys( + kwargs["name"], + ) except AzureMissingResourceHttpError as exc: storage_data = show_storage(kwargs={"name": kwargs["name"]}, call="function") if storage_data["storage_service_properties"]["status"] == "Creating": @@ -1367,7 +1381,8 @@ def regenerate_storage_keys(kwargs=None, conn=None, call=None): try: data = conn.regenerate_storage_account_keys( - service_name=kwargs["name"], key_type=kwargs["key_type"], + service_name=kwargs["name"], + key_type=kwargs["key_type"], ) return show_storage_keys(kwargs={"name": kwargs["name"]}, call="function") except AzureConflictHttpError: @@ -1797,7 +1812,9 @@ def show_service_certificate(kwargs=None, conn=None, call=None): raise SaltCloudSystemExit('A thumbprint must be specified as "thumbprint"') data = conn.get_service_certificate( - kwargs["name"], kwargs["thumbalgorithm"], kwargs["thumbprint"], + kwargs["name"], + kwargs["thumbalgorithm"], + kwargs["thumbprint"], ) return object_to_dict(data) @@ -1896,7 +1913,9 @@ def delete_service_certificate(kwargs=None, conn=None, call=None): try: data = conn.delete_service_certificate( - kwargs["name"], kwargs["thumbalgorithm"], kwargs["thumbprint"], + kwargs["name"], + kwargs["thumbalgorithm"], + kwargs["thumbprint"], ) return {"Success": "The service certificate was successfully deleted"} except AzureMissingResourceHttpError as exc: @@ -2000,7 +2019,9 @@ def add_management_certificate(kwargs=None, conn=None, call=None): try: conn.add_management_certificate( - kwargs["name"], kwargs["thumbprint"], kwargs["data"], + kwargs["name"], + kwargs["thumbprint"], + kwargs["data"], ) return {"Success": "The management certificate was successfully added"} except AzureConflictHttpError: @@ -2093,7 +2114,8 @@ def list_input_endpoints(kwargs=None, conn=None, call=None): raise SaltCloudSystemExit('A deployment name must be specified as "deployment"') path = "services/hostedservices/{}/deployments/{}".format( - kwargs["service"], kwargs["deployment"], + kwargs["service"], + kwargs["deployment"], ) data = query(path) @@ -2267,7 +2289,9 @@ xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> ) path = "services/hostedservices/{}/deployments/{}/roles/{}".format( - kwargs["service"], kwargs["deployment"], kwargs["role"], + kwargs["service"], + kwargs["deployment"], + kwargs["role"], ) query( path=path, @@ -2296,7 +2320,10 @@ def add_input_endpoint(kwargs=None, conn=None, call=None): timeout_for_tcp_idle_connection=4 """ return update_input_endpoint( - kwargs=kwargs, conn=conn, call="function", activity="add", + kwargs=kwargs, + conn=conn, + call="function", + activity="add", ) @@ -2315,7 +2342,10 @@ def delete_input_endpoint(kwargs=None, conn=None, call=None): deployment=mydeployment role=myrole name=HTTP """ return update_input_endpoint( - kwargs=kwargs, conn=conn, call="function", activity="delete", + kwargs=kwargs, + conn=conn, + call="function", + activity="delete", ) @@ -2351,7 +2381,8 @@ def show_deployment(kwargs=None, conn=None, call=None): ) data = conn.get_deployment_by_name( - service_name=kwargs["service_name"], deployment_name=kwargs["deployment_name"], + service_name=kwargs["service_name"], + deployment_name=kwargs["deployment_name"], ) return object_to_dict(data) @@ -2725,7 +2756,8 @@ def show_storage_container(kwargs=None, storage_conn=None, call=None): storage_conn = get_storage_conn(conn_kwargs=kwargs) data = storage_conn.get_container_properties( - container_name=kwargs["name"], x_ms_lease_id=kwargs.get("lease_id", None), + container_name=kwargs["name"], + x_ms_lease_id=kwargs.get("lease_id", None), ) return data @@ -2769,7 +2801,8 @@ def show_storage_container_metadata(kwargs=None, storage_conn=None, call=None): storage_conn = get_storage_conn(conn_kwargs=kwargs) data = storage_conn.get_container_metadata( - container_name=kwargs["name"], x_ms_lease_id=kwargs.get("lease_id", None), + container_name=kwargs["name"], + x_ms_lease_id=kwargs.get("lease_id", None), ) return data @@ -2866,7 +2899,8 @@ def show_storage_container_acl(kwargs=None, storage_conn=None, call=None): storage_conn = get_storage_conn(conn_kwargs=kwargs) data = storage_conn.get_container_acl( - container_name=kwargs["name"], x_ms_lease_id=kwargs.get("lease_id", None), + container_name=kwargs["name"], + x_ms_lease_id=kwargs.get("lease_id", None), ) return data @@ -3484,7 +3518,9 @@ def query(path, method="GET", data=None, params=None, header_dict=None, decode=T "backend", get_configured_provider(), __opts__, search_global=False ) url = "https://{management_host}/{subscription_id}/{path}".format( - management_host=management_host, subscription_id=subscription_id, path=path, + management_host=management_host, + subscription_id=subscription_id, + path=path, ) if header_dict is None: diff --git a/salt/cloud/clouds/oneandone.py b/salt/cloud/clouds/oneandone.py index f3a726077f8..bf73175f684 100644 --- a/salt/cloud/clouds/oneandone.py +++ b/salt/cloud/clouds/oneandone.py @@ -448,7 +448,9 @@ def list_nodes_select(conn=None, call=None): conn = get_conn() return salt.utils.cloud.list_nodes_select( - list_nodes_full(conn, "function"), __opts__["query.selection"], call, + list_nodes_full(conn, "function"), + __opts__["query.selection"], + call, ) diff --git a/salt/cloud/clouds/opennebula.py b/salt/cloud/clouds/opennebula.py index 128fe82bc50..9fe572f4ea2 100644 --- a/salt/cloud/clouds/opennebula.py +++ b/salt/cloud/clouds/opennebula.py @@ -338,7 +338,9 @@ def list_nodes_select(call=None): ) return __utils__["cloud.list_nodes_select"]( - list_nodes_full("function"), __opts__["query.selection"], call, + list_nodes_full("function"), + __opts__["query.selection"], + call, ) diff --git a/salt/cloud/clouds/packet.py b/salt/cloud/clouds/packet.py index 829d270622f..a0a2e08d2a3 100644 --- a/salt/cloud/clouds/packet.py +++ b/salt/cloud/clouds/packet.py @@ -513,7 +513,9 @@ def list_nodes_select(call=None): Return a list of the VMs that are on the provider, with select fields. """ return salt.utils.cloud.list_nodes_select( - list_nodes_full(), __opts__["query.selection"], call, + list_nodes_full(), + __opts__["query.selection"], + call, ) diff --git a/salt/cloud/clouds/parallels.py b/salt/cloud/clouds/parallels.py index b6f32c166d1..1d56e86e108 100644 --- a/salt/cloud/clouds/parallels.py +++ b/salt/cloud/clouds/parallels.py @@ -66,7 +66,11 @@ def get_configured_provider(): return config.is_provider_configured( __opts__, _get_active_provider_name() or __virtualname__, - ("user", "password", "url",), + ( + "user", + "password", + "url", + ), ) @@ -148,7 +152,9 @@ def list_nodes_select(call=None): Return a list of the VMs that are on the provider, with select fields """ return salt.utils.cloud.list_nodes_select( - list_nodes_full(), __opts__["query.selection"], call, + list_nodes_full(), + __opts__["query.selection"], + call, ) diff --git a/salt/cloud/clouds/proxmox.py b/salt/cloud/clouds/proxmox.py index b378d49e5d8..4afad4f8d2f 100644 --- a/salt/cloud/clouds/proxmox.py +++ b/salt/cloud/clouds/proxmox.py @@ -520,7 +520,9 @@ def list_nodes_select(call=None): salt-cloud -S my-proxmox-config """ return salt.utils.cloud.list_nodes_select( - list_nodes_full(), __opts__["query.selection"], call, + list_nodes_full(), + __opts__["query.selection"], + call, ) @@ -566,7 +568,9 @@ def _reconfigure_clone(vm_, vmid): if re.match(r"^(ide|sata|scsi)(\d+)$", setting): postParams = {setting: vm_[setting]} query( - "post", "nodes/{}/qemu/{}/config".format(vm_["host"], vmid), postParams, + "post", + "nodes/{}/qemu/{}/config".format(vm_["host"], vmid), + postParams, ) elif re.match(r"^net(\d+)$", setting): @@ -589,7 +593,9 @@ def _reconfigure_clone(vm_, vmid): # Convert the dictionary back into a string list postParams = {setting: _dictionary_to_stringlist(new_setting)} query( - "post", "nodes/{}/qemu/{}/config".format(vm_["host"], vmid), postParams, + "post", + "nodes/{}/qemu/{}/config".format(vm_["host"], vmid), + postParams, ) @@ -702,7 +708,11 @@ def create(vm_): ssh_username = config.get_cloud_config_value( "ssh_username", vm_, __opts__, default="root" ) - ssh_password = config.get_cloud_config_value("password", vm_, __opts__,) + ssh_password = config.get_cloud_config_value( + "password", + vm_, + __opts__, + ) ret["ip_address"] = ip_address ret["username"] = ssh_username diff --git a/salt/cloud/clouds/pyrax.py b/salt/cloud/clouds/pyrax.py index 212ca3ebe80..02dcec63540 100644 --- a/salt/cloud/clouds/pyrax.py +++ b/salt/cloud/clouds/pyrax.py @@ -48,7 +48,11 @@ def get_configured_provider(): return config.is_provider_configured( __opts__, _get_active_provider_name() or __virtualname__, - ("username", "identity_url", "compute_region",), + ( + "username", + "identity_url", + "compute_region", + ), ) diff --git a/salt/cloud/clouds/qingcloud.py b/salt/cloud/clouds/qingcloud.py index 5274a3005c5..718b9fb9dc8 100644 --- a/salt/cloud/clouds/qingcloud.py +++ b/salt/cloud/clouds/qingcloud.py @@ -596,7 +596,9 @@ def list_nodes_select(call=None): salt-cloud -S my-qingcloud """ return salt.utils.cloud.list_nodes_select( - list_nodes_full("function"), __opts__["query.selection"], call, + list_nodes_full("function"), + __opts__["query.selection"], + call, ) diff --git a/salt/cloud/clouds/saltify.py b/salt/cloud/clouds/saltify.py index 806a9cd2214..d2445caaf9c 100644 --- a/salt/cloud/clouds/saltify.py +++ b/salt/cloud/clouds/saltify.py @@ -216,7 +216,9 @@ def list_nodes_select(call=None): select fields. """ return salt.utils.cloud.list_nodes_select( - list_nodes_full("function"), __opts__["query.selection"], call, + list_nodes_full("function"), + __opts__["query.selection"], + call, ) @@ -434,7 +436,7 @@ def _verify(vm_): def destroy(name, call=None): - """ Destroy a node. + """Destroy a node. .. versionadded:: 2018.3.0 diff --git a/salt/cloud/clouds/scaleway.py b/salt/cloud/clouds/scaleway.py index 4e71d0bd559..108ad6c2ed8 100644 --- a/salt/cloud/clouds/scaleway.py +++ b/salt/cloud/clouds/scaleway.py @@ -61,16 +61,14 @@ def _get_active_provider_name(): def get_configured_provider(): - """ Return the first configured instance. - """ + """Return the first configured instance.""" return config.is_provider_configured( __opts__, _get_active_provider_name() or __virtualname__, ("token",) ) def avail_images(call=None): - """ Return a list of the images that are on the provider. - """ + """Return a list of the images that are on the provider.""" if call == "action": raise SaltCloudSystemExit( "The avail_images function must be called with " @@ -88,8 +86,7 @@ def avail_images(call=None): def list_nodes(call=None): - """ Return a list of the BareMetal servers that are on the provider. - """ + """Return a list of the BareMetal servers that are on the provider.""" if call == "action": raise SaltCloudSystemExit( "The list_nodes function must be called with -f or --function." @@ -124,8 +121,7 @@ def list_nodes(call=None): def list_nodes_full(call=None): - """ Return a list of the BareMetal servers that are on the provider. - """ + """Return a list of the BareMetal servers that are on the provider.""" if call == "action": raise SaltCloudSystemExit( "list_nodes_full must be called with -f or --function" @@ -144,17 +140,18 @@ def list_nodes_full(call=None): def list_nodes_select(call=None): - """ Return a list of the BareMetal servers that are on the provider, with + """Return a list of the BareMetal servers that are on the provider, with select fields. """ return salt.utils.cloud.list_nodes_select( - list_nodes_full("function"), __opts__["query.selection"], call, + list_nodes_full("function"), + __opts__["query.selection"], + call, ) def get_image(server_): - """ Return the image object to use. - """ + """Return the image object to use.""" images = avail_images() server_image = str( config.get_cloud_config_value("image", server_, __opts__, search_global=False) @@ -168,8 +165,7 @@ def get_image(server_): def create_node(args): - """ Create a node. - """ + """Create a node.""" node = query(method="servers", args=args, http_method="POST") action = query( @@ -269,8 +265,7 @@ def create(server_): return False def __query_node_data(server_name): - """ Called to check if the server has a public IP address. - """ + """Called to check if the server has a public IP address.""" data = show_instance(server_name, "action") if data and data.get("public_ip"): return data @@ -332,8 +327,7 @@ def query( http_method="GET", root="api_root", ): - """ Make a call to the Scaleway API. - """ + """Make a call to the Scaleway API.""" if root == "api_root": default_url = "https://cp-par1.scaleway.com" @@ -344,7 +338,11 @@ def query( base_path = str( config.get_cloud_config_value( - root, vm_, __opts__, search_global=False, default=default_url, + root, + vm_, + __opts__, + search_global=False, + default=default_url, ) ) @@ -387,8 +385,7 @@ def query( def script(server_): - """ Return the script deployment object. - """ + """Return the script deployment object.""" return salt.utils.cloud.os_script( config.get_cloud_config_value("script", server_, __opts__), server_, @@ -400,8 +397,7 @@ def script(server_): def show_instance(name, call=None): - """ Show the details from a Scaleway BareMetal server. - """ + """Show the details from a Scaleway BareMetal server.""" if call != "action": raise SaltCloudSystemExit( "The show_instance action must be called with -a or --action." @@ -427,7 +423,7 @@ def _get_node(name): def destroy(name, call=None): - """ Destroy a node. Will check termination protection and warn if enabled. + """Destroy a node. Will check termination protection and warn if enabled. CLI Example: diff --git a/salt/cloud/clouds/softlayer.py b/salt/cloud/clouds/softlayer.py index 62eefa60dfd..58e44e7f341 100644 --- a/salt/cloud/clouds/softlayer.py +++ b/salt/cloud/clouds/softlayer.py @@ -582,7 +582,9 @@ def list_nodes_select(call=None): Return a list of the VMs that are on the provider, with select fields """ return salt.utils.cloud.list_nodes_select( - list_nodes_full(), __opts__["query.selection"], call, + list_nodes_full(), + __opts__["query.selection"], + call, ) diff --git a/salt/cloud/clouds/softlayer_hw.py b/salt/cloud/clouds/softlayer_hw.py index be30bffff73..9a35258eb92 100644 --- a/salt/cloud/clouds/softlayer_hw.py +++ b/salt/cloud/clouds/softlayer_hw.py @@ -477,7 +477,9 @@ def list_nodes_select(call=None): Return a list of the VMs that are on the provider, with select fields """ return salt.utils.cloud.list_nodes_select( - list_nodes_full(), __opts__["query.selection"], call, + list_nodes_full(), + __opts__["query.selection"], + call, ) diff --git a/salt/cloud/clouds/tencentcloud.py b/salt/cloud/clouds/tencentcloud.py index 725a6444953..5611b0524ab 100644 --- a/salt/cloud/clouds/tencentcloud.py +++ b/salt/cloud/clouds/tencentcloud.py @@ -379,7 +379,9 @@ def list_nodes_select(call=None): salt-cloud -S """ return salt.utils.cloud.list_nodes_select( - list_nodes_full("function"), __opts__["query.selection"], call, + list_nodes_full("function"), + __opts__["query.selection"], + call, ) diff --git a/salt/cloud/clouds/vagrant.py b/salt/cloud/clouds/vagrant.py index fd143842bb2..4a4bdbdeaf4 100644 --- a/salt/cloud/clouds/vagrant.py +++ b/salt/cloud/clouds/vagrant.py @@ -60,8 +60,8 @@ def avail_locations(call=None): def avail_images(call=None): """This function returns a list of images available for this cloud provider. - vagrant will return a list of profiles. - salt-cloud --list-images my-cloud-provider + vagrant will return a list of profiles. + salt-cloud --list-images my-cloud-provider """ vm_ = get_configured_provider() return {"Profiles": [profile for profile in vm_["profiles"]]} @@ -175,7 +175,9 @@ def list_nodes_select(call=None): select fields. """ return salt.utils.cloud.list_nodes_select( - list_nodes_full("function"), __opts__["query.selection"], call, + list_nodes_full("function"), + __opts__["query.selection"], + call, ) diff --git a/salt/cloud/clouds/virtualbox.py b/salt/cloud/clouds/virtualbox.py index 51a79d1ddd9..c1c5da181ec 100644 --- a/salt/cloud/clouds/virtualbox.py +++ b/salt/cloud/clouds/virtualbox.py @@ -328,7 +328,9 @@ def list_nodes(kwargs=None, call=None): "public_ips", ] return __utils__["cloud.list_nodes_select"]( - list_nodes_full("function"), attributes, call, + list_nodes_full("function"), + attributes, + call, ) @@ -337,7 +339,9 @@ def list_nodes_select(call=None): Return a list of the VMs that are on the provider, with select fields """ return __utils__["cloud.list_nodes_select"]( - list_nodes_full("function"), __opts__["query.selection"], call, + list_nodes_full("function"), + __opts__["query.selection"], + call, ) diff --git a/salt/cloud/clouds/vmware.py b/salt/cloud/clouds/vmware.py index 1e9943ad78f..3fa5bad3e05 100644 --- a/salt/cloud/clouds/vmware.py +++ b/salt/cloud/clouds/vmware.py @@ -191,7 +191,11 @@ def get_configured_provider(): return config.is_provider_configured( __opts__, _get_active_provider_name() or __virtualname__, - ("url", "user", "password",), + ( + "url", + "user", + "password", + ), ) @@ -432,8 +436,10 @@ def _edit_existing_network_adapter( else: # If switch type not specified or does not match, show error and return if not switch_type: - err_msg = "The switch type to be used by '{}' has not been specified".format( - network_adapter.deviceInfo.label + err_msg = ( + "The switch type to be used by '{}' has not been specified".format( + network_adapter.deviceInfo.label + ) ) else: err_msg = "Cannot create '{}'. Invalid/unsupported switch type '{}'".format( @@ -519,8 +525,10 @@ def _add_new_network_adapter_helper( else: # If switch type not specified or does not match, show error and return if not switch_type: - err_msg = "The switch type to be used by '{}' has not been specified".format( - network_adapter_label + err_msg = ( + "The switch type to be used by '{}' has not been specified".format( + network_adapter_label + ) ) else: err_msg = "Cannot create '{}'. Invalid/unsupported switch type '{}'".format( @@ -3151,8 +3159,10 @@ def create(vm_): ) # get recommended datastores - recommended_datastores = si.content.storageResourceManager.RecommendDatastores( - storageSpec=storage_spec + recommended_datastores = ( + si.content.storageResourceManager.RecommendDatastores( + storageSpec=storage_spec + ) ) # apply storage DRS recommendations @@ -4369,7 +4379,9 @@ def add_host(kwargs=None, call=None): raise SaltCloudSystemExit("Specified datacenter does not exist.") spec = vim.host.ConnectSpec( - hostName=host_name, userName=host_user, password=host_password, + hostName=host_name, + userName=host_user, + password=host_password, ) if host_ssl_thumbprint: diff --git a/salt/cloud/clouds/vultrpy.py b/salt/cloud/clouds/vultrpy.py index fa7535d15f2..2171ffca94f 100644 --- a/salt/cloud/clouds/vultrpy.py +++ b/salt/cloud/clouds/vultrpy.py @@ -264,7 +264,9 @@ def list_nodes_select(conn=None, call=None): Return a list of the VMs that are on the provider, with select fields """ return __utils__["cloud.list_nodes_select"]( - list_nodes_full(), __opts__["query.selection"], call, + list_nodes_full(), + __opts__["query.selection"], + call, ) @@ -342,7 +344,11 @@ def create(vm_): vm_["driver"] = vm_["provider"] private_networking = config.get_cloud_config_value( - "enable_private_network", vm_, __opts__, search_global=False, default=False, + "enable_private_network", + vm_, + __opts__, + search_global=False, + default=False, ) ssh_key_ids = config.get_cloud_config_value( @@ -350,7 +356,11 @@ def create(vm_): ) startup_script = config.get_cloud_config_value( - "startup_script_id", vm_, __opts__, search_global=False, default=None, + "startup_script_id", + vm_, + __opts__, + search_global=False, + default=None, ) if startup_script and str(startup_script) not in avail_scripts(): @@ -361,7 +371,11 @@ def create(vm_): return False firewall_group_id = config.get_cloud_config_value( - "firewall_group_id", vm_, __opts__, search_global=False, default=None, + "firewall_group_id", + vm_, + __opts__, + search_global=False, + default=None, ) if firewall_group_id and str(firewall_group_id) not in avail_firewall_groups(): @@ -598,7 +612,10 @@ def _query(path, method="GET", data=None, params=None, header_dict=None, decode= Perform a query directly against the Vultr REST API """ api_key = config.get_cloud_config_value( - "api_key", get_configured_provider(), __opts__, search_global=False, + "api_key", + get_configured_provider(), + __opts__, + search_global=False, ) management_host = config.get_cloud_config_value( "management_host", @@ -608,7 +625,9 @@ def _query(path, method="GET", data=None, params=None, header_dict=None, decode= default="api.vultr.com", ) url = "https://{management_host}/v1/{path}?api_key={api_key}".format( - management_host=management_host, path=path, api_key=api_key, + management_host=management_host, + path=path, + api_key=api_key, ) if header_dict is None: diff --git a/salt/cloud/clouds/xen.py b/salt/cloud/clouds/xen.py index acf7f9667a6..69c11712e7c 100644 --- a/salt/cloud/clouds/xen.py +++ b/salt/cloud/clouds/xen.py @@ -342,7 +342,9 @@ def list_nodes_select(call=None): """ return salt.utils.cloud.list_nodes_select( - list_nodes_full(), __opts__["query.selection"], call, + list_nodes_full(), + __opts__["query.selection"], + call, ) diff --git a/salt/cloud/libcloudfuncs.py b/salt/cloud/libcloudfuncs.py index a7727668438..714dd4b0f00 100644 --- a/salt/cloud/libcloudfuncs.py +++ b/salt/cloud/libcloudfuncs.py @@ -57,8 +57,10 @@ def check_libcloud_version(reqver=LIBCLOUD_MINIMAL_VERSION, why=None): if LIBCLOUD_VERSION_INFO >= reqver: return libcloud.__version__ - errormsg = "Your version of libcloud is {}. salt-cloud requires >= libcloud {}".format( - libcloud.__version__, ".".join([str(num) for num in reqver]) + errormsg = ( + "Your version of libcloud is {}. salt-cloud requires >= libcloud {}".format( + libcloud.__version__, ".".join([str(num) for num in reqver]) + ) ) if why: errormsg += " for {}".format(why) @@ -219,7 +221,10 @@ def get_size(conn, vm_): return sizes[0] for size in sizes: - if vm_size and str(vm_size) in (str(size.id), str(size.name),): + if vm_size and str(vm_size) in ( + str(size.id), + str(size.name), + ): return size raise SaltCloudNotFound( "The specified size, '{}', could not be found.".format(vm_size) @@ -409,7 +414,9 @@ def list_nodes_select(conn=None, call=None): conn = get_conn() # pylint: disable=E0602 return salt.utils.cloud.list_nodes_select( - list_nodes_full(conn, "function"), __opts__["query.selection"], call, + list_nodes_full(conn, "function"), + __opts__["query.selection"], + call, ) diff --git a/salt/daemons/masterapi.py b/salt/daemons/masterapi.py index 07cf416115b..a50b011841a 100644 --- a/salt/daemons/masterapi.py +++ b/salt/daemons/masterapi.py @@ -149,7 +149,11 @@ def clean_old_jobs(opts): Clean out the old jobs from the job cache """ # TODO: better way to not require creating the masterminion every time? - mminion = salt.minion.MasterMinion(opts, states=False, rend=False,) + mminion = salt.minion.MasterMinion( + opts, + states=False, + rend=False, + ) # If the master job cache has a clean_old_jobs, call it fstr = "{}.clean_old_jobs".format(opts["master_job_cache"]) if fstr in mminion.returners: @@ -1186,7 +1190,9 @@ class LocalFuncs: except Exception as exc: # pylint: disable=broad-except log.exception("Exception occurred while introspecting %s", fun) data["return"] = "Exception occurred in wheel {}: {}: {}".format( - fun, exc.__class__.__name__, exc, + fun, + exc.__class__.__name__, + exc, ) data["success"] = False self.event.fire_event(data, salt.utils.event.tagify([jid, "ret"], "wheel")) diff --git a/salt/engines/slack.py b/salt/engines/slack.py index 24ab7f4d937..292c1926ca5 100644 --- a/salt/engines/slack.py +++ b/salt/engines/slack.py @@ -696,7 +696,9 @@ class SlackClient: except (StopIteration, AttributeError): outputter = None return salt.output.string_format( - {x: y["return"] for x, y in data.items()}, out=outputter, opts=__opts__, + {x: y["return"] for x, y in data.items()}, + out=outputter, + opts=__opts__, ) except Exception as exc: # pylint: disable=broad-except import pprint @@ -826,11 +828,13 @@ class SlackClient: this_job = outstanding[jid] channel = self.sc.server.channels.find(this_job["channel"]) return_text = self.format_return_text(result, function) - return_prefix = "@{}'s job `{}` (id: {}) (target: {}) returned".format( - this_job["user_name"], - this_job["cmdline"], - jid, - this_job["target"], + return_prefix = ( + "@{}'s job `{}` (id: {}) (target: {}) returned".format( + this_job["user_name"], + this_job["cmdline"], + jid, + this_job["target"], + ) ) channel.send_message(return_prefix) ts = time.time() @@ -901,7 +905,11 @@ class SlackClient: # according to https://github.com/saltstack/salt-api/issues/164, tgt_type has changed to expr_form with salt.client.LocalClient() as local: job_id = local.cmd_async( - str(target), cmd, arg=args, kwarg=kwargs, tgt_type=str(tgt_type), + str(target), + cmd, + arg=args, + kwarg=kwargs, + tgt_type=str(tgt_type), ) log.info("ret from local.cmd_async is %s", job_id) return job_id diff --git a/salt/exceptions.py b/salt/exceptions.py index 5ad50181fef..cf37dca743a 100644 --- a/salt/exceptions.py +++ b/salt/exceptions.py @@ -287,7 +287,8 @@ class SaltRenderError(SaltException): self.buffer, self.line_num, marker=marker ) exc_str += "; line {}\n\n{}".format( - self.line_num, salt.utils.stringutils.to_unicode(self.context), + self.line_num, + salt.utils.stringutils.to_unicode(self.context), ) super().__init__(exc_str) diff --git a/salt/grains/zfs.py b/salt/grains/zfs.py index b729ec96b4c..e903d010832 100644 --- a/salt/grains/zfs.py +++ b/salt/grains/zfs.py @@ -54,7 +54,9 @@ def _zfs_pool_data(): # collect zpool data zpool_list_cmd = __utils__["zfs.zpool_command"]( - "list", flags=["-H"], opts={"-o": "name,size"}, + "list", + flags=["-H"], + opts={"-o": "name,size"}, ) for zpool in __salt__["cmd.run"](zpool_list_cmd, ignore_retcode=True).splitlines(): if "zpool" not in grains: diff --git a/salt/loader/__init__.py b/salt/loader/__init__.py index f6f57915d5f..a44ba9fa4ac 100644 --- a/salt/loader/__init__.py +++ b/salt/loader/__init__.py @@ -78,7 +78,13 @@ def static_loader( ): funcs = LazyLoader( _module_dirs( - opts, ext_type, tag, int_type, ext_dirs, ext_type_dirs, base_path, + opts, + ext_type, + tag, + int_type, + ext_dirs, + ext_type_dirs, + base_path, ), opts, tag=tag, @@ -448,7 +454,10 @@ def tops(opts): return {} whitelist = list(opts["master_tops"].keys()) ret = LazyLoader( - _module_dirs(opts, "tops", "top"), opts, tag="top", whitelist=whitelist, + _module_dirs(opts, "tops", "top"), + opts, + tag="top", + whitelist=whitelist, ) return FilterDictWrapper(ret, ".top") @@ -492,7 +501,11 @@ def serializers(opts): :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only serializers present in the keyspace """ - return LazyLoader(_module_dirs(opts, "serializers"), opts, tag="serializers",) + return LazyLoader( + _module_dirs(opts, "serializers"), + opts, + tag="serializers", + ) def eauth_tokens(opts): @@ -501,7 +514,11 @@ def eauth_tokens(opts): :param dict opts: The Salt options dictionary :returns: LazyLoader instance, with only token backends present in the keyspace """ - return LazyLoader(_module_dirs(opts, "tokens"), opts, tag="tokens",) + return LazyLoader( + _module_dirs(opts, "tokens"), + opts, + tag="tokens", + ) def auth(opts, whitelist=None): @@ -688,7 +705,12 @@ def render(opts, functions, states=None, proxy=None, context=None): pack["__proxy__"] = proxy ret = LazyLoader( - _module_dirs(opts, "renderers", "render", ext_type_dirs="render_dirs",), + _module_dirs( + opts, + "renderers", + "render", + ext_type_dirs="render_dirs", + ), opts, tag="render", pack=pack, @@ -722,7 +744,12 @@ def grain_funcs(opts, proxy=None, context=None): _utils = utils(opts, proxy=proxy) pack = {"__utils__": utils(opts, proxy=proxy), "__context__": context} ret = LazyLoader( - _module_dirs(opts, "grains", "grain", ext_type_dirs="grains_dirs",), + _module_dirs( + opts, + "grains", + "grain", + ext_type_dirs="grains_dirs", + ), opts, tag="grains", extra_module_dirs=_utils.module_dirs, @@ -1102,7 +1129,11 @@ def netapi(opts): """ Return the network api functions """ - return LazyLoader(_module_dirs(opts, "netapi"), opts, tag="netapi",) + return LazyLoader( + _module_dirs(opts, "netapi"), + opts, + tag="netapi", + ) def executors(opts, functions=None, context=None, proxy=None): diff --git a/salt/loader/lazy.py b/salt/loader/lazy.py index 472a4488cf6..06ca48d1587 100644 --- a/salt/loader/lazy.py +++ b/salt/loader/lazy.py @@ -266,7 +266,8 @@ class LazyLoader(salt.utils.lazy.LazyDict): self.disabled = set( self.opts.get( - "disable_{}{}".format(self.tag, "" if self.tag[-1] == "s" else "s"), [], + "disable_{}{}".format(self.tag, "" if self.tag[-1] == "s" else "s"), + [], ) ) diff --git a/salt/log/setup.py b/salt/log/setup.py index 97982623b3f..78e0c592bb2 100644 --- a/salt/log/setup.py +++ b/salt/log/setup.py @@ -551,7 +551,10 @@ def setup_multiprocessing_logging_listener(opts, queue=None): __MP_MAINPROCESS_ID = os.getpid() __MP_LOGGING_QUEUE_PROCESS = multiprocessing.Process( target=__process_multiprocessing_logging_queue, - args=(opts, queue or get_multiprocessing_logging_queue(),), + args=( + opts, + queue or get_multiprocessing_logging_queue(), + ), ) __MP_LOGGING_QUEUE_PROCESS.daemon = True __MP_LOGGING_QUEUE_PROCESS.start() @@ -901,7 +904,9 @@ def __global_logging_exception_handler( ) except Exception: # pylint: disable=broad-except msg = "{}\n{}: {}\n(UNABLE TO FORMAT TRACEBACK)".format( - msg, exc_type.__name__, exc_value, + msg, + exc_type.__name__, + exc_value, ) try: _logger.error(msg) diff --git a/salt/master.py b/salt/master.py index 0c1e1259068..bba3b8c6243 100644 --- a/salt/master.py +++ b/salt/master.py @@ -376,7 +376,8 @@ class FileserverUpdate(salt.utils.process.SignalHandlingProcess): # process so that a register_after_fork() equivalent will work on Windows. def __setstate__(self, state): self.__init__( - state["opts"], log_queue=state["log_queue"], + state["opts"], + log_queue=state["log_queue"], ) def __getstate__(self): @@ -508,7 +509,8 @@ class FileserverUpdate(salt.utils.process.SignalHandlingProcess): for interval in self.buckets: self.update_threads[interval] = threading.Thread( - target=self.update, args=(interval, self.buckets[interval]), + target=self.update, + args=(interval, self.buckets[interval]), ) self.update_threads[interval].start() @@ -1169,7 +1171,10 @@ class MWorker(salt.utils.process.SignalHandlingProcess): ) os.nice(self.opts["mworker_niceness"]) - self.clear_funcs = ClearFuncs(self.opts, self.key,) + self.clear_funcs = ClearFuncs( + self.opts, + self.key, + ) self.aes_funcs = AESFuncs(self.opts) salt.utils.crypt.reinit_crypto() self.__bind() @@ -2140,7 +2145,9 @@ class ClearFuncs(TransportMethods): except Exception as exc: # pylint: disable=broad-except log.error("Exception occurred while introspecting %s: %s", fun, exc) data["return"] = "Exception occurred in wheel {}: {}: {}".format( - fun, exc.__class__.__name__, exc, + fun, + exc.__class__.__name__, + exc, ) data["success"] = False self.event.fire_event(data, tagify([jid, "ret"], "wheel")) diff --git a/salt/minion.py b/salt/minion.py index 5b0483b6ec9..04ea5f38196 100644 --- a/salt/minion.py +++ b/salt/minion.py @@ -1042,7 +1042,8 @@ class MinionManager(MinionBase): def _bind(self): # start up the event publisher, so we can see events during startup self.event_publisher = salt.utils.event.AsyncEventPublisher( - self.opts, io_loop=self.io_loop, + self.opts, + io_loop=self.io_loop, ) self.event = salt.utils.event.get_event( "minion", opts=self.opts, io_loop=self.io_loop @@ -1550,7 +1551,11 @@ class Minion(MinionBase): ) else: functions = salt.loader.minion_mods( - opts, utils=self.utils, notify=notify, proxy=proxy, context=context, + opts, + utils=self.utils, + notify=notify, + proxy=proxy, + context=context, ) returners = salt.loader.returners(opts, functions, proxy=proxy, context=context) errors = {} @@ -3006,7 +3011,8 @@ class Minion(MinionBase): if name in self.periodic_callbacks: return False self.periodic_callbacks[name] = salt.ext.tornado.ioloop.PeriodicCallback( - method, interval * 1000, + method, + interval * 1000, ) self.periodic_callbacks[name].start() return True @@ -3576,7 +3582,8 @@ class SyndicManager(MinionBase): # forward events every syndic_event_forward_timeout self.forward_events = salt.ext.tornado.ioloop.PeriodicCallback( - self._forward_events, self.opts["syndic_event_forward_timeout"] * 1000, + self._forward_events, + self.opts["syndic_event_forward_timeout"] * 1000, ) self.forward_events.start() @@ -3841,7 +3848,10 @@ class SProxyMinion(SMinion): self.matchers = salt.loader.matchers(self.opts) self.functions["sys.reload_modules"] = self.gen_modules self.executors = salt.loader.executors( - self.opts, functions=self.functions, proxy=self.proxy, context=context, + self.opts, + functions=self.functions, + proxy=self.proxy, + context=context, ) fq_proxyname = self.opts["proxy"]["proxytype"] diff --git a/salt/modules/artifactory.py b/salt/modules/artifactory.py index baa06d8fe22..65daa35419f 100644 --- a/salt/modules/artifactory.py +++ b/salt/modules/artifactory.py @@ -40,29 +40,29 @@ def get_latest_snapshot( use_literal_group_id=False, ): """ - Gets latest snapshot of the given artifact + Gets latest snapshot of the given artifact - artifactory_url - URL of artifactory instance - repository - Snapshot repository in artifactory to retrieve artifact from, for example: libs-snapshots - group_id - Group Id of the artifact - artifact_id - Artifact Id of the artifact - packaging - Packaging type (jar,war,ear,etc) - target_dir - Target directory to download artifact to (default: /tmp) - target_file - Target file to download artifact to (by default it is target_dir/artifact_id-snapshot_version.packaging) - classifier - Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. - username - Artifactory username. Optional parameter. - password - Artifactory password. Optional parameter. - """ + artifactory_url + URL of artifactory instance + repository + Snapshot repository in artifactory to retrieve artifact from, for example: libs-snapshots + group_id + Group Id of the artifact + artifact_id + Artifact Id of the artifact + packaging + Packaging type (jar,war,ear,etc) + target_dir + Target directory to download artifact to (default: /tmp) + target_file + Target file to download artifact to (by default it is target_dir/artifact_id-snapshot_version.packaging) + classifier + Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. + username + Artifactory username. Optional parameter. + password + Artifactory password. Optional parameter. + """ log.debug( "======================== MODULE FUNCTION: artifactory.get_latest_snapshot, artifactory_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, target_dir=%s, classifier=%s)", artifactory_url, @@ -122,31 +122,31 @@ def get_snapshot( use_literal_group_id=False, ): """ - Gets snapshot of the desired version of the artifact + Gets snapshot of the desired version of the artifact - artifactory_url - URL of artifactory instance - repository - Snapshot repository in artifactory to retrieve artifact from, for example: libs-snapshots - group_id - Group Id of the artifact - artifact_id - Artifact Id of the artifact - packaging - Packaging type (jar,war,ear,etc) - version - Version of the artifact - target_dir - Target directory to download artifact to (default: /tmp) - target_file - Target file to download artifact to (by default it is target_dir/artifact_id-snapshot_version.packaging) - classifier - Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. - username - Artifactory username. Optional parameter. - password - Artifactory password. Optional parameter. - """ + artifactory_url + URL of artifactory instance + repository + Snapshot repository in artifactory to retrieve artifact from, for example: libs-snapshots + group_id + Group Id of the artifact + artifact_id + Artifact Id of the artifact + packaging + Packaging type (jar,war,ear,etc) + version + Version of the artifact + target_dir + Target directory to download artifact to (default: /tmp) + target_file + Target file to download artifact to (by default it is target_dir/artifact_id-snapshot_version.packaging) + classifier + Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. + username + Artifactory username. Optional parameter. + password + Artifactory password. Optional parameter. + """ log.debug( "======================== MODULE FUNCTION: artifactory.get_snapshot(artifactory_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, version=%s, target_dir=%s, classifier=%s)", artifactory_url, @@ -196,29 +196,29 @@ def get_latest_release( use_literal_group_id=False, ): """ - Gets the latest release of the artifact + Gets the latest release of the artifact - artifactory_url - URL of artifactory instance - repository - Release repository in artifactory to retrieve artifact from, for example: libs-releases - group_id - Group Id of the artifact - artifact_id - Artifact Id of the artifact - packaging - Packaging type (jar,war,ear,etc) - target_dir - Target directory to download artifact to (default: /tmp) - target_file - Target file to download artifact to (by default it is target_dir/artifact_id-version.packaging) - classifier - Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. - username - Artifactory username. Optional parameter. - password - Artifactory password. Optional parameter. - """ + artifactory_url + URL of artifactory instance + repository + Release repository in artifactory to retrieve artifact from, for example: libs-releases + group_id + Group Id of the artifact + artifact_id + Artifact Id of the artifact + packaging + Packaging type (jar,war,ear,etc) + target_dir + Target directory to download artifact to (default: /tmp) + target_file + Target file to download artifact to (by default it is target_dir/artifact_id-version.packaging) + classifier + Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. + username + Artifactory username. Optional parameter. + password + Artifactory password. Optional parameter. + """ log.debug( "======================== MODULE FUNCTION: artifactory.get_latest_release(artifactory_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, target_dir=%s, classifier=%s)", artifactory_url, @@ -273,31 +273,31 @@ def get_release( use_literal_group_id=False, ): """ - Gets the specified release of the artifact + Gets the specified release of the artifact - artifactory_url - URL of artifactory instance - repository - Release repository in artifactory to retrieve artifact from, for example: libs-releases - group_id - Group Id of the artifact - artifact_id - Artifact Id of the artifact - packaging - Packaging type (jar,war,ear,etc) - version - Version of the artifact - target_dir - Target directory to download artifact to (default: /tmp) - target_file - Target file to download artifact to (by default it is target_dir/artifact_id-version.packaging) - classifier - Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. - username - Artifactory username. Optional parameter. - password - Artifactory password. Optional parameter. - """ + artifactory_url + URL of artifactory instance + repository + Release repository in artifactory to retrieve artifact from, for example: libs-releases + group_id + Group Id of the artifact + artifact_id + Artifact Id of the artifact + packaging + Packaging type (jar,war,ear,etc) + version + Version of the artifact + target_dir + Target directory to download artifact to (default: /tmp) + target_file + Target file to download artifact to (by default it is target_dir/artifact_id-version.packaging) + classifier + Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. + username + Artifactory username. Optional parameter. + password + Artifactory password. Optional parameter. + """ log.debug( "======================== MODULE FUNCTION: artifactory.get_release(artifactory_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, version=%s, target_dir=%s, classifier=%s)", artifactory_url, diff --git a/salt/modules/at.py b/salt/modules/at.py index 48333a78c74..d1dc5c170a4 100644 --- a/salt/modules/at.py +++ b/salt/modules/at.py @@ -215,7 +215,12 @@ def atrm(*args): ret = {"jobs": {"removed": opts, "tag": None}} else: opts = list( - list(map(str, [i["job"] for i in atq()["jobs"] if str(i["job"]) in args],)) + list( + map( + str, + [i["job"] for i in atq()["jobs"] if str(i["job"]) in args], + ) + ) ) ret = {"jobs": {"removed": opts, "tag": None}} diff --git a/salt/modules/augeas_cfg.py b/salt/modules/augeas_cfg.py index 2af91159809..7a92235c8ac 100644 --- a/salt/modules/augeas_cfg.py +++ b/salt/modules/augeas_cfg.py @@ -230,9 +230,10 @@ def execute(context=None, lens=None, commands=(), load_path=None): # if command.split fails arg will not be set if "arg" not in locals(): arg = command - ret["error"] = ( - "Invalid formatted command, " - "see debug log for details: {}".format(arg) + ret[ + "error" + ] = "Invalid formatted command, " "see debug log for details: {}".format( + arg ) return ret @@ -488,7 +489,7 @@ def ls(path, load_path=None): # pylint: disable=C0103 """ def _match(path): - """ Internal match function """ + """Internal match function""" try: matches = aug.match(salt.utils.stringutils.to_str(path)) except RuntimeError: diff --git a/salt/modules/bamboohr.py b/salt/modules/bamboohr.py index 7a5b69df427..5cdd05bee8e 100644 --- a/salt/modules/bamboohr.py +++ b/salt/modules/bamboohr.py @@ -179,7 +179,10 @@ def update_employee(emp_id, key=None, value=None, items=None): xml_items = "{}".format(xml_items) status, result = _query( - action="employees", command=emp_id, data=xml_items, method="POST", + action="employees", + command=emp_id, + data=xml_items, + method="POST", ) return show_employee(emp_id, ",".join(items.keys())) diff --git a/salt/modules/beacons.py b/salt/modules/beacons.py index 8e5b74c46c0..112fc816c84 100644 --- a/salt/modules/beacons.py +++ b/salt/modules/beacons.py @@ -188,9 +188,10 @@ def add(name, beacon_data, **kwargs): if not valid: ret["result"] = False - ret["comment"] = ( - "Beacon {} configuration invalid, " - "not adding.\n{}".format(name, vcomment) + ret[ + "comment" + ] = "Beacon {} configuration invalid, " "not adding.\n{}".format( + name, vcomment ) return ret except KeyError: @@ -286,9 +287,10 @@ def modify(name, beacon_data, **kwargs): if not valid: ret["result"] = False - ret["comment"] = ( - "Beacon {} configuration invalid, " - "not modifying.\n{}".format(name, vcomment) + ret[ + "comment" + ] = "Beacon {} configuration invalid, " "not modifying.\n{}".format( + name, vcomment ) return ret @@ -300,9 +302,10 @@ def modify(name, beacon_data, **kwargs): if not valid: ret["result"] = False - ret["comment"] = ( - "Beacon {} configuration invalid, " - "not modifying.\n{}".format(name, vcomment) + ret[ + "comment" + ] = "Beacon {} configuration invalid, " "not modifying.\n{}".format( + name, vcomment ) return ret diff --git a/salt/modules/bigip.py b/salt/modules/bigip.py index 98aed836246..8f8441bf692 100644 --- a/salt/modules/bigip.py +++ b/salt/modules/bigip.py @@ -1601,8 +1601,10 @@ def create_virtual( elif vlans["disabled"]: payload["vlans-disabled"] = True except Exception: # pylint: disable=broad-except - return "Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}".format( - vlans=vlans + return ( + "Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}".format( + vlans=vlans + ) ) elif vlans == "none": payload["vlans"] = "none" @@ -1888,8 +1890,10 @@ def modify_virtual( elif vlans["disabled"]: payload["vlans-disabled"] = True except Exception: # pylint: disable=broad-except - return "Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}".format( - vlans=vlans + return ( + "Error: Unable to Parse vlans dictionary: \n\tvlans={vlans}".format( + vlans=vlans + ) ) elif vlans == "none": payload["vlans"] = "none" @@ -1967,7 +1971,11 @@ def delete_virtual(hostname, username, password, name): def list_monitor( - hostname, username, password, monitor_type, name=None, + hostname, + username, + password, + monitor_type, + name=None, ): """ A function to connect to a bigip device and list an existing monitor. If no name is provided than all @@ -2163,7 +2171,11 @@ def delete_monitor(hostname, username, password, monitor_type, name): def list_profile( - hostname, username, password, profile_type, name=None, + hostname, + username, + password, + profile_type, + name=None, ): """ A function to connect to a bigip device and list an existing profile. If no name is provided than all diff --git a/salt/modules/boto_cloudfront.py b/salt/modules/boto_cloudfront.py index 4d78c892292..7e4db092d06 100644 --- a/salt/modules/boto_cloudfront.py +++ b/salt/modules/boto_cloudfront.py @@ -80,7 +80,12 @@ def __virtual__(): def _list_distributions( - conn, name=None, region=None, key=None, keyid=None, profile=None, + conn, + name=None, + region=None, + key=None, + keyid=None, + profile=None, ): """ Private function that returns an iterator over all CloudFront distributions. @@ -185,7 +190,12 @@ def get_distribution(name, region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: for _, dist in _list_distributions( - conn, name=name, region=region, key=key, keyid=keyid, profile=profile, + conn, + name=name, + region=region, + key=key, + keyid=keyid, + profile=profile, ): # _list_distributions should only return the one distribution # that we want (with the given name). @@ -231,7 +241,11 @@ def export_distributions(region=None, key=None, keyid=None, profile=None): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: for name, distribution in _list_distributions( - conn, region=region, key=key, keyid=keyid, profile=profile, + conn, + region=region, + key=key, + keyid=keyid, + profile=profile, ): config = distribution["distribution"]["DistributionConfig"] tags = distribution["tags"] @@ -250,11 +264,21 @@ def export_distributions(region=None, key=None, keyid=None, profile=None): log.trace("Boto client error: {}", exc) dumper = __utils__["yaml.get_dumper"]("IndentedSafeOrderedDumper") - return __utils__["yaml.dump"](results, default_flow_style=False, Dumper=dumper,) + return __utils__["yaml.dump"]( + results, + default_flow_style=False, + Dumper=dumper, + ) def create_distribution( - name, config, tags=None, region=None, key=None, keyid=None, profile=None, + name, + config, + tags=None, + region=None, + key=None, + keyid=None, + profile=None, ): """ Create a CloudFront distribution with the given name, config, and (optionally) tags. @@ -318,7 +342,13 @@ def create_distribution( def update_distribution( - name, config, tags=None, region=None, key=None, keyid=None, profile=None, + name, + config, + tags=None, + region=None, + key=None, + keyid=None, + profile=None, ): """ Update the config (and optionally tags) for the CloudFront distribution with the given name. @@ -372,7 +402,9 @@ def update_distribution( try: if "old" in config_diff or "new" in config_diff: conn.update_distribution( - DistributionConfig=config, Id=current_distribution["Id"], IfMatch=etag, + DistributionConfig=config, + Id=current_distribution["Id"], + IfMatch=etag, ) if tags: arn = current_distribution["ARN"] @@ -383,14 +415,16 @@ def update_distribution( ], } conn.tag_resource( - Resource=arn, Tags=tags_to_add, + Resource=arn, + Tags=tags_to_add, ) if "old" in tags_diff: tags_to_remove = { "Items": list(tags_diff["old"].keys()), } conn.untag_resource( - Resource=arn, TagKeys=tags_to_remove, + Resource=arn, + TagKeys=tags_to_remove, ) except botocore.exceptions.ClientError as err: return {"error": __utils__["boto3.get_error"](err)} diff --git a/salt/modules/boto_datapipeline.py b/salt/modules/boto_datapipeline.py index dabea59ef7c..52d5872d360 100644 --- a/salt/modules/boto_datapipeline.py +++ b/salt/modules/boto_datapipeline.py @@ -67,7 +67,9 @@ def create_pipeline( r = {} try: response = client.create_pipeline( - name=name, uniqueId=unique_id, description=description, + name=name, + uniqueId=unique_id, + description=description, ) r["result"] = response["pipelineId"] except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: @@ -130,7 +132,8 @@ def get_pipeline_definition( r = {} try: r["result"] = client.get_pipeline_definition( - pipelineId=pipeline_id, version=version, + pipelineId=pipeline_id, + version=version, ) except (botocore.exceptions.BotoCoreError, botocore.exceptions.ClientError) as e: r["error"] = str(e) @@ -255,5 +258,7 @@ def _get_session(region, key, keyid, profile): region = "us-east-1" return boto3.session.Session( - region_name=region, aws_secret_access_key=key, aws_access_key_id=keyid, + region_name=region, + aws_secret_access_key=key, + aws_access_key_id=keyid, ) diff --git a/salt/modules/boto_route53.py b/salt/modules/boto_route53.py index 51f74aff27f..9852b2d33a5 100644 --- a/salt/modules/boto_route53.py +++ b/salt/modules/boto_route53.py @@ -252,7 +252,7 @@ def zone_exists( error_retries=5, ): """ - Check for the existence of a Route53 hosted zone. + Check for the existence of a Route53 hosted zone. .. versionadded:: 2015.8.0 @@ -262,7 +262,7 @@ def zone_exists( salt myminion boto_route53.zone_exists example.org - retry_on_errors + retry_on_errors Continue to query if the zone exists after an error is raised. The previously used argument `retry_on_rate_limit` was deprecated for this argument. Users can still use @@ -277,7 +277,6 @@ def zone_exists( `rate_limit_retries` to ensure backwards compatibility, but please migrate to using the favored `error_retries` argument instead. - """ if region is None: region = "universal" @@ -546,7 +545,7 @@ def get_record( error_retries=5, ): """ - Get a record from a zone. + Get a record from a zone. CLI Example: @@ -554,7 +553,7 @@ def get_record( salt myminion boto_route53.get_record test.example.org example.org A - retry_on_errors + retry_on_errors Continue to query if the zone exists after an error is raised. The previously used argument `retry_on_rate_limit` was deprecated for this argument. Users can still use @@ -657,7 +656,7 @@ def add_record( error_retries=5, ): """ - Add a record to a zone. + Add a record to a zone. CLI Example: @@ -665,7 +664,7 @@ def add_record( salt myminion boto_route53.add_record test.example.org 1.1.1.1 example.org A - retry_on_errors + retry_on_errors Continue to query if the zone exists after an error is raised. The previously used argument `retry_on_rate_limit` was deprecated for this argument. Users can still use @@ -764,15 +763,15 @@ def update_record( error_retries=5, ): """ - Modify a record in a zone. + Modify a record in a zone. - CLI Example: + CLI Example: - .. code-block:: bash + .. code-block:: bash - salt myminion boto_route53.modify_record test.example.org 1.1.1.1 example.org A + salt myminion boto_route53.modify_record test.example.org 1.1.1.1 example.org A - retry_on_errors + retry_on_errors Continue to query if the zone exists after an error is raised. The previously used argument `retry_on_rate_limit` was deprecated for this argument. Users can still use @@ -853,15 +852,15 @@ def delete_record( error_retries=5, ): """ - Modify a record in a zone. + Modify a record in a zone. - CLI Example: + CLI Example: - .. code-block:: bash + .. code-block:: bash - salt myminion boto_route53.delete_record test.example.org example.org A + salt myminion boto_route53.delete_record test.example.org example.org A - retry_on_errors + retry_on_errors Continue to query if the zone exists after an error is raised. The previously used argument `retry_on_rate_limit` was deprecated for this argument. Users can still use diff --git a/salt/modules/boto_s3.py b/salt/modules/boto_s3.py index cde38cb099a..bef68657e9b 100644 --- a/salt/modules/boto_s3.py +++ b/salt/modules/boto_s3.py @@ -85,7 +85,12 @@ def __init__(opts): # pylint: disable=unused-argument def get_object_metadata( - name, extra_args=None, region=None, key=None, keyid=None, profile=None, + name, + extra_args=None, + region=None, + key=None, + keyid=None, + profile=None, ): """ Get metadata about an S3 object. @@ -121,7 +126,13 @@ def get_object_metadata( def upload_file( - source, name, extra_args=None, region=None, key=None, keyid=None, profile=None, + source, + name, + extra_args=None, + region=None, + key=None, + keyid=None, + profile=None, ): """ Upload a local file as an S3 object. diff --git a/salt/modules/boto_sqs.py b/salt/modules/boto_sqs.py index 4e808d6d36e..c2a572ab248 100644 --- a/salt/modules/boto_sqs.py +++ b/salt/modules/boto_sqs.py @@ -118,7 +118,12 @@ def exists(name, region=None, key=None, keyid=None, profile=None): def create( - name, attributes=None, region=None, key=None, keyid=None, profile=None, + name, + attributes=None, + region=None, + key=None, + keyid=None, + profile=None, ): """ Create an SQS queue. @@ -210,7 +215,12 @@ def get_attributes(name, region=None, key=None, keyid=None, profile=None): def set_attributes( - name, attributes, region=None, key=None, keyid=None, profile=None, + name, + attributes, + region=None, + key=None, + keyid=None, + profile=None, ): """ Set attributes on an SQS queue. diff --git a/salt/modules/boto_vpc.py b/salt/modules/boto_vpc.py index 33b3c7ed93c..1b6d02a654a 100644 --- a/salt/modules/boto_vpc.py +++ b/salt/modules/boto_vpc.py @@ -196,7 +196,12 @@ def __init__(opts): def check_vpc( - vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None, + vpc_id=None, + vpc_name=None, + region=None, + key=None, + keyid=None, + profile=None, ): """ Check whether a VPC with the given name or id exists. @@ -672,7 +677,13 @@ def _get_id( def get_id( - name=None, cidr=None, tags=None, region=None, key=None, keyid=None, profile=None, + name=None, + cidr=None, + tags=None, + region=None, + key=None, + keyid=None, + profile=None, ): """ Given VPC properties, return the VPC id if a match is found. @@ -883,7 +894,12 @@ def delete( def describe( - vpc_id=None, vpc_name=None, region=None, key=None, keyid=None, profile=None, + vpc_id=None, + vpc_name=None, + region=None, + key=None, + keyid=None, + profile=None, ): """ Describe a VPC's properties. If no VPC ID/Name is spcified then describe the default VPC. diff --git a/salt/modules/chronos.py b/salt/modules/chronos.py index d4a92e7e8ab..a76590cb4af 100644 --- a/salt/modules/chronos.py +++ b/salt/modules/chronos.py @@ -37,7 +37,9 @@ def _jobs(): Return the currently configured jobs. """ response = salt.utils.http.query( - "{}/scheduler/jobs".format(_base_url()), decode_type="json", decode=True, + "{}/scheduler/jobs".format(_base_url()), + decode_type="json", + decode=True, ) jobs = {} for job in response["dict"]: @@ -127,6 +129,7 @@ def rm_job(name): salt chronos-minion-id chronos.rm_job my-job """ response = salt.utils.http.query( - "{}/scheduler/job/{}".format(_base_url(), name), method="DELETE", + "{}/scheduler/job/{}".format(_base_url(), name), + method="DELETE", ) return True diff --git a/salt/modules/cimc.py b/salt/modules/cimc.py index 5bde68524e5..e555538a901 100644 --- a/salt/modules/cimc.py +++ b/salt/modules/cimc.py @@ -660,8 +660,10 @@ def set_hostname(hostname=None): raise salt.exceptions.CommandExecutionError("Hostname option must be provided.") dn = "sys/rack-unit-1/mgmt/if-1" - inconfig = """""".format( - hostname + inconfig = ( + """""".format( + hostname + ) ) ret = __proxy__["cimc.set_config_modify"](dn, inconfig, False) diff --git a/salt/modules/ciscoconfparse_mod.py b/salt/modules/ciscoconfparse_mod.py index 793ea69aff6..56924691245 100644 --- a/salt/modules/ciscoconfparse_mod.py +++ b/salt/modules/ciscoconfparse_mod.py @@ -54,8 +54,7 @@ def __virtual__(): def _get_ccp(config=None, config_path=None, saltenv="base"): - """ - """ + """ """ if config_path: config = __salt__["cp.get_file_str"](config_path, saltenv=saltenv) if config is False: @@ -257,7 +256,7 @@ def find_lines_w_child( salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2mAdq7z parent_line='line con' child_line='stopbits' salt '*' ciscoconfparse.find_lines_w_child config_path=https://bit.ly/2uIRxau parent_regex='ge-(.*)' child_regex='unit \d+' - """ + """ lines = find_objects_w_child( config=config, config_path=config_path, @@ -323,7 +322,7 @@ def find_objects_wo_child( child_regex='stopbits') for obj in objects: print(obj.text) - """ + """ ccp = _get_ccp(config=config, config_path=config_path, saltenv=saltenv) lines = ccp.find_objects_wo_child(parent_regex, child_regex, ignore_ws=ignore_ws) return lines diff --git a/salt/modules/cron.py b/salt/modules/cron.py index 007c2179ae0..8f680e76bde 100644 --- a/salt/modules/cron.py +++ b/salt/modules/cron.py @@ -55,12 +55,12 @@ def _cron_id(cron): def _cron_matched(cron, cmd, identifier=None): """Check if: - - we find a cron with same cmd, old state behavior - - but also be smart enough to remove states changed crons where we do - not removed priorly by a cron.absent by matching on the provided - identifier. - We assure retrocompatibility by only checking on identifier if - and only if an identifier was set on the serialized crontab + - we find a cron with same cmd, old state behavior + - but also be smart enough to remove states changed crons where we do + not removed priorly by a cron.absent by matching on the provided + identifier. + We assure retrocompatibility by only checking on identifier if + and only if an identifier was set on the serialized crontab """ ret, id_matched = False, None cid = _cron_id(cron) diff --git a/salt/modules/debian_service.py b/salt/modules/debian_service.py index 04c6cd5d37b..95d3ae00881 100644 --- a/salt/modules/debian_service.py +++ b/salt/modules/debian_service.py @@ -29,12 +29,16 @@ def __virtual__(): """ Only work on Debian and when systemd isn't running """ - if __grains__["os"] in ( - "Debian", - "Raspbian", - "Devuan", - "NILinuxRT", - ) and not salt.utils.systemd.booted(__context__): + if ( + __grains__["os"] + in ( + "Debian", + "Raspbian", + "Devuan", + "NILinuxRT", + ) + and not salt.utils.systemd.booted(__context__) + ): return __virtualname__ else: return ( diff --git a/salt/modules/djangomod.py b/salt/modules/djangomod.py index 7408b64528f..17942130e80 100644 --- a/salt/modules/djangomod.py +++ b/salt/modules/djangomod.py @@ -226,7 +226,10 @@ def createsuperuser( salt '*' django.createsuperuser user user@example.com """ args = ["noinput"] - kwargs = dict(email=email, username=username,) + kwargs = dict( + email=email, + username=username, + ) if database: kwargs["database"] = database return command( diff --git a/salt/modules/dockermod.py b/salt/modules/dockermod.py index a5326472ef0..69ee2d637bd 100644 --- a/salt/modules/dockermod.py +++ b/salt/modules/dockermod.py @@ -810,7 +810,8 @@ def _error_detail(data, item): ) except TypeError: msg = "{}: {}".format( - item["errorDetail"]["code"], item["errorDetail"]["message"], + item["errorDetail"]["code"], + item["errorDetail"]["message"], ) else: msg = item["errorDetail"]["message"] @@ -902,7 +903,7 @@ def _get_create_kwargs( client_args = get_client_args(["create_container", "host_config"]) except CommandExecutionError as exc: log.error( - "docker.create: Error getting client args: '%s'", exc, exc_info=True, + "docker.create: Error getting client args: '%s'", exc, exc_info=True ) raise CommandExecutionError("Failed to get client args: {}".format(exc)) @@ -1472,7 +1473,9 @@ def login(*registries): username, ) login_cmd = __salt__["cmd.run_all"]( - cmd, python_shell=False, output_loglevel="quiet", + cmd, + python_shell=False, + output_loglevel="quiet", ) results[registry] = login_cmd["retcode"] == 0 if not results[registry]: @@ -1552,7 +1555,9 @@ def logout(*registries): cmd.append(registry) log.debug("Attempting to logout of docker registry '%s'", registry) logout_cmd = __salt__["cmd.run_all"]( - cmd, python_shell=False, output_loglevel="quiet", + cmd, + python_shell=False, + output_loglevel="quiet", ) results[registry] = logout_cmd["retcode"] == 0 if not results[registry]: diff --git a/salt/modules/file.py b/salt/modules/file.py index c2f3d831ee7..64b3e0bab4d 100644 --- a/salt/modules/file.py +++ b/salt/modules/file.py @@ -174,7 +174,8 @@ def _chattr_version(): cmd = [tune2fs] result = __salt__["cmd.run"](cmd, ignore_retcode=True, python_shell=False) match = re.search( - r"tune2fs (?P[0-9\.]+)", salt.utils.stringutils.to_str(result), + r"tune2fs (?P[0-9\.]+)", + salt.utils.stringutils.to_str(result), ) if match is None: version = None @@ -587,7 +588,8 @@ def _cmp_attrs(path, attrs): new.add("e") return AttrChanges( - added="".join(new - old) or None, removed="".join(old - new) or None, + added="".join(new - old) or None, + removed="".join(old - new) or None, ) @@ -5072,11 +5074,15 @@ def check_perms( else: if diff_attrs.added: chattr( - name, operator="add", attributes=diff_attrs.added, + name, + operator="add", + attributes=diff_attrs.added, ) if diff_attrs.removed: chattr( - name, operator="remove", attributes=diff_attrs.removed, + name, + operator="remove", + attributes=diff_attrs.removed, ) cmp_attrs = _cmp_attrs(name, attrs) if any(attr for attr in cmp_attrs): @@ -5397,10 +5403,14 @@ def check_managed_changes( __clean_tmp(sfn) return False, comments if sfn and source and keep_mode: - if urllib.parse.urlparse(source).scheme in ( - "salt", - "file", - ) or source.startswith("/"): + if ( + urllib.parse.urlparse(source).scheme + in ( + "salt", + "file", + ) + or source.startswith("/") + ): try: mode = __salt__["cp.stat_file"](source, saltenv=saltenv, octal=True) except Exception as exc: # pylint: disable=broad-except diff --git a/salt/modules/gcp_addon.py b/salt/modules/gcp_addon.py index 934a4904303..76ec403af12 100644 --- a/salt/modules/gcp_addon.py +++ b/salt/modules/gcp_addon.py @@ -117,8 +117,10 @@ def route_create( packet to instance "instance-1"(if packet is intended to other network) """ - credentials = oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name( - credential_file + credentials = ( + oauth2client.service_account.ServiceAccountCredentials.from_json_keyfile_name( + credential_file + ) ) service = googleapiclient.discovery.build("compute", "v1", credentials=credentials) routes = service.routes() diff --git a/salt/modules/genesis.py b/salt/modules/genesis.py index 53b30207510..5c2be12388a 100644 --- a/salt/modules/genesis.py +++ b/salt/modules/genesis.py @@ -180,7 +180,10 @@ def bootstrap( if platform in ("rpm", "yum"): _bootstrap_yum( - root, pkgs=pkgs, exclude_pkgs=exclude_pkgs, epel_url=epel_url, + root, + pkgs=pkgs, + exclude_pkgs=exclude_pkgs, + epel_url=epel_url, ) elif platform == "deb": _bootstrap_deb( @@ -194,7 +197,10 @@ def bootstrap( ) elif platform == "pacman": _bootstrap_pacman( - root, img_format=img_format, pkgs=pkgs, exclude_pkgs=exclude_pkgs, + root, + img_format=img_format, + pkgs=pkgs, + exclude_pkgs=exclude_pkgs, ) if img_format != "dir": @@ -285,7 +291,11 @@ def _populate_cache(platform, pkg_cache, mount_dir): def _bootstrap_yum( - root, pkg_confs="/etc/yum*", pkgs=None, exclude_pkgs=None, epel_url=EPEL_URL, + root, + pkg_confs="/etc/yum*", + pkgs=None, + exclude_pkgs=None, + epel_url=EPEL_URL, ): """ Bootstrap an image using the yum tools @@ -364,7 +374,13 @@ def _bootstrap_yum( def _bootstrap_deb( - root, arch, flavor, repo_url=None, static_qemu=None, pkgs=None, exclude_pkgs=None, + root, + arch, + flavor, + repo_url=None, + static_qemu=None, + pkgs=None, + exclude_pkgs=None, ): """ Bootstrap an image using the Debian tools @@ -452,7 +468,11 @@ def _bootstrap_deb( def _bootstrap_pacman( - root, pkg_confs="/etc/pacman*", img_format="dir", pkgs=None, exclude_pkgs=None, + root, + pkg_confs="/etc/pacman*", + img_format="dir", + pkgs=None, + exclude_pkgs=None, ): """ Bootstrap an image using the pacman tools @@ -618,7 +638,10 @@ def _tar(name, root, path=None, compress="bzip2"): tarfile = "{}/{}.tar.{}".format(path, name, ext) out = __salt__["archive.tar"]( - options="{}pcf".format(compression), tarfile=tarfile, sources=".", dest=root, + options="{}pcf".format(compression), + tarfile=tarfile, + sources=".", + dest=root, ) @@ -642,7 +665,9 @@ def _untar(name, dest=None, path=None, compress="bz2"): tarfile = "{}/{}.tar.{}".format(path, name, ext) out = __salt__["archive.tar"]( - options="{}xf".format(compression), tarfile=tarfile, dest=dest, + options="{}xf".format(compression), + tarfile=tarfile, + dest=dest, ) diff --git a/salt/modules/glusterfs.py b/salt/modules/glusterfs.py index 4a869e9bd79..5de5110df35 100644 --- a/salt/modules/glusterfs.py +++ b/salt/modules/glusterfs.py @@ -68,7 +68,10 @@ def _gluster_xml(cmd): # We will pass the command string as stdin to allow for much longer # command strings. This is especially useful for creating large volumes # where the list of bricks exceeds 128 characters. - if _get_version() < (3, 6,): + if _get_version() < ( + 3, + 6, + ): result = __salt__["cmd.run"]( 'script -q -c "gluster --xml --mode=script"', stdin="{}\n\004".format(cmd) ) @@ -767,7 +770,10 @@ def get_max_op_version(): salt '*' glusterfs.get_max_op_version """ - if _get_version() < (3, 10,): + if _get_version() < ( + 3, + 10, + ): return ( False, "Glusterfs version must be 3.10+. Your version is {}.".format( diff --git a/salt/modules/hadoop.py b/salt/modules/hadoop.py index df65ff9538e..bd2d16c8177 100644 --- a/salt/modules/hadoop.py +++ b/salt/modules/hadoop.py @@ -28,16 +28,16 @@ def __virtual__(): def _hadoop_cmd(module, command, *args): """ - Hadoop/hdfs command wrapper + Hadoop/hdfs command wrapper - As Hadoop command has been deprecated this module will default - to use hdfs command and fall back to hadoop if it is not found + As Hadoop command has been deprecated this module will default + to use hdfs command and fall back to hadoop if it is not found - In order to prevent random execution the module name is checked + In order to prevent random execution the module name is checked - Follows hadoop command template: - hadoop module -command args - E.g.: hadoop dfs -ls / + Follows hadoop command template: + hadoop module -command args + E.g.: hadoop dfs -ls / """ tool = "hadoop" if salt.utils.path.which("hdfs"): diff --git a/salt/modules/incron.py b/salt/modules/incron.py index 57305963e10..ad13c6de6e5 100644 --- a/salt/modules/incron.py +++ b/salt/modules/incron.py @@ -58,7 +58,13 @@ def _render_tab(lst): for pre in lst["pre"]: ret.append("{}\n".format(pre)) for cron in lst["crons"]: - ret.append("{} {} {}\n".format(cron["path"], cron["mask"], cron["cmd"],)) + ret.append( + "{} {} {}\n".format( + cron["path"], + cron["mask"], + cron["cmd"], + ) + ) return ret diff --git a/salt/modules/influxdbmod.py b/salt/modules/influxdbmod.py index 42e71bfeec5..1225d966848 100644 --- a/salt/modules/influxdbmod.py +++ b/salt/modules/influxdbmod.py @@ -637,7 +637,7 @@ def create_continuous_query( .. code-block:: bash - salt '*' influxdb.create_continuous_query mydb cq_month 'SELECT mean(*) INTO mydb.a_month.:MEASUREMENT FROM mydb.a_week./.*/ GROUP BY time(5m), *' """ + salt '*' influxdb.create_continuous_query mydb cq_month 'SELECT mean(*) INTO mydb.a_month.:MEASUREMENT FROM mydb.a_week./.*/ GROUP BY time(5m), *'""" client = _client(**client_args) full_query = "CREATE CONTINUOUS QUERY {name} ON {database}" if resample_time: diff --git a/salt/modules/inspectlib/collector.py b/salt/modules/inspectlib/collector.py index 784cc213efa..a3ed0b0b1f1 100644 --- a/salt/modules/inspectlib/collector.py +++ b/salt/modules/inspectlib/collector.py @@ -257,7 +257,10 @@ class Inspector(EnvLoader): for p_type, p_list in ( ("f", files), ("d", directories), - ("l", links,), + ( + "l", + links, + ), ): for p_obj in p_list: stats = os.stat(p_obj) @@ -415,7 +418,12 @@ class Inspector(EnvLoader): all_links.extend(e_links) return self._get_unmanaged_files( - self._get_managed_files(), (all_files, all_dirs, all_links,) + self._get_managed_files(), + ( + all_files, + all_dirs, + all_links, + ), ) def _prepare_full_scan(self, **kwargs): diff --git a/salt/modules/jboss7.py b/salt/modules/jboss7.py index 180a0525472..62edc9d13e0 100644 --- a/salt/modules/jboss7.py +++ b/salt/modules/jboss7.py @@ -52,7 +52,7 @@ def status(jboss_config, host=None, server_config=None): salt '*' jboss7.status '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' - """ + """ log.debug("======================== MODULE FUNCTION: jboss7.status") if host is None and server_config is None: operation = ":read-attribute(name=server-state)" @@ -85,7 +85,7 @@ def stop_server(jboss_config, host=None): salt '*' jboss7.stop_server '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' - """ + """ log.debug("======================== MODULE FUNCTION: jboss7.stop_server") if host is None: operation = ":shutdown" @@ -124,7 +124,7 @@ def reload_(jboss_config, host=None): salt '*' jboss7.reload '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' - """ + """ log.debug("======================== MODULE FUNCTION: jboss7.reload") if host is None: operation = ":reload" @@ -306,8 +306,10 @@ def __get_datasource_resource_description(jboss_config, name, profile=None): profile, ) - operation = '/subsystem=datasources/data-source="{name}":read-resource-description'.format( - name=name + operation = ( + '/subsystem=datasources/data-source="{name}":read-resource-description'.format( + name=name + ) ) if profile is not None: operation = '/profile="{profile}"'.format(profile=profile) + operation @@ -332,7 +334,7 @@ def read_datasource(jboss_config, name, profile=None): .. code-block:: bash salt '*' jboss7.read_datasource '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' - """ + """ log.debug( "======================== MODULE FUNCTION: jboss7.read_datasource, name=%s", name, @@ -394,7 +396,7 @@ def update_simple_binding(jboss_config, binding_name, value, profile=None): .. code-block:: bash salt '*' jboss7.update_simple_binding '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' my_binding_name my_binding_value - """ + """ log.debug( "======================== MODULE FUNCTION: jboss7.update_simple_binding, binding_name=%s, value=%s, profile=%s", binding_name, @@ -425,7 +427,7 @@ def read_simple_binding(jboss_config, binding_name, profile=None): .. code-block:: bash salt '*' jboss7.read_simple_binding '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' my_binding_name - """ + """ log.debug( "======================== MODULE FUNCTION: jboss7.read_simple_binding, %s", binding_name, @@ -502,7 +504,7 @@ def remove_datasource(jboss_config, name, profile=None): .. code-block:: bash salt '*' jboss7.remove_datasource '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' my_datasource_name - """ + """ log.debug( "======================== MODULE FUNCTION: jboss7.remove_datasource, name=%s, profile=%s", name, @@ -532,7 +534,7 @@ def deploy(jboss_config, source_file): .. code-block:: bash salt '*' jboss7.deploy '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' /opt/deploy_files/my_deploy - """ + """ log.debug( "======================== MODULE FUNCTION: jboss7.deploy, source_file=%s", source_file, @@ -556,7 +558,7 @@ def list_deployments(jboss_config): salt '*' jboss7.list_deployments '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' - """ + """ log.debug("======================== MODULE FUNCTION: jboss7.list_deployments") command_result = __salt__["jboss7_cli.run_command"](jboss_config, "deploy") deployments = [] @@ -580,7 +582,7 @@ def undeploy(jboss_config, deployment): .. code-block:: bash salt '*' jboss7.undeploy '{"cli_path": "integration.modules.sysmod.SysModuleTest.test_valid_docs", "controller": "10.11.12.13:9999", "cli_user": "jbossadm", "cli_password": "jbossadm"}' my_deployment - """ + """ log.debug( "======================== MODULE FUNCTION: jboss7.undeploy, deployment=%s", deployment, diff --git a/salt/modules/junos.py b/salt/modules/junos.py index 24867abd474..8c964b8293a 100644 --- a/salt/modules/junos.py +++ b/salt/modules/junos.py @@ -1909,9 +1909,10 @@ def get_table( ret["table"][table]["args"] = args ret["table"][table]["command"] = data.GET_CMD except ConnectClosedError: - ret["message"] = ( - "Got ConnectClosedError exception. Connection lost " - "with {}".format(str(conn)) + ret[ + "message" + ] = "Got ConnectClosedError exception. Connection lost " "with {}".format( + str(conn) ) ret["out"] = False _restart_connection() diff --git a/salt/modules/k8s.py b/salt/modules/k8s.py index 25c8a9aa081..d0a8f8c390c 100644 --- a/salt/modules/k8s.py +++ b/salt/modules/k8s.py @@ -63,7 +63,7 @@ def _guess_apiserver(apiserver_url=None): def _kpost(url, data): - """ create any object in kubernetes based on URL """ + """create any object in kubernetes based on URL""" # Prepare headers headers = {"Content-Type": "application/json"} @@ -80,7 +80,7 @@ def _kpost(url, data): def _kput(url, data): - """ put any object in kubernetes based on URL """ + """put any object in kubernetes based on URL""" # Prepare headers headers = {"Content-Type": "application/json"} @@ -96,7 +96,7 @@ def _kput(url, data): def _kpatch(url, data): - """ patch any object in kubernetes based on URL """ + """patch any object in kubernetes based on URL""" # Prepare headers headers = {"Content-Type": "application/json-patch+json"} @@ -126,8 +126,8 @@ def _kname(obj): def _is_dns_subdomain(name): - """ Check that name is DNS subdomain: One or more lowercase rfc1035/rfc1123 - labels separated by '.' with a maximum length of 253 characters """ + """Check that name is DNS subdomain: One or more lowercase rfc1035/rfc1123 + labels separated by '.' with a maximum length of 253 characters""" dns_subdomain = re.compile(r"""^[a-z0-9\.-]{1,253}$""") if dns_subdomain.match(name): @@ -139,10 +139,10 @@ def _is_dns_subdomain(name): def _is_port_name(name): - """ Check that name is IANA service: An alphanumeric (a-z, and 0-9) string, + """Check that name is IANA service: An alphanumeric (a-z, and 0-9) string, with a maximum length of 15 characters, with the '-' character allowed anywhere except the first or the last character or adjacent to another '-' - character, it must contain at least a (a-z) character """ + character, it must contain at least a (a-z) character""" port_name = re.compile("""^[a-z0-9]{1,15}$""") if port_name.match(name): @@ -152,10 +152,10 @@ def _is_port_name(name): def _is_dns_label(name): - """ Check that name is DNS label: An alphanumeric (a-z, and 0-9) string, + """Check that name is DNS label: An alphanumeric (a-z, and 0-9) string, with a maximum length of 63 characters, with the '-' character allowed anywhere except the first or last character, suitable for use as a hostname - or segment in a domain name """ + or segment in a domain name""" dns_label = re.compile(r"""^[a-z0-9][a-z0-9\.-]{1,62}$""") if dns_label.match(name): @@ -396,7 +396,7 @@ def _get_namespaces(apiserver_url, name=""): def _create_namespace(namespace, apiserver_url): - """ create namespace on the defined k8s cluster """ + """create namespace on the defined k8s cluster""" # Prepare URL url = "{}/api/v1/namespaces".format(apiserver_url) # Prepare data @@ -507,7 +507,7 @@ def _update_secret(namespace, name, data, apiserver_url): def _create_secret(namespace, name, data, apiserver_url): - """ create namespace on the defined k8s cluster """ + """create namespace on the defined k8s cluster""" # Prepare URL url = "{}/api/v1/namespaces/{}/secrets".format(apiserver_url, namespace) # Prepare data diff --git a/salt/modules/linux_ip.py b/salt/modules/linux_ip.py index d8620c983fa..b56d64f6a1a 100644 --- a/salt/modules/linux_ip.py +++ b/salt/modules/linux_ip.py @@ -170,7 +170,10 @@ def _hex_to_octets(addr): Convert hex fields from /proc/net/route to octects """ return "{}:{}:{}:{}".format( - int(addr[6:8], 16), int(addr[4:6], 16), int(addr[2:4], 16), int(addr[0:2], 16), + int(addr[6:8], 16), + int(addr[4:6], 16), + int(addr[2:4], 16), + int(addr[0:2], 16), ) diff --git a/salt/modules/logadm.py b/salt/modules/logadm.py index aa276badc18..2587ac7d4e2 100644 --- a/salt/modules/logadm.py +++ b/salt/modules/logadm.py @@ -295,7 +295,10 @@ def rotate(name, pattern=None, conf_file=default_conf, **kwargs): command = "logadm -f {}".format(conf_file) for arg, val in kwargs.items(): if arg in option_toggles.values() and val: - command = "{} {}".format(command, _arg2opt(arg),) + command = "{} {}".format( + command, + _arg2opt(arg), + ) elif arg in option_flags.values(): command = "{} {} {}".format(command, _arg2opt(arg), _quote_args(str(val))) elif arg != "log_file": diff --git a/salt/modules/lxc.py b/salt/modules/lxc.py index 2d6a227a2c8..3ae206208d9 100644 --- a/salt/modules/lxc.py +++ b/salt/modules/lxc.py @@ -1630,17 +1630,20 @@ def init( run(name, "rm -f '{}'".format(SEED_MARKER), path=path, python_shell=False) gid = "/.lxc.initial_seed" gids = [gid, "/lxc.initial_seed"] - if any( - retcode( - name, - "test -e {}".format(x), - path=path, - chroot_fallback=True, - ignore_retcode=True, + if ( + any( + retcode( + name, + "test -e {}".format(x), + path=path, + chroot_fallback=True, + ignore_retcode=True, + ) + == 0 + for x in gids ) - == 0 - for x in gids - ) or not ret.get("result", True): + or not ret.get("result", True) + ): pass elif seed or seed_cmd: if seed: @@ -4373,7 +4376,10 @@ def write_conf(conf_file, conf): elif isinstance(line, dict): for key in list(line.keys()): out_line = None - if isinstance(line[key], (str, (str,), (int,), float),): + if isinstance( + line[key], + (str, (str,), (int,), float), + ): out_line = " = ".join((key, "{}".format(line[key]))) elif isinstance(line[key], dict): out_line = " = ".join((key, line[key]["value"])) diff --git a/salt/modules/lxd.py b/salt/modules/lxd.py index 1be1c4334d7..03d9023c8ad 100644 --- a/salt/modules/lxd.py +++ b/salt/modules/lxd.py @@ -212,7 +212,9 @@ def init( ) if "error:" in output: - raise CommandExecutionError(output[output.index("error:") + 7 :],) + raise CommandExecutionError( + output[output.index("error:") + 7 :], + ) return output @@ -239,11 +241,16 @@ def config_set(key, value): salt '*' lxd.config_set core.trust_password blah """ - cmd = 'lxc config set "{}" "{}"'.format(key, value,) + cmd = 'lxc config set "{}" "{}"'.format( + key, + value, + ) output = __salt__["cmd.run"](cmd) if "error:" in output: - raise CommandExecutionError(output[output.index("error:") + 7 :],) + raise CommandExecutionError( + output[output.index("error:") + 7 :], + ) return ('Config value "{}" successfully set.'.format(key),) @@ -268,7 +275,9 @@ def config_get(key): output = __salt__["cmd.run"](cmd) if "error:" in output: - raise CommandExecutionError(output[output.index("error:") + 7 :],) + raise CommandExecutionError( + output[output.index("error:") + 7 :], + ) return output @@ -311,7 +320,14 @@ def pylxd_client_get(remote_addr=None, cert=None, key=None, verify_cert=True): """ - pool_key = "|".join((str(remote_addr), str(cert), str(key), str(verify_cert),)) + pool_key = "|".join( + ( + str(remote_addr), + str(cert), + str(key), + str(verify_cert), + ) + ) if pool_key in _connection_pool: log.debug('Returning the client "%s" from our connection pool', remote_addr) @@ -358,7 +374,12 @@ def pylxd_client_get(remote_addr=None, cert=None, key=None, verify_cert=True): verify_cert, ) client = pylxd.Client( - endpoint=remote_addr, cert=(cert, key,), verify=verify_cert + endpoint=remote_addr, + cert=( + cert, + key, + ), + verify=verify_cert, ) except pylxd.exceptions.ClientConnectionFailed: raise CommandExecutionError("Failed to connect to '{}'".format(remote_addr)) @@ -378,7 +399,7 @@ def pylxd_client_get(remote_addr=None, cert=None, key=None, verify_cert=True): def pylxd_save_object(obj): - """ Saves an object (profile/image/container) and + """Saves an object (profile/image/container) and translate its execpetion on failure obj : @@ -687,38 +708,38 @@ def container_create( def container_get( name=None, remote_addr=None, cert=None, key=None, verify_cert=True, _raw=False ): - """ Gets a container from the LXD + """Gets a container from the LXD - name : - The name of the container to get. + name : + The name of the container to get. - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - _raw : - Return the pylxd object, this is internal and by states in use. + _raw : + Return the pylxd object, this is internal and by states in use. """ client = pylxd_client_get(remote_addr, cert, key, verify_cert) @@ -1092,57 +1113,57 @@ def container_migrate( src_key=None, src_verify_cert=None, ): - """ Migrate a container. + """Migrate a container. - If the container is running, it either must be shut down - first (use stop_and_start=True) or criu must be installed - on the source and destination machines. + If the container is running, it either must be shut down + first (use stop_and_start=True) or criu must be installed + on the source and destination machines. - For this operation both certs need to be authenticated, - use :mod:`lxd.authenticate ~/.config/lxc/client.crt ~/.config/lxc/client.key false - salt '*' lxd.authenticate https://srv02:8443 ~/.config/lxc/client.crt ~/.config/lxc/client.key false + # Authorize + salt '*' lxd.authenticate https://srv01:8443 ~/.config/lxc/client.crt ~/.config/lxc/client.key false + salt '*' lxd.authenticate https://srv02:8443 ~/.config/lxc/client.crt ~/.config/lxc/client.key false - # Migrate phpmyadmin from srv01 to srv02 - salt '*' lxd.container_migrate phpmyadmin stop_and_start=true remote_addr=https://srv02:8443 cert=~/.config/lxc/client.crt key=~/.config/lxc/client.key verify_cert=False src_remote_addr=https://srv01:8443 + # Migrate phpmyadmin from srv01 to srv02 + salt '*' lxd.container_migrate phpmyadmin stop_and_start=true remote_addr=https://srv02:8443 cert=~/.config/lxc/client.crt key=~/.config/lxc/client.key verify_cert=False src_remote_addr=https://srv01:8443 """ if src_cert is None: src_cert = cert @@ -1852,10 +1873,16 @@ def container_execute( result = container.execute(cmd) saltresult = {} if not hasattr(result, "exit_code"): - saltresult = dict(exit_code=0, stdout=result[0], stderr=result[1],) + saltresult = dict( + exit_code=0, + stdout=result[0], + stderr=result[1], + ) else: saltresult = dict( - exit_code=result.exit_code, stdout=result.stdout, stderr=result.stderr, + exit_code=result.exit_code, + stdout=result.stdout, + stderr=result.stderr, ) except pylxd.exceptions.NotFound as e: # TODO: Using exit_code 0 here is not always right, @@ -1877,43 +1904,43 @@ def container_execute( def profile_list( list_names=False, remote_addr=None, cert=None, key=None, verify_cert=True ): - """ Lists all profiles from the LXD. + """Lists all profiles from the LXD. - list_names : + list_names : - Return a list of names instead of full blown dicts. + Return a list of names instead of full blown dicts. - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - CLI Examples: + CLI Examples: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.profile_list true --out=json - salt '*' lxd.profile_list --out=json + salt '*' lxd.profile_list true --out=json + salt '*' lxd.profile_list --out=json """ client = pylxd_client_get(remote_addr, cert, key, verify_cert) @@ -1935,59 +1962,59 @@ def profile_create( key=None, verify_cert=True, ): - """ Creates a profile. + """Creates a profile. - name : - The name of the profile to get. + name : + The name of the profile to get. - config : - A config dict or None (None = unset). + config : + A config dict or None (None = unset). - Can also be a list: - [{'key': 'boot.autostart', 'value': 1}, - {'key': 'security.privileged', 'value': '1'}] + Can also be a list: + [{'key': 'boot.autostart', 'value': 1}, + {'key': 'security.privileged', 'value': '1'}] - devices : - A device dict or None (None = unset). + devices : + A device dict or None (None = unset). - description : - A description string or None (None = unset). + description : + A description string or None (None = unset). - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - CLI Examples: + CLI Examples: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.profile_create autostart config="{boot.autostart: 1, boot.autostart.delay: 2, boot.autostart.priority: 1}" - salt '*' lxd.profile_create shared_mounts devices="{shared_mount: {type: 'disk', source: '/home/shared', path: '/home/shared'}}" + salt '*' lxd.profile_create autostart config="{boot.autostart: 1, boot.autostart.delay: 2, boot.autostart.priority: 1}" + salt '*' lxd.profile_create shared_mounts devices="{shared_mount: {type: 'disk', source: '/home/shared', path: '/home/shared'}}" - See the `lxd-docs`_ for the details about the config and devices dicts. + See the `lxd-docs`_ for the details about the config and devices dicts. - .. _lxd-docs: https://github.com/lxc/lxd/blob/master/doc/rest-api.md#post-10 + .. _lxd-docs: https://github.com/lxc/lxd/blob/master/doc/rest-api.md#post-10 """ client = pylxd_client_get(remote_addr, cert, key, verify_cert) @@ -2008,44 +2035,44 @@ def profile_create( def profile_get( name, remote_addr=None, cert=None, key=None, verify_cert=True, _raw=False ): - """ Gets a profile from the LXD + """Gets a profile from the LXD - name : - The name of the profile to get. + name : + The name of the profile to get. - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - _raw : - Return the pylxd object, this is internal and by states in use. + _raw : + Return the pylxd object, this is internal and by states in use. - CLI Examples: + CLI Examples: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.profile_get autostart + salt '*' lxd.profile_get autostart """ client = pylxd_client_get(remote_addr, cert, key, verify_cert) @@ -2062,41 +2089,41 @@ def profile_get( def profile_delete(name, remote_addr=None, cert=None, key=None, verify_cert=True): - """ Deletes a profile. + """Deletes a profile. - name : - The name of the profile to delete. + name : + The name of the profile to delete. - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - CLI Example: + CLI Example: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.profile_delete shared_mounts + salt '*' lxd.profile_delete shared_mounts """ profile = profile_get(name, remote_addr, cert, key, verify_cert, _raw=True) @@ -2107,44 +2134,44 @@ def profile_delete(name, remote_addr=None, cert=None, key=None, verify_cert=True def profile_config_get( name, config_key, remote_addr=None, cert=None, key=None, verify_cert=True ): - """ Get a profile config item. + """Get a profile config item. - name : - The name of the profile to get the config item from. + name : + The name of the profile to get the config item from. - config_key : - The key for the item to retrieve. + config_key : + The key for the item to retrieve. - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - CLI Example: + CLI Example: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.profile_config_get autostart boot.autostart + salt '*' lxd.profile_config_get autostart boot.autostart """ profile = profile_get(name, remote_addr, cert, key, verify_cert, _raw=True) @@ -2160,47 +2187,47 @@ def profile_config_set( key=None, verify_cert=True, ): - """ Set a profile config item. + """Set a profile config item. - name : - The name of the profile to set the config item to. + name : + The name of the profile to set the config item to. - config_key : - The items key. + config_key : + The items key. - config_value : - Its items value. + config_value : + Its items value. - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - CLI Example: + CLI Example: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.profile_config_set autostart boot.autostart 0 + salt '*' lxd.profile_config_set autostart boot.autostart 0 """ profile = profile_get(name, remote_addr, cert, key, verify_cert, _raw=True) @@ -2210,44 +2237,44 @@ def profile_config_set( def profile_config_delete( name, config_key, remote_addr=None, cert=None, key=None, verify_cert=True ): - """ Delete a profile config item. + """Delete a profile config item. - name : - The name of the profile to delete the config item. + name : + The name of the profile to delete the config item. - config_key : - The config key for the value to retrieve. + config_key : + The config key for the value to retrieve. - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - CLI Example: + CLI Example: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.profile_config_delete autostart boot.autostart.delay + salt '*' lxd.profile_config_delete autostart boot.autostart.delay """ profile = profile_get(name, remote_addr, cert, key, verify_cert, _raw=True) @@ -2257,44 +2284,44 @@ def profile_config_delete( def profile_device_get( name, device_name, remote_addr=None, cert=None, key=None, verify_cert=True ): - """ Get a profile device. + """Get a profile device. - name : - The name of the profile to get the device from. + name : + The name of the profile to get the device from. - device_name : - The name of the device to retrieve. + device_name : + The name of the device to retrieve. - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - CLI Example: + CLI Example: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.profile_device_get default eth0 + salt '*' lxd.profile_device_get default eth0 """ profile = profile_get(name, remote_addr, cert, key, verify_cert, _raw=True) @@ -2311,44 +2338,44 @@ def profile_device_set( verify_cert=True, **kwargs ): - """ Set a profile device. + """Set a profile device. - name : - The name of the profile to set the device to. + name : + The name of the profile to set the device to. - device_name : - The name of the device to set. + device_name : + The name of the device to set. - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - CLI Example: + CLI Example: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.profile_device_set autostart eth1 nic nictype=bridged parent=lxdbr0 + salt '*' lxd.profile_device_set autostart eth1 nic nictype=bridged parent=lxdbr0 """ profile = profile_get(name, remote_addr, cert, key, verify_cert, _raw=True) @@ -2363,44 +2390,44 @@ def profile_device_set( def profile_device_delete( name, device_name, remote_addr=None, cert=None, key=None, verify_cert=True ): - """ Delete a profile device. + """Delete a profile device. - name : - The name of the profile to delete the device. + name : + The name of the profile to delete the device. - device_name : - The name of the device to delete. + device_name : + The name of the device to delete. - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - CLI Example: + CLI Example: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.profile_device_delete autostart eth1 + salt '*' lxd.profile_device_delete autostart eth1 """ profile = profile_get(name, remote_addr, cert, key, verify_cert, _raw=True) @@ -2414,44 +2441,44 @@ def profile_device_delete( def image_list( list_aliases=False, remote_addr=None, cert=None, key=None, verify_cert=True ): - """ Lists all images from the LXD. + """Lists all images from the LXD. - list_aliases : + list_aliases : - Return a dict with the fingerprint as key and - a list of aliases as value instead. + Return a dict with the fingerprint as key and + a list of aliases as value instead. - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - CLI Examples: + CLI Examples: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.image_list true --out=json - salt '*' lxd.image_list --out=json + salt '*' lxd.image_list true --out=json + salt '*' lxd.image_list --out=json """ client = pylxd_client_get(remote_addr, cert, key, verify_cert) @@ -2465,44 +2492,44 @@ def image_list( def image_get( fingerprint, remote_addr=None, cert=None, key=None, verify_cert=True, _raw=False ): - """ Get an image by its fingerprint + """Get an image by its fingerprint - fingerprint : - The fingerprint of the image to retrieve + fingerprint : + The fingerprint of the image to retrieve - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - _raw : False - Return the raw pylxd object or a dict of it? + _raw : False + Return the raw pylxd object or a dict of it? - CLI Examples: + CLI Examples: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.image_get + salt '*' lxd.image_get """ client = pylxd_client_get(remote_addr, cert, key, verify_cert) @@ -2523,44 +2550,44 @@ def image_get( def image_get_by_alias( alias, remote_addr=None, cert=None, key=None, verify_cert=True, _raw=False ): - """ Get an image by an alias + """Get an image by an alias - alias : - The alias of the image to retrieve + alias : + The alias of the image to retrieve - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - _raw : False - Return the raw pylxd object or a dict of it? + _raw : False + Return the raw pylxd object or a dict of it? - CLI Examples: + CLI Examples: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.image_get_by_alias xenial/amd64 + salt '*' lxd.image_get_by_alias xenial/amd64 """ client = pylxd_client_get(remote_addr, cert, key, verify_cert) @@ -2577,42 +2604,42 @@ def image_get_by_alias( def image_delete(image, remote_addr=None, cert=None, key=None, verify_cert=True): - """ Delete an image by an alias or fingerprint + """Delete an image by an alias or fingerprint - name : - The alias or fingerprint of the image to delete, - can be a obj for the states. + name : + The alias or fingerprint of the image to delete, + can be a obj for the states. - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - CLI Examples: + CLI Examples: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.image_delete xenial/amd64 + salt '*' lxd.image_delete xenial/amd64 """ image = _verify_image(image, remote_addr, cert, key, verify_cert) @@ -2633,56 +2660,56 @@ def image_from_simplestreams( auto_update=False, _raw=False, ): - """ Create an image from simplestreams + """Create an image from simplestreams - server : - Simplestreams server URI + server : + Simplestreams server URI - alias : - The alias of the image to retrieve + alias : + The alias of the image to retrieve - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - aliases : [] - List of aliases to append to the copied image + aliases : [] + List of aliases to append to the copied image - public : False - Make this image public available + public : False + Make this image public available - auto_update : False - Should LXD auto update that image? + auto_update : False + Should LXD auto update that image? - _raw : False - Return the raw pylxd object or a dict of the image? + _raw : False + Return the raw pylxd object or a dict of the image? - CLI Examples: + CLI Examples: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.image_from_simplestreams "https://cloud-images.ubuntu.com/releases" "trusty/amd64" aliases='["t", "trusty/amd64"]' auto_update=True + salt '*' lxd.image_from_simplestreams "https://cloud-images.ubuntu.com/releases" "trusty/amd64" aliases='["t", "trusty/amd64"]' auto_update=True """ if aliases is None: aliases = [] @@ -2717,53 +2744,53 @@ def image_from_url( auto_update=False, _raw=False, ): - """ Create an image from an url + """Create an image from an url - url : - The URL from where to download the image + url : + The URL from where to download the image - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - aliases : [] - List of aliases to append to the copied image + aliases : [] + List of aliases to append to the copied image - public : False - Make this image public available + public : False + Make this image public available - auto_update : False - Should LXD auto update that image? + auto_update : False + Should LXD auto update that image? - _raw : False - Return the raw pylxd object or a dict of the image? + _raw : False + Return the raw pylxd object or a dict of the image? - CLI Examples: + CLI Examples: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.image_from_url https://dl.stgraber.org/lxd aliases='["busybox-amd64"]' + salt '*' lxd.image_from_url https://dl.stgraber.org/lxd aliases='["busybox-amd64"]' """ if aliases is None: aliases = [] @@ -2798,53 +2825,53 @@ def image_from_file( saltenv="base", _raw=False, ): - """ Create an image from a file + """Create an image from a file - filename : - The filename of the rootfs + filename : + The filename of the rootfs - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - aliases : [] - List of aliases to append to the copied image + aliases : [] + List of aliases to append to the copied image - public : False - Make this image public available + public : False + Make this image public available - saltenv : base - The saltenv to use for salt:// copies + saltenv : base + The saltenv to use for salt:// copies - _raw : False - Return the raw pylxd object or a dict of the image? + _raw : False + Return the raw pylxd object or a dict of the image? - CLI Examples: + CLI Examples: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.image_from_file salt://lxd/files/busybox.tar.xz aliases=["busybox-amd64"] + salt '*' lxd.image_from_file salt://lxd/files/busybox.tar.xz aliases=["busybox-amd64"] """ if aliases is None: aliases = [] @@ -2886,7 +2913,7 @@ def image_copy_lxd( auto_update=None, _raw=False, ): - """ Copy an image from another LXD instance + """Copy an image from another LXD instance source : An alias or a fingerprint of the source. @@ -3004,47 +3031,47 @@ def image_alias_add( key=None, verify_cert=True, ): - """ Create an alias on the given image + """Create an alias on the given image - image : - An image alias, a fingerprint or a image object + image : + An image alias, a fingerprint or a image object - alias : - The alias to add + alias : + The alias to add - description : - Description of the alias + description : + Description of the alias - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - CLI Examples: + CLI Examples: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.image_alias_add xenial/amd64 x "Short version of xenial/amd64" + salt '*' lxd.image_alias_add xenial/amd64 x "Short version of xenial/amd64" """ image = _verify_image(image, remote_addr, cert, key, verify_cert) @@ -3059,44 +3086,44 @@ def image_alias_add( def image_alias_delete( image, alias, remote_addr=None, cert=None, key=None, verify_cert=True ): - """ Delete an alias (this is currently not restricted to the image) + """Delete an alias (this is currently not restricted to the image) - image : - An image alias, a fingerprint or a image object + image : + An image alias, a fingerprint or a image object - alias : - The alias to delete + alias : + The alias to delete - remote_addr : - An URL to a remote Server, you also have to give cert and key if - you provide remote_addr and its a TCP Address! + remote_addr : + An URL to a remote Server, you also have to give cert and key if + you provide remote_addr and its a TCP Address! - Examples: - https://myserver.lan:8443 - /var/lib/mysocket.sock + Examples: + https://myserver.lan:8443 + /var/lib/mysocket.sock - cert : - PEM Formatted SSL Certificate. + cert : + PEM Formatted SSL Certificate. - Examples: - ~/.config/lxc/client.crt + Examples: + ~/.config/lxc/client.crt - key : - PEM Formatted SSL Key. + key : + PEM Formatted SSL Key. - Examples: - ~/.config/lxc/client.key + Examples: + ~/.config/lxc/client.key - verify_cert : True - Wherever to verify the cert, this is by default True - but in the most cases you want to set it off as LXD - normally uses self-signed certificates. + verify_cert : True + Wherever to verify the cert, this is by default True + but in the most cases you want to set it off as LXD + normally uses self-signed certificates. - CLI Examples: + CLI Examples: - .. code-block:: bash + .. code-block:: bash - salt '*' lxd.image_alias_add xenial/amd64 x "Short version of xenial/amd64" + salt '*' lxd.image_alias_add xenial/amd64 x "Short version of xenial/amd64" """ image = _verify_image(image, remote_addr, cert, key, verify_cert) @@ -3361,21 +3388,21 @@ def normalize_input_values(config, devices): def sync_config_devices(obj, newconfig, newdevices, test=False): - """ Syncs the given config and devices with the object - (a profile or a container) - returns a changes dict with all changes made. + """Syncs the given config and devices with the object + (a profile or a container) + returns a changes dict with all changes made. - obj : - The object to sync with / or just test with. + obj : + The object to sync with / or just test with. - newconfig: - The new config to check with the obj. + newconfig: + The new config to check with the obj. - newdevices: - The new devices to check with the obj. + newdevices: + The new devices to check with the obj. - test: - Wherever to not change anything and give "Would change" message. + test: + Wherever to not change anything and give "Would change" message. """ changes = {} @@ -3420,9 +3447,10 @@ def sync_config_devices(obj, newconfig, newdevices, test=False): if newconfig[k] != obj.config[k]: if not test: - config_changes[k] = ( - 'Changed config key "{}" to "{}", ' - 'its value was "{}"'.format(k, newconfig[k], obj.config[k]) + config_changes[ + k + ] = 'Changed config key "{}" to "{}", ' 'its value was "{}"'.format( + k, newconfig[k], obj.config[k] ) obj.config[k] = newconfig[k] else: @@ -3507,13 +3535,13 @@ def sync_config_devices(obj, newconfig, newdevices, test=False): def _set_property_dict_item(obj, prop, key, value): - """ Sets the dict item key of the attr from obj. + """Sets the dict item key of the attr from obj. - Basicaly it does getattr(obj, prop)[key] = value. + Basicaly it does getattr(obj, prop)[key] = value. - For the disk device we added some checks to make - device changes on the CLI saver. + For the disk device we added some checks to make + device changes on the CLI saver. """ attr = getattr(obj, prop) if prop == "devices": diff --git a/salt/modules/mac_assistive.py b/salt/modules/mac_assistive.py index ada7d3e96be..2b2771abe1a 100644 --- a/salt/modules/mac_assistive.py +++ b/salt/modules/mac_assistive.py @@ -64,15 +64,12 @@ def install(app_id, enable=True): ) client_type = _client_type(app_id) enable_str = "1" if enable else "0" - cmd = ( - 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' - "\"INSERT or REPLACE INTO access VALUES('kTCCServiceAccessibility','{}',{},{},1,NULL{}{})\"".format( - app_id, - client_type, - enable_str, - ",NULL" if ge_el_capitan else "", - ",NULL,NULL,NULL,NULL,''" if ge_mojave else "", - ) + cmd = 'sqlite3 "/Library/Application Support/com.apple.TCC/TCC.db" ' "\"INSERT or REPLACE INTO access VALUES('kTCCServiceAccessibility','{}',{},{},1,NULL{}{})\"".format( + app_id, + client_type, + enable_str, + ",NULL" if ge_el_capitan else "", + ",NULL,NULL,NULL,NULL,''" if ge_mojave else "", ) call = __salt__["cmd.run_all"](cmd, output_loglevel="debug", python_shell=False) diff --git a/salt/modules/mac_power.py b/salt/modules/mac_power.py index 4eb0dfa009c..01fc561e834 100644 --- a/salt/modules/mac_power.py +++ b/salt/modules/mac_power.py @@ -120,7 +120,12 @@ def set_sleep(minutes): state = [] for check in (get_computer_sleep, get_display_sleep, get_harddisk_sleep): - state.append(salt.utils.mac_utils.confirm_updated(value, check,)) + state.append( + salt.utils.mac_utils.confirm_updated( + value, + check, + ) + ) return all(state) @@ -163,7 +168,10 @@ def set_computer_sleep(minutes): cmd = "systemsetup -setcomputersleep {}".format(value) salt.utils.mac_utils.execute_return_success(cmd) - return salt.utils.mac_utils.confirm_updated(str(value), get_computer_sleep,) + return salt.utils.mac_utils.confirm_updated( + str(value), + get_computer_sleep, + ) def get_display_sleep(): @@ -205,7 +213,10 @@ def set_display_sleep(minutes): cmd = "systemsetup -setdisplaysleep {}".format(value) salt.utils.mac_utils.execute_return_success(cmd) - return salt.utils.mac_utils.confirm_updated(str(value), get_display_sleep,) + return salt.utils.mac_utils.confirm_updated( + str(value), + get_display_sleep, + ) def get_harddisk_sleep(): @@ -247,7 +258,10 @@ def set_harddisk_sleep(minutes): cmd = "systemsetup -setharddisksleep {}".format(value) salt.utils.mac_utils.execute_return_success(cmd) - return salt.utils.mac_utils.confirm_updated(str(value), get_harddisk_sleep,) + return salt.utils.mac_utils.confirm_updated( + str(value), + get_harddisk_sleep, + ) def get_wake_on_modem(): @@ -292,7 +306,10 @@ def set_wake_on_modem(enabled): cmd = "systemsetup -setwakeonmodem {}".format(state) salt.utils.mac_utils.execute_return_success(cmd) - return salt.utils.mac_utils.confirm_updated(state, get_wake_on_modem,) + return salt.utils.mac_utils.confirm_updated( + state, + get_wake_on_modem, + ) def get_wake_on_network(): @@ -339,7 +356,10 @@ def set_wake_on_network(enabled): cmd = "systemsetup -setwakeonnetworkaccess {}".format(state) salt.utils.mac_utils.execute_return_success(cmd) - return salt.utils.mac_utils.confirm_updated(state, get_wake_on_network,) + return salt.utils.mac_utils.confirm_updated( + state, + get_wake_on_network, + ) def get_restart_power_failure(): @@ -386,7 +406,10 @@ def set_restart_power_failure(enabled): cmd = "systemsetup -setrestartpowerfailure {}".format(state) salt.utils.mac_utils.execute_return_success(cmd) - return salt.utils.mac_utils.confirm_updated(state, get_restart_power_failure,) + return salt.utils.mac_utils.confirm_updated( + state, + get_restart_power_failure, + ) def get_restart_freeze(): @@ -482,4 +505,7 @@ def set_sleep_on_power_button(enabled): cmd = "systemsetup -setallowpowerbuttontosleepcomputer {}".format(state) salt.utils.mac_utils.execute_return_success(cmd) - return salt.utils.mac_utils.confirm_updated(state, get_sleep_on_power_button,) + return salt.utils.mac_utils.confirm_updated( + state, + get_sleep_on_power_button, + ) diff --git a/salt/modules/mac_system.py b/salt/modules/mac_system.py index bce0736a6e9..8d5cbe36fed 100644 --- a/salt/modules/mac_system.py +++ b/salt/modules/mac_system.py @@ -288,7 +288,9 @@ def set_remote_events(enable): __utils__["mac_utils.execute_return_success"](cmd) return __utils__["mac_utils.confirm_updated"]( - state, get_remote_events, normalize_ret=True, + state, + get_remote_events, + normalize_ret=True, ) @@ -328,7 +330,10 @@ def set_computer_name(name): cmd = 'scutil --set ComputerName "{}"'.format(name) __utils__["mac_utils.execute_return_success"](cmd) - return __utils__["mac_utils.confirm_updated"](name, get_computer_name,) + return __utils__["mac_utils.confirm_updated"]( + name, + get_computer_name, + ) def get_subnet_name(): @@ -373,7 +378,10 @@ def set_subnet_name(name): cmd = 'systemsetup -setlocalsubnetname "{}"'.format(name) __utils__["mac_utils.execute_return_success"](cmd) - return __utils__["mac_utils.confirm_updated"](name, get_subnet_name,) + return __utils__["mac_utils.confirm_updated"]( + name, + get_subnet_name, + ) def get_startup_disk(): @@ -440,7 +448,10 @@ def set_startup_disk(path): cmd = "systemsetup -setstartupdisk {}".format(path) __utils__["mac_utils.execute_return_result"](cmd) - return __utils__["mac_utils.confirm_updated"](path, get_startup_disk,) + return __utils__["mac_utils.confirm_updated"]( + path, + get_startup_disk, + ) def get_restart_delay(): @@ -504,7 +515,10 @@ def set_restart_delay(seconds): cmd = "systemsetup -setwaitforstartupafterpowerfailure {}".format(seconds) __utils__["mac_utils.execute_return_success"](cmd) - return __utils__["mac_utils.confirm_updated"](seconds, get_restart_delay,) + return __utils__["mac_utils.confirm_updated"]( + seconds, + get_restart_delay, + ) def get_disable_keyboard_on_lock(): @@ -558,7 +572,9 @@ def set_disable_keyboard_on_lock(enable): __utils__["mac_utils.execute_return_success"](cmd) return __utils__["mac_utils.confirm_updated"]( - state, get_disable_keyboard_on_lock, normalize_ret=True, + state, + get_disable_keyboard_on_lock, + normalize_ret=True, ) @@ -628,4 +644,7 @@ def set_boot_arch(arch="default"): cmd = "systemsetup -setkernelbootarchitecture {}".format(arch) __utils__["mac_utils.execute_return_success"](cmd) - return __utils__["mac_utils.confirm_updated"](arch, get_boot_arch,) + return __utils__["mac_utils.confirm_updated"]( + arch, + get_boot_arch, + ) diff --git a/salt/modules/marathon.py b/salt/modules/marathon.py index cec5eb48fae..c749f28015e 100644 --- a/salt/modules/marathon.py +++ b/salt/modules/marathon.py @@ -59,7 +59,9 @@ def apps(): salt marathon-minion-id marathon.apps """ response = salt.utils.http.query( - "{}/v2/apps".format(_base_url()), decode_type="json", decode=True, + "{}/v2/apps".format(_base_url()), + decode_type="json", + decode=True, ) return {"apps": [app["id"] for app in response["dict"]["apps"]]} @@ -88,7 +90,9 @@ def app(id): salt marathon-minion-id marathon.app my-app """ response = salt.utils.http.query( - "{}/v2/apps/{}".format(_base_url(), id), decode_type="json", decode=True, + "{}/v2/apps/{}".format(_base_url(), id), + decode_type="json", + decode=True, ) return response["dict"] @@ -159,7 +163,9 @@ def info(): salt marathon-minion-id marathon.info """ response = salt.utils.http.query( - "{}/v2/info".format(_base_url()), decode_type="json", decode=True, + "{}/v2/info".format(_base_url()), + decode_type="json", + decode=True, ) return response["dict"] diff --git a/salt/modules/napalm_mod.py b/salt/modules/napalm_mod.py index 99b3b2d6b8b..d52fe306684 100644 --- a/salt/modules/napalm_mod.py +++ b/salt/modules/napalm_mod.py @@ -1067,7 +1067,7 @@ def pyeapi_call(method, *args, **kwargs): salt '*' napalm.pyeapi_call run_commands 'show version' encoding=text salt '*' napalm.pyeapi_call get_config as_string=True - """ + """ pyeapi_kwargs = pyeapi_nxos_api_args(**kwargs) return __salt__["pyeapi.call"](method, *args, **pyeapi_kwargs) @@ -1154,7 +1154,7 @@ def pyeapi_config( .. code-block:: bash salt '*' napalm.pyeapi_config 'ntp server 1.2.3.4' - """ + """ pyeapi_kwargs = pyeapi_nxos_api_args(**kwargs) return __salt__["pyeapi.config"]( commands=commands, diff --git a/salt/modules/napalm_network.py b/salt/modules/napalm_network.py index 38aefb9c13e..95f5dcecf17 100644 --- a/salt/modules/napalm_network.py +++ b/salt/modules/napalm_network.py @@ -122,8 +122,7 @@ def _safe_commit_config(loaded_result, napalm_device): def _safe_dicard_config(loaded_result, napalm_device): - """ - """ + """ """ log.debug("Discarding the config") log.debug(loaded_result) _discarded = discard_config(inherit_napalm_device=napalm_device) diff --git a/salt/modules/network.py b/salt/modules/network.py index 7855820e5aa..95e86df4ccd 100644 --- a/salt/modules/network.py +++ b/salt/modules/network.py @@ -1417,7 +1417,10 @@ def mod_hostname(hostname): if hostname_cmd.endswith("hostnamectl"): result = __salt__["cmd.run_all"]( - "{} set-hostname {}".format(hostname_cmd, hostname,) + "{} set-hostname {}".format( + hostname_cmd, + hostname, + ) ) if result["retcode"] != 0: log.debug( @@ -1480,8 +1483,10 @@ def mod_hostname(hostname): if __grains__["lsb_distrib_id"] == "nilrt": str_hostname = __utils__["stringutils.to_str"](hostname) nirtcfg_cmd = "/usr/local/natinst/bin/nirtcfg" - nirtcfg_cmd += " --set section=SystemSettings,token='Host_Name',value='{}'".format( - str_hostname + nirtcfg_cmd += ( + " --set section=SystemSettings,token='Host_Name',value='{}'".format( + str_hostname + ) ) if __salt__["cmd.run_all"](nirtcfg_cmd)["retcode"] != 0: raise CommandExecutionError( @@ -1817,13 +1822,17 @@ def default_route(family=None): if __grains__["kernel"] == "Linux": default_route["inet"] = ["0.0.0.0", "default"] default_route["inet6"] = ["::/0", "default"] - elif __grains__["os"] in [ - "FreeBSD", - "NetBSD", - "OpenBSD", - "MacOS", - "Darwin", - ] or __grains__["kernel"] in ("SunOS", "AIX"): + elif ( + __grains__["os"] + in [ + "FreeBSD", + "NetBSD", + "OpenBSD", + "MacOS", + "Darwin", + ] + or __grains__["kernel"] in ("SunOS", "AIX") + ): default_route["inet"] = ["default"] default_route["inet6"] = ["default"] else: diff --git a/salt/modules/nexus.py b/salt/modules/nexus.py index f749ce52852..721d7265343 100644 --- a/salt/modules/nexus.py +++ b/salt/modules/nexus.py @@ -55,29 +55,29 @@ def get_latest_snapshot( password=None, ): """ - Gets latest snapshot of the given artifact + Gets latest snapshot of the given artifact - nexus_url - URL of nexus instance - repository - Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots - group_id - Group Id of the artifact - artifact_id - Artifact Id of the artifact - packaging - Packaging type (jar,war,ear,etc) - target_dir - Target directory to download artifact to (default: /tmp) - target_file - Target file to download artifact to (by default it is target_dir/artifact_id-snapshot_version.packaging) - classifier - Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. - username - nexus username. Optional parameter. - password - nexus password. Optional parameter. - """ + nexus_url + URL of nexus instance + repository + Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots + group_id + Group Id of the artifact + artifact_id + Artifact Id of the artifact + packaging + Packaging type (jar,war,ear,etc) + target_dir + Target directory to download artifact to (default: /tmp) + target_file + Target file to download artifact to (by default it is target_dir/artifact_id-snapshot_version.packaging) + classifier + Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. + username + nexus username. Optional parameter. + password + nexus password. Optional parameter. + """ log.debug( "======================== MODULE FUNCTION: nexus.get_latest_snapshot, nexus_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, target_dir=%s, classifier=%s)", nexus_url, @@ -132,31 +132,31 @@ def get_snapshot( password=None, ): """ - Gets snapshot of the desired version of the artifact + Gets snapshot of the desired version of the artifact - nexus_url - URL of nexus instance - repository - Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots - group_id - Group Id of the artifact - artifact_id - Artifact Id of the artifact - packaging - Packaging type (jar,war,ear,etc) - version - Version of the artifact - target_dir - Target directory to download artifact to (default: /tmp) - target_file - Target file to download artifact to (by default it is target_dir/artifact_id-snapshot_version.packaging) - classifier - Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. - username - nexus username. Optional parameter. - password - nexus password. Optional parameter. - """ + nexus_url + URL of nexus instance + repository + Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots + group_id + Group Id of the artifact + artifact_id + Artifact Id of the artifact + packaging + Packaging type (jar,war,ear,etc) + version + Version of the artifact + target_dir + Target directory to download artifact to (default: /tmp) + target_file + Target file to download artifact to (by default it is target_dir/artifact_id-snapshot_version.packaging) + classifier + Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. + username + nexus username. Optional parameter. + password + nexus password. Optional parameter. + """ log.debug( "======================== MODULE FUNCTION: nexus.get_snapshot(nexus_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, version=%s, target_dir=%s, classifier=%s)", nexus_url, @@ -201,27 +201,27 @@ def get_snapshot_version_string( password=None, ): """ - Gets the specific version string of a snapshot of the desired version of the artifact + Gets the specific version string of a snapshot of the desired version of the artifact - nexus_url - URL of nexus instance - repository - Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots - group_id - Group Id of the artifact - artifact_id - Artifact Id of the artifact - packaging - Packaging type (jar,war,ear,etc) - version - Version of the artifact - classifier - Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. - username - nexus username. Optional parameter. - password - nexus password. Optional parameter. - """ + nexus_url + URL of nexus instance + repository + Snapshot repository in nexus to retrieve artifact from, for example: libs-snapshots + group_id + Group Id of the artifact + artifact_id + Artifact Id of the artifact + packaging + Packaging type (jar,war,ear,etc) + version + Version of the artifact + classifier + Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. + username + nexus username. Optional parameter. + password + nexus password. Optional parameter. + """ log.debug( "======================== MODULE FUNCTION: nexus.get_snapshot_version_string(nexus_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, version=%s, classifier=%s)", nexus_url, @@ -262,29 +262,29 @@ def get_latest_release( password=None, ): """ - Gets the latest release of the artifact + Gets the latest release of the artifact - nexus_url - URL of nexus instance - repository - Release repository in nexus to retrieve artifact from, for example: libs-releases - group_id - Group Id of the artifact - artifact_id - Artifact Id of the artifact - packaging - Packaging type (jar,war,ear,etc) - target_dir - Target directory to download artifact to (default: /tmp) - target_file - Target file to download artifact to (by default it is target_dir/artifact_id-version.packaging) - classifier - Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. - username - nexus username. Optional parameter. - password - nexus password. Optional parameter. - """ + nexus_url + URL of nexus instance + repository + Release repository in nexus to retrieve artifact from, for example: libs-releases + group_id + Group Id of the artifact + artifact_id + Artifact Id of the artifact + packaging + Packaging type (jar,war,ear,etc) + target_dir + Target directory to download artifact to (default: /tmp) + target_file + Target file to download artifact to (by default it is target_dir/artifact_id-version.packaging) + classifier + Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. + username + nexus username. Optional parameter. + password + nexus password. Optional parameter. + """ log.debug( "======================== MODULE FUNCTION: nexus.get_latest_release(nexus_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, target_dir=%s, classifier=%s)", nexus_url, @@ -330,31 +330,31 @@ def get_release( password=None, ): """ - Gets the specified release of the artifact + Gets the specified release of the artifact - nexus_url - URL of nexus instance - repository - Release repository in nexus to retrieve artifact from, for example: libs-releases - group_id - Group Id of the artifact - artifact_id - Artifact Id of the artifact - packaging - Packaging type (jar,war,ear,etc) - version - Version of the artifact - target_dir - Target directory to download artifact to (default: /tmp) - target_file - Target file to download artifact to (by default it is target_dir/artifact_id-version.packaging) - classifier - Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. - username - nexus username. Optional parameter. - password - nexus password. Optional parameter. - """ + nexus_url + URL of nexus instance + repository + Release repository in nexus to retrieve artifact from, for example: libs-releases + group_id + Group Id of the artifact + artifact_id + Artifact Id of the artifact + packaging + Packaging type (jar,war,ear,etc) + version + Version of the artifact + target_dir + Target directory to download artifact to (default: /tmp) + target_file + Target file to download artifact to (by default it is target_dir/artifact_id-version.packaging) + classifier + Artifact classifier name (ex: sources,javadoc,etc). Optional parameter. + username + nexus username. Optional parameter. + password + nexus password. Optional parameter. + """ log.debug( "======================== MODULE FUNCTION: nexus.get_release(nexus_url=%s, repository=%s, group_id=%s, artifact_id=%s, packaging=%s, version=%s, target_dir=%s, classifier=%s)", nexus_url, @@ -507,11 +507,13 @@ def _get_release_url( def _get_artifact_metadata_url(nexus_url, repository, group_id, artifact_id): group_url = __get_group_id_subpath(group_id) # for released versions the suffix for the file is same as version - artifact_metadata_url = "{nexus_url}/{repository}/{group_url}/{artifact_id}/maven-metadata.xml".format( - nexus_url=nexus_url, - repository=repository, - group_url=group_url, - artifact_id=artifact_id, + artifact_metadata_url = ( + "{nexus_url}/{repository}/{group_url}/{artifact_id}/maven-metadata.xml".format( + nexus_url=nexus_url, + repository=repository, + group_url=group_url, + artifact_id=artifact_id, + ) ) log.debug("artifact_metadata_url=%s", artifact_metadata_url) return artifact_metadata_url diff --git a/salt/modules/nilrt_ip.py b/salt/modules/nilrt_ip.py index 55162a39f7f..84612d7a17d 100644 --- a/salt/modules/nilrt_ip.py +++ b/salt/modules/nilrt_ip.py @@ -98,12 +98,14 @@ def _get_technologies(): tech = "" technologies = pyconnman.ConnManager().get_technologies() for path, params in technologies: - tech += "{}\n\tName = {}\n\tType = {}\n\tPowered = {}\n\tConnected = {}\n".format( - path, - params["Name"], - params["Type"], - params["Powered"] == 1, - params["Connected"] == 1, + tech += ( + "{}\n\tName = {}\n\tType = {}\n\tPowered = {}\n\tConnected = {}\n".format( + path, + params["Name"], + params["Type"], + params["Powered"] == 1, + params["Connected"] == 1, + ) ) return tech diff --git a/salt/modules/pagerduty_util.py b/salt/modules/pagerduty_util.py index e9a1fba1d37..8f782344925 100644 --- a/salt/modules/pagerduty_util.py +++ b/salt/modules/pagerduty_util.py @@ -41,7 +41,11 @@ def get_users(profile="pagerduty", subdomain=None, api_key=None): """ return _list_items( - "users", "id", profile=profile, subdomain=subdomain, api_key=api_key, + "users", + "id", + profile=profile, + subdomain=subdomain, + api_key=api_key, ) @@ -57,7 +61,11 @@ def get_services(profile="pagerduty", subdomain=None, api_key=None): """ return _list_items( - "services", "id", profile=profile, subdomain=subdomain, api_key=api_key, + "services", + "id", + profile=profile, + subdomain=subdomain, + api_key=api_key, ) @@ -73,7 +81,11 @@ def get_schedules(profile="pagerduty", subdomain=None, api_key=None): """ return _list_items( - "schedules", "id", profile=profile, subdomain=subdomain, api_key=api_key, + "schedules", + "id", + profile=profile, + subdomain=subdomain, + api_key=api_key, ) diff --git a/salt/modules/panos.py b/salt/modules/panos.py index 2d18958d649..e9bf2c8b774 100644 --- a/salt/modules/panos.py +++ b/salt/modules/panos.py @@ -638,13 +638,13 @@ def get_ha_config(): def get_ha_link(): """ - Show high-availability link-monitoring state. + Show high-availability link-monitoring state. - CLI Example: + CLI Example: - .. code-block:: bash + .. code-block:: bash - salt '*' panos.get_ha_link + salt '*' panos.get_ha_link """ query = { @@ -1510,7 +1510,10 @@ def get_zones(vsys="1"): def install_antivirus( - version=None, latest=False, synch=False, skip_commit=False, + version=None, + latest=False, + synch=False, + skip_commit=False, ): """ Install anti-virus packages. diff --git a/salt/modules/pdbedit.py b/salt/modules/pdbedit.py index e42febd2c64..67e1387fd56 100644 --- a/salt/modules/pdbedit.py +++ b/salt/modules/pdbedit.py @@ -380,7 +380,8 @@ def modify( for change in changes: cmds.append( "{flag}{value}".format( - flag=flags[change], value=shlex.quote(changes[change]), + flag=flags[change], + value=shlex.quote(changes[change]), ) ) if reset_login_hours: @@ -390,7 +391,8 @@ def modify( res = __salt__["cmd.run_all"]( "pdbedit --modify --user {login} {changes}".format( - login=shlex.quote(login), changes=" ".join(cmds), + login=shlex.quote(login), + changes=" ".join(cmds), ), ) diff --git a/salt/modules/postfix.py b/salt/modules/postfix.py index 725deb9fc60..aa67793fafe 100644 --- a/salt/modules/postfix.py +++ b/salt/modules/postfix.py @@ -137,7 +137,14 @@ def set_master( new_conf = [] dict_key = "{} {}".format(service, conn_type) new_line = _format_master( - service, conn_type, private, unpriv, chroot, wakeup, maxproc, command, + service, + conn_type, + private, + unpriv, + chroot, + wakeup, + maxproc, + command, ) for line in conf_list: if isinstance(line, dict): @@ -190,7 +197,14 @@ def _format_master( maxproc = "-" conf_line = "{:9s} {:5s} {:7s} {:7s} {:7s} {:7s} {:7s} {}".format( - service, conn_type, private, unpriv, chroot, wakeup, maxproc, command, + service, + conn_type, + private, + unpriv, + chroot, + wakeup, + maxproc, + command, ) # print(conf_line) return conf_line diff --git a/salt/modules/postgres.py b/salt/modules/postgres.py index 2ae446d300d..610ecbb9ea7 100644 --- a/salt/modules/postgres.py +++ b/salt/modules/postgres.py @@ -1285,7 +1285,9 @@ def _role_cmd_args( ) ) if isinstance(valid_until, str) and bool(valid_until): - escaped_valid_until = "'{}'".format(valid_until.replace("'", "''"),) + escaped_valid_until = "'{}'".format( + valid_until.replace("'", "''"), + ) skip_superuser = False if bool(db_role) and bool(superuser) == bool(db_role["superuser"]): skip_superuser = True diff --git a/salt/modules/proxy.py b/salt/modules/proxy.py index daee4e46a43..81453b83bdd 100644 --- a/salt/modules/proxy.py +++ b/salt/modules/proxy.py @@ -422,7 +422,8 @@ def set_proxy_bypass(domains, network_service="Ethernet"): """ servers_str = " ".join(domains) cmd = "networksetup -setproxybypassdomains {} {}".format( - network_service, servers_str, + network_service, + servers_str, ) out = __salt__["cmd.run"](cmd) diff --git a/salt/modules/purefa.py b/salt/modules/purefa.py index f2fc4e16bac..143f0283c20 100644 --- a/salt/modules/purefa.py +++ b/salt/modules/purefa.py @@ -104,7 +104,7 @@ def _get_system(): 2) From environment (PUREFA_IP and PUREFA_API) 3) From the pillar (PUREFA_IP and PUREFA_API) - """ + """ agent = { "base": USER_AGENT_BASE, "class": __name__, diff --git a/salt/modules/purefb.py b/salt/modules/purefb.py index d86fc3aaacf..0439c4b9615 100644 --- a/salt/modules/purefb.py +++ b/salt/modules/purefb.py @@ -92,7 +92,7 @@ def _get_blade(): 2) From environment (PUREFB_IP and PUREFB_API) 3) From the pillar (PUREFB_IP and PUREFB_API) - """ + """ try: blade_name = __opts__["pure_tags"]["fb"].get("san_ip") diff --git a/salt/modules/qemu_img.py b/salt/modules/qemu_img.py index 30f8a1f48fa..4cc0966597d 100644 --- a/salt/modules/qemu_img.py +++ b/salt/modules/qemu_img.py @@ -41,7 +41,8 @@ def make_image(location, size, fmt): if not os.path.isdir(os.path.dirname(location)): return "" if not __salt__["cmd.retcode"]( - "qemu-img create -f {} {} {}M".format(fmt, location, size), python_shell=False, + "qemu-img create -f {} {} {}M".format(fmt, location, size), + python_shell=False, ): return location return "" diff --git a/salt/modules/qemu_nbd.py b/salt/modules/qemu_nbd.py index b29f956bdf6..5791290e3d0 100644 --- a/salt/modules/qemu_nbd.py +++ b/salt/modules/qemu_nbd.py @@ -55,7 +55,8 @@ def connect(image): while True: # Sometimes nbd does not "take hold", loop until we can verify __salt__["cmd.run"]( - "qemu-nbd -c {} {}".format(nbd, image), python_shell=False, + "qemu-nbd -c {} {}".format(nbd, image), + python_shell=False, ) if not __salt__["cmd.retcode"]("{} {}".format(fdisk, nbd)): break @@ -76,7 +77,8 @@ def mount(nbd, root=None): salt '*' qemu_nbd.mount /dev/nbd0 """ __salt__["cmd.run"]( - "partprobe {}".format(nbd), python_shell=False, + "partprobe {}".format(nbd), + python_shell=False, ) ret = {} if root is None: diff --git a/salt/modules/rallydev.py b/salt/modules/rallydev.py index 72bcdf8adb5..392ec7ab86b 100644 --- a/salt/modules/rallydev.py +++ b/salt/modules/rallydev.py @@ -198,7 +198,10 @@ def update_item(name, id_, field=None, value=None, postdata=None): ) status, result = _query( - action=name, command=id_, method="POST", data=salt.utils.json.dumps(postdata), + action=name, + command=id_, + method="POST", + data=salt.utils.json.dumps(postdata), ) return result diff --git a/salt/modules/rbac_solaris.py b/salt/modules/rbac_solaris.py index 2f302cd7781..8f4100e6d34 100644 --- a/salt/modules/rbac_solaris.py +++ b/salt/modules/rbac_solaris.py @@ -155,7 +155,8 @@ def profile_add(user, profile): if len(valid_profiles) > 0: res = __salt__["cmd.run_all"]( 'usermod -P "{profiles}" {login}'.format( - login=user, profiles=",".join(set(profile_get(user) + valid_profiles)), + login=user, + profiles=",".join(set(profile_get(user) + valid_profiles)), ) ) if res["retcode"] > 0: @@ -353,7 +354,8 @@ def role_add(user, role): if len(valid_roles) > 0: res = __salt__["cmd.run_all"]( 'usermod -R "{roles}" {login}'.format( - login=user, roles=",".join(set(role_get(user) + valid_roles)), + login=user, + roles=",".join(set(role_get(user) + valid_roles)), ) ) if res["retcode"] > 0: @@ -551,7 +553,8 @@ def auth_add(user, auth): if len(valid_auths) > 0: res = __salt__["cmd.run_all"]( 'usermod -A "{auths}" {login}'.format( - login=user, auths=",".join(set(auth_get(user, False) + valid_auths)), + login=user, + auths=",".join(set(auth_get(user, False) + valid_auths)), ) ) if res["retcode"] > 0: diff --git a/salt/modules/rpmbuild_pkgbuild.py b/salt/modules/rpmbuild_pkgbuild.py index 7acef55594e..4608f231f52 100644 --- a/salt/modules/rpmbuild_pkgbuild.py +++ b/salt/modules/rpmbuild_pkgbuild.py @@ -318,8 +318,10 @@ def _get_gpg_key_resources(keyid, env, use_passphrase, gnupghome, runas): ) if local_uids: - define_gpg_name = "--define='%_signature gpg' --define='%_gpg_name {}'".format( - local_uids[0] + define_gpg_name = ( + "--define='%_signature gpg' --define='%_gpg_name {}'".format( + local_uids[0] + ) ) # need to update rpm with public key diff --git a/salt/modules/rsync.py b/salt/modules/rsync.py index 32c6eaed5eb..eb9dbe1f54b 100644 --- a/salt/modules/rsync.py +++ b/salt/modules/rsync.py @@ -80,67 +80,67 @@ def rsync( saltenv="base", ): """ - .. versionchanged:: 2016.3.0 - Return data now contains just the output of the rsync command, instead - of a dictionary as returned from :py:func:`cmd.run_all - `. + .. versionchanged:: 2016.3.0 + Return data now contains just the output of the rsync command, instead + of a dictionary as returned from :py:func:`cmd.run_all + `. - Rsync files from src to dst + Rsync files from src to dst - src - The source location where files will be rsynced from. + src + The source location where files will be rsynced from. - dst - The destination location where files will be rsynced to. + dst + The destination location where files will be rsynced to. - delete : False - Whether to enable the rsync `--delete` flag, which - will delete extraneous files from dest dirs + delete : False + Whether to enable the rsync `--delete` flag, which + will delete extraneous files from dest dirs - force : False - Whether to enable the rsync `--force` flag, which - will force deletion of dirs even if not empty. + force : False + Whether to enable the rsync `--force` flag, which + will force deletion of dirs even if not empty. - update : False - Whether to enable the rsync `--update` flag, which - forces rsync to skip any files which exist on the - destination and have a modified time that is newer - than the source file. + update : False + Whether to enable the rsync `--update` flag, which + forces rsync to skip any files which exist on the + destination and have a modified time that is newer + than the source file. - passwordfile - A file that contains a password for accessing an - rsync daemon. The file should contain just the - password. + passwordfile + A file that contains a password for accessing an + rsync daemon. The file should contain just the + password. - exclude - Whether to enable the rsync `--exclude` flag, which - will exclude files matching a PATTERN. + exclude + Whether to enable the rsync `--exclude` flag, which + will exclude files matching a PATTERN. - excludefrom - Whether to enable the rsync `--excludefrom` flag, which - will read exclude patterns from a file. + excludefrom + Whether to enable the rsync `--excludefrom` flag, which + will read exclude patterns from a file. - dryrun : False - Whether to enable the rsync `--dry-run` flag, which - will perform a trial run with no changes made. + dryrun : False + Whether to enable the rsync `--dry-run` flag, which + will perform a trial run with no changes made. - rsh - Whether to enable the rsync `--rsh` flag, to - specify the remote shell to use. + rsh + Whether to enable the rsync `--rsh` flag, to + specify the remote shell to use. - additional_opts - Any additional rsync options, should be specified as a list. + additional_opts + Any additional rsync options, should be specified as a list. - saltenv - Specify a salt fileserver environment to be used. + saltenv + Specify a salt fileserver environment to be used. - CLI Example: + CLI Example: - .. code-block:: bash + .. code-block:: bash - salt '*' rsync.rsync /path/to/src /path/to/dest delete=True update=True passwordfile=/etc/pass.crt exclude=exclude/dir - salt '*' rsync.rsync /path/to/src delete=True excludefrom=/xx.ini - salt '*' rsync.rsync /path/to/src delete=True exclude='[exclude1/dir,exclude2/dir]' additional_opts='["--partial", "--bwlimit=5000"]' + salt '*' rsync.rsync /path/to/src /path/to/dest delete=True update=True passwordfile=/etc/pass.crt exclude=exclude/dir + salt '*' rsync.rsync /path/to/src delete=True excludefrom=/xx.ini + salt '*' rsync.rsync /path/to/src delete=True exclude='[exclude1/dir,exclude2/dir]' additional_opts='["--partial", "--bwlimit=5000"]' """ if not src: src = __salt__["config.option"]("rsync.src") diff --git a/salt/modules/saltcheck.py b/salt/modules/saltcheck.py index dbc9413c97b..e3b32f2916b 100644 --- a/salt/modules/saltcheck.py +++ b/salt/modules/saltcheck.py @@ -869,7 +869,9 @@ class SaltCheck: value[ "module.function [args]{}".format(assertion_section_repr_title) ] = "{} {}{}".format( - mod_and_func, dumps(args), assertion_section_repr_value, + mod_and_func, + dumps(args), + assertion_section_repr_value, ) value["saltcheck assertion"] = "{}{} {}".format( ("" if expected_return is None else "{} ".format(expected_return)), diff --git a/salt/modules/schedule.py b/salt/modules/schedule.py index 7117b6536d0..32ce5465bf4 100644 --- a/salt/modules/schedule.py +++ b/salt/modules/schedule.py @@ -280,7 +280,8 @@ def delete(name, **kwargs): res = __salt__["event.fire"](event_data, "manage_schedule") if res: event_ret = event_bus.get_event( - tag="/salt/minion/minion_schedule_delete_complete", wait=30, + tag="/salt/minion/minion_schedule_delete_complete", + wait=30, ) if event_ret and event_ret["complete"]: schedule = event_ret["schedule"] @@ -496,7 +497,8 @@ def add(name, **kwargs): ) if res: event_ret = event_bus.get_event( - tag="/salt/minion/minion_schedule_add_complete", wait=30, + tag="/salt/minion/minion_schedule_add_complete", + wait=30, ) if event_ret and event_ret["complete"]: schedule = event_ret["schedule"] @@ -797,7 +799,8 @@ def save(**kwargs): ) if res: event_ret = event_bus.get_event( - tag="/salt/minion/minion_schedule_saved", wait=30, + tag="/salt/minion/minion_schedule_saved", + wait=30, ) if event_ret and event_ret["complete"]: ret["result"] = True @@ -836,7 +839,8 @@ def enable(**kwargs): ) if res: event_ret = event_bus.get_event( - tag="/salt/minion/minion_schedule_enabled_complete", wait=30, + tag="/salt/minion/minion_schedule_enabled_complete", + wait=30, ) if event_ret and event_ret["complete"]: schedule = event_ret["schedule"] @@ -879,7 +883,8 @@ def disable(**kwargs): ) if res: event_ret = event_bus.get_event( - tag="/salt/minion/minion_schedule_disabled_complete", wait=30, + tag="/salt/minion/minion_schedule_disabled_complete", + wait=30, ) if event_ret and event_ret["complete"]: schedule = event_ret["schedule"] @@ -1262,7 +1267,8 @@ def skip_job(name, current_time, **kwargs): res = __salt__["event.fire"](event_data, "manage_schedule") if res: event_ret = event_bus.get_event( - tag="/salt/minion/minion_schedule_skip_job_complete", wait=30, + tag="/salt/minion/minion_schedule_skip_job_complete", + wait=30, ) if event_ret and event_ret["complete"]: schedule = event_ret["schedule"] @@ -1310,7 +1316,8 @@ def show_next_fire_time(name, **kwargs): res = __salt__["event.fire"](event_data, "manage_schedule") if res: event_ret = event_bus.get_event( - tag="/salt/minion/minion_schedule_next_fire_time_complete", wait=30, + tag="/salt/minion/minion_schedule_next_fire_time_complete", + wait=30, ) except KeyError: # Effectively a no-op, since we can't really return without an event system diff --git a/salt/modules/slack_notify.py b/salt/modules/slack_notify.py index 021f09036ec..d0d32fabe18 100644 --- a/salt/modules/slack_notify.py +++ b/salt/modules/slack_notify.py @@ -160,7 +160,13 @@ def find_user(name, api_key=None): def post_message( - channel, message, from_name, api_key=None, icon=None, attachments=None, blocks=None, + channel, + message, + from_name, + api_key=None, + icon=None, + attachments=None, + blocks=None, ): """ Send a message to a Slack channel. diff --git a/salt/modules/smartos_imgadm.py b/salt/modules/smartos_imgadm.py index 9623dac924e..688371cdd24 100644 --- a/salt/modules/smartos_imgadm.py +++ b/salt/modules/smartos_imgadm.py @@ -71,8 +71,12 @@ def _parse_image_meta(image=None, detail=False): if docker_repo and docker_tag: name = "{}:{}".format(docker_repo, docker_tag) - description = "Docker image imported from {repo}:{tag} on {date}.".format( - repo=docker_repo, tag=docker_tag, date=published, + description = ( + "Docker image imported from {repo}:{tag} on {date}.".format( + repo=docker_repo, + tag=docker_tag, + date=published, + ) ) if name and detail: @@ -86,7 +90,9 @@ def _parse_image_meta(image=None, detail=False): } elif name: ret = "{name}@{version} [{published}]".format( - name=name, version=version, published=published, + name=name, + version=version, + published=published, ) else: log.debug("smartos_image - encountered invalid image payload: %s", image) diff --git a/salt/modules/solaris_fmadm.py b/salt/modules/solaris_fmadm.py index 9fff1b6fee8..4257c921a5c 100644 --- a/salt/modules/solaris_fmadm.py +++ b/salt/modules/solaris_fmadm.py @@ -485,7 +485,9 @@ def faulty(): salt '*' fmadm.faulty """ fmadm = _check_fmadm() - cmd = "{cmd} faulty".format(cmd=fmadm,) + cmd = "{cmd} faulty".format( + cmd=fmadm, + ) res = __salt__["cmd.run_all"](cmd) result = {} if res["stdout"] == "": diff --git a/salt/modules/splunk.py b/salt/modules/splunk.py index 726017ba2ca..07ea8122eb1 100644 --- a/salt/modules/splunk.py +++ b/salt/modules/splunk.py @@ -73,7 +73,8 @@ def _get_secret_key(profile): def _generate_password(email): m = hmac.new( - base64.b64decode(_get_secret_key("splunk")), str([email, SERVICE_NAME]), + base64.b64decode(_get_secret_key("splunk")), + str([email, SERVICE_NAME]), ) return base64.urlsafe_b64encode(m.digest()).strip().replace("=", "") diff --git a/salt/modules/state.py b/salt/modules/state.py index 5e02312a428..5eebc90310e 100644 --- a/salt/modules/state.py +++ b/salt/modules/state.py @@ -2425,7 +2425,10 @@ def _disabled(funs): err = ( 'The state file "{0}" is currently disabled by "{1}", ' "to re-enable, run state.enable {1}." - ).format(state, _state,) + ).format( + state, + _state, + ) ret.append(err) continue else: @@ -2433,7 +2436,9 @@ def _disabled(funs): err = ( 'The state file "{0}" is currently disabled, ' "to re-enable, run state.enable {0}." - ).format(_state,) + ).format( + _state, + ) ret.append(err) continue return ret diff --git a/salt/modules/status.py b/salt/modules/status.py index ce0ed92a0b7..0cba1d3e43f 100644 --- a/salt/modules/status.py +++ b/salt/modules/status.py @@ -235,7 +235,10 @@ def uptime(): raise CommandExecutionError("Cannot find kern.boottime system parameter") data = bt_data.split("{")[-1].split("}")[0].strip().replace(" ", "") uptime = { - k: int(v,) for k, v in [p.strip().split("=") for p in data.split(",")] + k: int( + v, + ) + for k, v in [p.strip().split("=") for p in data.split(",")] } seconds = int(curr_seconds - uptime["sec"]) elif salt.utils.platform.is_aix(): diff --git a/salt/modules/supervisord.py b/salt/modules/supervisord.py index 200e03f300d..eee4a9f42cf 100644 --- a/salt/modules/supervisord.py +++ b/salt/modules/supervisord.py @@ -85,7 +85,9 @@ def start(name="all", user=None, conf_file=None, bin_env=None): if name.endswith(":*"): name = name[:-1] ret = __salt__["cmd.run_all"]( - _ctl_cmd("start", name, conf_file, bin_env), runas=user, python_shell=False, + _ctl_cmd("start", name, conf_file, bin_env), + runas=user, + python_shell=False, ) return _get_return(ret) @@ -113,7 +115,9 @@ def restart(name="all", user=None, conf_file=None, bin_env=None): if name.endswith(":*"): name = name[:-1] ret = __salt__["cmd.run_all"]( - _ctl_cmd("restart", name, conf_file, bin_env), runas=user, python_shell=False, + _ctl_cmd("restart", name, conf_file, bin_env), + runas=user, + python_shell=False, ) return _get_return(ret) @@ -141,7 +145,9 @@ def stop(name="all", user=None, conf_file=None, bin_env=None): if name.endswith(":*"): name = name[:-1] ret = __salt__["cmd.run_all"]( - _ctl_cmd("stop", name, conf_file, bin_env), runas=user, python_shell=False, + _ctl_cmd("stop", name, conf_file, bin_env), + runas=user, + python_shell=False, ) return _get_return(ret) @@ -169,7 +175,9 @@ def add(name, user=None, conf_file=None, bin_env=None): elif name.endswith(":*"): name = name[:-2] ret = __salt__["cmd.run_all"]( - _ctl_cmd("add", name, conf_file, bin_env), runas=user, python_shell=False, + _ctl_cmd("add", name, conf_file, bin_env), + runas=user, + python_shell=False, ) return _get_return(ret) @@ -197,7 +205,9 @@ def remove(name, user=None, conf_file=None, bin_env=None): elif name.endswith(":*"): name = name[:-2] ret = __salt__["cmd.run_all"]( - _ctl_cmd("remove", name, conf_file, bin_env), runas=user, python_shell=False, + _ctl_cmd("remove", name, conf_file, bin_env), + runas=user, + python_shell=False, ) return _get_return(ret) @@ -221,7 +231,9 @@ def reread(user=None, conf_file=None, bin_env=None): salt '*' supervisord.reread """ ret = __salt__["cmd.run_all"]( - _ctl_cmd("reread", None, conf_file, bin_env), runas=user, python_shell=False, + _ctl_cmd("reread", None, conf_file, bin_env), + runas=user, + python_shell=False, ) return _get_return(ret) @@ -255,7 +267,9 @@ def update(user=None, conf_file=None, bin_env=None, name=None): name = name[:-2] ret = __salt__["cmd.run_all"]( - _ctl_cmd("update", name, conf_file, bin_env), runas=user, python_shell=False, + _ctl_cmd("update", name, conf_file, bin_env), + runas=user, + python_shell=False, ) return _get_return(ret) @@ -307,7 +321,9 @@ def status_raw(name=None, user=None, conf_file=None, bin_env=None): salt '*' supervisord.status_raw """ ret = __salt__["cmd.run_all"]( - _ctl_cmd("status", name, conf_file, bin_env), runas=user, python_shell=False, + _ctl_cmd("status", name, conf_file, bin_env), + runas=user, + python_shell=False, ) return _get_return(ret) @@ -331,7 +347,9 @@ def custom(command, user=None, conf_file=None, bin_env=None): salt '*' supervisord.custom "mstop '*gunicorn*'" """ ret = __salt__["cmd.run_all"]( - _ctl_cmd(command, None, conf_file, bin_env), runas=user, python_shell=False, + _ctl_cmd(command, None, conf_file, bin_env), + runas=user, + python_shell=False, ) return _get_return(ret) diff --git a/salt/modules/tls.py b/salt/modules/tls.py index cd430ab7d0c..a2b7115a832 100644 --- a/salt/modules/tls.py +++ b/salt/modules/tls.py @@ -232,7 +232,12 @@ def _new_serial(ca_name): """ hashnum = int( binascii.hexlify( - b"_".join((salt.utils.stringutils.to_bytes(_microtime()), os.urandom(5),)) + b"_".join( + ( + salt.utils.stringutils.to_bytes(_microtime()), + os.urandom(5), + ) + ) ), 16, ) @@ -1628,7 +1633,9 @@ def create_pkcs12(ca_name, CN, passphrase="", cacert_path=None, replace=False): ) return ('Created PKCS#12 Certificate for "{0}": ' '"{1}/{2}/certs/{0}.p12"').format( - CN, cert_base_path(), ca_name, + CN, + cert_base_path(), + ca_name, ) @@ -1797,7 +1804,9 @@ def create_empty_crl( crl = OpenSSL.crypto.CRL() crl_text = crl.export( - ca_cert, ca_key, digest=salt.utils.stringutils.to_bytes(digest), + ca_cert, + ca_key, + digest=salt.utils.stringutils.to_bytes(digest), ) with salt.utils.files.fopen(crl_file, "w") as f: @@ -1918,9 +1927,10 @@ def revoke_cert( ).format(cert_path, cert_filename, serial_number) except ValueError: ret["retcode"] = 1 - ret["comment"] = ( - "Revocation date '{}' does not match" - "format '{}'".format(revoke_date, two_digit_year_fmt) + ret[ + "comment" + ] = "Revocation date '{}' does not match" "format '{}'".format( + revoke_date, two_digit_year_fmt ) return ret elif index_serial_subject in line: diff --git a/salt/modules/tomcat.py b/salt/modules/tomcat.py index ab3f00ee45f..c1157fbafbf 100644 --- a/salt/modules/tomcat.py +++ b/salt/modules/tomcat.py @@ -633,7 +633,13 @@ def passwd(passwd, user="", alg="sha1", realm=None): digest = hasattr(hashlib, alg) and getattr(hashlib, alg) or None if digest: if realm: - digest.update("{}:{}:{}".format(user, realm, passwd,)) + digest.update( + "{}:{}:{}".format( + user, + realm, + passwd, + ) + ) else: digest.update(passwd) diff --git a/salt/modules/twilio_notify.py b/salt/modules/twilio_notify.py index 0332c31c7ab..abfb65fb4fe 100644 --- a/salt/modules/twilio_notify.py +++ b/salt/modules/twilio_notify.py @@ -63,7 +63,8 @@ def _get_twilio(profile): """ creds = __salt__["config.option"](profile) client = TwilioRestClient( - creds.get("twilio.account_sid"), creds.get("twilio.auth_token"), + creds.get("twilio.account_sid"), + creds.get("twilio.auth_token"), ) return client diff --git a/salt/modules/vagrant.py b/salt/modules/vagrant.py index 15d4357b918..5bc505471d3 100644 --- a/salt/modules/vagrant.py +++ b/salt/modules/vagrant.py @@ -78,7 +78,7 @@ def _build_machine_uri(machine, cwd): def _update_vm_info(name, vm_): - """ store the vm_ information keyed by name """ + """store the vm_ information keyed by name""" __utils__["sdb.sdb_set"](_build_sdb_uri(name), vm_, __opts__) # store machine-to-name mapping, too diff --git a/salt/modules/vboxmanage.py b/salt/modules/vboxmanage.py index 833b94e9eb4..ea66d9e41c3 100644 --- a/salt/modules/vboxmanage.py +++ b/salt/modules/vboxmanage.py @@ -131,7 +131,8 @@ def list_nodes(): "public_ips": [], } ret[node]["size"] = "{} RAM, {} CPU".format( - nodes[node]["Memory size"], nodes[node]["Number of CPUs"], + nodes[node]["Memory size"], + nodes[node]["Number of CPUs"], ) return ret diff --git a/salt/modules/vsphere.py b/salt/modules/vsphere.py index 5b5f2314c12..84984003be9 100644 --- a/salt/modules/vsphere.py +++ b/salt/modules/vsphere.py @@ -2408,7 +2408,12 @@ def test_vcenter_connection(service_instance=None): @depends(HAS_PYVMOMI) @ignores_kwargs("credstore") def system_info( - host, username, password, protocol=None, port=None, verify_ssl=True, + host, + username, + password, + protocol=None, + port=None, + verify_ssl=True, ): """ Return system information about a VMware environment. @@ -6051,11 +6056,15 @@ def _apply_cluster_dict(cluster_spec, cluster_dict, vsan_spec=None, vsan_61=True vim.ClusterFailoverResourcesAdmissionControlPolicy, ): - das_config.admissionControlPolicy = vim.ClusterFailoverResourcesAdmissionControlPolicy( - cpuFailoverResourcesPercent=adm_pol_dict["cpu_failover_percent"], - memoryFailoverResourcesPercent=adm_pol_dict[ - "memory_failover_percent" - ], + das_config.admissionControlPolicy = ( + vim.ClusterFailoverResourcesAdmissionControlPolicy( + cpuFailoverResourcesPercent=adm_pol_dict[ + "cpu_failover_percent" + ], + memoryFailoverResourcesPercent=adm_pol_dict[ + "memory_failover_percent" + ], + ) ) if "default_vm_settings" in ha_dict: vm_set_dict = ha_dict["default_vm_settings"] @@ -8105,7 +8114,8 @@ def add_host_to_dvs( ) pnic_backing = vim.dvs.HostMember.PnicBacking(pnicSpec=[dvs_pnic_spec]) dvs_hostmember_config_spec = vim.dvs.HostMember.ConfigSpec( - host=host_ref, operation="add", + host=host_ref, + operation="add", ) dvs_config = vim.DVSConfigSpec( configVersion=dvs.config.configVersion, host=[dvs_hostmember_config_spec] diff --git a/salt/modules/win_lgpo.py b/salt/modules/win_lgpo.py index 265c6660b8b..3df1521ae29 100644 --- a/salt/modules/win_lgpo.py +++ b/salt/modules/win_lgpo.py @@ -7339,7 +7339,8 @@ def _write_regpol_data( "Version", int( "{}{}".format( - str(version_nums[0]).zfill(4), str(version_nums[1]).zfill(4), + str(version_nums[0]).zfill(4), + str(version_nums[1]).zfill(4), ), 16, ), @@ -7583,8 +7584,11 @@ def _writeAdminTemplateRegPolFile( admPolicy, this_list, ) - existing_data = _policyFileReplaceOrAppendList( - disabled_list_strings, existing_data + existing_data = ( + _policyFileReplaceOrAppendList( + disabled_list_strings, + existing_data, + ) ) elif ( etree.QName(child_item).localname @@ -7762,8 +7766,10 @@ def _writeAdminTemplateRegPolFile( None, test_items=False, ) - existing_data = _policyFileReplaceOrAppendList( - list_strings, existing_data + existing_data = ( + _policyFileReplaceOrAppendList( + list_strings, existing_data + ) ) elif etree.QName( child_item @@ -7775,29 +7781,35 @@ def _writeAdminTemplateRegPolFile( if base_policy_settings[adm_namespace][ admPolicy ][child_item.attrib["id"]]: - value_string = _checkValueItemParent( - child_item, - admPolicy, - child_key, - child_valuename, - TRUE_VALUE_XPATH, - None, - check_deleted=False, - test_item=False, + value_string = ( + _checkValueItemParent( + child_item, + admPolicy, + child_key, + child_valuename, + TRUE_VALUE_XPATH, + None, + check_deleted=False, + test_item=False, + ) ) else: - value_string = _checkValueItemParent( - child_item, - admPolicy, - child_key, - child_valuename, - FALSE_VALUE_XPATH, - None, - check_deleted=False, - test_item=False, + value_string = ( + _checkValueItemParent( + child_item, + admPolicy, + child_key, + child_valuename, + FALSE_VALUE_XPATH, + None, + check_deleted=False, + test_item=False, + ) + ) + existing_data = ( + _policyFileReplaceOrAppend( + value_string, existing_data ) - existing_data = _policyFileReplaceOrAppend( - value_string, existing_data ) elif ( etree.QName(child_item).localname @@ -7830,8 +7842,11 @@ def _writeAdminTemplateRegPolFile( "I have enabled value string of %s", enabled_value_string, ) - existing_data = _policyFileReplaceOrAppend( - enabled_value_string, existing_data + existing_data = ( + _policyFileReplaceOrAppend( + enabled_value_string, + existing_data, + ) ) elif ( etree.QName(child_item).localname @@ -7851,28 +7866,34 @@ def _writeAdminTemplateRegPolFile( ], ).strip() ): - enabled_value_string = _checkValueItemParent( - enum_item, - child_item.attrib["id"], - child_key, - child_valuename, - VALUE_XPATH, - None, - check_deleted=False, - test_item=False, + enabled_value_string = ( + _checkValueItemParent( + enum_item, + child_item.attrib["id"], + child_key, + child_valuename, + VALUE_XPATH, + None, + check_deleted=False, + test_item=False, + ) ) - existing_data = _policyFileReplaceOrAppend( - enabled_value_string, - existing_data, + existing_data = ( + _policyFileReplaceOrAppend( + enabled_value_string, + existing_data, + ) ) if VALUE_LIST_XPATH(enum_item): - enabled_list_strings = _checkListItem( - enum_item, - admPolicy, - child_key, - VALUE_LIST_XPATH, - None, - test_items=False, + enabled_list_strings = ( + _checkListItem( + enum_item, + admPolicy, + child_key, + VALUE_LIST_XPATH, + None, + test_items=False, + ) ) log.trace( "working with valueList portion of %s", @@ -7906,10 +7927,12 @@ def _writeAdminTemplateRegPolFile( "I have enabled value string of %s", enabled_value_string, ) - existing_data = _policyFileReplaceOrAppend( - enabled_value_string, - existing_data, - append_only=True, + existing_data = ( + _policyFileReplaceOrAppend( + enabled_value_string, + existing_data, + append_only=True, + ) ) try: _write_regpol_data( @@ -9859,9 +9882,9 @@ def set_( policy_namespace ][policy_name] ): - temp_element_name = child_item.attrib[ - "id" - ] + temp_element_name = ( + child_item.attrib["id"] + ) else: msg = ( 'Element "{}" must be included' diff --git a/salt/modules/win_pkg.py b/salt/modules/win_pkg.py index 6ea7bc9713e..3c66d331b24 100644 --- a/salt/modules/win_pkg.py +++ b/salt/modules/win_pkg.py @@ -167,7 +167,9 @@ def latest_version(*names, **kwargs): # check, whether latest available version # is newer than latest installed version if compare_versions( - ver1=str(latest_available), oper=">", ver2=str(latest_installed), + ver1=str(latest_available), + oper=">", + ver2=str(latest_installed), ): log.debug( "Upgrade of %s from %s to %s is available", @@ -2032,7 +2034,8 @@ def remove(name=None, pkgs=None, **kwargs): # If still no uninstaller found, fail if not uninstaller: log.error( - "No installer or uninstaller configured for package %s", pkgname, + "No installer or uninstaller configured for package %s", + pkgname, ) ret[pkgname] = {"no uninstaller defined": target} continue diff --git a/salt/modules/win_wua.py b/salt/modules/win_wua.py index 936f7e47308..12719791e0c 100644 --- a/salt/modules/win_wua.py +++ b/salt/modules/win_wua.py @@ -987,7 +987,12 @@ def set_wu_settings( ret["msupdate"] = msupdate except Exception as error: # pylint: disable=broad-except # pylint: disable=unpacking-non-sequence,unbalanced-tuple-unpacking - (hr, msg, exc, arg,) = error.args + ( + hr, + msg, + exc, + arg, + ) = error.args # pylint: enable=unpacking-non-sequence,unbalanced-tuple-unpacking # Consider checking for -2147024891 (0x80070005) Access Denied ret["Comment"] = "Failed with failure code: {}".format(exc[5]) @@ -1003,7 +1008,12 @@ def set_wu_settings( ret["msupdate"] = msupdate except Exception as error: # pylint: disable=broad-except # pylint: disable=unpacking-non-sequence,unbalanced-tuple-unpacking - (hr, msg, exc, arg,) = error.args + ( + hr, + msg, + exc, + arg, + ) = error.args # pylint: enable=unpacking-non-sequence,unbalanced-tuple-unpacking # Consider checking for the following # -2147024891 (0x80070005) Access Denied diff --git a/salt/modules/zfs.py b/salt/modules/zfs.py index 6cba7f6fee1..c35f3d93abc 100644 --- a/salt/modules/zfs.py +++ b/salt/modules/zfs.py @@ -71,7 +71,11 @@ def exists(name, **kwargs): ## Check if 'name' of 'type' exists res = __salt__["cmd.run_all"]( - __utils__["zfs.zfs_command"](command="list", opts=opts, target=name,), + __utils__["zfs.zfs_command"]( + command="list", + opts=opts, + target=name, + ), python_shell=False, ignore_retcode=True, ) @@ -188,7 +192,11 @@ def destroy(name, **kwargs): ## Destroy filesystem/volume/snapshot/... res = __salt__["cmd.run_all"]( - __utils__["zfs.zfs_command"](command="destroy", flags=flags, target=name,), + __utils__["zfs.zfs_command"]( + command="destroy", + flags=flags, + target=name, + ), python_shell=False, ) @@ -251,7 +259,11 @@ def rename(name, new_name, **kwargs): ## Rename filesystem/volume/snapshot/... res = __salt__["cmd.run_all"]( - __utils__["zfs.zfs_command"](command="rename", flags=flags, target=target,), + __utils__["zfs.zfs_command"]( + command="rename", + flags=flags, + target=target, + ), python_shell=False, ) @@ -335,7 +347,10 @@ def list_(name=None, **kwargs): ## parse zfs list res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( - command="list", flags=flags, opts=opts, target=name, + command="list", + flags=flags, + opts=opts, + target=name, ), python_shell=False, ) @@ -374,7 +389,10 @@ def list_mount(): """ ## List mounted filesystem res = __salt__["cmd.run_all"]( - __utils__["zfs.zfs_command"](command="mount",), python_shell=False, + __utils__["zfs.zfs_command"]( + command="mount", + ), + python_shell=False, ) if res["retcode"] == 0: @@ -429,7 +447,10 @@ def mount(name=None, **kwargs): ## Mount filesystem res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( - command="mount", flags=flags, opts=opts, target=name, + command="mount", + flags=flags, + opts=opts, + target=name, ), python_shell=False, ) @@ -480,7 +501,11 @@ def unmount(name, **kwargs): ## Unmount filesystem res = __salt__["cmd.run_all"]( - __utils__["zfs.zfs_command"](command="unmount", flags=flags, target=name,), + __utils__["zfs.zfs_command"]( + command="unmount", + flags=flags, + target=name, + ), python_shell=False, ) @@ -523,7 +548,10 @@ def inherit(prop, name, **kwargs): ## Inherit property res = __salt__["cmd.run_all"]( __utils__["zfs.zfs_command"]( - command="inherit", flags=flags, property_name=prop, target=name, + command="inherit", + flags=flags, + property_name=prop, + target=name, ), python_shell=False, ) @@ -575,7 +603,11 @@ def diff(name_a, name_b=None, **kwargs): ## Diff filesystem/snapshot res = __salt__["cmd.run_all"]( - __utils__["zfs.zfs_command"](command="diff", flags=flags, target=target,), + __utils__["zfs.zfs_command"]( + command="diff", + flags=flags, + target=target, + ), python_shell=False, ) @@ -650,7 +682,11 @@ def rollback(name, **kwargs): ## Rollback to snapshot res = __salt__["cmd.run_all"]( - __utils__["zfs.zfs_command"](command="rollback", flags=flags, target=name,), + __utils__["zfs.zfs_command"]( + command="rollback", + flags=flags, + target=name, + ), python_shell=False, ) @@ -752,7 +788,10 @@ def promote(name): """ ## Promote clone res = __salt__["cmd.run_all"]( - __utils__["zfs.zfs_command"](command="promote", target=name,), + __utils__["zfs.zfs_command"]( + command="promote", + target=name, + ), python_shell=False, ) @@ -799,7 +838,10 @@ def bookmark(snapshot, bookmark): ## Bookmark snapshot res = __salt__["cmd.run_all"]( - __utils__["zfs.zfs_command"](command="bookmark", target=target,), + __utils__["zfs.zfs_command"]( + command="bookmark", + target=target, + ), python_shell=False, ) @@ -838,7 +880,11 @@ def holds(snapshot, **kwargs): ## Lookup holds res = __salt__["cmd.run_all"]( - __utils__["zfs.zfs_command"](command="holds", flags=flags, target=target,), + __utils__["zfs.zfs_command"]( + command="holds", + flags=flags, + target=target, + ), python_shell=False, ) @@ -846,7 +892,12 @@ def holds(snapshot, **kwargs): if res["retcode"] == 0: for hold in res["stdout"].splitlines(): hold_data = OrderedDict( - list(zip(["name", "tag", "timestamp"], hold.split("\t"),)) + list( + zip( + ["name", "tag", "timestamp"], + hold.split("\t"), + ) + ) ) ret[hold_data["tag"].strip()] = hold_data["timestamp"] @@ -904,7 +955,11 @@ def hold(tag, *snapshot, **kwargs): ## hold snapshot res = __salt__["cmd.run_all"]( - __utils__["zfs.zfs_command"](command="hold", flags=flags, target=target,), + __utils__["zfs.zfs_command"]( + command="hold", + flags=flags, + target=target, + ), python_shell=False, ) @@ -961,7 +1016,11 @@ def release(tag, *snapshot, **kwargs): ## release snapshot res = __salt__["cmd.run_all"]( - __utils__["zfs.zfs_command"](command="release", flags=flags, target=target,), + __utils__["zfs.zfs_command"]( + command="release", + flags=flags, + target=target, + ), python_shell=False, ) @@ -1171,11 +1230,14 @@ def get(*dataset, **kwargs): if "value" in ds_data: if kwargs.get("parsable", True): ds_data["value"] = __utils__["zfs.from_auto"]( - ds_data["property"], ds_data["value"], + ds_data["property"], + ds_data["value"], ) else: ds_data["value"] = __utils__["zfs.to_auto"]( - ds_data["property"], ds_data["value"], convert_to_human=True, + ds_data["property"], + ds_data["value"], + convert_to_human=True, ) if ds_data["name"] not in ret: diff --git a/salt/modules/zk_concurrency.py b/salt/modules/zk_concurrency.py index 34172bc8be9..7d7bef87434 100644 --- a/salt/modules/zk_concurrency.py +++ b/salt/modules/zk_concurrency.py @@ -28,7 +28,12 @@ try: # https://github.com/python-zk/kazoo/pull/206 class _Semaphore(kazoo.recipe.lock.Semaphore): def __init__( - self, client, path, identifier=None, max_leases=1, ephemeral_lease=True, + self, + client, + path, + identifier=None, + max_leases=1, + ephemeral_lease=True, ): identifier = identifier or gethostname() kazoo.recipe.lock.Semaphore.__init__( diff --git a/salt/modules/zoneadm.py b/salt/modules/zoneadm.py index 9359cdd33b8..4b2b91c0d22 100644 --- a/salt/modules/zoneadm.py +++ b/salt/modules/zoneadm.py @@ -419,7 +419,11 @@ def verify(zone): ret = {"status": True} ## verify zone - res = __salt__["cmd.run_all"]("zoneadm -z {zone} verify".format(zone=zone,)) + res = __salt__["cmd.run_all"]( + "zoneadm -z {zone} verify".format( + zone=zone, + ) + ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] ret["message"] = ret["message"].replace("zoneadm: ", "") diff --git a/salt/modules/zonecfg.py b/salt/modules/zonecfg.py index 06e36e76f23..bf3b913faf6 100644 --- a/salt/modules/zonecfg.py +++ b/salt/modules/zonecfg.py @@ -244,7 +244,10 @@ def create(zone, brand, zonepath, force=False): _dump_cfg(cfg_file) res = __salt__["cmd.run_all"]( - "zonecfg -z {zone} -f {cfg}".format(zone=zone, cfg=cfg_file,) + "zonecfg -z {zone} -f {cfg}".format( + zone=zone, + cfg=cfg_file, + ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] @@ -283,7 +286,10 @@ def create_from_template(zone, template): # create from template _dump_cfg(template) res = __salt__["cmd.run_all"]( - "zonecfg -z {zone} create -t {tmpl} -F".format(zone=zone, tmpl=template,) + "zonecfg -z {zone} create -t {tmpl} -F".format( + zone=zone, + tmpl=template, + ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] @@ -311,7 +317,11 @@ def delete(zone): ret = {"status": True} # delete zone - res = __salt__["cmd.run_all"]("zonecfg -z {zone} delete -F".format(zone=zone,)) + res = __salt__["cmd.run_all"]( + "zonecfg -z {zone} delete -F".format( + zone=zone, + ) + ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] if ret["message"] == "": @@ -343,7 +353,8 @@ def export(zone, path=None): # export zone res = __salt__["cmd.run_all"]( "zonecfg -z {zone} export{path}".format( - zone=zone, path=" -f {}".format(path) if path else "", + zone=zone, + path=" -f {}".format(path) if path else "", ) ) ret["status"] = res["retcode"] == 0 @@ -376,7 +387,10 @@ def import_(zone, path): # create from file _dump_cfg(path) res = __salt__["cmd.run_all"]( - "zonecfg -z {zone} -f {path}".format(zone=zone, path=path,) + "zonecfg -z {zone} -f {path}".format( + zone=zone, + path=path, + ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] @@ -424,7 +438,10 @@ def _property(methode, zone, key, value): if cfg_file: _dump_cfg(cfg_file) res = __salt__["cmd.run_all"]( - "zonecfg -z {zone} -f {path}".format(zone=zone, path=cfg_file,) + "zonecfg -z {zone} -f {path}".format( + zone=zone, + path=cfg_file, + ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] @@ -457,7 +474,12 @@ def set_property(zone, key, value): salt '*' zonecfg.set_property deathscythe cpu-shares 100 """ - return _property("set", zone, key, value,) + return _property( + "set", + zone, + key, + value, + ) def clear_property(zone, key): @@ -475,7 +497,12 @@ def clear_property(zone, key): salt '*' zonecfg.clear_property deathscythe cpu-shares """ - return _property("clear", zone, key, None,) + return _property( + "clear", + zone, + key, + None, + ) def _resource(methode, zone, resource_type, resource_selector, **kwargs): @@ -546,7 +573,10 @@ def _resource(methode, zone, resource_type, resource_selector, **kwargs): if cfg_file: _dump_cfg(cfg_file) res = __salt__["cmd.run_all"]( - "zonecfg -z {zone} -f {path}".format(zone=zone, path=cfg_file,) + "zonecfg -z {zone} -f {path}".format( + zone=zone, + path=cfg_file, + ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] @@ -647,7 +677,10 @@ def remove_resource(zone, resource_type, resource_key, resource_value): if cfg_file: _dump_cfg(cfg_file) res = __salt__["cmd.run_all"]( - "zonecfg -z {zone} -f {path}".format(zone=zone, path=cfg_file,) + "zonecfg -z {zone} -f {path}".format( + zone=zone, + path=cfg_file, + ) ) ret["status"] = res["retcode"] == 0 ret["message"] = res["stdout"] if ret["status"] else res["stderr"] @@ -681,7 +714,11 @@ def info(zone, show_all=False): ret = {} # dump zone - res = __salt__["cmd.run_all"]("zonecfg -z {zone} info".format(zone=zone,)) + res = __salt__["cmd.run_all"]( + "zonecfg -z {zone} info".format( + zone=zone, + ) + ) if res["retcode"] == 0: # parse output resname = None diff --git a/salt/modules/zpool.py b/salt/modules/zpool.py index ead090e4d86..051d9c661a1 100644 --- a/salt/modules/zpool.py +++ b/salt/modules/zpool.py @@ -86,7 +86,8 @@ def healthy(): # if all pools are healthy, otherwise we will get # the same output that we expect from zpool status res = __salt__["cmd.run_all"]( - __utils__["zfs.zpool_command"]("status", flags=["-x"]), python_shell=False, + __utils__["zfs.zpool_command"]("status", flags=["-x"]), + python_shell=False, ) return res["stdout"] == "all pools are healthy" @@ -111,7 +112,8 @@ def status(zpool=None): ## collect status output res = __salt__["cmd.run_all"]( - __utils__["zfs.zpool_command"]("status", target=zpool), python_shell=False, + __utils__["zfs.zpool_command"]("status", target=zpool), + python_shell=False, ) if res["retcode"] != 0: @@ -194,7 +196,10 @@ def status(zpool=None): # NOTE: transform data into dict stat_data = OrderedDict( list( - zip(header, [x for x in line.strip().split(" ") if x not in [""]],) + zip( + header, + [x for x in line.strip().split(" ") if x not in [""]], + ) ) ) @@ -307,7 +312,12 @@ def iostat(zpool=None, sample_time=5, parsable=True): # NOTE: transform data into dict io_data = OrderedDict( - list(zip(header, [x for x in line.strip().split(" ") if x not in [""]],)) + list( + zip( + header, + [x for x in line.strip().split(" ") if x not in [""]], + ) + ) ) # NOTE: normalize values @@ -415,7 +425,14 @@ def list_(properties="size,alloc,free,cap,frag,health", zpool=None, parsable=Tru ## parse list output for line in res["stdout"].splitlines(): # NOTE: transform data into dict - zpool_data = OrderedDict(list(zip(properties, line.strip().split("\t"),))) + zpool_data = OrderedDict( + list( + zip( + properties, + line.strip().split("\t"), + ) + ) + ) # NOTE: normalize values if parsable: @@ -547,7 +564,10 @@ def set(zpool, prop, value): # set property res = __salt__["cmd.run_all"]( __utils__["zfs.zpool_command"]( - command="set", property_name=prop, property_value=value, target=zpool, + command="set", + property_name=prop, + property_value=value, + target=zpool, ), python_shell=False, ) @@ -572,7 +592,10 @@ def exists(zpool): # list for zpool # NOTE: retcode > 0 if zpool does not exists res = __salt__["cmd.run_all"]( - __utils__["zfs.zpool_command"](command="list", target=zpool,), + __utils__["zfs.zpool_command"]( + command="list", + target=zpool, + ), python_shell=False, ignore_retcode=True, ) @@ -600,7 +623,9 @@ def destroy(zpool, force=False): # destroy zpool res = __salt__["cmd.run_all"]( __utils__["zfs.zpool_command"]( - command="destroy", flags=["-f"] if force else None, target=zpool, + command="destroy", + flags=["-f"] if force else None, + target=zpool, ), python_shell=False, ) @@ -647,7 +672,11 @@ def scrub(zpool, stop=False, pause=False): ## Scrub storage pool res = __salt__["cmd.run_all"]( - __utils__["zfs.zpool_command"](command="scrub", flags=action, target=zpool,), + __utils__["zfs.zpool_command"]( + command="scrub", + flags=action, + target=zpool, + ), python_shell=False, ) @@ -827,7 +856,11 @@ def add(zpool, *vdevs, **kwargs): ## Update storage pool res = __salt__["cmd.run_all"]( - __utils__["zfs.zpool_command"](command="add", flags=flags, target=target,), + __utils__["zfs.zpool_command"]( + command="add", + flags=flags, + target=target, + ), python_shell=False, ) @@ -880,7 +913,11 @@ def attach(zpool, device, new_device, force=False): ## Update storage pool res = __salt__["cmd.run_all"]( - __utils__["zfs.zpool_command"](command="attach", flags=flags, target=target,), + __utils__["zfs.zpool_command"]( + command="attach", + flags=flags, + target=target, + ), python_shell=False, ) @@ -913,7 +950,10 @@ def detach(zpool, device): """ ## Update storage pool res = __salt__["cmd.run_all"]( - __utils__["zfs.zpool_command"](command="detach", target=[zpool, device],), + __utils__["zfs.zpool_command"]( + command="detach", + target=[zpool, device], + ), python_shell=False, ) @@ -1060,7 +1100,11 @@ def replace(zpool, old_device, new_device=None, force=False): ## Replace device res = __salt__["cmd.run_all"]( - __utils__["zfs.zpool_command"](command="replace", flags=flags, target=target,), + __utils__["zfs.zpool_command"]( + command="replace", + flags=flags, + target=target, + ), python_shell=False, ) @@ -1100,7 +1144,9 @@ def create_file_vdev(size, *vdevs): else: res = __salt__["cmd.run_all"]( "{mkfile} {size} {vdev}".format( - mkfile=_mkfile_cmd, size=size, vdev=vdev, + mkfile=_mkfile_cmd, + size=size, + vdev=vdev, ), python_shell=False, ) @@ -1150,7 +1196,11 @@ def export(*pools, **kwargs): ## Export pools res = __salt__["cmd.run_all"]( - __utils__["zfs.zpool_command"](command="export", flags=flags, target=targets,), + __utils__["zfs.zpool_command"]( + command="export", + flags=flags, + target=targets, + ), python_shell=False, ) @@ -1334,7 +1384,11 @@ def online(zpool, *vdevs, **kwargs): ## Bring online device res = __salt__["cmd.run_all"]( - __utils__["zfs.zpool_command"](command="online", flags=flags, target=target,), + __utils__["zfs.zpool_command"]( + command="online", + flags=flags, + target=target, + ), python_shell=False, ) @@ -1384,7 +1438,11 @@ def offline(zpool, *vdevs, **kwargs): ## Take a device offline res = __salt__["cmd.run_all"]( - __utils__["zfs.zpool_command"](command="offline", flags=flags, target=target,), + __utils__["zfs.zpool_command"]( + command="offline", + flags=flags, + target=target, + ), python_shell=False, ) @@ -1413,7 +1471,9 @@ def labelclear(device, force=False): ## clear label for all specified device res = __salt__["cmd.run_all"]( __utils__["zfs.zpool_command"]( - command="labelclear", flags=["-f"] if force else None, target=device, + command="labelclear", + flags=["-f"] if force else None, + target=device, ), python_shell=False, ) @@ -1454,7 +1514,10 @@ def clear(zpool, device=None): ## clear storage pool errors res = __salt__["cmd.run_all"]( - __utils__["zfs.zpool_command"](command="clear", target=target,), + __utils__["zfs.zpool_command"]( + command="clear", + target=target, + ), python_shell=False, ) @@ -1482,7 +1545,10 @@ def reguid(zpool): """ ## generate new GUID for pool res = __salt__["cmd.run_all"]( - __utils__["zfs.zpool_command"](command="reguid", target=zpool,), + __utils__["zfs.zpool_command"]( + command="reguid", + target=zpool, + ), python_shell=False, ) @@ -1507,7 +1573,10 @@ def reopen(zpool): """ ## reopen all devices fro pool res = __salt__["cmd.run_all"]( - __utils__["zfs.zpool_command"](command="reopen", target=zpool,), + __utils__["zfs.zpool_command"]( + command="reopen", + target=zpool, + ), python_shell=False, ) @@ -1552,7 +1621,10 @@ def upgrade(zpool=None, version=None): ## Upgrade pool res = __salt__["cmd.run_all"]( __utils__["zfs.zpool_command"]( - command="upgrade", flags=flags, opts=opts, target=zpool, + command="upgrade", + flags=flags, + opts=opts, + target=zpool, ), python_shell=False, ) @@ -1598,7 +1670,11 @@ def history(zpool=None, internal=False, verbose=False): ## Lookup history res = __salt__["cmd.run_all"]( - __utils__["zfs.zpool_command"](command="history", flags=flags, target=zpool,), + __utils__["zfs.zpool_command"]( + command="history", + flags=flags, + target=zpool, + ), python_shell=False, ) diff --git a/salt/netapi/rest_tornado/saltnado.py b/salt/netapi/rest_tornado/saltnado.py index 5fb8157ce5c..0d7be51f38b 100644 --- a/salt/netapi/rest_tornado/saltnado.py +++ b/salt/netapi/rest_tornado/saltnado.py @@ -426,7 +426,8 @@ class BaseSaltAPIHandler(salt.ext.tornado.web.RequestHandler): # pylint: disabl if not hasattr(self.application, "event_listener"): log.debug("init a listener") self.application.event_listener = EventListener( - self.application.mod_opts, self.application.opts, + self.application.mod_opts, + self.application.opts, ) if not hasattr(self, "saltclients"): diff --git a/salt/netapi/rest_tornado/saltnado_websockets.py b/salt/netapi/rest_tornado/saltnado_websockets.py index ca8ebad678c..08f4b7ad157 100644 --- a/salt/netapi/rest_tornado/saltnado_websockets.py +++ b/salt/netapi/rest_tornado/saltnado_websockets.py @@ -369,9 +369,7 @@ class AllEventsHandler( pass def on_close(self, *args, **kwargs): - """Cleanup. - - """ + """Cleanup.""" log.debug("In the websocket close method") self.close() diff --git a/salt/output/__init__.py b/salt/output/__init__.py index 25a4766ef13..32d0560772d 100644 --- a/salt/output/__init__.py +++ b/salt/output/__init__.py @@ -191,7 +191,8 @@ def get_printout(out, opts=None, **kwargs): # error when old minions are asking for it if out != "grains": log.error( - "Invalid outputter %s specified, fall back to nested", out, + "Invalid outputter %s specified, fall back to nested", + out, ) return outputters["nested"] return outputters[out] diff --git a/salt/pillar/__init__.py b/salt/pillar/__init__.py index 78ad444a8d3..0f2dc1bf5d6 100644 --- a/salt/pillar/__init__.py +++ b/salt/pillar/__init__.py @@ -239,7 +239,8 @@ class AsyncRemotePillar(RemotePillarMixin): load["ext"] = self.ext try: ret_pillar = yield self.channel.crypted_transfer_decode_dictentry( - load, dictkey="pillar", + load, + dictkey="pillar", ) except Exception: # pylint: disable=broad-except log.exception("Exception getting pillar:") @@ -326,7 +327,8 @@ class RemotePillar(RemotePillarMixin): if self.ext: load["ext"] = self.ext ret_pillar = self.channel.crypted_transfer_decode_dictentry( - load, dictkey="pillar", + load, + dictkey="pillar", ) if not isinstance(ret_pillar, dict): @@ -818,7 +820,9 @@ class Pillar: continue for match, data in body.items(): if self.matchers["confirm_top.confirm_top"]( - match, data, self.opts.get("nodegroups", {}), + match, + data, + self.opts.get("nodegroups", {}), ): if saltenv not in matches: matches[saltenv] = env_matches = [] @@ -939,7 +943,10 @@ class Pillar: else: include_parts = sls.split(".")[:-1] sub_sls = ".".join(include_parts + [sub_sls[1:]]) - matches = fnmatch.filter(self.avail[saltenv], sub_sls,) + matches = fnmatch.filter( + self.avail[saltenv], + sub_sls, + ) matched_pstates.extend(matches) except KeyError: errors.extend( @@ -1150,7 +1157,10 @@ class Pillar: ext = self._external_pillar_data(pillar, val, key) except Exception as exc: # pylint: disable=broad-except errors.append( - "Failed to load ext_pillar {}: {}".format(key, exc.__str__(),) + "Failed to load ext_pillar {}: {}".format( + key, + exc.__str__(), + ) ) log.error( "Exception caught loading ext_pillar '%s':\n%s", diff --git a/salt/pillar/hg_pillar.py b/salt/pillar/hg_pillar.py index 8a72d2550c3..6b573fec79d 100644 --- a/salt/pillar/hg_pillar.py +++ b/salt/pillar/hg_pillar.py @@ -93,7 +93,7 @@ class Repo: """ def __init__(self, repo_uri): - """ Initialize a hg repo (or open it if it already exists) """ + """Initialize a hg repo (or open it if it already exists)""" self.repo_uri = repo_uri cachedir = os.path.join(__opts__["cachedir"], "hg_pillar") hash_type = getattr(hashlib, __opts__.get("hash_type", "md5")) diff --git a/salt/pillar/mysql.py b/salt/pillar/mysql.py index 6f2330ed766..7d910682fa1 100644 --- a/salt/pillar/mysql.py +++ b/salt/pillar/mysql.py @@ -133,8 +133,8 @@ class MySQLExtPillar(SqlBaseExtPillar): def extract_queries(self, args, kwargs): # pylint: disable=useless-super-delegation """ - This function normalizes the config block into a set of queries we - can use. The return is a list of consistently laid out dicts. + This function normalizes the config block into a set of queries we + can use. The return is a list of consistently laid out dicts. """ return super().extract_queries(args, kwargs) diff --git a/salt/pillar/postgres.py b/salt/pillar/postgres.py index a4bf8a0d107..41ac3da03b1 100644 --- a/salt/pillar/postgres.py +++ b/salt/pillar/postgres.py @@ -104,8 +104,8 @@ class POSTGRESExtPillar(SqlBaseExtPillar): def extract_queries(self, args, kwargs): # pylint: disable=useless-super-delegation """ - This function normalizes the config block into a set of queries we - can use. The return is a list of consistently laid out dicts. + This function normalizes the config block into a set of queries we + can use. The return is a list of consistently laid out dicts. """ return super().extract_queries(args, kwargs) diff --git a/salt/pillar/vmware_pillar.py b/salt/pillar/vmware_pillar.py index 08bdb18e568..81a85b80134 100644 --- a/salt/pillar/vmware_pillar.py +++ b/salt/pillar/vmware_pillar.py @@ -388,9 +388,9 @@ def ext_pillar(minion_id, pillar, **kwargs): # pylint: disable=W0613 ] = customValue.value type_specific_pillar_attribute = [] if type_name in type_specific_pillar_attributes: - type_specific_pillar_attribute = type_specific_pillar_attributes[ - type_name - ] + type_specific_pillar_attribute = ( + type_specific_pillar_attributes[type_name] + ) vmware_pillar[pillar_key] = dictupdate.update( vmware_pillar[pillar_key], _crawl_attribute( diff --git a/salt/platform/win.py b/salt/platform/win.py index 60dcd331226..13d75f15962 100644 --- a/salt/platform/win.py +++ b/salt/platform/win.py @@ -786,13 +786,17 @@ _win(ntdll.NtAllocateLocallyUniqueId, NTSTATUS, LPLUID) # _Out_ LUID # https://msdn.microsoft.com/en-us/library/aa378279 _win( - secur32.LsaFreeReturnBuffer, NTSTATUS, wintypes.LPVOID, + secur32.LsaFreeReturnBuffer, + NTSTATUS, + wintypes.LPVOID, ) # _In_ Buffer # https://msdn.microsoft.com/en-us/library/aa378265 _win( - secur32.LsaConnectUntrusted, NTSTATUS, LPHANDLE, + secur32.LsaConnectUntrusted, + NTSTATUS, + LPHANDLE, ) # _Out_ LsaHandle diff --git a/salt/proxy/chronos.py b/salt/proxy/chronos.py index b128a550ece..69b06d63e44 100644 --- a/salt/proxy/chronos.py +++ b/salt/proxy/chronos.py @@ -60,13 +60,16 @@ def ping(): decode=True, ) log.debug( - "chronos.info returned successfully: %s", response, + "chronos.info returned successfully: %s", + response, ) if "dict" in response: return True except Exception as ex: # pylint: disable=broad-except log.error( - "error pinging chronos with base_url %s: %s", CONFIG[CONFIG_BASE_URL], ex, + "error pinging chronos with base_url %s: %s", + CONFIG[CONFIG_BASE_URL], + ex, ) return False diff --git a/salt/proxy/cimc.py b/salt/proxy/cimc.py index cf8c680e572..046ef2e70f3 100644 --- a/salt/proxy/cimc.py +++ b/salt/proxy/cimc.py @@ -193,8 +193,10 @@ def get_config_resolver_class(cid=None, hierarchical=False): if hierarchical is True: h = "true" - payload = ''.format( - cookie, h, cid + payload = ( + ''.format( + cookie, h, cid + ) ) r = __utils__["http.query"]( DETAILS["url"], diff --git a/salt/proxy/marathon.py b/salt/proxy/marathon.py index 72242c99171..5347276bbdb 100644 --- a/salt/proxy/marathon.py +++ b/salt/proxy/marathon.py @@ -55,10 +55,13 @@ def ping(): """ try: response = salt.utils.http.query( - "{}/ping".format(CONFIG[CONFIG_BASE_URL]), decode_type="plain", decode=True, + "{}/ping".format(CONFIG[CONFIG_BASE_URL]), + decode_type="plain", + decode=True, ) log.debug( - "marathon.info returned successfully: %s", response, + "marathon.info returned successfully: %s", + response, ) if "text" in response and response["text"].strip() == "pong": return True diff --git a/salt/returners/__init__.py b/salt/returners/__init__.py index 7cb58ba5320..5ad44a7ff65 100644 --- a/salt/returners/__init__.py +++ b/salt/returners/__init__.py @@ -71,7 +71,15 @@ def get_returner_options(virtualname=None, ret=None, attrs=None, **kwargs): cfg = __salt__.get("config.option", __opts__) # browse the config for relevant options, store them in a dict - _options = dict(_options_browser(cfg, ret_config, defaults, virtualname, attrs,)) + _options = dict( + _options_browser( + cfg, + ret_config, + defaults, + virtualname, + attrs, + ) + ) # override some values with relevant profile options _options.update( @@ -128,7 +136,11 @@ def _fetch_option(cfg, ret_config, virtualname, attr_name): # Using ret_config to override the default configuration key ret_cfg = cfg("{}.{}".format(ret_config, virtualname), {}) - override_default_cfg_key = "{}.{}.{}".format(ret_config, virtualname, attr_name,) + override_default_cfg_key = "{}.{}.{}".format( + ret_config, + virtualname, + attr_name, + ) override_cfg_default = cfg(override_default_cfg_key) # Look for the configuration item in the override location diff --git a/salt/returners/couchbase_return.py b/salt/returners/couchbase_return.py index f22d55e6023..ecd4b300f92 100644 --- a/salt/returners/couchbase_return.py +++ b/salt/returners/couchbase_return.py @@ -181,7 +181,9 @@ def prep_jid(nocache=False, passed_jid=None): try: cb_.add( - str(jid), {"nocache": nocache}, ttl=_get_ttl(), + str(jid), + {"nocache": nocache}, + ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: # TODO: some sort of sleep or something? Spinning is generally bad practice @@ -202,7 +204,9 @@ def returner(load): ret_doc = {"return": load["return"], "full_ret": salt.utils.json.dumps(load)} cb_.add( - hn_key, ret_doc, ttl=_get_ttl(), + hn_key, + ret_doc, + ttl=_get_ttl(), ) except couchbase.exceptions.KeyExistsError: log.error( diff --git a/salt/returners/elasticsearch_return.py b/salt/returners/elasticsearch_return.py index ffdbf8fd8bc..067dc15fb04 100644 --- a/salt/returners/elasticsearch_return.py +++ b/salt/returners/elasticsearch_return.py @@ -276,7 +276,8 @@ def returner(ret): # Prefix the key with the run order so it can be sorted new_uid = "{}_|-{}".format( - str(data["__run_num__"]).zfill(max_chars), uid, + str(data["__run_num__"]).zfill(max_chars), + uid, ) ret["return"][new_uid] = ret["return"].pop(uid) diff --git a/salt/returners/etcd_return.py b/salt/returners/etcd_return.py index 6327f2d1d6d..0f5ca973b1b 100644 --- a/salt/returners/etcd_return.py +++ b/salt/returners/etcd_return.py @@ -115,7 +115,9 @@ def returner(ret): client, path = _get_conn(__opts__, write_profile) # Make a note of this minion for the external job cache client.set( - "/".join((path, "minions", ret["id"])), ret["jid"], ttl=ttl, + "/".join((path, "minions", ret["id"])), + ret["jid"], + ttl=ttl, ) for field in ret: @@ -136,7 +138,9 @@ def save_load(jid, load, minions=None): else: ttl = __opts__.get("etcd.ttl") client.set( - "/".join((path, "jobs", jid, ".load.p")), salt.utils.json.dumps(load), ttl=ttl, + "/".join((path, "jobs", jid, ".load.p")), + salt.utils.json.dumps(load), + ttl=ttl, ) diff --git a/salt/returners/kafka_return.py b/salt/returners/kafka_return.py index 36d20a345dc..18d641023f6 100644 --- a/salt/returners/kafka_return.py +++ b/salt/returners/kafka_return.py @@ -61,8 +61,8 @@ def _get_conn(): def _delivery_report(err, msg): - """ Called once for each message produced to indicate delivery result. - Triggered by poll() or flush(). """ + """Called once for each message produced to indicate delivery result. + Triggered by poll() or flush().""" if err is not None: log.error("Message delivery failed: %s", err) else: diff --git a/salt/returners/splunk.py b/salt/returners/splunk.py index 52cf126388a..77bf78c2f28 100644 --- a/salt/returners/splunk.py +++ b/salt/returners/splunk.py @@ -80,7 +80,8 @@ def _send_splunk(event, index_override=None, sourcetype_override=None): # Get Splunk Options opts = _get_options() log.info( - "Options: %s", salt.utils.json.dumps(opts), + "Options: %s", + salt.utils.json.dumps(opts), ) http_event_collector_key = opts["token"] http_event_collector_host = opts["indexer"] @@ -107,7 +108,8 @@ def _send_splunk(event, index_override=None, sourcetype_override=None): # Add the event payload.update({"event": event}) log.info( - "Payload: %s", salt.utils.json.dumps(payload), + "Payload: %s", + salt.utils.json.dumps(payload), ) # Fire it off splunk_event.sendEvent(payload) diff --git a/salt/runners/bgp.py b/salt/runners/bgp.py index d78da435dc9..2a1eee09b6a 100644 --- a/salt/runners/bgp.py +++ b/salt/runners/bgp.py @@ -388,12 +388,14 @@ def neighbors(*asns, **kwargs): if "vrf" in display_fields: row["vrf"] = vrf if "connection_stats" in display_fields: - connection_stats = "{state} {active}/{received}/{accepted}/{damped}".format( - state=neighbor.get("connection_state", -1), - active=neighbor.get("active_prefix_count", -1), - received=neighbor.get("received_prefix_count", -1), - accepted=neighbor.get("accepted_prefix_count", -1), - damped=neighbor.get("suppressed_prefix_count", -1), + connection_stats = ( + "{state} {active}/{received}/{accepted}/{damped}".format( + state=neighbor.get("connection_state", -1), + active=neighbor.get("active_prefix_count", -1), + received=neighbor.get("received_prefix_count", -1), + accepted=neighbor.get("accepted_prefix_count", -1), + damped=neighbor.get("suppressed_prefix_count", -1), + ) ) row["connection_stats"] = connection_stats if ( diff --git a/salt/runners/manage.py b/salt/runners/manage.py index 2ef14ed4758..ecee3895044 100644 --- a/salt/runners/manage.py +++ b/salt/runners/manage.py @@ -540,9 +540,10 @@ def safe_accept(target, tgt_type="glob"): elif minion not in pending: failures[minion] = "Minion key {} not found by salt-key".format(minion) elif pending[minion] != finger: - failures[minion] = ( - "Minion key {} does not match the key in " - "salt-key: {}".format(finger, pending[minion]) + failures[ + minion + ] = "Minion key {} does not match the key in " "salt-key: {}".format( + finger, pending[minion] ) else: subprocess.call(["salt-key", "-qya", minion]) diff --git a/salt/runners/net.py b/salt/runners/net.py index 2e6ae28930e..166a8ee2570 100644 --- a/salt/runners/net.py +++ b/salt/runners/net.py @@ -336,8 +336,10 @@ def interfaces( net_runner_opts = _get_net_runner_opts() if pattern: - title = 'Pattern "{}" found in the description of the following interfaces'.format( - pattern + title = ( + 'Pattern "{}" found in the description of the following interfaces'.format( + pattern + ) ) if not title: title = "Details" @@ -953,8 +955,10 @@ def find(addr, best=True, display=_DEFAULT_DISPLAY): elif ip: device, interface, mac = _find_interfaces_mac(ip) if device and interface: - title = "IP Address {ip} is set for interface {interface}, on {device}".format( - interface=interface, device=device, ip=ip + title = ( + "IP Address {ip} is set for interface {interface}, on {device}".format( + interface=interface, device=device, ip=ip + ) ) results["int_ip"] = interfaces( device=device, interface=interface, title=title, display=display diff --git a/salt/runners/spacewalk.py b/salt/runners/spacewalk.py index 7720f9c9998..638e338b496 100644 --- a/salt/runners/spacewalk.py +++ b/salt/runners/spacewalk.py @@ -167,8 +167,10 @@ def api(server, command, *args, **kwargs): try: client, key = _get_session(server) except Exception as exc: # pylint: disable=broad-except - err_msg = "Exception raised when connecting to spacewalk server ({}): {}".format( - server, exc + err_msg = ( + "Exception raised when connecting to spacewalk server ({}): {}".format( + server, exc + ) ) log.error(err_msg) return {call: err_msg} @@ -202,8 +204,10 @@ def addGroupsToKey(server, activation_key, groups): try: client, key = _get_session(server) except Exception as exc: # pylint: disable=broad-except - err_msg = "Exception raised when connecting to spacewalk server ({}): {}".format( - server, exc + err_msg = ( + "Exception raised when connecting to spacewalk server ({}): {}".format( + server, exc + ) ) log.error(err_msg) return {"Error": err_msg} @@ -228,8 +232,10 @@ def deleteAllGroups(server): try: client, key = _get_session(server) except Exception as exc: # pylint: disable=broad-except - err_msg = "Exception raised when connecting to spacewalk server ({}): {}".format( - server, exc + err_msg = ( + "Exception raised when connecting to spacewalk server ({}): {}".format( + server, exc + ) ) log.error(err_msg) return {"Error": err_msg} @@ -265,8 +271,10 @@ def deleteAllSystems(server): try: client, key = _get_session(server) except Exception as exc: # pylint: disable=broad-except - err_msg = "Exception raised when connecting to spacewalk server ({}): {}".format( - server, exc + err_msg = ( + "Exception raised when connecting to spacewalk server ({}): {}".format( + server, exc + ) ) log.error(err_msg) return {"Error": err_msg} @@ -299,8 +307,10 @@ def deleteAllActivationKeys(server): try: client, key = _get_session(server) except Exception as exc: # pylint: disable=broad-except - err_msg = "Exception raised when connecting to spacewalk server ({}): {}".format( - server, exc + err_msg = ( + "Exception raised when connecting to spacewalk server ({}): {}".format( + server, exc + ) ) log.error(err_msg) return {"Error": err_msg} @@ -336,8 +346,10 @@ def unregister(name, server_url): try: client, key = _get_session(server_url) except Exception as exc: # pylint: disable=broad-except - err_msg = "Exception raised when connecting to spacewalk server ({}): {}".format( - server_url, exc + err_msg = ( + "Exception raised when connecting to spacewalk server ({}): {}".format( + server_url, exc + ) ) log.error(err_msg) return {name: err_msg} diff --git a/salt/scripts.py b/salt/scripts.py index d3e36884184..ac47ed6c585 100644 --- a/salt/scripts.py +++ b/salt/scripts.py @@ -301,7 +301,12 @@ def proxy_minion_process(queue): proxyminion = salt.cli.daemons.ProxyMinion() proxyminion.start() # pylint: disable=broad-except - except (Exception, SaltClientError, SaltReqTimeoutError, SaltSystemExit,) as exc: + except ( + Exception, + SaltClientError, + SaltReqTimeoutError, + SaltSystemExit, + ) as exc: # pylint: enable=broad-except log.error("Proxy Minion failed to start: ", exc_info=True) restart = True diff --git a/salt/sdb/sqlite3.py b/salt/sdb/sqlite3.py index 1ebc85716f3..9f89a5321a4 100644 --- a/salt/sdb/sqlite3.py +++ b/salt/sdb/sqlite3.py @@ -123,7 +123,8 @@ def set_(key, value, profile=None): conn, cur, table = _connect(profile) value = memoryview(salt.utils.msgpack.packb(value)) q = profile.get( - "set_query", ("INSERT OR REPLACE INTO {} VALUES (:key, :value)").format(table), + "set_query", + ("INSERT OR REPLACE INTO {} VALUES (:key, :value)").format(table), ) conn.execute(q, {"key": key, "value": value}) conn.commit() diff --git a/salt/sdb/tism.py b/salt/sdb/tism.py index 8304c2079da..08b05b08b4a 100644 --- a/salt/sdb/tism.py +++ b/salt/sdb/tism.py @@ -59,7 +59,9 @@ def get(key, service=None, profile=None): # pylint: disable=W0613 request = {"token": profile["token"], "encsecret": key} result = http.query( - profile["url"], method="POST", data=salt.utils.json.dumps(request), + profile["url"], + method="POST", + data=salt.utils.json.dumps(request), ) decrypted = result.get("body") diff --git a/salt/spm/__init__.py b/salt/spm/__init__.py index b692acfddba..7b84ca8b9e2 100644 --- a/salt/spm/__init__.py +++ b/salt/spm/__init__.py @@ -818,7 +818,11 @@ class SPMClient: metadata_filename = "{}/SPM-METADATA".format(repo_path) with salt.utils.files.fopen(metadata_filename, "w") as mfh: salt.utils.yaml.safe_dump( - repo_metadata, mfh, indent=4, canonical=False, default_flow_style=False, + repo_metadata, + mfh, + indent=4, + canonical=False, + default_flow_style=False, ) log.debug("Wrote %s", metadata_filename) diff --git a/salt/spm/pkgfiles/local.py b/salt/spm/pkgfiles/local.py index 1f852149745..c4270679844 100644 --- a/salt/spm/pkgfiles/local.py +++ b/salt/spm/pkgfiles/local.py @@ -135,7 +135,11 @@ def install_file(package, formula_tar, member, formula_def, conn=None): if node_type in ("master", "minion"): # Module files are distributed via extmods directory member.name = new_name.name.replace("{}/_".format(package), "") - out_path = os.path.join(salt.syspaths.CACHE_DIR, node_type, "extmods",) + out_path = os.path.join( + salt.syspaths.CACHE_DIR, + node_type, + "extmods", + ) else: # Module files are distributed via _modules, _states, etc member.name = new_name.name.replace("{}/".format(package), "") diff --git a/salt/state.py b/salt/state.py index 69e28e31dab..7b8b3b8c4a5 100644 --- a/salt/state.py +++ b/salt/state.py @@ -535,7 +535,8 @@ class Compiler: 'Illegal requisite "{}", ' "is SLS {}\n" ).format( - str(req_val), body["__sls__"], + str(req_val), + body["__sls__"], ) ) continue @@ -2461,7 +2462,10 @@ class State: comment = ( 'The state function "{0}" is currently disabled by "{1}", ' "to re-enable, run state.enable {1}." - ).format(state_, pat,) + ).format( + state_, + pat, + ) _tag = _gen_tag(low) disabled[_tag] = { "changes": {}, @@ -2816,10 +2820,10 @@ class State: self.opts.get("state_events", True) or fire_event ): if not self.opts.get("master_uri"): - ev_func = lambda ret, tag, preload=None: salt.utils.event.get_master_event( - self.opts, self.opts["sock_dir"], listen=False - ).fire_event( - ret, tag + ev_func = ( + lambda ret, tag, preload=None: salt.utils.event.get_master_event( + self.opts, self.opts["sock_dir"], listen=False + ).fire_event(ret, tag) ) else: ev_func = self.functions["event.fire_master"] @@ -2827,11 +2831,13 @@ class State: ret = {"ret": chunk_ret} if fire_event is True: tag = salt.utils.event.tagify( - [self.jid, self.opts["id"], str(chunk_ret["name"])], "state_result", + [self.jid, self.opts["id"], str(chunk_ret["name"])], + "state_result", ) elif isinstance(fire_event, str): tag = salt.utils.event.tagify( - [self.jid, self.opts["id"], str(fire_event)], "state_result", + [self.jid, self.opts["id"], str(fire_event)], + "state_result", ) else: tag = salt.utils.event.tagify( diff --git a/salt/states/aptpkg.py b/salt/states/aptpkg.py index 2b6bd67d59e..62b83f37b26 100644 --- a/salt/states/aptpkg.py +++ b/salt/states/aptpkg.py @@ -32,7 +32,9 @@ def held(name): The name of the package, e.g., 'tmux' """ ret = {"name": name, "changes": {}, "result": False, "comment": ""} - state = __salt__["pkg.get_selections"](pattern=name,) + state = __salt__["pkg.get_selections"]( + pattern=name, + ) if not state: ret.update(comment="Package {} does not have a state".format(name)) elif not salt.utils.data.is_true(state.get("hold", False)): diff --git a/salt/states/archive.py b/salt/states/archive.py index c9d212eefe4..e49ab94ee60 100644 --- a/salt/states/archive.py +++ b/salt/states/archive.py @@ -65,14 +65,17 @@ def _checksum_file_path(path): if re.match(r"..[/\\]", relpath): # path is a local file relpath = salt.utils.path.join( - "local", os.path.splitdrive(path)[-1].lstrip("/\\"), + "local", + os.path.splitdrive(path)[-1].lstrip("/\\"), ) except ValueError as exc: # The path is on a different drive (Windows) if str(exc).startswith("path is on"): drive, path = os.path.splitdrive(path) relpath = salt.utils.path.join( - "local", drive.rstrip(":"), path.lstrip("/\\"), + "local", + drive.rstrip(":"), + path.lstrip("/\\"), ) elif str(exc).startswith("Cannot mix UNC"): relpath = salt.utils.path.join("unc", path) @@ -867,7 +870,8 @@ def extracted( "Invalid archive_format '{}'. Either set it to a supported " "value ({}) or remove this argument and the archive format will " "be guessed based on file extension.".format( - archive_format, ", ".join(valid_archive_formats), + archive_format, + ", ".join(valid_archive_formats), ) ) return ret @@ -1158,7 +1162,9 @@ def extracted( "top-level directory by adding it to the 'name' " "value (for example, setting 'name' to {} " "instead of {}).".format( - archive_format, os.path.join(name, "some_dir"), name, + archive_format, + os.path.join(name, "some_dir"), + name, ) ) return ret @@ -1628,7 +1634,8 @@ def extracted( ret["changes"]["directories_created"] = [name] ret["changes"]["extracted_files"] = files ret["comment"] = "{} extracted to {}".format( - salt.utils.url.redact_http_basic_auth(source_match), name, + salt.utils.url.redact_http_basic_auth(source_match), + name, ) _add_explanation(ret, source_hash_trigger, contents_missing) ret["comment"] += ". Output was trimmed to {} number of lines".format( diff --git a/salt/states/at.py b/salt/states/at.py index d390bcbc6ea..2e1dec6ad4d 100644 --- a/salt/states/at.py +++ b/salt/states/at.py @@ -61,7 +61,10 @@ def present(name, timespec, tag=None, user=None, job=None, unique_tag=False): # quick return on test=True if __opts__["test"]: ret["result"] = None - ret["comment"] = "job {} added and will run on {}".format(job, timespec,) + ret["comment"] = "job {} added and will run on {}".format( + job, + timespec, + ) return ret # quick return if unique_tag and job exists @@ -82,12 +85,26 @@ def present(name, timespec, tag=None, user=None, job=None, unique_tag=False): ret["comment"] = "user {} does not exists".format(user) return ret ret["comment"] = "job {} added and will run as {} on {}".format( - job, user, timespec, + job, + user, + timespec, + ) + res = __salt__["at.at"]( + timespec, + job, + tag=tag, + runas=user, ) - res = __salt__["at.at"](timespec, job, tag=tag, runas=user,) else: - ret["comment"] = "job {} added and will run on {}".format(job, timespec,) - res = __salt__["at.at"](timespec, job, tag=tag,) + ret["comment"] = "job {} added and will run on {}".format( + job, + timespec, + ) + res = __salt__["at.at"]( + timespec, + job, + tag=tag, + ) # set ret['changes'] if "jobs" in res and len(res["jobs"]) > 0: diff --git a/salt/states/azurearm_network.py b/salt/states/azurearm_network.py index 426b3c9302d..7c07262a7b8 100644 --- a/salt/states/azurearm_network.py +++ b/salt/states/azurearm_network.py @@ -2430,8 +2430,9 @@ def route_present( "new": next_hop_type, } - if next_hop_type.lower() == "virtualappliance" and next_hop_ip_address != route.get( - "next_hop_ip_address" + if ( + next_hop_type.lower() == "virtualappliance" + and next_hop_ip_address != route.get("next_hop_ip_address") ): ret["changes"]["next_hop_ip_address"] = { "old": route.get("next_hop_ip_address"), diff --git a/salt/states/boto_apigateway.py b/salt/states/boto_apigateway.py index 8764d40ae8e..ad9a086c043 100644 --- a/salt/states/boto_apigateway.py +++ b/salt/states/boto_apigateway.py @@ -1458,9 +1458,10 @@ class _Swagger: ret = _log_changes(ret, "delete_api", delete_api_response) else: - ret["comment"] = ( - "api already absent for swagger file: " - "{}, desc: {}".format(self.rest_api_name, self.info_json) + ret[ + "comment" + ] = "api already absent for swagger file: " "{}, desc: {}".format( + self.rest_api_name, self.info_json ) return ret @@ -1591,13 +1592,12 @@ class _Swagger: ret["result"] = False ret["abort"] = True if "error" in update_model_schema_response: - ret["comment"] = ( - "Failed to update existing model {} with schema {}, " - "error: {}".format( - model, - _dict_to_json_pretty(schema), - update_model_schema_response["error"]["message"], - ) + ret[ + "comment" + ] = "Failed to update existing model {} with schema {}, " "error: {}".format( + model, + _dict_to_json_pretty(schema), + update_model_schema_response["error"]["message"], ) return ret @@ -1616,13 +1616,12 @@ class _Swagger: ret["result"] = False ret["abort"] = True if "error" in create_model_response: - ret["comment"] = ( - "Failed to create model {}, schema {}, " - "error: {}".format( - model, - _dict_to_json_pretty(schema), - create_model_response["error"]["message"], - ) + ret[ + "comment" + ] = "Failed to create model {}, schema {}, " "error: {}".format( + model, + _dict_to_json_pretty(schema), + create_model_response["error"]["message"], ) return ret diff --git a/salt/states/boto_cloudfront.py b/salt/states/boto_cloudfront.py index 70536a05c68..db83cc10b80 100644 --- a/salt/states/boto_cloudfront.py +++ b/salt/states/boto_cloudfront.py @@ -61,7 +61,13 @@ def __virtual__(): def present( - name, config, tags, region=None, key=None, keyid=None, profile=None, + name, + config, + tags, + region=None, + key=None, + keyid=None, + profile=None, ): """ Ensure the CloudFront distribution is present. @@ -108,12 +114,17 @@ def present( } res = __salt__["boto_cloudfront.get_distribution"]( - name, region=region, key=key, keyid=keyid, profile=profile, + name, + region=region, + key=key, + keyid=keyid, + profile=profile, ) if "error" in res: ret["result"] = False ret["comment"] = "Error checking distribution {}: {}".format( - name, res["error"], + name, + res["error"], ) return ret @@ -126,12 +137,19 @@ def present( return ret res = __salt__["boto_cloudfront.create_distribution"]( - name, config, tags, region=region, key=key, keyid=keyid, profile=profile, + name, + config, + tags, + region=region, + key=key, + keyid=keyid, + profile=profile, ) if "error" in res: ret["result"] = False ret["comment"] = "Error creating distribution {}: {}".format( - name, res["error"], + name, + res["error"], ) return ret @@ -149,7 +167,8 @@ def present( "tags": tags, } diffed_config = __utils__["dictdiffer.deep_diff"]( - full_config_old, full_config_new, + full_config_old, + full_config_new, ) def _yaml_safe_dump(attrs): @@ -172,7 +191,9 @@ def present( any_changes = bool("old" in diffed_config or "new" in diffed_config) if not any_changes: ret["result"] = True - ret["comment"] = "Distribution {} has correct config.".format(name,) + ret["comment"] = "Distribution {} has correct config.".format( + name, + ) return ret if __opts__["test"]: @@ -184,12 +205,19 @@ def present( return ret res = __salt__["boto_cloudfront.update_distribution"]( - name, config, tags, region=region, key=key, keyid=keyid, profile=profile, + name, + config, + tags, + region=region, + key=key, + keyid=keyid, + profile=profile, ) if "error" in res: ret["result"] = False ret["comment"] = "Error updating distribution {}: {}".format( - name, res["error"], + name, + res["error"], ) return ret diff --git a/salt/states/boto_cognitoidentity.py b/salt/states/boto_cognitoidentity.py index 3e2c9d0b968..90bad219e27 100644 --- a/salt/states/boto_cognitoidentity.py +++ b/salt/states/boto_cognitoidentity.py @@ -260,9 +260,10 @@ def pool_present( if r.get("created"): updated_identity_pool = r.get("identity_pool") IdentityPoolId = updated_identity_pool.get("IdentityPoolId") - ret["comment"] = ( - "A new identity pool with name {}, id {} " - "is created.".format(IdentityPoolName, IdentityPoolId) + ret[ + "comment" + ] = "A new identity pool with name {}, id {} " "is created.".format( + IdentityPoolName, IdentityPoolId ) else: ret["result"] = False @@ -278,19 +279,19 @@ def pool_present( if r.get("updated"): updated_identity_pool = r.get("identity_pool") - ret["comment"] = ( - "Existing identity pool with name {}, id {} " - "is updated.".format(IdentityPoolName, IdentityPoolId) + ret[ + "comment" + ] = "Existing identity pool with name {}, id {} " "is updated.".format( + IdentityPoolName, IdentityPoolId ) else: ret["result"] = False - ret["comment"] = ( - "Failed to update an existing identity pool {} {}: " - "{}".format( - IdentityPoolName, - IdentityPoolId, - r["error"].get("message", r["error"]), - ) + ret[ + "comment" + ] = "Failed to update an existing identity pool {} {}: " "{}".format( + IdentityPoolName, + IdentityPoolId, + r["error"].get("message", r["error"]), ) return ret @@ -386,9 +387,10 @@ def pool_absent( return ret if __opts__["test"]: - ret["comment"] = ( - "The following matched identity pools will be " - "deleted.\n{}".format(identity_pools) + ret[ + "comment" + ] = "The following matched identity pools will be " "deleted.\n{}".format( + identity_pools ) ret["result"] = None return ret @@ -418,8 +420,10 @@ def pool_absent( ) else: ret["result"] = False - failure_comment = "Identity Pool Id {} not deleted, returned count 0".format( - IdentityPoolId + failure_comment = ( + "Identity Pool Id {} not deleted, returned count 0".format( + IdentityPoolId + ) ) ret["comment"] = "{}\n{}".format(ret["comment"], failure_comment) return ret diff --git a/salt/states/boto_datapipeline.py b/salt/states/boto_datapipeline.py index eafb6b17bca..e42e328791e 100644 --- a/salt/states/boto_datapipeline.py +++ b/salt/states/boto_datapipeline.py @@ -142,7 +142,12 @@ def present( return ret result_create_pipeline = __salt__["boto_datapipeline.create_pipeline"]( - name, name, region=region, key=key, keyid=keyid, profile=profile, + name, + name, + region=region, + key=key, + keyid=keyid, + profile=profile, ) if "error" in result_create_pipeline: ret["result"] = False @@ -171,7 +176,11 @@ def present( if _immutable_fields_error(result_pipeline_definition): # If update not possible, delete and retry result_delete_pipeline = __salt__["boto_datapipeline.delete_pipeline"]( - pipeline_id, region=region, key=key, keyid=keyid, profile=profile, + pipeline_id, + region=region, + key=key, + keyid=keyid, + profile=profile, ) if "error" in result_delete_pipeline: ret["result"] = False @@ -181,7 +190,12 @@ def present( return ret result_create_pipeline = __salt__["boto_datapipeline.create_pipeline"]( - name, name, region=region, key=key, keyid=keyid, profile=profile, + name, + name, + region=region, + key=key, + keyid=keyid, + profile=profile, ) if "error" in result_create_pipeline: ret["result"] = False @@ -218,7 +232,11 @@ def present( return ret result_activate_pipeline = __salt__["boto_datapipeline.activate_pipeline"]( - pipeline_id, region=region, key=key, keyid=keyid, profile=profile, + pipeline_id, + region=region, + key=key, + keyid=keyid, + profile=profile, ) if "error" in result_activate_pipeline: ret["result"] = False @@ -303,7 +321,11 @@ def _pipeline_present_with_definition( that contains a dict with region, key and keyid. """ result_pipeline_id = __salt__["boto_datapipeline.pipeline_id_from_name"]( - name, region=region, key=key, keyid=keyid, profile=profile, + name, + region=region, + key=key, + keyid=keyid, + profile=profile, ) if "error" in result_pipeline_id: return False, {} @@ -565,7 +587,11 @@ def absent(name, region=None, key=None, keyid=None, profile=None): ret = {"name": name, "result": True, "comment": "", "changes": {}} result_pipeline_id = __salt__["boto_datapipeline.pipeline_id_from_name"]( - name, region=region, key=key, keyid=keyid, profile=profile, + name, + region=region, + key=key, + keyid=keyid, + profile=profile, ) if "error" not in result_pipeline_id: pipeline_id = result_pipeline_id["result"] @@ -575,7 +601,11 @@ def absent(name, region=None, key=None, keyid=None, profile=None): return ret else: __salt__["boto_datapipeline.delete_pipeline"]( - pipeline_id, region=region, key=key, keyid=keyid, profile=profile, + pipeline_id, + region=region, + key=key, + keyid=keyid, + profile=profile, ) ret["changes"]["old"] = {"pipeline_id": pipeline_id} ret["changes"]["new"] = None diff --git a/salt/states/boto_dynamodb.py b/salt/states/boto_dynamodb.py index bc8e7c1e65b..8e563ba0574 100644 --- a/salt/states/boto_dynamodb.py +++ b/salt/states/boto_dynamodb.py @@ -632,7 +632,12 @@ def _update_global_secondary_indexes( changes_old.setdefault("global_indexes", {}) changes_new.setdefault("global_indexes", {}) success = __salt__["boto_dynamodb.update_global_secondary_index"]( - name, index_updates, region=region, key=key, keyid=keyid, profile=profile, + name, + index_updates, + region=region, + key=key, + keyid=keyid, + profile=profile, ) if success: diff --git a/salt/states/boto_ec2.py b/salt/states/boto_ec2.py index 265afa67db7..926292599f9 100644 --- a/salt/states/boto_ec2.py +++ b/salt/states/boto_ec2.py @@ -1001,11 +1001,10 @@ def instance_present( if r[0].get("instance_id"): if r[0]["instance_id"] != instance_id: ret["result"] = False - ret["comment"] = ( - "EIP {} is already associated with instance " - "{}.".format( - public_ip if public_ip else allocation_id, r[0]["instance_id"] - ) + ret[ + "comment" + ] = "EIP {} is already associated with instance " "{}.".format( + public_ip if public_ip else allocation_id, r[0]["instance_id"] ) return ret else: @@ -1228,9 +1227,10 @@ def instance_absent( ) except CommandExecutionError as e: ret["result"] = None - ret["comment"] = ( - "Couldn't determine current status of instance " - "{}.".format(instance_name or name) + ret[ + "comment" + ] = "Couldn't determine current status of instance " "{}.".format( + instance_name or name ) return ret @@ -1434,8 +1434,10 @@ def volume_absent( ret["comment"] = "Volume matching criteria not found, assuming already absent" return ret if len(vols) > 1: - msg = "More than one volume matched criteria, can't continue in state {}".format( - name + msg = ( + "More than one volume matched criteria, can't continue in state {}".format( + name + ) ) log.error(msg) ret["comment"] = msg @@ -2075,12 +2077,11 @@ def private_ips_absent( else: # Testing mode, show that there were ips to remove - ret["comment"] = ( - "ips on eni: {}\n" - "ips that would be removed: {}\n".format( - "\n\t- " + "\n\t- ".join(ret["changes"]["old"]), - "\n\t- " + "\n\t- ".join(ips_to_remove), - ) + ret[ + "comment" + ] = "ips on eni: {}\n" "ips that would be removed: {}\n".format( + "\n\t- " + "\n\t- ".join(ret["changes"]["old"]), + "\n\t- " + "\n\t- ".join(ips_to_remove), ) ret["changes"] = {} ret["result"] = None diff --git a/salt/states/boto_elasticsearch_domain.py b/salt/states/boto_elasticsearch_domain.py index df864eb3dcc..603db60b220 100644 --- a/salt/states/boto_elasticsearch_domain.py +++ b/salt/states/boto_elasticsearch_domain.py @@ -275,11 +275,11 @@ def present( )["domain"] if _status.get("ElasticsearchVersion") != str(ElasticsearchVersion): ret["result"] = False - ret["comment"] = ( - "Failed to update domain: version cannot be modified " - "from {} to {}.".format( - _status.get("ElasticsearchVersion"), str(ElasticsearchVersion), - ) + ret[ + "comment" + ] = "Failed to update domain: version cannot be modified " "from {} to {}.".format( + _status.get("ElasticsearchVersion"), + str(ElasticsearchVersion), ) return ret _describe = __salt__["boto_elasticsearch_domain.describe"]( diff --git a/salt/states/boto_rds.py b/salt/states/boto_rds.py index e0fff2ca7ea..fff6327d181 100644 --- a/salt/states/boto_rds.py +++ b/salt/states/boto_rds.py @@ -470,9 +470,10 @@ def replica_present( ) if not modified: ret["result"] = False - ret["comment"] = ( - "Failed to update parameter group of {} RDS " - "instance.".format(name) + ret[ + "comment" + ] = "Failed to update parameter group of {} RDS " "instance.".format( + name ) ret["changes"]["old"] = pmg_name ret["changes"]["new"] = db_parameter_group_name diff --git a/salt/states/boto_s3.py b/salt/states/boto_s3.py index 40a953c2764..8073abe6dd4 100644 --- a/salt/states/boto_s3.py +++ b/salt/states/boto_s3.py @@ -187,12 +187,18 @@ def object_present( digest = salt.utils.hashutils.get_hash(source, form=hash_type) except OSError as e: ret["result"] = False - ret["comment"] = "Could not read local file {}: {}".format(source, e,) + ret["comment"] = "Could not read local file {}: {}".format( + source, + e, + ) return ret except ValueError as e: # Invalid hash type exception from get_hash ret["result"] = False - ret["comment"] = "Could not hash local file {}: {}".format(source, e,) + ret["comment"] = "Could not hash local file {}: {}".format( + source, + e, + ) return ret HASH_METADATA_KEY = "salt_managed_content_hash" @@ -227,7 +233,9 @@ def object_present( ) if "error" in r: ret["result"] = False - ret["comment"] = "Failed to check if S3 object exists: {}.".format(r["error"],) + ret["comment"] = "Failed to check if S3 object exists: {}.".format( + r["error"], + ) return ret if r["result"]: @@ -284,7 +292,10 @@ def object_present( if "error" in r: ret["result"] = False - ret["comment"] = "Failed to {} S3 object: {}.".format(action, r["error"],) + ret["comment"] = "Failed to {} S3 object: {}.".format( + action, + r["error"], + ) return ret ret["result"] = True diff --git a/salt/states/boto_sqs.py b/salt/states/boto_sqs.py index 8db68fb417b..0c3784070c9 100644 --- a/salt/states/boto_sqs.py +++ b/salt/states/boto_sqs.py @@ -75,7 +75,12 @@ def __virtual__(): def present( - name, attributes=None, region=None, key=None, keyid=None, profile=None, + name, + attributes=None, + region=None, + key=None, + keyid=None, + profile=None, ): """ Ensure the SQS queue exists. @@ -107,7 +112,11 @@ def present( } r = __salt__["boto_sqs.exists"]( - name, region=region, key=key, keyid=keyid, profile=profile, + name, + region=region, + key=key, + keyid=keyid, + profile=profile, ) if "error" in r: ret["result"] = False @@ -119,7 +128,9 @@ def present( else: if __opts__["test"]: ret["result"] = None - ret["comment"].append("SQS queue {} is set to be created.".format(name),) + ret["comment"].append( + "SQS queue {} is set to be created.".format(name), + ) ret["changes"] = {"old": None, "new": name} return ret @@ -148,11 +159,17 @@ def present( return ret r = __salt__["boto_sqs.get_attributes"]( - name, region=region, key=key, keyid=keyid, profile=profile, + name, + region=region, + key=key, + keyid=keyid, + profile=profile, ) if "error" in r: ret["result"] = False - ret["comment"].append("Failed to get queue attributes: {}".format(r["error"]),) + ret["comment"].append( + "Failed to get queue attributes: {}".format(r["error"]), + ) return ret current_attributes = r["result"] @@ -198,27 +215,41 @@ def present( ret["result"] = None ret["comment"].append( "Attribute(s) {} set to be updated:\n{}".format( - attr_names, attributes_diff, + attr_names, + attributes_diff, ) ) ret["changes"] = {"attributes": {"diff": attributes_diff}} return ret r = __salt__["boto_sqs.set_attributes"]( - name, attrs_to_set, region=region, key=key, keyid=keyid, profile=profile, + name, + attrs_to_set, + region=region, + key=key, + keyid=keyid, + profile=profile, ) if "error" in r: ret["result"] = False - ret["comment"].append("Failed to set queue attributes: {}".format(r["error"]),) + ret["comment"].append( + "Failed to set queue attributes: {}".format(r["error"]), + ) return ret - ret["comment"].append("Updated SQS queue attribute(s) {}.".format(attr_names),) + ret["comment"].append( + "Updated SQS queue attribute(s) {}.".format(attr_names), + ) ret["changes"]["attributes"] = {"diff": attributes_diff} return ret def absent( - name, region=None, key=None, keyid=None, profile=None, + name, + region=None, + key=None, + keyid=None, + profile=None, ): """ Ensure the named sqs queue is deleted. @@ -242,7 +273,11 @@ def absent( ret = {"name": name, "result": True, "comment": "", "changes": {}} r = __salt__["boto_sqs.exists"]( - name, region=region, key=key, keyid=keyid, profile=profile, + name, + region=region, + key=key, + keyid=keyid, + profile=profile, ) if "error" in r: ret["result"] = False @@ -250,7 +285,10 @@ def absent( return ret if not r["result"]: - ret["comment"] = "SQS queue {} does not exist in {}.".format(name, region,) + ret["comment"] = "SQS queue {} does not exist in {}.".format( + name, + region, + ) return ret if __opts__["test"]: @@ -260,7 +298,11 @@ def absent( return ret r = __salt__["boto_sqs.delete"]( - name, region=region, key=key, keyid=keyid, profile=profile, + name, + region=region, + key=key, + keyid=keyid, + profile=profile, ) if "error" in r: ret["result"] = False diff --git a/salt/states/boto_vpc.py b/salt/states/boto_vpc.py index 56dc7db7841..c061827d5e8 100644 --- a/salt/states/boto_vpc.py +++ b/salt/states/boto_vpc.py @@ -1262,8 +1262,10 @@ def _routes_present( profile=profile, ) if "error" in r: - msg = "Error looking up id for VPC peering connection {}: {}".format( - i.get("vpc_peering_connection_name"), r["error"]["message"] + msg = ( + "Error looking up id for VPC peering connection {}: {}".format( + i.get("vpc_peering_connection_name"), r["error"]["message"] + ) ) ret["comment"] = msg ret["result"] = False @@ -1478,8 +1480,10 @@ def _subnets_present( profile=profile, ) if "error" in r: - msg = "Failed to associate subnet {} with route table {}: {}.".format( - sn, route_table_name, r["error"]["message"] + msg = ( + "Failed to associate subnet {} with route table {}: {}.".format( + sn, route_table_name, r["error"]["message"] + ) ) ret["comment"] = msg ret["result"] = False @@ -2035,11 +2039,10 @@ def vpc_peering_connection_present( keyid=keyid, profile=profile, ): - ret["comment"] = ( - "VPC peering {} already requested - pending " - "acceptance by {}".format( - conn_name, peer_owner_id or peer_vpc_name or peer_vpc_id - ) + ret[ + "comment" + ] = "VPC peering {} already requested - pending " "acceptance by {}".format( + conn_name, peer_owner_id or peer_vpc_name or peer_vpc_id ) log.info(ret["comment"]) return ret diff --git a/salt/states/chronos_job.py b/salt/states/chronos_job.py index f068f5bf213..7bea17b8335 100644 --- a/salt/states/chronos_job.py +++ b/salt/states/chronos_job.py @@ -48,7 +48,9 @@ def config(name, config): if existing_config: update_config = copy.deepcopy(existing_config) salt.utils.configcomparer.compare_and_update_config( - config, update_config, ret["changes"], + config, + update_config, + ret["changes"], ) else: # the job is not configured--we need to create it from scratch @@ -76,10 +78,12 @@ def config(name, config): log.debug("_old schedule: %s", _old) if len(_new) == 3 and len(_old) == 3: log.debug( - "_new[0] == _old[0]: %s", str(_new[0]) == str(_old[0]), + "_new[0] == _old[0]: %s", + str(_new[0]) == str(_old[0]), ) log.debug( - "_new[2] == _old[2]: %s", str(_new[2]) == str(_old[2]), + "_new[2] == _old[2]: %s", + str(_new[2]) == str(_old[2]), ) if str(_new[0]) == str(_old[0]) and str(_new[2]) == str( _old[2] @@ -100,7 +104,8 @@ def config(name, config): if "exception" in update_result: ret["result"] = False ret["comment"] = "Failed to update job config for {}: {}".format( - name, update_result["exception"], + name, + update_result["exception"], ) return ret else: diff --git a/salt/states/cloud.py b/salt/states/cloud.py index 2492863ce80..c3e9746bd30 100644 --- a/salt/states/cloud.py +++ b/salt/states/cloud.py @@ -120,7 +120,9 @@ def present(name, cloud_provider, onlyif=None, unless=None, opts=None, **kwargs) elif info and "Error" in info: ret["result"] = False ret["comment"] = "Failed to create instance {} using profile {}: {}".format( - name, profile, info["Error"], + name, + profile, + info["Error"], ) else: ret["result"] = False @@ -185,7 +187,8 @@ def absent(name, onlyif=None, unless=None): elif "Error" in info: ret["result"] = False ret["comment"] = ("Failed to destroy instance {}: {}").format( - name, info["Error"], + name, + info["Error"], ) else: ret["result"] = False @@ -261,7 +264,10 @@ def profile(name, profile, onlyif=None, unless=None, opts=None, **kwargs): if info and not error: node_info = info.get(name) ret["result"] = True - default_msg = "Created instance {} using profile {}".format(name, profile,) + default_msg = "Created instance {} using profile {}".format( + name, + profile, + ) # some providers support changes if "changes" in node_info: ret["changes"] = node_info["changes"] @@ -272,12 +278,15 @@ def profile(name, profile, onlyif=None, unless=None, opts=None, **kwargs): elif error: ret["result"] = False ret["comment"] = ("Failed to create instance {} using profile {}: {}").format( - name, profile, "{}\n{}\n".format(main_error, name_error).strip(), + name, + profile, + "{}\n{}\n".format(main_error, name_error).strip(), ) else: ret["result"] = False ret["comment"] = "Failed to create instance {} using profile {}".format( - name, profile, + name, + profile, ) return ret diff --git a/salt/states/docker_container.py b/salt/states/docker_container.py index 4be61c18556..b2d32d9a5f9 100644 --- a/salt/states/docker_container.py +++ b/salt/states/docker_container.py @@ -188,7 +188,8 @@ def _resolve_image(ret, image, client_timeout): # Image not pulled locally, so try pulling it try: pull_result = __salt__["docker.pull"]( - image, client_timeout=client_timeout, + image, + client_timeout=client_timeout, ) except Exception as exc: # pylint: disable=broad-except raise CommandExecutionError("Failed to pull {}: {}".format(image, exc)) @@ -1843,7 +1844,9 @@ def running( if not skip_comparison: container_changes = __salt__["docker.compare_containers"]( - name, temp_container_name, ignore="Hostname", + name, + temp_container_name, + ignore="Hostname", ) if container_changes: if _check_diff(container_changes): @@ -2273,9 +2276,10 @@ def run( pass else: ret["result"] = False if failhard and retcode != 0 else True - ret["comment"] = ( - "Container ran and exited with a return code of " - "{}".format(retcode) + ret[ + "comment" + ] = "Container ran and exited with a return code of " "{}".format( + retcode ) if remove: diff --git a/salt/states/docker_network.py b/salt/states/docker_network.py index 0aa53a5a82d..79945bc3ec8 100644 --- a/salt/states/docker_network.py +++ b/salt/states/docker_network.py @@ -619,9 +619,10 @@ def present( # Set the comment now to say that it already exists, if we need to # recreate the network with new config we'll update the comment later. - ret["comment"] = ( - "Network '{}' already exists, and is configured " - "as specified".format(name) + ret[ + "comment" + ] = "Network '{}' already exists, and is configured " "as specified".format( + name ) log.trace("Details of docker network '%s': %s", name, network) diff --git a/salt/states/ethtool.py b/salt/states/ethtool.py index b636aa99488..612b2c2c0fc 100644 --- a/salt/states/ethtool.py +++ b/salt/states/ethtool.py @@ -202,9 +202,10 @@ def ring(name, **kwargs): return ret if new: ret["result"] = None - ret["comment"] = ( - "Device {} ring parameters are set to be " - "updated:\n{}".format(name, "\n".join(diff)) + ret[ + "comment" + ] = "Device {} ring parameters are set to be " "updated:\n{}".format( + name, "\n".join(diff) ) return ret @@ -280,9 +281,10 @@ def offload(name, **kwargs): return ret if new: ret["result"] = None - ret["comment"] = ( - "Device {} offload settings are set to be " - "updated:\n{}".format(name, "\n".join(diff)) + ret[ + "comment" + ] = "Device {} offload settings are set to be " "updated:\n{}".format( + name, "\n".join(diff) ) return ret diff --git a/salt/states/file.py b/salt/states/file.py index 0efc2ad9439..aaa9b5d4f03 100644 --- a/salt/states/file.py +++ b/salt/states/file.py @@ -1465,9 +1465,10 @@ def hardlink( # except for let the user know that this has already happened. if _hardlink_same(name, target): ret["result"] = True - ret["comment"] = ( - "Target of hard link {} is already pointing " - "to {}".format(name, target) + ret[ + "comment" + ] = "Target of hard link {} is already pointing " "to {}".format( + name, target ) return ret @@ -1745,9 +1746,10 @@ def symlink( name, win_owner ) else: - ret["comment"] = ( - "Symlink {} is present and owned by " - "{}:{}".format(name, user, group) + ret[ + "comment" + ] = "Symlink {} is present and owned by " "{}:{}".format( + name, user, group ) else: if _set_symlink_ownership(name, user, group, win_owner): @@ -1757,22 +1759,25 @@ def symlink( ) ret["changes"]["ownership"] = win_owner else: - ret["comment"] = ( - "Set ownership of symlink {} to " - "{}:{}".format(name, user, group) + ret[ + "comment" + ] = "Set ownership of symlink {} to " "{}:{}".format( + name, user, group ) ret["changes"]["ownership"] = "{}:{}".format(user, group) else: ret["result"] = False if salt.utils.platform.is_windows(): - ret["comment"] += ( - "Failed to set ownership of symlink " - "{} to {}".format(name, win_owner) + ret[ + "comment" + ] += "Failed to set ownership of symlink " "{} to {}".format( + name, win_owner ) else: - ret["comment"] += ( - "Failed to set ownership of symlink {} to " - "{}:{}".format(name, user, group) + ret[ + "comment" + ] += "Failed to set ownership of symlink {} to " "{}:{}".format( + name, user, group ) return ret @@ -2985,9 +2990,10 @@ def managed( else: ret["comment"] = "File {} not updated".format(name) elif not ret["changes"] and ret["result"]: - ret["comment"] = ( - "File {} exists with proper permissions. " - "No changes made.".format(name) + ret[ + "comment" + ] = "File {} exists with proper permissions. " "No changes made.".format( + name ) return ret @@ -3751,9 +3757,10 @@ def directory( # As above with user, we need to make sure group exists. if isinstance(gid, str): ret["result"] = False - ret["comment"] = ( - "Failed to enforce group ownership " - "for group {}".format(group) + ret[ + "comment" + ] = "Failed to enforce group ownership " "for group {}".format( + group ) else: ret["result"] = False @@ -5242,7 +5249,8 @@ def keyvalue( if not key_values: msg = "is empty" return _error( - ret, "file.keyvalue key and value not supplied and key_values " + msg, + ret, + "file.keyvalue key and value not supplied and key_values " + msg, ) # try to open the file and only return a comment if ignore_if_missing is @@ -5754,9 +5762,10 @@ def blockreplace( ) except Exception as exc: # pylint: disable=broad-except log.exception("Encountered error managing block") - ret["comment"] = ( - "Encountered error managing block: {}. " - "See the log for details.".format(exc) + ret[ + "comment" + ] = "Encountered error managing block: {}. " "See the log for details.".format( + exc ) return ret @@ -7199,9 +7208,10 @@ def copy_( ) ret["result"] = None else: - ret["comment"] = ( - 'The target file "{}" exists and will not be ' - "overwritten".format(name) + ret[ + "comment" + ] = 'The target file "{}" exists and will not be ' "overwritten".format( + name ) ret["result"] = True return ret @@ -7287,9 +7297,10 @@ def rename(name, source, force=False, makedirs=False, **kwargs): if os.path.lexists(source) and os.path.lexists(name): if not force: - ret["comment"] = ( - 'The target file "{}" exists and will not be ' - "overwritten".format(name) + ret[ + "comment" + ] = 'The target file "{}" exists and will not be ' "overwritten".format( + name ) return ret elif not __opts__["test"]: @@ -7971,9 +7982,10 @@ def mknod(name, ntype, major=0, minor=0, user=None, group=None, mode="0600"): elif ntype == "p": # Check for file existence if __salt__["file.file_exists"](name): - ret["comment"] = ( - "File {} exists and is not a fifo pipe. Refusing to " - "continue".format(name) + ret[ + "comment" + ] = "File {} exists and is not a fifo pipe. Refusing to " "continue".format( + name ) # Check if it is a fifo @@ -8371,9 +8383,10 @@ def shortcut( ret["changes"]["ownership"] = "{}".format(user) else: ret["result"] = False - ret["comment"] += ( - "Failed to set ownership of shortcut {} to " - "{}".format(name, user) + ret[ + "comment" + ] += "Failed to set ownership of shortcut {} to " "{}".format( + name, user ) return ret @@ -8554,9 +8567,10 @@ def cached( ) if local_hash == source_sum["hsum"]: ret["result"] = True - ret["comment"] = ( - "File {} is present on the minion and has hash " - "{}".format(full_path, local_hash) + ret[ + "comment" + ] = "File {} is present on the minion and has hash " "{}".format( + full_path, local_hash ) else: ret["comment"] = ( @@ -8638,9 +8652,10 @@ def cached( return ret if not local_copy: - ret["comment"] = ( - "Failed to cache {}, check minion log for more " - "information".format(salt.utils.url.redact_http_basic_auth(name)) + ret[ + "comment" + ] = "Failed to cache {}, check minion log for more " "information".format( + salt.utils.url.redact_http_basic_auth(name) ) return ret diff --git a/salt/states/gpg.py b/salt/states/gpg.py index 6b7c7370c07..4329e6685a6 100644 --- a/salt/states/gpg.py +++ b/salt/states/gpg.py @@ -82,7 +82,9 @@ def present( if current_keys[key]["trust"] != TRUST_MAP[trust]: # update trust level result = __salt__["gpg.trust_key"]( - keyid=key, trust_level=trust, user=user, + keyid=key, + trust_level=trust, + user=user, ) if "result" in result and not result["result"]: ret["result"] = result["result"] @@ -103,7 +105,12 @@ def present( ret["comment"].append("GPG Public Key {} already in keychain ".format(key)) else: - result = __salt__["gpg.receive_keys"](keyserver, key, user, gnupghome,) + result = __salt__["gpg.receive_keys"]( + keyserver, + key, + user, + gnupghome, + ) if "result" in result and not result["result"]: ret["result"] = result["result"] ret["comment"].append(result["comment"]) @@ -113,7 +120,9 @@ def present( if trust: if trust in _VALID_TRUST_VALUES: result = __salt__["gpg.trust_key"]( - keyid=key, trust_level=trust, user=user, + keyid=key, + trust_level=trust, + user=user, ) if "result" in result and not result["result"]: ret["result"] = result["result"] @@ -163,7 +172,11 @@ def absent(name, keys=None, user=None, gnupghome=None, **kwargs): for key in keys: if key in current_keys: - result = __salt__["gpg.delete_key"](key, user, gnupghome,) + result = __salt__["gpg.delete_key"]( + key, + user, + gnupghome, + ) if "result" in result and not result["result"]: ret["result"] = result["result"] ret["comment"].append(result["comment"]) diff --git a/salt/states/grafana4_org.py b/salt/states/grafana4_org.py index 05c1b9a86ee..4ae49a003f5 100644 --- a/salt/states/grafana4_org.py +++ b/salt/states/grafana4_org.py @@ -192,9 +192,10 @@ def present( ) elif role != db_users[username]["role"]: if __opts__["test"]: - ret["comment"] = ( - "Org {} user {} role will be " - "updated".format(name, username) + ret[ + "comment" + ] = "Org {} user {} role will be " "updated".format( + name, username ) return ret __salt__["grafana4.update_org_user"]( diff --git a/salt/states/grains.py b/salt/states/grains.py index 7012d246bad..679b33a40a8 100644 --- a/salt/states/grains.py +++ b/salt/states/grains.py @@ -437,9 +437,10 @@ def append(name, value, convert=False, delimiter=DEFAULT_TARGET_DELIM): if grain or name in __grains__: if isinstance(grain, list): if value in grain: - ret["comment"] = ( - "Value {1} is already in the list " - "for grain {0}".format(name, value) + ret[ + "comment" + ] = "Value {1} is already in the list " "for grain {0}".format( + name, value ) return ret if __opts__["test"]: diff --git a/salt/states/influxdb_user.py b/salt/states/influxdb_user.py index b7fe3d65060..e1a6c3c9839 100644 --- a/salt/states/influxdb_user.py +++ b/salt/states/influxdb_user.py @@ -118,9 +118,10 @@ def present(name, passwd, admin=False, grants=None, **client_args): else: if __opts__["test"]: ret["result"] = None - ret["comment"] = ( - "User {} will be updated with the " - "following changes:".format(name) + ret[ + "comment" + ] = "User {} will be updated with the " "following changes:".format( + name ) for k, v in ret["changes"].items(): ret["comment"] += "\n{} => {}".format(k, v) diff --git a/salt/states/kapacitor.py b/salt/states/kapacitor.py index f50321989e7..23f99ff2e8a 100644 --- a/salt/states/kapacitor.py +++ b/salt/states/kapacitor.py @@ -121,7 +121,10 @@ def task_present( if old_script != new_script: ret["changes"]["TICKscript diff"] = "\n".join( - difflib.unified_diff(old_script.splitlines(), new_script.splitlines(),) + difflib.unified_diff( + old_script.splitlines(), + new_script.splitlines(), + ) ) comments.append("Task script updated") diff --git a/salt/states/ldap.py b/salt/states/ldap.py index cad37218444..ebfcd7db971 100644 --- a/salt/states/ldap.py +++ b/salt/states/ldap.py @@ -528,4 +528,6 @@ def _toset(thing): try: return OrderedSet(str(x) for x in thing) except TypeError: - return OrderedSet(str(thing),) + return OrderedSet( + str(thing), + ) diff --git a/salt/states/loop.py b/salt/states/loop.py index fcfbc3923bc..b9fb2d07c6c 100644 --- a/salt/states/loop.py +++ b/salt/states/loop.py @@ -216,16 +216,18 @@ def until_no_eval( ) if cmp_res: ret["result"] = True - ret["comment"] = ( - "Call provided the expected results in {} attempts" - "".format(current_attempt) + ret[ + "comment" + ] = "Call provided the expected results in {} attempts" "".format( + current_attempt ) break time.sleep(period) else: - ret["comment"] = ( - "Call did not produce the expected result after {} attempts" - "".format(current_attempt) + ret[ + "comment" + ] = "Call did not produce the expected result after {} attempts" "".format( + current_attempt ) log.debug( "%s:until_no_eval:\n" "\t\tResults of all attempts: %s", diff --git a/salt/states/lvs_service.py b/salt/states/lvs_service.py index a45d4409509..4e12c321773 100644 --- a/salt/states/lvs_service.py +++ b/salt/states/lvs_service.py @@ -14,7 +14,10 @@ def __virtual__(): def present( - name, protocol=None, service_address=None, scheduler="wlc", + name, + protocol=None, + service_address=None, + scheduler="wlc", ): """ Ensure that the named service is present. diff --git a/salt/states/lxd_container.py b/salt/states/lxd_container.py index b2c58dab74f..395f1374ea2 100644 --- a/salt/states/lxd_container.py +++ b/salt/states/lxd_container.py @@ -315,7 +315,8 @@ def present( if __opts__["test"]: changes["running"] = "Would start the container" return _unchanged( - ret, 'Container "{}" would get changed and started.'.format(name), + ret, + 'Container "{}" would get changed and started.'.format(name), ) else: container.start(wait=True) @@ -325,7 +326,8 @@ def present( if __opts__["test"]: changes["stopped"] = "Would stopped the container" return _unchanged( - ret, 'Container "{}" would get changed and stopped.'.format(name), + ret, + 'Container "{}" would get changed and stopped.'.format(name), ) else: container.stop(wait=True) @@ -675,7 +677,7 @@ def migrated( src_key=None, src_verify_cert=None, ): - """ Ensure a container is migrated to another host + """Ensure a container is migrated to another host If the container is running, it either must be shut down first (use stop_and_start=True) or criu must be installed diff --git a/salt/states/marathon_app.py b/salt/states/marathon_app.py index 1df39665f36..3d44503db61 100644 --- a/salt/states/marathon_app.py +++ b/salt/states/marathon_app.py @@ -49,7 +49,9 @@ def config(name, config): if existing_config: update_config = copy.deepcopy(existing_config) salt.utils.configcomparer.compare_and_update_config( - config, update_config, ret["changes"], + config, + update_config, + ret["changes"], ) else: # the app is not configured--we need to create it from scratch @@ -71,7 +73,8 @@ def config(name, config): if "exception" in update_result: ret["result"] = False ret["comment"] = "Failed to update app config for {}: {}".format( - name, update_result["exception"], + name, + update_result["exception"], ) return ret else: diff --git a/salt/states/modjk_worker.py b/salt/states/modjk_worker.py index a38dd51c4b6..657e0b1ed42 100644 --- a/salt/states/modjk_worker.py +++ b/salt/states/modjk_worker.py @@ -127,9 +127,10 @@ def _talk2modjk(name, lbn, target, action, profile="default", tgt_type="glob"): return ret if status["errors"]: ret["result"] = False - ret["comment"] = ( - "the following balancers could not find the " - "worker {}: {}".format(name, status["errors"]) + ret[ + "comment" + ] = "the following balancers could not find the " "worker {}: {}".format( + name, status["errors"] ) return ret if not status["wrong_state"]: diff --git a/salt/states/msteams.py b/salt/states/msteams.py index f4db009339b..d84387c7d68 100644 --- a/salt/states/msteams.py +++ b/salt/states/msteams.py @@ -75,7 +75,10 @@ def post_card(name, message, hook_url=None, title=None, theme_color=None): try: result = __salt__["msteams.post_card"]( - message=message, hook_url=hook_url, title=title, theme_color=theme_color, + message=message, + hook_url=hook_url, + title=title, + theme_color=theme_color, ) except SaltInvocationError as sie: ret["comment"] = "Failed to send message ({}): {}".format(sie, name) diff --git a/salt/states/mysql_database.py b/salt/states/mysql_database.py index b4419556064..d62a1a054d1 100644 --- a/salt/states/mysql_database.py +++ b/salt/states/mysql_database.py @@ -63,7 +63,9 @@ def present(name, character_set=None, collate=None, **connection_args): if character_set and character_set != existing_charset: alter_charset = True log.debug( - "character set differes from %s : %s", character_set, existing_charset, + "character set differes from %s : %s", + character_set, + existing_charset, ) comment = ("Database character set {} != {} needs to be updated").format( @@ -79,7 +81,9 @@ def present(name, character_set=None, collate=None, **connection_args): if collate and collate != existing_collate: alter_collate = True log.debug( - "collate set differs from %s : %s", collate, existing_collate, + "collate set differs from %s : %s", + collate, + existing_collate, ) comment = ("Database collate {} != {} needs to be updated").format( diff --git a/salt/states/mysql_grants.py b/salt/states/mysql_grants.py index 7c964cf1c96..f3b7ce121dd 100644 --- a/salt/states/mysql_grants.py +++ b/salt/states/mysql_grants.py @@ -257,18 +257,20 @@ def absent( else: err = _get_mysql_error() if err is not None: - ret["comment"] = ( - "Unable to revoke grant {} on {} for " - "{}@{} ({})".format(grant, database, user, host, err) + ret[ + "comment" + ] = "Unable to revoke grant {} on {} for " "{}@{} ({})".format( + grant, database, user, host, err ) ret["result"] = False return ret else: err = _get_mysql_error() if err is not None: - ret["comment"] = ( - "Unable to determine if grant {} on {} for " - "{}@{} exists ({})".format(grant, database, user, host, err) + ret[ + "comment" + ] = "Unable to determine if grant {} on {} for " "{}@{} exists ({})".format( + grant, database, user, host, err ) ret["result"] = False return ret diff --git a/salt/states/network.py b/salt/states/network.py index f20863113b4..d9ec5a4c28b 100644 --- a/salt/states/network.py +++ b/salt/states/network.py @@ -554,9 +554,10 @@ def managed(name, enabled=True, **kwargs): elif old != new: diff = difflib.unified_diff(old, new, lineterm="") ret["result"] = None - ret["comment"] = ( - "Bond interface {} is set to be " - "updated:\n{}".format(name, "\n".join(diff)) + ret[ + "comment" + ] = "Bond interface {} is set to be " "updated:\n{}".format( + name, "\n".join(diff) ) else: if not old and new: @@ -719,9 +720,10 @@ def routes(name, **kwargs): elif old != new: diff = difflib.unified_diff(old, new, lineterm="") ret["result"] = None - ret["comment"] = ( - "Interface {} routes are set to be " - "updated:\n{}".format(name, "\n".join(diff)) + ret[ + "comment" + ] = "Interface {} routes are set to be " "updated:\n{}".format( + name, "\n".join(diff) ) return ret if not old and new: @@ -783,9 +785,10 @@ def system(name, **kwargs): elif old != new: diff = difflib.unified_diff(old, new, lineterm="") ret["result"] = None - ret["comment"] = ( - "Global network settings are set to be " - "updated:\n{}".format("\n".join(diff)) + ret[ + "comment" + ] = "Global network settings are set to be " "updated:\n{}".format( + "\n".join(diff) ) return ret if not old and new: diff --git a/salt/states/nftables.py b/salt/states/nftables.py index 0886b774e6e..e91d8bcd741 100644 --- a/salt/states/nftables.py +++ b/salt/states/nftables.py @@ -286,9 +286,10 @@ def append(name, family="ipv4", **kwargs): if "save" in kwargs: if kwargs["save"]: __salt__["nftables.save"](filename=None, family=family) - ret["comment"] = ( - "Set and Saved nftables rule for {} to: " - "{} for {}".format(name, command.strip(), family) + ret[ + "comment" + ] = "Set and Saved nftables rule for {} to: " "{} for {}".format( + name, command.strip(), family ) return ret else: @@ -360,9 +361,10 @@ def insert(name, family="ipv4", **kwargs): if "save" in kwargs: if kwargs["save"]: __salt__["nftables.save"](filename=None, family=family) - ret["comment"] = ( - "Set and Saved nftables rule for {} to: " - "{} for {}".format(name, command.strip(), family) + ret[ + "comment" + ] = "Set and Saved nftables rule for {} to: " "{} for {}".format( + name, command.strip(), family ) return ret else: @@ -438,9 +440,10 @@ def delete(name, family="ipv4", **kwargs): if "save" in kwargs: if kwargs["save"]: __salt__["nftables.save"](filename=None, family=family) - ret["comment"] = ( - "Deleted and Saved nftables rule for {} for {}" - "{}".format(name, command.strip(), family) + ret[ + "comment" + ] = "Deleted and Saved nftables rule for {} for {}" "{}".format( + name, command.strip(), family ) return ret else: diff --git a/salt/states/pagerduty.py b/salt/states/pagerduty.py index e4eace4524f..bfdd82f28ac 100644 --- a/salt/states/pagerduty.py +++ b/salt/states/pagerduty.py @@ -60,7 +60,10 @@ def create_event(name, details, service_key, profile): ret["comment"] = "Need to create event: {}".format(name) return ret __salt__["pagerduty.create_event"]( - description=name, details=details, service_key=service_key, profile=profile, + description=name, + details=details, + service_key=service_key, + profile=profile, ) ret["result"] = True ret["comment"] = "Created event: {}".format(name) diff --git a/salt/states/panos.py b/salt/states/panos.py index 536eb97ac1b..fb915bbdb78 100644 --- a/salt/states/panos.py +++ b/salt/states/panos.py @@ -1205,28 +1205,34 @@ def security_rule_exists( else: member_string = "" if datafilter: - member_string += "{}".format( - datafilter + member_string += ( + "{}".format( + datafilter + ) ) if fileblock: - member_string += "{}".format( - fileblock + member_string += ( + "{}".format(fileblock) ) if spyware: member_string += "{}".format(spyware) if urlfilter: - member_string += "{}".format( - urlfilter + member_string += ( + "{}".format(urlfilter) ) if virus: member_string += "{}".format(virus) if vulnerability: - member_string += "{}".format( - vulnerability + member_string += ( + "{}".format( + vulnerability + ) ) if wildfire: - member_string += "{}".format( - wildfire + member_string += ( + "{}".format( + wildfire + ) ) if member_string != "": profile_string = "{}".format(member_string) diff --git a/salt/states/pdbedit.py b/salt/states/pdbedit.py index a01e5ef3775..15d7cdd1753 100644 --- a/salt/states/pdbedit.py +++ b/salt/states/pdbedit.py @@ -126,7 +126,8 @@ def managed(name, **kwargs): ret["changes"] = res elif res[name] in ["updated"]: ret["changes"][name] = salt.utils.data.compare_dicts( - saved, __salt__["pdbedit.list"](hashes=True)[name], + saved, + __salt__["pdbedit.list"](hashes=True)[name], ) elif res[name] not in ["unchanged"]: ret["result"] = False diff --git a/salt/states/pip_state.py b/salt/states/pip_state.py index dc7833a770a..9fb7ad52585 100644 --- a/salt/states/pip_state.py +++ b/salt/states/pip_state.py @@ -69,7 +69,11 @@ def pip_has_internal_exceptions_mod(ver): """ True when the pip version has the `pip._internal.exceptions` module """ - return salt.utils.versions.compare(ver1=ver, oper=">=", ver2="10.0",) + return salt.utils.versions.compare( + ver1=ver, + oper=">=", + ver2="10.0", + ) def pip_has_exceptions_mod(ver): diff --git a/salt/states/pkg.py b/salt/states/pkg.py index 9cb285b35c2..fef45cab1e6 100644 --- a/salt/states/pkg.py +++ b/salt/states/pkg.py @@ -603,7 +603,8 @@ def _find_install_targets( # pylint: enable=not-callable elif sources: desired = __salt__["pkg_resource.pack_sources"]( - sources, normalize=normalize, + sources, + normalize=normalize, ) if not desired: @@ -2302,9 +2303,10 @@ def downloaded( ret["comment"] = exc.strerror_without_changes else: ret["changes"] = {} - ret["comment"] = ( - "An error was encountered while downloading " - "package(s): {}".format(exc) + ret[ + "comment" + ] = "An error was encountered while downloading " "package(s): {}".format( + exc ) return ret @@ -2404,18 +2406,20 @@ def patch_installed(name, advisory_ids=None, downloadonly=None, **kwargs): ret["comment"] = exc.strerror_without_changes else: ret["changes"] = {} - ret["comment"] = ( - "An error was encountered while downloading " - "package(s): {}".format(exc) + ret[ + "comment" + ] = "An error was encountered while downloading " "package(s): {}".format( + exc ) return ret if not ret["changes"] and not ret["comment"]: status = "downloaded" if downloadonly else "installed" ret["result"] = True - ret["comment"] = ( - "Advisory patch is not needed or related packages " - "are already {}".format(status) + ret[ + "comment" + ] = "Advisory patch is not needed or related packages " "are already {}".format( + status ) return ret @@ -2469,159 +2473,159 @@ def latest( **kwargs ): """ - Ensure that the named package is installed and the latest available - package. If the package can be updated, this state function will update - the package. Generally it is better for the - :mod:`installed ` function to be - used, as :mod:`latest ` will update the package - whenever a new package is available. + Ensure that the named package is installed and the latest available + package. If the package can be updated, this state function will update + the package. Generally it is better for the + :mod:`installed ` function to be + used, as :mod:`latest ` will update the package + whenever a new package is available. - .. note:: - Any argument which is either a) not explicitly defined for this state, - or b) not a global state argument like ``saltenv``, or - ``reload_modules``, will be passed through to the call to - ``pkg.install`` to install the package(s). For example, you can include - a ``disablerepo`` argument on platforms that use yum/dnf to disable - that repo: + .. note:: + Any argument which is either a) not explicitly defined for this state, + or b) not a global state argument like ``saltenv``, or + ``reload_modules``, will be passed through to the call to + ``pkg.install`` to install the package(s). For example, you can include + a ``disablerepo`` argument on platforms that use yum/dnf to disable + that repo: - .. code-block:: yaml + .. code-block:: yaml - mypkg: + mypkg: + pkg.latest: + - disablerepo: base,updates + + To see what is supported, check :ref:`this page ` to find + the documentation for your platform's ``pkg`` module, then look at the + documentation for the ``install`` function. + + Any argument that is passed through to the ``install`` function, which + is not defined for that function, will be silently ignored. + + name + The name of the package to maintain at the latest available version. + This parameter is ignored if "pkgs" is used. + + fromrepo + Specify a repository from which to install + + skip_verify + Skip the GPG verification check for the package to be installed + + refresh + This parameter controls whether or not the package repo database is + updated prior to checking for the latest available version of the + requested packages. + + If ``True``, the package database will be refreshed (``apt-get update`` + or equivalent, depending on platform) before checking for the latest + available version of the requested packages. + + If ``False``, the package database will *not* be refreshed before + checking. + + If unset, then Salt treats package database refreshes differently + depending on whether or not a ``pkg`` state has been executed already + during the current Salt run. Once a refresh has been performed in a + ``pkg`` state, for the remainder of that Salt run no other refreshes + will be performed for ``pkg`` states which do not explicitly set + ``refresh`` to ``True``. This prevents needless additional refreshes + from slowing down the Salt run. + + :param str cache_valid_time: + + .. versionadded:: 2016.11.0 + + This parameter sets the value in seconds after which the cache is + marked as invalid, and a cache update is necessary. This overwrites + the ``refresh`` parameter's default behavior. + + Example: + + .. code-block:: yaml + + httpd: + pkg.latest: + - refresh: True + - cache_valid_time: 300 + + In this case, a refresh will not take place for 5 minutes since the last + ``apt-get update`` was executed on the system. + + .. note:: + + This parameter is available only on Debian based distributions and + has no effect on the rest. + + :param bool resolve_capabilities: + Turn on resolving capabilities. This allow one to name "provides" or alias names for packages. + + .. versionadded:: 2018.3.0 + + Multiple Package Installation Options: + + (Not yet supported for: FreeBSD, OpenBSD, MacOS, and Solaris pkgutil) + + pkgs + A list of packages to maintain at the latest available version. + + .. code-block:: yaml + + mypkgs: + pkg.latest: + - pkgs: + - foo + - bar + - baz + + install_recommends + Whether to install the packages marked as recommended. Default is + ``True``. Currently only works with APT-based systems. + + .. versionadded:: 2015.5.0 + + .. code-block:: yaml + + httpd: + pkg.latest: + - install_recommends: False + + only_upgrade + Only upgrade the packages, if they are already installed. Default is + ``False``. Currently only works with APT-based systems. + + .. versionadded:: 2015.5.0 + + .. code-block:: yaml + + httpd: + pkg.latest: + - only_upgrade: True + + .. note:: + If this parameter is set to True and the package is not already + installed, the state will fail. + + report_reboot_exit_codes + If the installer exits with a recognized exit code indicating that + a reboot is required, the module function + + *win_system.set_reboot_required_witnessed* + + will be called, preserving the knowledge of this event + for the remainder of the current boot session. For the time being, + ``3010`` is the only recognized exit code, but this + is subject to future refinement. The value of this param + defaults to ``True``. This parameter has no effect on + non-Windows systems. + + .. versionadded:: 2016.11.0 + + .. code-block:: yaml + + ms vcpp installed: pkg.latest: - - disablerepo: base,updates - - To see what is supported, check :ref:`this page ` to find - the documentation for your platform's ``pkg`` module, then look at the - documentation for the ``install`` function. - - Any argument that is passed through to the ``install`` function, which - is not defined for that function, will be silently ignored. - - name - The name of the package to maintain at the latest available version. - This parameter is ignored if "pkgs" is used. - - fromrepo - Specify a repository from which to install - - skip_verify - Skip the GPG verification check for the package to be installed - - refresh - This parameter controls whether or not the package repo database is - updated prior to checking for the latest available version of the - requested packages. - - If ``True``, the package database will be refreshed (``apt-get update`` - or equivalent, depending on platform) before checking for the latest - available version of the requested packages. - - If ``False``, the package database will *not* be refreshed before - checking. - - If unset, then Salt treats package database refreshes differently - depending on whether or not a ``pkg`` state has been executed already - during the current Salt run. Once a refresh has been performed in a - ``pkg`` state, for the remainder of that Salt run no other refreshes - will be performed for ``pkg`` states which do not explicitly set - ``refresh`` to ``True``. This prevents needless additional refreshes - from slowing down the Salt run. - - :param str cache_valid_time: - - .. versionadded:: 2016.11.0 - - This parameter sets the value in seconds after which the cache is - marked as invalid, and a cache update is necessary. This overwrites - the ``refresh`` parameter's default behavior. - - Example: - - .. code-block:: yaml - - httpd: - pkg.latest: - - refresh: True - - cache_valid_time: 300 - - In this case, a refresh will not take place for 5 minutes since the last - ``apt-get update`` was executed on the system. - - .. note:: - - This parameter is available only on Debian based distributions and - has no effect on the rest. - - :param bool resolve_capabilities: - Turn on resolving capabilities. This allow one to name "provides" or alias names for packages. - - .. versionadded:: 2018.3.0 - - Multiple Package Installation Options: - - (Not yet supported for: FreeBSD, OpenBSD, MacOS, and Solaris pkgutil) - - pkgs - A list of packages to maintain at the latest available version. - - .. code-block:: yaml - - mypkgs: - pkg.latest: - - pkgs: - - foo - - bar - - baz - - install_recommends - Whether to install the packages marked as recommended. Default is - ``True``. Currently only works with APT-based systems. - - .. versionadded:: 2015.5.0 - - .. code-block:: yaml - - httpd: - pkg.latest: - - install_recommends: False - - only_upgrade - Only upgrade the packages, if they are already installed. Default is - ``False``. Currently only works with APT-based systems. - - .. versionadded:: 2015.5.0 - - .. code-block:: yaml - - httpd: - pkg.latest: - - only_upgrade: True - - .. note:: - If this parameter is set to True and the package is not already - installed, the state will fail. - - report_reboot_exit_codes - If the installer exits with a recognized exit code indicating that - a reboot is required, the module function - - *win_system.set_reboot_required_witnessed* - - will be called, preserving the knowledge of this event - for the remainder of the current boot session. For the time being, - ``3010`` is the only recognized exit code, but this - is subject to future refinement. The value of this param - defaults to ``True``. This parameter has no effect on - non-Windows systems. - - .. versionadded:: 2016.11.0 - - .. code-block:: yaml - - ms vcpp installed: - pkg.latest: - - name: ms-vcpp - - report_reboot_exit_codes: False + - name: ms-vcpp + - report_reboot_exit_codes: False """ refresh = salt.utils.pkg.check_refresh(__opts__, refresh) diff --git a/salt/states/ports.py b/salt/states/ports.py index f600bdba855..022f02694ee 100644 --- a/salt/states/ports.py +++ b/salt/states/ports.py @@ -142,9 +142,10 @@ def installed(name, options=None): bad_opts = [x for x in options if x not in default_options] if bad_opts: ret["result"] = False - ret["comment"] = ( - "The following options are not available for " - "{}: {}".format(name, ", ".join(bad_opts)) + ret[ + "comment" + ] = "The following options are not available for " "{}: {}".format( + name, ", ".join(bad_opts) ) return ret diff --git a/salt/states/postgres_schema.py b/salt/states/postgres_schema.py index 3bf2573d19f..5770d5c4f2a 100644 --- a/salt/states/postgres_schema.py +++ b/salt/states/postgres_schema.py @@ -152,9 +152,10 @@ def absent( if __salt__["postgres.schema_exists"](dbname, name, **db_args): if __opts__["test"]: ret["result"] = None - ret["comment"] = ( - "Schema {} is set to be removed" - " from database {}".format(name, dbname) + ret[ + "comment" + ] = "Schema {} is set to be removed" " from database {}".format( + name, dbname ) return ret elif __salt__["postgres.schema_remove"](dbname, name, **db_args): diff --git a/salt/states/saltmod.py b/salt/states/saltmod.py index c4c75b80bb1..5cdbf066ea1 100644 --- a/salt/states/saltmod.py +++ b/salt/states/saltmod.py @@ -748,7 +748,8 @@ def runner(name, **kwargs): success = out.get("success", True) ret = {"name": name, "changes": {"return": runner_return}, "result": success} ret["comment"] = "Runner function '{}' {}.".format( - name, "executed" if success else "failed", + name, + "executed" if success else "failed", ) ret["__orchestration__"] = True @@ -989,7 +990,8 @@ def wheel(name, **kwargs): success = out.get("success", True) ret = {"name": name, "changes": {"return": wheel_return}, "result": success} ret["comment"] = "Wheel function '{}' {}.".format( - name, "executed" if success else "failed", + name, + "executed" if success else "failed", ) ret["__orchestration__"] = True diff --git a/salt/states/selinux.py b/salt/states/selinux.py index 8bd3c98abe8..0b78c5a34c3 100644 --- a/salt/states/selinux.py +++ b/salt/states/selinux.py @@ -505,7 +505,10 @@ def port_policy_present(name, sel_type, protocol=None, port=None, sel_range=None """ ret = {"name": name, "result": False, "changes": {}, "comment": ""} old_state = __salt__["selinux.port_get_policy"]( - name=name, sel_type=sel_type, protocol=protocol, port=port, + name=name, + sel_type=sel_type, + protocol=protocol, + port=port, ) if old_state: ret.update( @@ -533,7 +536,10 @@ def port_policy_present(name, sel_type, protocol=None, port=None, sel_range=None else: ret.update({"result": True}) new_state = __salt__["selinux.port_get_policy"]( - name=name, sel_type=sel_type, protocol=protocol, port=port, + name=name, + sel_type=sel_type, + protocol=protocol, + port=port, ) ret["changes"].update({"old": old_state, "new": new_state}) return ret @@ -560,7 +566,10 @@ def port_policy_absent(name, sel_type=None, protocol=None, port=None): """ ret = {"name": name, "result": False, "changes": {}, "comment": ""} old_state = __salt__["selinux.port_get_policy"]( - name=name, sel_type=sel_type, protocol=protocol, port=port, + name=name, + sel_type=sel_type, + protocol=protocol, + port=port, ) if not old_state: ret.update( @@ -577,14 +586,19 @@ def port_policy_absent(name, sel_type=None, protocol=None, port=None): ret.update({"result": None}) else: delete_ret = __salt__["selinux.port_delete_policy"]( - name=name, protocol=protocol, port=port, + name=name, + protocol=protocol, + port=port, ) if delete_ret["retcode"] != 0: ret.update({"comment": "Error deleting policy: {}".format(delete_ret)}) else: ret.update({"result": True}) new_state = __salt__["selinux.port_get_policy"]( - name=name, sel_type=sel_type, protocol=protocol, port=port, + name=name, + sel_type=sel_type, + protocol=protocol, + port=port, ) ret["changes"].update({"old": old_state, "new": new_state}) return ret diff --git a/salt/states/service.py b/salt/states/service.py index 0ee7871c6d0..ca5a03d5c0f 100644 --- a/salt/states/service.py +++ b/salt/states/service.py @@ -846,7 +846,10 @@ def masked(name, runtime=False): try: if __salt__["service.masked"](name, runtime): - ret["comment"] = "Service {} is already {}".format(name, mask_type,) + ret["comment"] = "Service {} is already {}".format( + name, + mask_type, + ) return ret if __opts__["test"]: diff --git a/salt/states/smartos.py b/salt/states/smartos.py index 8fd8899a35f..9ae2c722036 100644 --- a/salt/states/smartos.py +++ b/salt/states/smartos.py @@ -503,7 +503,8 @@ def image_present(name): # docker image was imported ret["result"] = True ret["comment"] = "image {} ({}) is present".format( - name, __salt__["imgadm.docker_to_uuid"](name), + name, + __salt__["imgadm.docker_to_uuid"](name), ) elif name in __salt__["imgadm.list"](): # image was already imported diff --git a/salt/states/smtp.py b/salt/states/smtp.py index c40e795a371..2c8068363e7 100644 --- a/salt/states/smtp.py +++ b/salt/states/smtp.py @@ -63,7 +63,10 @@ def send_msg( return ret if __opts__["test"]: - ret["comment"] = "Need to send message to {}: {}".format(recipient, name,) + ret["comment"] = "Need to send message to {}: {}".format( + recipient, + name, + ) return ret command = __salt__["smtp.send_msg"]( message=name, diff --git a/salt/states/ssh_auth.py b/salt/states/ssh_auth.py index 42f3b6ddb90..4fff55be41b 100644 --- a/salt/states/ssh_auth.py +++ b/salt/states/ssh_auth.py @@ -356,9 +356,10 @@ def present( ) return ret elif data == "no change": - ret["comment"] = ( - "The authorized host key {} is already present " - "for user {}".format(name, user) + ret[ + "comment" + ] = "The authorized host key {} is already present " "for user {}".format( + name, user ) elif data == "new": ret["changes"][name] = "New" diff --git a/salt/states/trafficserver.py b/salt/states/trafficserver.py index 7c2ed8e5539..c491f176bac 100644 --- a/salt/states/trafficserver.py +++ b/salt/states/trafficserver.py @@ -200,7 +200,10 @@ def config(name, value): ret = {"name": name, "changes": {}, "result": None, "comment": ""} if __opts__["test"]: - ret["comment"] = "Configuring {} to {}".format(name, value,) + ret["comment"] = "Configuring {} to {}".format( + name, + value, + ) return ret __salt__["trafficserver.set_config"](name, value) diff --git a/salt/states/user.py b/salt/states/user.py index 8abb35a85c7..7a5f7696b20 100644 --- a/salt/states/user.py +++ b/salt/states/user.py @@ -848,9 +848,10 @@ def present( __salt__["shadow.del_password"](name) spost = __salt__["shadow.info"](name) if spost["passwd"] != "": - ret["comment"] = ( - "User {} created but failed to " - "empty password".format(name) + ret[ + "comment" + ] = "User {} created but failed to " "empty password".format( + name ) ret["result"] = False ret["changes"]["password"] = "" diff --git a/salt/states/win_network.py b/salt/states/win_network.py index b1683635f21..9266e591fb2 100644 --- a/salt/states/win_network.py +++ b/salt/states/win_network.py @@ -312,18 +312,20 @@ def managed( else: if not __salt__["ip.enable"](name): ret["result"] = False - ret["comment"] = ( - "Failed to enable interface '{}' to " - "make changes".format(name) + ret[ + "comment" + ] = "Failed to enable interface '{}' to " "make changes".format( + name ) return ret errors = _validate(dns_proto, dns_servers, ip_proto, ip_addrs, gateway) if errors: ret["result"] = False - ret["comment"] = ( - "The following SLS configuration errors were " - "detected:\n- {}".format("\n- ".join(errors)) + ret[ + "comment" + ] = "The following SLS configuration errors were " "detected:\n- {}".format( + "\n- ".join(errors) ) return ret @@ -382,9 +384,10 @@ def managed( ) ret["result"] = None - ret["comment"] = ( - "The following changes will be made to " - "interface '{}':\n- {}".format(name, "\n- ".join(comments)) + ret[ + "comment" + ] = "The following changes will be made to " "interface '{}':\n- {}".format( + name, "\n- ".join(comments) ) return ret diff --git a/salt/states/xmpp.py b/salt/states/xmpp.py index 5d07238015a..2186c37bbca 100644 --- a/salt/states/xmpp.py +++ b/salt/states/xmpp.py @@ -43,10 +43,15 @@ def send_msg(name, recipient, profile): """ ret = {"name": name, "changes": {}, "result": None, "comment": ""} if __opts__["test"]: - ret["comment"] = "Need to send message to {}: {}".format(recipient, name,) + ret["comment"] = "Need to send message to {}: {}".format( + recipient, + name, + ) return ret __salt__["xmpp.send_msg_multi"]( - message=name, recipients=[recipient], profile=profile, + message=name, + recipients=[recipient], + profile=profile, ) ret["result"] = True ret["comment"] = "Sent message to {}: {}".format(recipient, name) @@ -89,7 +94,10 @@ def send_msg_multi(name, profile, recipients=None, rooms=None): return ret __salt__["xmpp.send_msg_multi"]( - message=name, recipients=recipients, rooms=rooms, profile=profile, + message=name, + recipients=recipients, + rooms=rooms, + profile=profile, ) ret["result"] = True ret["comment"] = "Sent message to" + comment diff --git a/salt/states/zabbix_action.py b/salt/states/zabbix_action.py index 457c27f3102..14e4b45674e 100644 --- a/salt/states/zabbix_action.py +++ b/salt/states/zabbix_action.py @@ -81,7 +81,8 @@ def present(name, params, **kwargs): input_params = __salt__["zabbix.substitute_params"](params, **kwargs) log.info( - "Zabbix Action: input params: %s", str(json.dumps(input_params, indent=4)), + "Zabbix Action: input params: %s", + str(json.dumps(input_params, indent=4)), ) search = { @@ -93,7 +94,8 @@ def present(name, params, **kwargs): # GET Action object if exists action_get = __salt__["zabbix.run_query"]("action.get", search, **kwargs) log.info( - "Zabbix Action: action.get result: %s", str(json.dumps(action_get, indent=4)), + "Zabbix Action: action.get result: %s", + str(json.dumps(action_get, indent=4)), ) existing_obj = ( @@ -105,7 +107,8 @@ def present(name, params, **kwargs): if existing_obj: diff_params = __salt__["zabbix.compare_params"](input_params, existing_obj) log.info( - "Zabbix Action: input params: {%s", str(json.dumps(input_params, indent=4)), + "Zabbix Action: input params: {%s", + str(json.dumps(input_params, indent=4)), ) log.info( "Zabbix Action: Object comparison result. Differences: %s", @@ -139,7 +142,8 @@ def present(name, params, **kwargs): "action.update", diff_params, **kwargs ) log.info( - "Zabbix Action: action.update result: %s", str(action_update), + "Zabbix Action: action.update result: %s", + str(action_update), ) if action_update: ret["result"] = True diff --git a/salt/states/zabbix_template.py b/salt/states/zabbix_template.py index 76074a925b9..f3aad5badeb 100644 --- a/salt/states/zabbix_template.py +++ b/salt/states/zabbix_template.py @@ -676,7 +676,8 @@ def present(name, params, static_host_list=True, **kwargs): defined_obj = __salt__["zabbix.substitute_params"](template_definition, **kwargs) log.info( - "SUBSTITUTED template_definition: %s", str(json.dumps(defined_obj, indent=4)), + "SUBSTITUTED template_definition: %s", + str(json.dumps(defined_obj, indent=4)), ) tmpl_get = __salt__["zabbix.run_query"]( @@ -740,7 +741,8 @@ def present(name, params, static_host_list=True, **kwargs): diff_params["new"][zabbix_id_mapper["template"]] = template_id diff_params["old"][zabbix_id_mapper["template"]] = template_id log.info( - "TEMPLATE: update params: %s", str(json.dumps(diff_params, indent=4)), + "TEMPLATE: update params: %s", + str(json.dumps(diff_params, indent=4)), ) CHANGE_STACK.append( @@ -771,7 +773,8 @@ def present(name, params, static_host_list=True, **kwargs): log.info("\n\ntemplate_components: %s", json.dumps(template_components, indent=4)) log.info("\n\ndiscovery_components: %s", json.dumps(discovery_components, indent=4)) log.info( - "\n\nCurrent CHANGE_STACK: %s", str(json.dumps(CHANGE_STACK, indent=4)), + "\n\nCurrent CHANGE_STACK: %s", + str(json.dumps(CHANGE_STACK, indent=4)), ) if existing_obj or not dry_run: @@ -808,7 +811,8 @@ def present(name, params, static_host_list=True, **kwargs): ) log.info( - "\n\nCurrent CHANGE_STACK: %s", str(json.dumps(CHANGE_STACK, indent=4)), + "\n\nCurrent CHANGE_STACK: %s", + str(json.dumps(CHANGE_STACK, indent=4)), ) for d_rule_component in discovery_components: @@ -826,7 +830,8 @@ def present(name, params, static_host_list=True, **kwargs): for proto_name in DISCOVERYRULE_COMPONENT_ORDER: log.info( - "\n\n\n\n\nPROTOTYPE_NAME: %s\n\n", str(json.dumps(proto_name)), + "\n\n\n\n\nPROTOTYPE_NAME: %s\n\n", + str(json.dumps(proto_name)), ) existing_p_list = _get_existing_template_c_list( proto_name, parent_id, **kwargs @@ -856,7 +861,8 @@ def present(name, params, static_host_list=True, **kwargs): ) log.info( - "\n\nCurrent CHANGE_STACK: %s", str(json.dumps(CHANGE_STACK, indent=4)), + "\n\nCurrent CHANGE_STACK: %s", + str(json.dumps(CHANGE_STACK, indent=4)), ) if not CHANGE_STACK: diff --git a/salt/states/zabbix_usermacro.py b/salt/states/zabbix_usermacro.py index 8b82d39101a..d1d9419ee08 100644 --- a/salt/states/zabbix_usermacro.py +++ b/salt/states/zabbix_usermacro.py @@ -53,8 +53,8 @@ def present(name, value, hostid=None, **kwargs): comment_usermacro_updated = "Usermacro {} updated on hostid {}.".format( name, hostid ) - comment_usermacro_notcreated = "Unable to create usermacro: {} on hostid {}. ".format( - name, hostid + comment_usermacro_notcreated = ( + "Unable to create usermacro: {} on hostid {}. ".format(name, hostid) ) comment_usermacro_exists = "Usermacro {} already exists on hostid {}.".format( name, hostid @@ -202,11 +202,11 @@ def absent(name, hostid=None, **kwargs): comment_usermacro_deleted = "Usermacro {} deleted from hostid {}.".format( name, hostid ) - comment_usermacro_notdeleted = "Unable to delete usermacro: {} from hostid {}.".format( - name, hostid + comment_usermacro_notdeleted = ( + "Unable to delete usermacro: {} from hostid {}.".format(name, hostid) ) - comment_usermacro_notexists = "Usermacro {} does not exist on hostid {}.".format( - name, hostid + comment_usermacro_notexists = ( + "Usermacro {} does not exist on hostid {}.".format(name, hostid) ) changes_usermacro_deleted = { name: { diff --git a/salt/states/zabbix_valuemap.py b/salt/states/zabbix_valuemap.py index f39b7d48baa..8759752c032 100644 --- a/salt/states/zabbix_valuemap.py +++ b/salt/states/zabbix_valuemap.py @@ -55,7 +55,8 @@ def present(name, params, **kwargs): params["name"] = name input_params = __salt__["zabbix.substitute_params"](params, **kwargs) log.info( - "Zabbix Value map: input params: %s", str(json.dumps(input_params, indent=4)), + "Zabbix Value map: input params: %s", + str(json.dumps(input_params, indent=4)), ) search = {"output": "extend", "selectMappings": "extend", "filter": {"name": name}} @@ -148,7 +149,8 @@ def present(name, params, **kwargs): "valuemap.create", input_params, **kwargs ) log.info( - "Zabbix Value map: valuemap.create result: %s", str(valuemap_create), + "Zabbix Value map: valuemap.create result: %s", + str(valuemap_create), ) if valuemap_create: diff --git a/salt/states/zfs.py b/salt/states/zfs.py index e3e874b47f0..f0c3f5834cb 100644 --- a/salt/states/zfs.py +++ b/salt/states/zfs.py @@ -105,9 +105,15 @@ def _absent(name, dataset_type, force=False, recursive=False): ret["result"] = mod_res["destroyed"] if ret["result"]: ret["changes"][name] = "destroyed" - ret["comment"] = "{} {} was destroyed".format(dataset_type, name,) + ret["comment"] = "{} {} was destroyed".format( + dataset_type, + name, + ) else: - ret["comment"] = "failed to destroy {} {}".format(dataset_type, name,) + ret["comment"] = "failed to destroy {} {}".format( + dataset_type, + name, + ) if "error" in mod_res: ret["comment"] = mod_res["error"] else: @@ -270,9 +276,13 @@ def hold_absent(name, snapshot, recursive=False): ret["result"] = mod_res["released"] if ret["result"]: ret["changes"] = {snapshot: {name: "released"}} - ret["comment"] = "hold {} released".format(name,) + ret["comment"] = "hold {} released".format( + name, + ) else: - ret["comment"] = "failed to release hold {}".format(name,) + ret["comment"] = "failed to release hold {}".format( + name, + ) if "error" in mod_res: ret["comment"] = mod_res["error"] elif "error" in holds: @@ -281,7 +291,9 @@ def hold_absent(name, snapshot, recursive=False): ret["comment"] = holds["error"] else: ## NOTE: no hold found with name for snapshot - ret["comment"] = "hold {} is absent".format(name,) + ret["comment"] = "hold {} is absent".format( + name, + ) return ret @@ -323,7 +335,10 @@ def hold_present(name, snapshot, recursive=False): holds = __salt__["zfs.holds"](snapshot) if name in holds: ## NOTE: hold with name already exists for snapshot - ret["comment"] = "hold {} is present for {}".format(name, snapshot,) + ret["comment"] = "hold {} is present for {}".format( + name, + snapshot, + ) else: ## NOTE: no hold found with name for snapshot if not __opts__["test"]: @@ -434,7 +449,11 @@ def _dataset_present( if __salt__["zfs.exists"](name, **{"type": dataset_type}): ## NOTE: fetch current volume properties properties_current = __salt__["zfs.get"]( - name, type=dataset_type, fields="value", depth=0, parsable=True, + name, + type=dataset_type, + fields="value", + depth=0, + parsable=True, ).get(name, OrderedDict()) ## NOTE: add volsize to properties @@ -517,10 +536,16 @@ def _dataset_present( ret["changes"][name] = mod_res_action if properties: ret["changes"][name] = properties - ret["comment"] = "{} {} was {}".format(dataset_type, name, mod_res_action,) + ret["comment"] = "{} {} was {}".format( + dataset_type, + name, + mod_res_action, + ) else: ret["comment"] = "failed to {} {} {}".format( - mod_res_action[:-1], dataset_type, name, + mod_res_action[:-1], + dataset_type, + name, ) if "error" in mod_res: ret["comment"] = mod_res["error"] @@ -856,7 +881,8 @@ def _schedule_snapshot_prepare(dataset, prefix, snapshots): if snapshots[hold]: ## NOTE: extract datetime from snapshot name timestamp = datetime.strptime( - snapshots[hold][-1], "{}@{}-%Y%m%d_%H%M%S".format(dataset, prefix), + snapshots[hold][-1], + "{}@{}-%Y%m%d_%H%M%S".format(dataset, prefix), ).replace(second=0, microsecond=0) ## NOTE: compare current timestamp to timestamp from snapshot @@ -945,7 +971,9 @@ def scheduled_snapshot(name, prefix, recursive=True, schedule=None): snapshots["_schedule"][hold] = schedule[hold] else: ret["result"] = False - ret["comment"] = "schedule value for {} is not an integer".format(hold,) + ret["comment"] = "schedule value for {} is not an integer".format( + hold, + ) break total_count += snapshots["_schedule"][hold] if ret["result"] and total_count == 0: @@ -997,7 +1025,8 @@ def scheduled_snapshot(name, prefix, recursive=True, schedule=None): if not mod_res["held"]: ret["result"] = False ret["comment"] = "error adding hold ({}) to snapshot ({})".format( - hold, snapshot_name, + hold, + snapshot_name, ) break @@ -1026,7 +1055,8 @@ def scheduled_snapshot(name, prefix, recursive=True, schedule=None): if not mod_res["released"]: ret["result"] = False ret["comment"] = "error adding hold ({}) to snapshot ({})".format( - hold, snapshot_name, + hold, + snapshot_name, ) ## NOTE: mark as prunable @@ -1043,7 +1073,9 @@ def scheduled_snapshot(name, prefix, recursive=True, schedule=None): if not mod_res["destroyed"]: ret["result"] = False - ret["comment"] = "error prunding snapshot ({1})".format(snapshot_name,) + ret["comment"] = "error prunding snapshot ({1})".format( + snapshot_name, + ) break if ret["result"] and snapshots["_prunable"]: diff --git a/salt/states/zone.py b/salt/states/zone.py index 4e03f8aab11..91ad29508d5 100644 --- a/salt/states/zone.py +++ b/salt/states/zone.py @@ -318,7 +318,8 @@ def resource_present( ret["result"] = True if resource_selector_property: ret["comment"] = "the {} resource {} is up to date.".format( - resource_type, resource_selector_value, + resource_type, + resource_selector_value, ) else: ret["comment"] = "the {} resource is up to date.".format( @@ -375,7 +376,8 @@ def resource_present( ret[ "comment" ] = "The {} resource {} was updated.".format( - resource_type, resource_selector_value, + resource_type, + resource_selector_value, ) else: ret[ @@ -388,7 +390,8 @@ def resource_present( ret[ "comment" ] = "The {} resource {} was not updated.".format( - resource_type, resource_selector_value, + resource_type, + resource_selector_value, ) else: ret[ @@ -422,11 +425,13 @@ def resource_present( ret["changes"][resource_type][key] = _parse_value(kwargs[key]) if ret["comment"] == "": ret["comment"] = "The {} resource {} was added.".format( - resource_type, resource_selector_value, + resource_type, + resource_selector_value, ) elif ret["comment"] == "": ret["comment"] = "The {} resource {} was not added.".format( - resource_type, resource_selector_value, + resource_type, + resource_selector_value, ) else: ## zone does not exist @@ -515,20 +520,23 @@ def resource_absent( ] = "removed" if ret["comment"] == "": ret["comment"] = "The {} resource {} was removed.".format( - resource_type, resource_selector_value, + resource_type, + resource_selector_value, ) elif "messages" in zonecfg_res: ret["comment"] = zonecfg_res["message"] else: ret["comment"] = "The {} resource {} was not removed.".format( - resource_type, resource_selector_value, + resource_type, + resource_selector_value, ) # resource already absent if ret["result"] is None: ret["result"] = True ret["comment"] = "The {} resource {} was absent.".format( - resource_type, resource_selector_value, + resource_type, + resource_selector_value, ) else: ## zone does not exist @@ -582,7 +590,8 @@ def booted(name, single=False): if zones[zone]["uuid"] == name: ret["comment"].append( "The zone {} has a uuid of {}, please use the zone name instead!".format( - zone, name, + zone, + name, ) ) @@ -634,7 +643,8 @@ def halted(name, graceful=True): if zones[zone]["uuid"] == name: ret["comment"].append( "The zone {} has a uuid of {}, please use the zone name instead!".format( - zone, name, + zone, + name, ) ) ## note: a non existing zone is not running, we do not consider this a failure @@ -665,7 +675,8 @@ def export(name, path, replace=False): ## pretend we did the correct thing ret["result"] = True ret["comment"] = "Zone configartion for {} exported to {}".format( - name, path, + name, + path, ) ret["changes"][name] = "exported" if __salt__["file.file_exists"](path) and not replace: @@ -674,7 +685,8 @@ def export(name, path, replace=False): ret[ "comment" ] = "File {} exists, zone configuration for {} not exported.".format( - path, name, + path, + name, ) else: ## export and update file @@ -691,14 +703,16 @@ def export(name, path, replace=False): ret[ "comment" ] = "Unable to export zone configuration for {} to {}!".format( - name, path, + name, + path, ) else: ret["result"] = True ret[ "comment" ] = "Zone configuration for {} was exported to {}.".format( - name, path, + name, + path, ) ret["changes"][name] = "exported" else: @@ -723,14 +737,16 @@ def export(name, path, replace=False): ret[ "comment" ] = "Unable to be re-export zone configuration for {} to {}!".format( - name, path, + name, + path, ) else: ret["result"] = True ret[ "comment" ] = "Zone configuration for {} was re-exported to {}.".format( - name, path, + name, + path, ) ret["changes"][name] = "exported" else: @@ -750,7 +766,8 @@ def export(name, path, replace=False): if zones[zone]["uuid"] == name: ret["comment"].append( "The zone {} has a uuid of {}, please use the zone name instead!".format( - name, path, + name, + path, ) ) @@ -793,7 +810,10 @@ def import_(name, path, mode="import", nodataset=False, brand_opts=None): if name not in zones: if __opts__["test"]: ret["result"] = True - ret["comment"] = "Zone {} was imported from {}.".format(name, path,) + ret["comment"] = "Zone {} was imported from {}.".format( + name, + path, + ) ret["changes"][name] = "imported" else: if __salt__["file.file_exists"](path): @@ -806,19 +826,26 @@ def import_(name, path, mode="import", nodataset=False, brand_opts=None): else: ret["result"] = True ret["changes"][name] = "imported" - ret["comment"] = "Zone {} was imported from {}.".format(name, path,) + ret["comment"] = "Zone {} was imported from {}.".format( + name, + path, + ) if mode.lower() == "attach": res_attach = __salt__["zoneadm.attach"](name, False, brand_opts) ret["result"] = res_attach["status"] if res_attach["status"]: ret["changes"][name] = "attached" ret["comment"] = "Zone {} was attached from {}.".format( - name, path, + name, + path, ) else: ret["comment"] = [] ret["comment"].append( - "Failed to attach zone {} from {}!".format(name, path,) + "Failed to attach zone {} from {}!".format( + name, + path, + ) ) if "message" in res_attach: ret["comment"].append(res_attach["message"]) @@ -831,12 +858,16 @@ def import_(name, path, mode="import", nodataset=False, brand_opts=None): if res_install["status"]: ret["changes"][name] = "installed" ret["comment"] = "Zone {} was installed from {}.".format( - name, path, + name, + path, ) else: ret["comment"] = [] ret["comment"].append( - "Failed to install zone {} from {}!".format(name, path,) + "Failed to install zone {} from {}!".format( + name, + path, + ) ) if "message" in res_install: ret["comment"].append(res_install["message"]) @@ -979,9 +1010,9 @@ def present(name, brand, zonepath, properties=None, resources=None): not resource_selector_property and key in _zonecfg_resource_default_selectors ): - resource_selector_property = _zonecfg_resource_default_selectors[ - key - ] + resource_selector_property = ( + _zonecfg_resource_default_selectors[key] + ) res = None if resource_prune: diff --git a/salt/states/zpool.py b/salt/states/zpool.py index cadf877c6ff..e64b2f38a4a 100644 --- a/salt/states/zpool.py +++ b/salt/states/zpool.py @@ -346,7 +346,9 @@ def present( # import pool if config["import"]: mod_res = __salt__["zpool.import"]( - name, force=config["force"], dir=config["import_dirs"], + name, + force=config["force"], + dir=config["import_dirs"], ) ret["result"] = mod_res["imported"] diff --git a/salt/transport/client.py b/salt/transport/client.py index 5b9cbf61173..58719daacc3 100644 --- a/salt/transport/client.py +++ b/salt/transport/client.py @@ -21,7 +21,10 @@ class ReqChannel: def factory(opts, **kwargs): # All Sync interfaces are just wrappers around the Async ones return SyncWrapper( - AsyncReqChannel.factory, (opts,), kwargs, loop_kwarg="io_loop", + AsyncReqChannel.factory, + (opts,), + kwargs, + loop_kwarg="io_loop", ) def close(self): @@ -60,7 +63,10 @@ class PushChannel: @staticmethod def factory(opts, **kwargs): return SyncWrapper( - AsyncPushChannel.factory, (opts,), kwargs, loop_kwarg="io_loop", + AsyncPushChannel.factory, + (opts,), + kwargs, + loop_kwarg="io_loop", ) def send(self, load, tries=3, timeout=60): @@ -78,7 +84,10 @@ class PullChannel: @staticmethod def factory(opts, **kwargs): return SyncWrapper( - AsyncPullChannel.factory, (opts,), kwargs, loop_kwarg="io_loop", + AsyncPullChannel.factory, + (opts,), + kwargs, + loop_kwarg="io_loop", ) diff --git a/salt/transport/ipc.py b/salt/transport/ipc.py index 29210d75226..a8b8d1759ff 100644 --- a/salt/transport/ipc.py +++ b/salt/transport/ipc.py @@ -136,7 +136,8 @@ class IPCServer: with salt.utils.asynchronous.current_ioloop(self.io_loop): salt.ext.tornado.netutil.add_accept_handler( - self.sock, self.handle_connection, + self.sock, + self.handle_connection, ) self._started = True @@ -161,7 +162,9 @@ class IPCServer: @salt.ext.tornado.gen.coroutine def return_message(msg): pack = salt.transport.frame.frame_msg_ipc( - msg, header={"mid": header["mid"]}, raw_body=True, + msg, + header={"mid": header["mid"]}, + raw_body=True, ) yield stream.write(pack) @@ -208,7 +211,9 @@ class IPCServer: log.trace("IPCServer: Handling connection " "to address: %s", address) try: with salt.utils.asynchronous.current_ioloop(self.io_loop): - stream = IOStream(connection,) + stream = IOStream( + connection, + ) self.io_loop.spawn_callback(self.handle_stream, stream) except Exception as exc: # pylint: disable=broad-except log.error("IPC streaming error: %s", exc) @@ -532,7 +537,8 @@ class IPCMessagePublisher: with salt.utils.asynchronous.current_ioloop(self.io_loop): salt.ext.tornado.netutil.add_accept_handler( - self.sock, self.handle_connection, + self.sock, + self.handle_connection, ) self._started = True diff --git a/salt/transport/tcp.py b/salt/transport/tcp.py index 2566242e67c..e5db56503e6 100644 --- a/salt/transport/tcp.py +++ b/salt/transport/tcp.py @@ -310,7 +310,11 @@ class AsyncTCPReqChannel(salt.transport.client.ReqChannel): self._closing = False self.message_client = SaltMessageClientPool( self.opts, - args=(self.opts, master_host, int(master_port),), + args=( + self.opts, + master_host, + int(master_port), + ), kwargs={ "io_loop": self.io_loop, "resolver": resolver, @@ -429,7 +433,9 @@ class AsyncTCPReqChannel(salt.transport.client.ReqChannel): @salt.ext.tornado.gen.coroutine def _uncrypted_transfer(self, load, tries=3, timeout=60): ret = yield self.message_client.send( - self._package_load(load), timeout=timeout, tries=tries, + self._package_load(load), + timeout=timeout, + tries=tries, ) raise salt.ext.tornado.gen.Return(ret) @@ -563,7 +569,9 @@ class AsyncTCPPubChannel( "tag": tag, } req_channel = salt.utils.asynchronous.SyncWrapper( - AsyncTCPReqChannel, (self.opts,), loop_kwarg="io_loop", + AsyncTCPReqChannel, + (self.opts,), + loop_kwarg="io_loop", ) try: req_channel.send(load, timeout=60) @@ -833,7 +841,11 @@ class TCPReqServerChannel( elif req_fun == "send_private": stream.write( salt.transport.frame.frame_msg( - self._encrypt_private(ret, req_opts["key"], req_opts["tgt"],), + self._encrypt_private( + ret, + req_opts["key"], + req_opts["tgt"], + ), header=header, ) ) @@ -1385,7 +1397,10 @@ class SaltMessageClient: future.tries, ) self.send( - msg, timeout=future.timeout, tries=future.tries, future=future, + msg, + timeout=future.timeout, + tries=future.tries, + future=future, ) else: @@ -1699,7 +1714,9 @@ class TCPPubServerChannel(salt.transport.server.PubServerChannel): pull_uri = os.path.join(self.opts["sock_dir"], "publish_pull.ipc") pull_sock = salt.transport.ipc.IPCMessageServer( - pull_uri, io_loop=self.io_loop, payload_handler=pub_server.publish_payload, + pull_uri, + io_loop=self.io_loop, + payload_handler=pub_server.publish_payload, ) # Securely create socket @@ -1745,7 +1762,9 @@ class TCPPubServerChannel(salt.transport.server.PubServerChannel): # TODO: switch to the actual asynchronous interface # pub_sock = salt.transport.ipc.IPCMessageClient(self.opts, io_loop=self.io_loop) pub_sock = salt.utils.asynchronous.SyncWrapper( - salt.transport.ipc.IPCMessageClient, (pull_uri,), loop_kwarg="io_loop", + salt.transport.ipc.IPCMessageClient, + (pull_uri,), + loop_kwarg="io_loop", ) pub_sock.connect() diff --git a/salt/transport/zeromq.py b/salt/transport/zeromq.py index 0ff536f10da..8aaad6df6b4 100644 --- a/salt/transport/zeromq.py +++ b/salt/transport/zeromq.py @@ -79,11 +79,13 @@ def _get_master_uri(master_ip, master_port, source_ip=None, source_port=None): # The source:port syntax for ZeroMQ has been added in libzmq 4.1.6 # which is included in the pyzmq wheels starting with 16.0.1. if source_ip and source_port: - master_uri = "tcp://{source_ip}:{source_port};{master_ip}:{master_port}".format( - source_ip=ip_bracket(source_ip), - source_port=source_port, - master_ip=ip_bracket(master_ip), - master_port=master_port, + master_uri = ( + "tcp://{source_ip}:{source_port};{master_ip}:{master_port}".format( + source_ip=ip_bracket(source_ip), + source_port=source_port, + master_ip=ip_bracket(master_ip), + master_port=master_port, + ) ) elif source_ip and not source_port: master_uri = "tcp://{source_ip}:0;{master_ip}:{master_port}".format( @@ -97,11 +99,13 @@ def _get_master_uri(master_ip, master_port, source_ip=None, source_port=None): if ipaddress.ip_address(master_ip).version == 4 else ip_bracket("::") ) - master_uri = "tcp://{ip_any}:{source_port};{master_ip}:{master_port}".format( - ip_any=ip_any, - source_port=source_port, - master_ip=ip_bracket(master_ip), - master_port=master_port, + master_uri = ( + "tcp://{ip_any}:{source_port};{master_ip}:{master_port}".format( + ip_any=ip_any, + source_port=source_port, + master_ip=ip_bracket(master_ip), + master_port=master_port, + ) ) else: log.warning( @@ -194,7 +198,10 @@ class AsyncZeroMQReqChannel(salt.transport.client.ReqChannel): key, AsyncReqMessageClientPool( result.opts, - args=(result.opts, self.master_uri,), + args=( + result.opts, + self.master_uri, + ), kwargs={"io_loop": self._io_loop}, ), ) @@ -254,7 +261,10 @@ class AsyncZeroMQReqChannel(salt.transport.client.ReqChannel): ) self.message_client = AsyncReqMessageClientPool( self.opts, - args=(self.opts, self.master_uri,), + args=( + self.opts, + self.master_uri, + ), kwargs={"io_loop": self._io_loop}, ) self._closing = False @@ -419,7 +429,9 @@ class AsyncZeroMQReqChannel(salt.transport.client.ReqChannel): :param int timeout: The number of seconds on a response before failing """ ret = yield self.message_client.send( - self._package_load(load), timeout=timeout, tries=tries, + self._package_load(load), + timeout=timeout, + tries=tries, ) raise salt.ext.tornado.gen.Return(ret) @@ -878,7 +890,11 @@ class ZeroMQReqServerChannel( elif req_fun == "send_private": stream.send( self.serial.dumps( - self._encrypt_private(ret, req_opts["key"], req_opts["tgt"],) + self._encrypt_private( + ret, + req_opts["key"], + req_opts["tgt"], + ) ) ) else: @@ -1357,7 +1373,10 @@ class AsyncReqMessageClient: future.tries, ) self.send( - message, timeout=future.timeout, tries=future.tries, future=future, + message, + timeout=future.timeout, + tries=future.tries, + future=future, ) else: diff --git a/salt/utils/asynchronous.py b/salt/utils/asynchronous.py index 836dd44c596..7a78f9f91fc 100644 --- a/salt/utils/asynchronous.py +++ b/salt/utils/asynchronous.py @@ -113,7 +113,8 @@ class SyncWrapper: def wrap(*args, **kwargs): results = [] thread = threading.Thread( - target=self._target, args=(key, args, kwargs, results, self.io_loop), + target=self._target, + args=(key, args, kwargs, results, self.io_loop), ) thread.start() thread.join() diff --git a/salt/utils/aws.py b/salt/utils/aws.py index 83dba27e5a3..8030640036b 100644 --- a/salt/utils/aws.py +++ b/salt/utils/aws.py @@ -164,7 +164,9 @@ def sig2(method, endpoint, params, provider, aws_api_version): querystring = urllib.parse.urlencode(list(zip(keys, values))) canonical = "{}\n{}\n/\n{}".format( - method.encode("utf-8"), endpoint.encode("utf-8"), querystring.encode("utf-8"), + method.encode("utf-8"), + endpoint.encode("utf-8"), + querystring.encode("utf-8"), ) hashed = hmac.new(secret_access_key, canonical, hashlib.sha256) @@ -332,7 +334,13 @@ def sig4( # Add signing information to the request authorization_header = ( "{} Credential={}/{}, SignedHeaders={}, Signature={}" - ).format(algorithm, access_key_id, credential_scope, signed_headers, signature,) + ).format( + algorithm, + access_key_id, + credential_scope, + signed_headers, + signature, + ) new_headers["Authorization"] = authorization_header diff --git a/salt/utils/azurearm.py b/salt/utils/azurearm.py index c881ff2eda6..3522d9d1f3a 100644 --- a/salt/utils/azurearm.py +++ b/salt/utils/azurearm.py @@ -180,7 +180,8 @@ def get_client(client_type, **kwargs): if client_type == "subscription": client = Client( - credentials=credentials, base_url=cloud_env.endpoints.resource_manager, + credentials=credentials, + base_url=cloud_env.endpoints.resource_manager, ) else: client = Client( diff --git a/salt/utils/boto3mod.py b/salt/utils/boto3mod.py index a743667c11d..48784ed7020 100644 --- a/salt/utils/boto3mod.py +++ b/salt/utils/boto3mod.py @@ -311,6 +311,5 @@ def ordered(obj): def json_objs_equal(left, right): - """ Compare two parsed JSON objects, given non-ordering in JSON objects - """ + """Compare two parsed JSON objects, given non-ordering in JSON objects""" return ordered(left) == ordered(right) diff --git a/salt/utils/cloud.py b/salt/utils/cloud.py index a17ac402286..9ddc8a3bd6d 100644 --- a/salt/utils/cloud.py +++ b/salt/utils/cloud.py @@ -1305,7 +1305,10 @@ def deploy_windows( local_path = "/".join(comps[:-1]) installer = comps[-1] salt.utils.smb.put_file( - win_installer, "salttemp\\{}".format(installer), "C$", conn=smb_conn, + win_installer, + "salttemp\\{}".format(installer), + "C$", + conn=smb_conn, ) if use_winrm: @@ -1797,7 +1800,9 @@ def deploy_script( **ssh_kwargs ) # The deploy command is now our wrapper - deploy_command = "'{}/environ-deploy-wrapper.sh'".format(tmp_dir,) + deploy_command = "'{}/environ-deploy-wrapper.sh'".format( + tmp_dir, + ) if root_cmd(deploy_command, tty, sudo, **ssh_kwargs) != 0: raise SaltCloudSystemExit( "Executing the command '{}' failed".format(deploy_command) @@ -2769,7 +2774,12 @@ def init_cachedir(base=None): # FIXME: This function seems used nowhere. Dead code? def request_minion_cachedir( - minion_id, opts=None, fingerprint="", pubkey=None, provider=None, base=None, + minion_id, + opts=None, + fingerprint="", + pubkey=None, + provider=None, + base=None, ): """ Creates an entry in the requested/ cachedir. This means that Salt Cloud has @@ -2803,7 +2813,10 @@ def request_minion_cachedir( def change_minion_cachedir( - minion_id, cachedir, data=None, base=None, + minion_id, + cachedir, + data=None, + base=None, ): """ Changes the info inside a minion's cachedir entry. The type of cachedir @@ -3427,7 +3440,12 @@ def userdata_template(opts, vm_, userdata): blacklist = opts["renderer_blacklist"] whitelist = opts["renderer_whitelist"] templated = salt.template.compile_template( - ":string:", rend, renderer, blacklist, whitelist, input_data=userdata, + ":string:", + rend, + renderer, + blacklist, + whitelist, + input_data=userdata, ) if not isinstance(templated, str): # template renderers like "jinja" should return a StringIO diff --git a/salt/utils/configcomparer.py b/salt/utils/configcomparer.py index 05c6020deb8..ef67e65e5f1 100644 --- a/salt/utils/configcomparer.py +++ b/salt/utils/configcomparer.py @@ -34,7 +34,10 @@ def compare_and_update_config(config, update_config, changes, namespace=""): if namespace: _namespace = "{}.{}".format(namespace, _namespace) update_config[key] = compare_and_update_config( - value, update_config.get(key, None), changes, namespace=_namespace, + value, + update_config.get(key, None), + changes, + namespace=_namespace, ) return update_config @@ -66,7 +69,10 @@ def compare_and_update_config(config, update_config, changes, namespace=""): _update = update_config[idx] if _update: update_config[idx] = compare_and_update_config( - config[idx], _update, changes, namespace=_namespace, + config[idx], + _update, + changes, + namespace=_namespace, ) else: changes[_namespace] = { diff --git a/salt/utils/configparser.py b/salt/utils/configparser.py index a9c8da8ac52..6a3b1e689ea 100644 --- a/salt/utils/configparser.py +++ b/salt/utils/configparser.py @@ -45,7 +45,10 @@ class GitConfigParser(RawConfigParser): # pylint: disable=useless-super-delegation def __init__( - self, defaults=None, dict_type=_default_dict, allow_no_value=True, + self, + defaults=None, + dict_type=_default_dict, + allow_no_value=True, ): """ Changes default value for allow_no_value from False to True diff --git a/salt/utils/context.py b/salt/utils/context.py index 979d7ba6568..45776ab4c71 100644 --- a/salt/utils/context.py +++ b/salt/utils/context.py @@ -141,9 +141,7 @@ class ContextDict(MutableMapping): class ChildContextDict(MutableMapping): - """An overrideable child of ContextDict - - """ + """An overrideable child of ContextDict""" def __init__(self, parent, overrides=None, threadsafe=False): self.parent = parent diff --git a/salt/utils/decorators/jinja.py b/salt/utils/decorators/jinja.py index 17f8dee1bc8..25b89f91313 100644 --- a/salt/utils/decorators/jinja.py +++ b/salt/utils/decorators/jinja.py @@ -17,13 +17,11 @@ class JinjaFilter: salt_jinja_filters = {} def __init__(self, name=None): - """ - """ + """ """ self.name = name def __call__(self, function): - """ - """ + """ """ name = self.name or function.__name__ if name not in self.salt_jinja_filters: log.debug("Marking '%s' as a jinja filter", name) @@ -43,13 +41,11 @@ class JinjaTest: salt_jinja_tests = {} def __init__(self, name=None): - """ - """ + """ """ self.name = name def __call__(self, function): - """ - """ + """ """ name = self.name or function.__name__ if name not in self.salt_jinja_tests: log.debug("Marking '%s' as a jinja test", name) @@ -69,13 +65,11 @@ class JinjaGlobal: salt_jinja_globals = {} def __init__(self, name=None): - """ - """ + """ """ self.name = name def __call__(self, function): - """ - """ + """ """ name = self.name or function.__name__ if name not in self.salt_jinja_globals: log.debug("Marking '%s' as a jinja global", name) diff --git a/salt/utils/dictdiffer.py b/salt/utils/dictdiffer.py index fa4a892c4f5..73cce4c741d 100644 --- a/salt/utils/dictdiffer.py +++ b/salt/utils/dictdiffer.py @@ -101,42 +101,42 @@ def recursive_diff(past_dict, current_dict, ignore_missing_keys=True): class RecursiveDictDiffer(DictDiffer): """ - Calculates a recursive diff between the current_dict and the past_dict - creating a diff in the format + Calculates a recursive diff between the current_dict and the past_dict + creating a diff in the format - {'new': new_value, 'old': old_value} + {'new': new_value, 'old': old_value} - It recursively searches differences in common keys whose values are - dictionaries creating a diff dict in the format + It recursively searches differences in common keys whose values are + dictionaries creating a diff dict in the format - {'common_key' : {'new': new_value, 'old': old_value} + {'common_key' : {'new': new_value, 'old': old_value} - The class overrides all DictDiffer methods, returning lists of keys and - subkeys using the . notation (i.e 'common_key1.common_key2.changed_key') + The class overrides all DictDiffer methods, returning lists of keys and + subkeys using the . notation (i.e 'common_key1.common_key2.changed_key') - The class provides access to: - (1) the added, removed, changes keys and subkeys (using the . notation) - ``added``, ``removed``, ``changed`` methods - (2) the diffs in the format above (diff property) - ``diffs`` property - (3) a dict with the new changed values only (new_values property) - ``new_values`` property - (4) a dict with the old changed values only (old_values property) - ``old_values`` property - (5) a string representation of the changes in the format: - ``changes_str`` property + The class provides access to: + (1) the added, removed, changes keys and subkeys (using the . notation) + ``added``, ``removed``, ``changed`` methods + (2) the diffs in the format above (diff property) + ``diffs`` property + (3) a dict with the new changed values only (new_values property) + ``new_values`` property + (4) a dict with the old changed values only (old_values property) + ``old_values`` property + (5) a string representation of the changes in the format: + ``changes_str`` property - Note: - The <_null_> value is a reserved value + Note: + The <_null_> value is a reserved value -.. code-block:: text + .. code-block:: text - common_key1: - common_key2: - changed_key1 from '' to '' - changed_key2 from '[, ..]' to '[, ..]' - common_key3: - changed_key3 from to + common_key1: + common_key2: + changed_key1 from '' to '' + changed_key2 from '[, ..]' to '[, ..]' + common_key3: + changed_key3 from to """ diff --git a/salt/utils/dns.py b/salt/utils/dns.py index 8b461c308dc..0aa5342385a 100644 --- a/salt/utils/dns.py +++ b/salt/utils/dns.py @@ -63,18 +63,46 @@ class RFC: CAA_TAGS = ("issue", "issuewild", "iodef") # http://www.iana.org/assignments/dns-sshfp-rr-parameters/dns-sshfp-rr-parameters.xhtml - SSHFP_ALGO = OrderedDict(((1, "rsa"), (2, "dsa"), (3, "ecdsa"), (4, "ed25519"),)) + SSHFP_ALGO = OrderedDict( + ( + (1, "rsa"), + (2, "dsa"), + (3, "ecdsa"), + (4, "ed25519"), + ) + ) - SSHFP_HASH = OrderedDict(((1, "sha1"), (2, "sha256"),)) + SSHFP_HASH = OrderedDict( + ( + (1, "sha1"), + (2, "sha256"), + ) + ) # http://www.iana.org/assignments/dane-parameters/dane-parameters.xhtml TLSA_USAGE = OrderedDict( - ((0, "pkixta"), (1, "pkixee"), (2, "daneta"), (3, "daneee"),) + ( + (0, "pkixta"), + (1, "pkixee"), + (2, "daneta"), + (3, "daneee"), + ) ) - TLSA_SELECT = OrderedDict(((0, "cert"), (1, "spki"),)) + TLSA_SELECT = OrderedDict( + ( + (0, "cert"), + (1, "spki"), + ) + ) - TLSA_MATCHING = OrderedDict(((0, "full"), (1, "sha256"), (2, "sha512"),)) + TLSA_MATCHING = OrderedDict( + ( + (0, "full"), + (1, "sha256"), + (2, "sha512"), + ) + ) SRV_PROTO = ("tcp", "udp", "sctp") @@ -808,7 +836,12 @@ def mx_rec(rdatas): :param rdata: DNS record data :return: dict w/fields """ - rschema = OrderedDict((("preference", int), ("name", str),)) + rschema = OrderedDict( + ( + ("preference", int), + ("name", str), + ) + ) return _data2rec_group(rschema, rdatas, "preference") @@ -936,7 +969,12 @@ def srv_rec(rdatas): :return: dict w/fields """ rschema = OrderedDict( - (("prio", int), ("weight", int), ("port", _to_port), ("name", str),) + ( + ("prio", int), + ("weight", int), + ("port", _to_port), + ("name", str), + ) ) return _data2rec_group(rschema, rdatas, "prio") diff --git a/salt/utils/entrypoints.py b/salt/utils/entrypoints.py index 216b03c5677..a2f7497fc7e 100644 --- a/salt/utils/entrypoints.py +++ b/salt/utils/entrypoints.py @@ -73,7 +73,8 @@ def iter_entry_points(group, name=None): def name_and_version_from_entry_point(entry_point): if USE_IMPORTLIB_METADATA_STDLIB or USE_IMPORTLIB_METADATA: return types.SimpleNamespace( - name=entry_point.dist.metadata["name"], version=entry_point.dist.version, + name=entry_point.dist.metadata["name"], + version=entry_point.dist.version, ) elif USE_PKG_RESOURCES: return types.SimpleNamespace( diff --git a/salt/utils/event.py b/salt/utils/event.py index 3c91daa2b46..b6684829a12 100644 --- a/salt/utils/event.py +++ b/salt/utils/event.py @@ -1191,7 +1191,9 @@ class EventPublisher(salt.utils.process.SignalHandlingProcess): ) self.puller = salt.transport.ipc.IPCMessageServer( - epull_uri, io_loop=self.io_loop, payload_handler=self.handle_publish, + epull_uri, + io_loop=self.io_loop, + payload_handler=self.handle_publish, ) # Start the master event publisher diff --git a/salt/utils/functools.py b/salt/utils/functools.py index a93972693a4..9366b728993 100644 --- a/salt/utils/functools.py +++ b/salt/utils/functools.py @@ -44,7 +44,11 @@ def alias_function(fun, name, doc=None): Copy a function """ alias_fun = types.FunctionType( - fun.__code__, fun.__globals__, str(name), fun.__defaults__, fun.__closure__, + fun.__code__, + fun.__globals__, + str(name), + fun.__defaults__, + fun.__closure__, ) alias_fun.__dict__.update(fun.__dict__) diff --git a/salt/utils/gitfs.py b/salt/utils/gitfs.py index 51c0aaa0e32..14ba60c8882 100644 --- a/salt/utils/gitfs.py +++ b/salt/utils/gitfs.py @@ -862,7 +862,11 @@ class GitProvider: msg = ( "{} is enabled and {} lockfile {} is present for " "{} remote '{}'.".format( - global_lock_key, lock_type, lock_file, self.role, self.id, + global_lock_key, + lock_type, + lock_file, + self.role, + self.id, ) ) if pid: @@ -1012,7 +1016,9 @@ class GitProvider: and blacklist. """ return salt.utils.stringutils.check_whitelist_blacklist( - tgt_env, whitelist=self.saltenv_whitelist, blacklist=self.saltenv_blacklist, + tgt_env, + whitelist=self.saltenv_whitelist, + blacklist=self.saltenv_blacklist, ) def _fetch(self): diff --git a/salt/utils/github.py b/salt/utils/github.py index 1e4a6ed197c..1d6824f2ae9 100644 --- a/salt/utils/github.py +++ b/salt/utils/github.py @@ -45,7 +45,12 @@ def get_user_pubkeys(users): user = tmp_user url = "https://api.github.com/users/{}/keys".format(user) - result = salt.utils.http.query(url, "GET", decode=False, text=True,) + result = salt.utils.http.query( + url, + "GET", + decode=False, + text=True, + ) keys = salt.utils.json.loads(result["text"]) diff --git a/salt/utils/http.py b/salt/utils/http.py index d57006e1c58..2f37a51b5cf 100644 --- a/salt/utils/http.py +++ b/salt/utils/http.py @@ -806,7 +806,10 @@ def get_ca_bundle(opts=None): def update_ca_bundle( - target=None, source=None, opts=None, merge_files=None, + target=None, + source=None, + opts=None, + merge_files=None, ): """ Attempt to update the CA bundle file from a URL diff --git a/salt/utils/job.py b/salt/utils/job.py index f2e756c9c9d..d4bab8a2c7a 100644 --- a/salt/utils/job.py +++ b/salt/utils/job.py @@ -140,7 +140,7 @@ def store_job(opts, load, event=None, mminion=None): mminion.returners[fstr](load) except Exception: # pylint: disable=broad-except log.critical( - "The specified '%s' returner threw a stack trace", job_cache, exc_info=True, + "The specified '%s' returner threw a stack trace", job_cache, exc_info=True ) if opts.get("job_cache_store_endtime") and updateetfstr in mminion.returners: diff --git a/salt/utils/minions.py b/salt/utils/minions.py index aa6180db98e..99777fb57fe 100644 --- a/salt/utils/minions.py +++ b/salt/utils/minions.py @@ -80,7 +80,7 @@ def _nodegroup_regex(nodegroup, words, opers): def parse_target(target_expression): """Parse `target_expressing` splitting it into `engine`, `delimiter`, - `pattern` - returns a dict""" + `pattern` - returns a dict""" match = TARGET_REX.match(target_expression) if not match: diff --git a/salt/utils/napalm.py b/salt/utils/napalm.py index 2d17c3aca19..890319b719d 100644 --- a/salt/utils/napalm.py +++ b/salt/utils/napalm.py @@ -179,8 +179,10 @@ def call(napalm_device, method, *args, **kwargs): traceback.format_exc() ) # let's get the full traceback and display for debugging reasons. if isinstance(error, NotImplementedError): - comment = "{method} is not implemented for the NAPALM {driver} driver!".format( - method=method, driver=napalm_device.get("DRIVER_NAME") + comment = ( + "{method} is not implemented for the NAPALM {driver} driver!".format( + method=method, driver=napalm_device.get("DRIVER_NAME") + ) ) elif ( retry diff --git a/salt/utils/network.py b/salt/utils/network.py index ee29d84af38..177e6b9e794 100644 --- a/salt/utils/network.py +++ b/salt/utils/network.py @@ -914,7 +914,9 @@ def linux_interfaces(): ) elif ifconfig_path: cmd = subprocess.Popen( - [ifconfig_path, "-a"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + [ifconfig_path, "-a"], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, ).communicate()[0] ifaces = _interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) return ifaces @@ -1057,7 +1059,9 @@ def junos_interfaces(): """ ifconfig_path = salt.utils.path.which("ifconfig") cmd = subprocess.Popen( - [ifconfig_path, "-a"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + [ifconfig_path, "-a"], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, ).communicate()[0] return _junos_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) @@ -1074,7 +1078,9 @@ def netbsd_interfaces(): ifconfig_path = salt.utils.path.which("ifconfig") cmd = subprocess.Popen( - [ifconfig_path, "-a"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + [ifconfig_path, "-a"], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, ).communicate()[0] return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd)) @@ -1218,7 +1224,9 @@ def _hw_addr_aix(iface): cmd = subprocess.Popen( ["grep", "Hardware Address"], stdin=subprocess.Popen( - ["entstat", "-d", iface], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + ["entstat", "-d", iface], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, ).stdout, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, diff --git a/salt/utils/odict.py b/salt/utils/odict.py index 0077d1331a5..bfc22826c5e 100644 --- a/salt/utils/odict.py +++ b/salt/utils/odict.py @@ -311,7 +311,7 @@ except (ImportError, AttributeError): class DefaultOrderedDict(OrderedDict): - "Dictionary that remembers insertion order and " + "Dictionary that remembers insertion order and" def __init__(self, default_factory=None, *a, **kw): if default_factory is not None and not isinstance(default_factory, Callable): diff --git a/salt/utils/openstack/nova.py b/salt/utils/openstack/nova.py index 187cc0bd6c5..a1d08ee513c 100644 --- a/salt/utils/openstack/nova.py +++ b/salt/utils/openstack/nova.py @@ -639,7 +639,9 @@ class SaltNova: if self.volume_conn is None: raise SaltCloudSystemExit("No cinder endpoint available") - volumes = self.volume_list(search_opts={"display_name": name},) + volumes = self.volume_list( + search_opts={"display_name": name}, + ) volume = volumes[name] return volume diff --git a/salt/utils/parsers.py b/salt/utils/parsers.py index 0f123ab5976..b09db836889 100644 --- a/salt/utils/parsers.py +++ b/salt/utils/parsers.py @@ -1402,7 +1402,9 @@ class OutputOptionsMixIn(metaclass=MixInMeta): dest="output", help=( "Print the output from the '{}' command using the " - "specified outputter.".format(self.get_prog_name(),) + "specified outputter.".format( + self.get_prog_name(), + ) ), ) group.add_option( diff --git a/salt/utils/pkg/win.py b/salt/utils/pkg/win.py index ea77d8489c3..8418b06a784 100644 --- a/salt/utils/pkg/win.py +++ b/salt/utils/pkg/win.py @@ -160,11 +160,13 @@ class RegSoftwareInfo: "{}\\Software\\Microsoft\\Windows\\" "CurrentVersion\\Uninstall\\{}" ).format(sid, key_guid) if self.__squid: - self.__reg_products_path = "{}\\Software\\Classes\\Installer\\Products\\{}".format( - sid, self.__squid + self.__reg_products_path = ( + "{}\\Software\\Classes\\Installer\\Products\\{}".format( + sid, self.__squid + ) ) - self.__reg_upgradecode_path = "{}\\Software\\Microsoft\\Installer\\UpgradeCodes".format( - sid + self.__reg_upgradecode_path = ( + "{}\\Software\\Microsoft\\Installer\\UpgradeCodes".format(sid) ) self.__reg_patches_path = ( "Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\" @@ -174,12 +176,14 @@ class RegSoftwareInfo: self.__reg_hive = "HKEY_LOCAL_MACHINE" self.__reg_32bit = use_32bit self.__reg_32bit_access = self.__use_32bit_lookup[use_32bit] - self.__reg_uninstall_path = "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{}".format( - key_guid + self.__reg_uninstall_path = ( + "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\{}".format( + key_guid + ) ) if self.__squid: - self.__reg_products_path = "Software\\Classes\\Installer\\Products\\{}".format( - self.__squid + self.__reg_products_path = ( + "Software\\Classes\\Installer\\Products\\{}".format(self.__squid) ) self.__reg_upgradecode_path = ( "Software\\Classes\\Installer\\UpgradeCodes" @@ -490,11 +494,13 @@ class RegSoftwareInfo: # Check if we have already scanned these upgrade codes before, and also # check if they have been updated in the registry since last time we scanned. - if have_scan_key in self.__upgrade_code_have_scan and self.__upgrade_code_have_scan[ - have_scan_key - ] == ( - squid_upgrade_code_all, - suc_pytime, + if ( + have_scan_key in self.__upgrade_code_have_scan + and self.__upgrade_code_have_scan[have_scan_key] + == ( + squid_upgrade_code_all, + suc_pytime, + ) ): log.debug( "Scan skipped for upgrade codes, no changes (%s)", have_scan_key @@ -577,11 +583,13 @@ class RegSoftwareInfo: # Scan the patches for the DisplayName of active patches. for patch_squid in squid_patch_all: try: - patch_squid_handle = win32api.RegOpenKeyEx( # pylint: disable=no-member - pat_all_handle, - patch_squid, - 0, - win32con.KEY_READ | self.__reg_32bit_access, + patch_squid_handle = ( + win32api.RegOpenKeyEx( # pylint: disable=no-member + pat_all_handle, + patch_squid, + 0, + win32con.KEY_READ | self.__reg_32bit_access, + ) ) ( patch_display_name, @@ -1057,7 +1065,11 @@ class WinSoftware: "version capture within object '{}' failed " "for pkg id: '{}' it returned '{}' '{}' " "'{}'".format( - str(self.__pkg_obj), pkg_id, version_str, src, version_user_str, + str(self.__pkg_obj), + pkg_id, + version_str, + src, + version_user_str, ) ) @@ -1447,9 +1459,9 @@ class WinSoftware: def __main(): """This module can also be run directly for testing - Args: - detail|list : Provide ``detail`` or version ``list``. - system|system+user: System installed and System and User installs. + Args: + detail|list : Provide ``detail`` or version ``list``. + system|system+user: System installed and System and User installs. """ if len(sys.argv) < 3: sys.stderr.write( diff --git a/salt/utils/platform.py b/salt/utils/platform.py index 9f5da46ae20..be01f321533 100644 --- a/salt/utils/platform.py +++ b/salt/utils/platform.py @@ -95,7 +95,9 @@ def is_smartos_globalzone(): else: try: zonename_proc = subprocess.Popen( - ["zonename"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + ["zonename"], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, ) zonename_output = ( zonename_proc.communicate()[0].strip().decode(__salt_system_encoding__) @@ -121,7 +123,9 @@ def is_smartos_zone(): else: try: zonename_proc = subprocess.Popen( - ["zonename"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + ["zonename"], + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, ) zonename_output = ( zonename_proc.communicate()[0].strip().decode(__salt_system_encoding__) diff --git a/salt/utils/process.py b/salt/utils/process.py index 5df3e42c6d5..9038b40ba1c 100644 --- a/salt/utils/process.py +++ b/salt/utils/process.py @@ -542,7 +542,10 @@ class ProcessManager: # create a nicer name for the debug log if name is None: if isinstance(tgt, types.FunctionType): - name = "{}.{}".format(tgt.__module__, tgt.__name__,) + name = "{}.{}".format( + tgt.__module__, + tgt.__name__, + ) else: name = "{}{}.{}".format( tgt.__module__, diff --git a/salt/utils/pycrypto.py b/salt/utils/pycrypto.py index 1d8d971cd57..aebde812a6c 100644 --- a/salt/utils/pycrypto.py +++ b/salt/utils/pycrypto.py @@ -53,7 +53,11 @@ def secure_password(length=20, use_random=True): break except UnicodeDecodeError: continue - pw += re.sub(salt.utils.stringutils.to_str(r"[\W_]"), "", char,) + pw += re.sub( + salt.utils.stringutils.to_str(r"[\W_]"), + "", + char, + ) else: pw += random.SystemRandom().choice(string.ascii_letters + string.digits) return pw diff --git a/salt/utils/schedule.py b/salt/utils/schedule.py index 01d5b3d71ff..f950713c1e0 100644 --- a/salt/utils/schedule.py +++ b/salt/utils/schedule.py @@ -1068,9 +1068,10 @@ class Schedule: "whens" in self.opts["grains"] and i in self.opts["grains"]["whens"] ): if not isinstance(self.opts["grains"]["whens"], dict): - data["_error"] = ( - 'Grain "whens" must be a dict. ' - "Ignoring job {}.".format(data["name"]) + data[ + "_error" + ] = 'Grain "whens" must be a dict. ' "Ignoring job {}.".format( + data["name"] ) log.error(data["_error"]) return @@ -1082,9 +1083,10 @@ class Schedule: try: when_ = dateutil_parser.parse(when_) except ValueError: - data["_error"] = ( - "Invalid date string {}. " - "Ignoring job {}.".format(i, data["name"]) + data[ + "_error" + ] = "Invalid date string {}. " "Ignoring job {}.".format( + i, data["name"] ) log.error(data["_error"]) return @@ -1340,9 +1342,10 @@ class Schedule: try: start = dateutil_parser.parse(start) except ValueError: - data["_error"] = ( - "Invalid date string for start. " - "Ignoring job {}.".format(data["name"]) + data[ + "_error" + ] = "Invalid date string for start. " "Ignoring job {}.".format( + data["name"] ) log.error(data["_error"]) return @@ -1351,9 +1354,10 @@ class Schedule: try: end = dateutil_parser.parse(end) except ValueError: - data["_error"] = ( - "Invalid date string for end." - " Ignoring job {}.".format(data["name"]) + data[ + "_error" + ] = "Invalid date string for end." " Ignoring job {}.".format( + data["name"] ) log.error(data["_error"]) return diff --git a/salt/utils/timed_subprocess.py b/salt/utils/timed_subprocess.py index c7d22898e66..a3ffe3d38e4 100644 --- a/salt/utils/timed_subprocess.py +++ b/salt/utils/timed_subprocess.py @@ -108,7 +108,8 @@ class TimedProc: threading.Timer(10, terminate).start() raise salt.exceptions.TimedProcTimeoutError( "{} : Timed out after {} seconds".format( - self.command, str(self.timeout), + self.command, + str(self.timeout), ) ) return self.process.returncode diff --git a/salt/utils/vault.py b/salt/utils/vault.py index f370502008b..28573ace8b1 100644 --- a/salt/utils/vault.py +++ b/salt/utils/vault.py @@ -463,8 +463,10 @@ def _v2_the_path(path, pfilter, ptype="data"): """ possible_types = ["data", "metadata", "destroy"] assert ptype in possible_types - msg = "Path {} already contains {} in the right place - saltstack duct tape?".format( - path, ptype + msg = ( + "Path {} already contains {} in the right place - saltstack duct tape?".format( + path, ptype + ) ) path = path.rstrip("/").lstrip("/") diff --git a/salt/utils/vmware.py b/salt/utils/vmware.py index 99218cc6557..c177fac1b7f 100644 --- a/salt/utils/vmware.py +++ b/salt/utils/vmware.py @@ -262,7 +262,9 @@ def _get_service_instance( ) log.trace( - "Connecting using the '%s' mechanism, with username '%s'", mechanism, username, + "Connecting using the '%s' mechanism, with username '%s'", + mechanism, + username, ) default_msg = ( "Could not connect to host '{}'. " diff --git a/salt/utils/win_osinfo.py b/salt/utils/win_osinfo.py index 21615808c7c..71fdc5f85ee 100644 --- a/salt/utils/win_osinfo.py +++ b/salt/utils/win_osinfo.py @@ -14,7 +14,10 @@ except (ImportError, ValueError): HAS_WIN32 = False if HAS_WIN32: - kernel32 = ctypes.WinDLL("kernel32", use_last_error=True,) + kernel32 = ctypes.WinDLL( + "kernel32", + use_last_error=True, + ) # Although utils are often directly imported, it is also possible to use the diff --git a/salt/utils/win_runas.py b/salt/utils/win_runas.py index 0365d450ef8..56d4e563176 100644 --- a/salt/utils/win_runas.py +++ b/salt/utils/win_runas.py @@ -108,7 +108,9 @@ def runas(cmdLine, username, password=None, cwd=None): # accounts have this permission by default. try: impersonation_token = salt.platform.win.impersonate_sid( - salt.platform.win.SYSTEM_SID, session_id=0, privs=["SeTcbPrivilege"], + salt.platform.win.SYSTEM_SID, + session_id=0, + privs=["SeTcbPrivilege"], ) except OSError: log.debug("Unable to impersonate SYSTEM user") @@ -263,14 +265,18 @@ def runas_unpriv(cmd, username, password, cwd=None): # Create a pipe to set as stdout in the child. The write handle needs to be # inheritable. c2pread, c2pwrite = salt.platform.win.CreatePipe( - inherit_read=False, inherit_write=True, + inherit_read=False, + inherit_write=True, ) errread, errwrite = salt.platform.win.CreatePipe( - inherit_read=False, inherit_write=True, + inherit_read=False, + inherit_write=True, ) # Create inheritable copy of the stdin - stdin = salt.platform.win.kernel32.GetStdHandle(salt.platform.win.STD_INPUT_HANDLE,) + stdin = salt.platform.win.kernel32.GetStdHandle( + salt.platform.win.STD_INPUT_HANDLE, + ) dupin = salt.platform.win.DuplicateHandle(srchandle=stdin, inherit=True) # Get startup info structure diff --git a/salt/utils/zfs.py b/salt/utils/zfs.py index 1e96b21cafa..98546298e7b 100644 --- a/salt/utils/zfs.py +++ b/salt/utils/zfs.py @@ -543,10 +543,16 @@ def to_size(value, convert_to_human=True): # see libzfs implementation linked above v_size_float = float(value) / v_multiplier if v_size_float == int(v_size_float): - value = "{:.0f}{}".format(v_size_float, zfs_size[v_power - 1],) + value = "{:.0f}{}".format( + v_size_float, + zfs_size[v_power - 1], + ) else: for v_precision in ["{:.2f}{}", "{:.1f}{}", "{:.0f}{}"]: - v_size = v_precision.format(v_size_float, zfs_size[v_power - 1],) + v_size = v_precision.format( + v_size_float, + zfs_size[v_power - 1], + ) if len(v_size) <= 5: value = v_size break diff --git a/salt/version.py b/salt/version.py index b5c6fada03e..6eaa0518a6e 100644 --- a/salt/version.py +++ b/salt/version.py @@ -721,7 +721,9 @@ def dependency_information(include_salt_cloud=False): ] if include_salt_cloud: - libs.append(("Apache Libcloud", "libcloud", "__version__"),) + libs.append( + ("Apache Libcloud", "libcloud", "__version__"), + ) for name, imp, attr in libs: if imp is None: diff --git a/salt/wheel/__init__.py b/salt/wheel/__init__.py index 53c3d8527fd..057fefd574d 100644 --- a/salt/wheel/__init__.py +++ b/salt/wheel/__init__.py @@ -68,7 +68,8 @@ class WheelClient( if interface == "0.0.0.0": interface = "127.0.0.1" master_uri = "tcp://{}:{}".format( - salt.utils.zeromq.ip_bracket(interface), str(self.opts["ret_port"]), + salt.utils.zeromq.ip_bracket(interface), + str(self.opts["ret_port"]), ) with salt.transport.client.ReqChannel.factory( self.opts, crypt="clear", master_uri=master_uri, usage="master_call" diff --git a/salt/wheel/config.py b/salt/wheel/config.py index 80f135075ee..a5dfee0b602 100644 --- a/salt/wheel/config.py +++ b/salt/wheel/config.py @@ -70,7 +70,10 @@ def update_config(file_name, yaml_contents): __opts__["config_dir"], os.path.dirname(__opts__["default_include"]) ) try: - yaml_out = salt.utils.yaml.safe_dump(yaml_contents, default_flow_style=False,) + yaml_out = salt.utils.yaml.safe_dump( + yaml_contents, + default_flow_style=False, + ) if not os.path.exists(dir_path): log.debug("Creating directory %s", dir_path) diff --git a/scripts/suse/zypper/plugins/commit/zyppnotify b/scripts/suse/zypper/plugins/commit/zyppnotify index 51ac02254e7..23e03df8fdd 100755 --- a/scripts/suse/zypper/plugins/commit/zyppnotify +++ b/scripts/suse/zypper/plugins/commit/zyppnotify @@ -50,7 +50,7 @@ class DriftDetector(Plugin): def PLUGINEND(self, headers, body): """ - Hook when plugin closes Zypper's transaction. + Hook when plugin closes Zypper's transaction. """ if "SALT_RUNNING" not in os.environ: with open(self.ck_path, "w") as ck_fh: diff --git a/tests/conftest.py b/tests/conftest.py index 5221d17acfc..0456e319b24 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -175,7 +175,10 @@ def pytest_addoption(parser): help="Run proxy tests (DEPRECATED)", ) test_selection_group.addoption( - "--run-slow", action="store_true", default=False, help="Run slow tests.", + "--run-slow", + action="store_true", + default=False, + help="Run slow tests.", ) output_options_group = parser.getgroup("Output Options") @@ -590,7 +593,8 @@ def groups_collection_modifyitems(config, items): terminal_reporter = config.pluginmanager.get_plugin("terminalreporter") terminal_reporter.write( - "Running test group #{} ({} tests)\n".format(group_id, len(items)), yellow=True, + "Running test group #{} ({} tests)\n".format(group_id, len(items)), + yellow=True, ) @@ -1107,7 +1111,8 @@ def sshd_server(salt_factories, sshd_config_dir, salt_master): "UsePAM": "yes", } factory = salt_factories.get_sshd_daemon( - sshd_config_dict=sshd_config_dict, config_dir=sshd_config_dir, + sshd_config_dict=sshd_config_dict, + config_dir=sshd_config_dir, ) with factory.started(): yield factory diff --git a/tests/integration/cli/test_batch.py b/tests/integration/cli/test_batch.py index 4691df70599..09b31e1bd92 100644 --- a/tests/integration/cli/test_batch.py +++ b/tests/integration/cli/test_batch.py @@ -26,7 +26,8 @@ class BatchTest(ShellCase): """ ret = "Executing run on [{}]".format(repr("sub_minion")) cmd = self.run_salt( - '"*minion" test.echo "batch testing" -b 50%', timeout=self.run_timeout, + '"*minion" test.echo "batch testing" -b 50%', + timeout=self.run_timeout, ) self.assertIn(ret, cmd) @@ -38,7 +39,8 @@ class BatchTest(ShellCase): """ ret = "Executing run on [{}, {}]".format(repr("minion"), repr("sub_minion")) cmd = self.run_salt( - '"*minion" test.ping --batch-size 2', timeout=self.run_timeout, + '"*minion" test.ping --batch-size 2', + timeout=self.run_timeout, ) self.assertIn(ret, cmd) diff --git a/tests/integration/client/test_kwarg.py b/tests/integration/client/test_kwarg.py index 191d2f7fcaa..e482d127a74 100644 --- a/tests/integration/client/test_kwarg.py +++ b/tests/integration/client/test_kwarg.py @@ -91,7 +91,10 @@ class StdTest(ModuleCase): @pytest.mark.slow_test def test_full_return_kwarg(self): ret = self.client.cmd( - "minion", "test.ping", full_return=True, timeout=self.TIMEOUT, + "minion", + "test.ping", + full_return=True, + timeout=self.TIMEOUT, ) for mid, data in ret.items(): self.assertIn("retcode", data) diff --git a/tests/integration/client/test_standard.py b/tests/integration/client/test_standard.py index df6dcd49561..3efb3cc5244 100644 --- a/tests/integration/client/test_standard.py +++ b/tests/integration/client/test_standard.py @@ -20,12 +20,21 @@ class StdTest(ModuleCase): """ Test cli function """ - cmd_iter = self.client.cmd_cli("minion", "test.ping", timeout=20,) + cmd_iter = self.client.cmd_cli( + "minion", + "test.ping", + timeout=20, + ) for ret in cmd_iter: self.assertTrue(ret["minion"]) # make sure that the iter waits for long running jobs too - cmd_iter = self.client.cmd_cli("minion", "test.sleep", [6], timeout=20,) + cmd_iter = self.client.cmd_cli( + "minion", + "test.sleep", + [6], + timeout=20, + ) num_ret = 0 for ret in cmd_iter: num_ret += 1 @@ -40,7 +49,11 @@ class StdTest(ModuleCase): pass # ping that minion and ensure it times out try: - cmd_iter = self.client.cmd_cli("footest", "test.ping", timeout=20,) + cmd_iter = self.client.cmd_cli( + "footest", + "test.ping", + timeout=20, + ) num_ret = 0 for ret in cmd_iter: num_ret += 1 @@ -54,7 +67,10 @@ class StdTest(ModuleCase): """ test cmd_iter """ - cmd_iter = self.client.cmd_iter("minion", "test.ping",) + cmd_iter = self.client.cmd_iter( + "minion", + "test.ping", + ) for ret in cmd_iter: self.assertTrue(ret["minion"]) @@ -63,7 +79,10 @@ class StdTest(ModuleCase): """ test cmd_iter_no_block """ - cmd_iter = self.client.cmd_iter_no_block("minion", "test.ping",) + cmd_iter = self.client.cmd_iter_no_block( + "minion", + "test.ping", + ) for ret in cmd_iter: if ret is None: continue @@ -74,7 +93,10 @@ class StdTest(ModuleCase): """ test cmd_batch """ - cmd_batch = self.client.cmd_batch("minion", "test.ping",) + cmd_batch = self.client.cmd_batch( + "minion", + "test.ping", + ) for ret in cmd_batch: self.assertTrue(ret["minion"]) @@ -83,7 +105,11 @@ class StdTest(ModuleCase): """ test cmd_batch with raw option """ - cmd_batch = self.client.cmd_batch("minion", "test.ping", raw=True,) + cmd_batch = self.client.cmd_batch( + "minion", + "test.ping", + raw=True, + ) for ret in cmd_batch: self.assertTrue(ret["data"]["success"]) @@ -92,7 +118,11 @@ class StdTest(ModuleCase): """ test cmd_iter """ - ret = self.client.cmd_full_return("minion", "test.ping", timeout=20,) + ret = self.client.cmd_full_return( + "minion", + "test.ping", + timeout=20, + ) self.assertIn("minion", ret) self.assertEqual({"ret": True, "success": True}, ret["minion"]) diff --git a/tests/integration/client/test_syndic.py b/tests/integration/client/test_syndic.py index 81df0aff162..d5709b79cc0 100644 --- a/tests/integration/client/test_syndic.py +++ b/tests/integration/client/test_syndic.py @@ -22,4 +22,10 @@ class TestSyndic(SyndicCase): """ test.fib """ - self.assertEqual(self.run_function("test.fib", ["20"],)[0], 6765) + self.assertEqual( + self.run_function( + "test.fib", + ["20"], + )[0], + 6765, + ) diff --git a/tests/integration/modules/test_cp.py b/tests/integration/modules/test_cp.py index 4cf29519b35..4ea10b26998 100644 --- a/tests/integration/modules/test_cp.py +++ b/tests/integration/modules/test_cp.py @@ -64,7 +64,8 @@ class CPModuleTest(ModuleCase): @with_tempfile() @skipIf( - salt.utils.platform.is_windows(), "This test hangs on Windows on Py3", + salt.utils.platform.is_windows(), + "This test hangs on Windows on Py3", ) def test_get_file_templated_paths(self, tgt): """ @@ -394,7 +395,10 @@ class CPModuleTest(ModuleCase): """ cp.cache_master """ - ret = self.run_function("cp.cache_master", [tgt],) + ret = self.run_function( + "cp.cache_master", + [tgt], + ) for path in ret: self.assertTrue(os.path.exists(path)) @@ -517,7 +521,9 @@ class CPModuleTest(ModuleCase): with temp_file( "top.sls", top_sls, RUNTIME_VARS.TMP_BASEENV_STATE_TREE ), temp_file("core.sls", core_state, RUNTIME_VARS.TMP_BASEENV_STATE_TREE): - ret = self.run_function("cp.list_states",) + ret = self.run_function( + "cp.list_states", + ) self.assertIn("core", ret) self.assertIn("top", ret) diff --git a/tests/integration/modules/test_git.py b/tests/integration/modules/test_git.py index c4e5272a515..e477a6df894 100644 --- a/tests/integration/modules/test_git.py +++ b/tests/integration/modules/test_git.py @@ -391,7 +391,9 @@ class GitModuleTest(ModuleCase): self.assertTrue( "'cwd' argument required unless global=True" in self.run_function( - "git.config_set", ["foo.single"], value=cfg_local["foo.single"][0], + "git.config_set", + ["foo.single"], + value=cfg_local["foo.single"][0], ) ) log.debug("Set single local value") @@ -512,7 +514,11 @@ class GitModuleTest(ModuleCase): log.debug("Unset a single local value") self.assertTrue( - self.run_function("git.config_unset", ["foo.single"], cwd=self.repo,) + self.run_function( + "git.config_unset", + ["foo.single"], + cwd=self.repo, + ) ) log.debug("Unset an entire local multivar") self.assertTrue( @@ -894,7 +900,10 @@ class GitModuleTest(ModuleCase): worktree_path2 = worktree_path2.replace("\\", "/") # Add the worktrees - ret = self.run_function("git.worktree_add", [self.repo, worktree_path],) + ret = self.run_function( + "git.worktree_add", + [self.repo, worktree_path], + ) self.assertTrue(worktree_add_prefix in ret) self.assertTrue(worktree_basename in ret) ret = self.run_function("git.worktree_add", [self.repo, worktree_path2]) diff --git a/tests/integration/modules/test_mine.py b/tests/integration/modules/test_mine.py index ec4f2a2453b..2808a214976 100644 --- a/tests/integration/modules/test_mine.py +++ b/tests/integration/modules/test_mine.py @@ -135,10 +135,18 @@ class MineTest(ModuleCase, ShellCase): """ self.assertFalse(self.run_function("mine.send", ["foo.__spam_and_cheese"])) self.assertTrue( - self.run_function("mine.send", ["grains.items"], minion_tgt="minion",) + self.run_function( + "mine.send", + ["grains.items"], + minion_tgt="minion", + ) ) self.assertTrue( - self.run_function("mine.send", ["grains.items"], minion_tgt="sub_minion",) + self.run_function( + "mine.send", + ["grains.items"], + minion_tgt="sub_minion", + ) ) ret = self.run_function("mine.get", ["sub_minion", "grains.items"]) self.assertEqual(ret["sub_minion"]["id"], "sub_minion") diff --git a/tests/integration/modules/test_mysql.py b/tests/integration/modules/test_mysql.py index 953851f062a..df4fc9c616c 100644 --- a/tests/integration/modules/test_mysql.py +++ b/tests/integration/modules/test_mysql.py @@ -373,7 +373,8 @@ class MysqlModuleDbTest(ModuleCase, SaltReturnAssertsMixin): "CREATE TABLE {tblname} (" " id INT NOT NULL AUTO_INCREMENT PRIMARY KEY," " data VARCHAR(100)) ENGINE={engine};".format( - tblname=mysqlmod.quote_identifier(tablename), engine=engine, + tblname=mysqlmod.quote_identifier(tablename), + engine=engine, ) ) insert_query = "INSERT INTO {tblname} (data) VALUES ".format( @@ -401,7 +402,8 @@ class MysqlModuleDbTest(ModuleCase, SaltReturnAssertsMixin): "Unexpected query result while populating test table" " '{}' : '{}'" ).format( - tablename, ret, + tablename, + ret, ) ) self.assertEqual(ret["rows affected"], 0) @@ -419,7 +421,8 @@ class MysqlModuleDbTest(ModuleCase, SaltReturnAssertsMixin): "Unexpected query result while populating test table" " '{}' : '{}'" ).format( - tablename, ret, + tablename, + ret, ) ) self.assertEqual(ret["rows affected"], 101) @@ -437,7 +440,8 @@ class MysqlModuleDbTest(ModuleCase, SaltReturnAssertsMixin): "Unexpected query result while removing rows on test table" " '{}' : '{}'" ).format( - tablename, ret, + tablename, + ret, ) ) self.assertEqual(ret["rows affected"], 50) @@ -1389,7 +1393,8 @@ class MysqlModuleUserGrantTest(ModuleCase, SaltReturnAssertsMixin): "CREATE TABLE {tblname} (" " id INT NOT NULL AUTO_INCREMENT PRIMARY KEY," " data VARCHAR(100)) ENGINE={engine};".format( - tblname=mysqlmod.quote_identifier(self.table1), engine="MYISAM", + tblname=mysqlmod.quote_identifier(self.table1), + engine="MYISAM", ) ) log.info("Adding table '%s'", self.table1) @@ -1404,7 +1409,8 @@ class MysqlModuleUserGrantTest(ModuleCase, SaltReturnAssertsMixin): "CREATE TABLE {tblname} (" " id INT NOT NULL AUTO_INCREMENT PRIMARY KEY," " data VARCHAR(100)) ENGINE={engine};".format( - tblname=mysqlmod.quote_identifier(self.table2), engine="MYISAM", + tblname=mysqlmod.quote_identifier(self.table2), + engine="MYISAM", ) ) log.info("Adding table '%s'", self.table2) diff --git a/tests/integration/modules/test_pip.py b/tests/integration/modules/test_pip.py index 57229e75c04..4b809e089fb 100644 --- a/tests/integration/modules/test_pip.py +++ b/tests/integration/modules/test_pip.py @@ -87,7 +87,14 @@ class PipModuleTest(ModuleCase): """ return any(w in ret for w in ["URLError", "Download error"]) - def pip_successful_install(self, target, expect=("irc3-plugins-test", "pep8",)): + def pip_successful_install( + self, + target, + expect=( + "irc3-plugins-test", + "pep8", + ), + ): """ isolate regex for extracting `successful install` message from pip """ diff --git a/tests/integration/modules/test_pkg.py b/tests/integration/modules/test_pkg.py index ccf69998fcc..f647eb09162 100644 --- a/tests/integration/modules/test_pkg.py +++ b/tests/integration/modules/test_pkg.py @@ -108,8 +108,10 @@ class PkgModuleTest(ModuleCase, SaltReturnAssertsMixin): name = "SaltStack repo for RHEL/CentOS {}".format( grains["osmajorrelease"] ) - baseurl = "http://repo.saltstack.com/yum/redhat/{}/x86_64/latest/".format( - grains["osmajorrelease"] + baseurl = ( + "http://repo.saltstack.com/yum/redhat/{}/x86_64/latest/".format( + grains["osmajorrelease"] + ) ) gpgkey = "https://repo.saltstack.com/yum/rhel{}/SALTSTACK-GPG-KEY.pub".format( grains["osmajorrelease"] diff --git a/tests/integration/modules/test_test.py b/tests/integration/modules/test_test.py index 34c926cd5e7..2c2501b2d9b 100644 --- a/tests/integration/modules/test_test.py +++ b/tests/integration/modules/test_test.py @@ -67,14 +67,25 @@ class TestModuleTest(ModuleCase, AdaptedConfigurationTestCaseMixin): """ test.fib """ - self.assertEqual(self.run_function("test.fib", ["20"],)[0], 6765) + self.assertEqual( + self.run_function( + "test.fib", + ["20"], + )[0], + 6765, + ) @pytest.mark.slow_test def test_collatz(self): """ test.collatz """ - self.assertEqual(self.run_function("test.collatz", ["40"],)[0][-1], 2) + self.assertEqual( + self.run_function("test.collatz", ["40"],)[ + 0 + ][-1], + 2, + ) @pytest.mark.slow_test def test_outputter(self): diff --git a/tests/integration/modules/test_tls.py b/tests/integration/modules/test_tls.py index 76442bd4bc5..b28f88cc489 100644 --- a/tests/integration/modules/test_tls.py +++ b/tests/integration/modules/test_tls.py @@ -74,17 +74,23 @@ class TLSModuleTest(ModuleCase, LoaderModuleMockMixin): empty_crl_filename = os.path.join(self.tempdir, "empty.crl") tls.create_ca(self.ca_name) tls.create_csr( - ca_name=self.ca_name, CN="testing.localhost", + ca_name=self.ca_name, + CN="testing.localhost", ) tls.create_ca_signed_cert( - ca_name=self.ca_name, CN="testing.localhost", + ca_name=self.ca_name, + CN="testing.localhost", ) tls.create_empty_crl( - ca_name=self.ca_name, crl_file=empty_crl_filename, + ca_name=self.ca_name, + crl_file=empty_crl_filename, ) ret = tls.validate( cert=os.path.join( - self.tempdir, self.ca_name, "certs", "testing.localhost.crt", + self.tempdir, + self.ca_name, + "certs", + "testing.localhost.crt", ), ca_name=self.ca_name, crl_file=empty_crl_filename, @@ -96,13 +102,16 @@ class TLSModuleTest(ModuleCase, LoaderModuleMockMixin): revoked_crl_filename = os.path.join(self.tempdir, "revoked.crl") tls.create_ca(self.ca_name) tls.create_csr( - ca_name=self.ca_name, CN="testing.bad.localhost", + ca_name=self.ca_name, + CN="testing.bad.localhost", ) tls.create_ca_signed_cert( - ca_name=self.ca_name, CN="testing.bad.localhost", + ca_name=self.ca_name, + CN="testing.bad.localhost", ) tls.create_empty_crl( - ca_name=self.ca_name, crl_file=revoked_crl_filename, + ca_name=self.ca_name, + crl_file=revoked_crl_filename, ) tls.revoke_cert( ca_name=self.ca_name, @@ -112,7 +121,10 @@ class TLSModuleTest(ModuleCase, LoaderModuleMockMixin): self.assertFalse( tls.validate( cert=os.path.join( - self.tempdir, self.ca_name, "certs", "testing.bad.localhost.crt", + self.tempdir, + self.ca_name, + "certs", + "testing.bad.localhost.crt", ), ca_name=self.ca_name, crl_file=revoked_crl_filename, @@ -123,13 +135,16 @@ class TLSModuleTest(ModuleCase, LoaderModuleMockMixin): revoked_crl_filename = None tls.create_ca(self.ca_name) tls.create_csr( - ca_name=self.ca_name, CN="testing.bad.localhost", + ca_name=self.ca_name, + CN="testing.bad.localhost", ) tls.create_ca_signed_cert( - ca_name=self.ca_name, CN="testing.bad.localhost", + ca_name=self.ca_name, + CN="testing.bad.localhost", ) tls.create_empty_crl( - ca_name=self.ca_name, crl_file=revoked_crl_filename, + ca_name=self.ca_name, + crl_file=revoked_crl_filename, ) tls.revoke_cert( ca_name=self.ca_name, @@ -139,7 +154,10 @@ class TLSModuleTest(ModuleCase, LoaderModuleMockMixin): self.assertFalse( tls.validate( cert=os.path.join( - self.tempdir, self.ca_name, "certs", "testing.bad.localhost.crt", + self.tempdir, + self.ca_name, + "certs", + "testing.bad.localhost.crt", ), ca_name=self.ca_name, crl_file=revoked_crl_filename, diff --git a/tests/integration/netapi/rest_cherrypy/test_app_pam.py b/tests/integration/netapi/rest_cherrypy/test_app_pam.py index 30ba3d152de..f99616f4357 100644 --- a/tests/integration/netapi/rest_cherrypy/test_app_pam.py +++ b/tests/integration/netapi/rest_cherrypy/test_app_pam.py @@ -71,7 +71,7 @@ class TestAuthPAM(cptc.BaseRestCherryPyTest, ModuleCase): Test login while specifying login service with bad passwd This test ensures this PR is working correctly: https://github.com/saltstack/salt/pull/31826 - """ + """ copyauth_creds = AUTH_CREDS.copy() copyauth_creds["service"] = "login" copyauth_creds["password"] = "wrong_password" diff --git a/tests/integration/netapi/rest_tornado/test_app.py b/tests/integration/netapi/rest_tornado/test_app.py index 5e9960f3602..cdd5f33cf84 100644 --- a/tests/integration/netapi/rest_tornado/test_app.py +++ b/tests/integration/netapi/rest_tornado/test_app.py @@ -44,7 +44,11 @@ class TestSaltAPIHandler(SaltnadoIntegrationTestsBase): """ Test the root path which returns the list of clients we support """ - response = self.fetch("/", connect_timeout=30, request_timeout=30,) + response = self.fetch( + "/", + connect_timeout=30, + request_timeout=30, + ) self.assertEqual(response.code, 200) response_obj = salt.utils.json.loads(response.body) self.assertEqual( diff --git a/tests/integration/netapi/test_client.py b/tests/integration/netapi/test_client.py index 810c2472ab4..5158a7bb85c 100644 --- a/tests/integration/netapi/test_client.py +++ b/tests/integration/netapi/test_client.py @@ -446,7 +446,8 @@ class NetapiSSHClientAuthTest(SSHCase): else: hashed_password = salt.utils.pycrypto.gen_hash(password=self.USERA_PWD) add_pwd = self.mod_case.run_function( - "shadow.set_password", [self.USERA, hashed_password], + "shadow.set_password", + [self.USERA, hashed_password], ) self.assertTrue(add_pwd) except AssertionError: diff --git a/tests/integration/runners/test_nacl.py b/tests/integration/runners/test_nacl.py index 4da8a7418fb..eb4339a61dd 100644 --- a/tests/integration/runners/test_nacl.py +++ b/tests/integration/runners/test_nacl.py @@ -32,7 +32,9 @@ class NaclTest(ShellCase): Test keygen """ # Store the data - ret = self.run_run_plus("nacl.keygen",) + ret = self.run_run_plus( + "nacl.keygen", + ) self.assertIn("pk", ret["return"]) self.assertIn("sk", ret["return"]) @@ -42,7 +44,9 @@ class NaclTest(ShellCase): Test keygen """ # Store the data - ret = self.run_run_plus("nacl.keygen",) + ret = self.run_run_plus( + "nacl.keygen", + ) self.assertIn("pk", ret["return"]) self.assertIn("sk", ret["return"]) pk = ret["return"]["pk"] @@ -51,7 +55,11 @@ class NaclTest(ShellCase): unencrypted_data = "hello" # Encrypt with pk - ret = self.run_run_plus("nacl.enc", data=unencrypted_data, pk=pk,) + ret = self.run_run_plus( + "nacl.enc", + data=unencrypted_data, + pk=pk, + ) self.assertIn("return", ret) @pytest.mark.slow_test @@ -60,7 +68,9 @@ class NaclTest(ShellCase): Store, list, fetch, then flush data """ # Store the data - ret = self.run_run_plus("nacl.keygen",) + ret = self.run_run_plus( + "nacl.keygen", + ) self.assertIn("pk", ret["return"]) self.assertIn("sk", ret["return"]) pk = ret["return"]["pk"] @@ -69,12 +79,20 @@ class NaclTest(ShellCase): unencrypted_data = b"hello" # Encrypt with pk - ret = self.run_run_plus("nacl.enc", data=unencrypted_data, pk=pk,) + ret = self.run_run_plus( + "nacl.enc", + data=unencrypted_data, + pk=pk, + ) self.assertIn("return", ret) encrypted_data = ret["return"] # Decrypt with sk - ret = self.run_run_plus("nacl.dec", data=encrypted_data, sk=sk,) + ret = self.run_run_plus( + "nacl.dec", + data=encrypted_data, + sk=sk, + ) self.assertIn("return", ret) self.assertEqual(unencrypted_data, ret["return"]) @@ -84,7 +102,9 @@ class NaclTest(ShellCase): Generate keys, encrypt, then decrypt. """ # Store the data - ret = self.run_run_plus("nacl.keygen",) + ret = self.run_run_plus( + "nacl.keygen", + ) self.assertIn("pk", ret["return"]) self.assertIn("sk", ret["return"]) pk = ret["return"]["pk"] @@ -93,11 +113,19 @@ class NaclTest(ShellCase): unencrypted_data = b"hello" # Encrypt with pk - ret = self.run_run_plus("nacl.sealedbox_encrypt", data=unencrypted_data, pk=pk,) + ret = self.run_run_plus( + "nacl.sealedbox_encrypt", + data=unencrypted_data, + pk=pk, + ) encrypted_data = ret["return"] # Decrypt with sk - ret = self.run_run_plus("nacl.sealedbox_decrypt", data=encrypted_data, sk=sk,) + ret = self.run_run_plus( + "nacl.sealedbox_decrypt", + data=encrypted_data, + sk=sk, + ) self.assertEqual(unencrypted_data, ret["return"]) @pytest.mark.slow_test @@ -106,7 +134,9 @@ class NaclTest(ShellCase): Generate keys, encrypt, then decrypt. """ # Store the data - ret = self.run_run_plus("nacl.keygen",) + ret = self.run_run_plus( + "nacl.keygen", + ) self.assertIn("pk", ret["return"]) self.assertIn("sk", ret["return"]) pk = ret["return"]["pk"] @@ -115,11 +145,19 @@ class NaclTest(ShellCase): unencrypted_data = b"hello" # Encrypt with pk - ret = self.run_run_plus("nacl.secretbox_encrypt", data=unencrypted_data, sk=sk,) + ret = self.run_run_plus( + "nacl.secretbox_encrypt", + data=unencrypted_data, + sk=sk, + ) encrypted_data = ret["return"] # Decrypt with sk - ret = self.run_run_plus("nacl.secretbox_decrypt", data=encrypted_data, sk=sk,) + ret = self.run_run_plus( + "nacl.secretbox_decrypt", + data=encrypted_data, + sk=sk, + ) self.assertEqual(unencrypted_data, ret["return"]) @pytest.mark.slow_test @@ -128,7 +166,9 @@ class NaclTest(ShellCase): Store, list, fetch, then flush data """ # Store the data - ret = self.run_run_plus("nacl.keygen",) + ret = self.run_run_plus( + "nacl.keygen", + ) self.assertIn("pk", ret["return"]) self.assertIn("sk", ret["return"]) pk = ret["return"]["pk"] @@ -137,12 +177,20 @@ class NaclTest(ShellCase): unencrypted_data = b"hello" # Encrypt with pk - ret = self.run_run_plus("nacl.enc", data=unencrypted_data, pk=None,) + ret = self.run_run_plus( + "nacl.enc", + data=unencrypted_data, + pk=None, + ) self.assertIn("Exception: no pubkey or pk_file found", ret["return"]) self.assertIn("return", ret) encrypted_data = ret["return"] # Decrypt with sk - ret = self.run_run_plus("nacl.dec", data=encrypted_data, sk=None,) + ret = self.run_run_plus( + "nacl.dec", + data=encrypted_data, + sk=None, + ) self.assertIn("Exception: no key or sk_file found", ret["return"]) diff --git a/tests/integration/runners/test_runner_returns.py b/tests/integration/runners/test_runner_returns.py index 42e7b7cf870..e57c5d82c2d 100644 --- a/tests/integration/runners/test_runner_returns.py +++ b/tests/integration/runners/test_runner_returns.py @@ -37,7 +37,10 @@ class RunnerReturnsTest(ShellCase): raise self.conf = tempfile.NamedTemporaryFile( - mode="w", suffix=".conf", dir=self.master_d_dir, delete=False, + mode="w", + suffix=".conf", + dir=self.master_d_dir, + delete=False, ) def tearDown(self): diff --git a/tests/integration/states/test_beacon.py b/tests/integration/states/test_beacon.py index 962cf8fd6fa..e142ebf9a36 100644 --- a/tests/integration/states/test_beacon.py +++ b/tests/integration/states/test_beacon.py @@ -13,8 +13,7 @@ class BeaconStateTestCase(ModuleCase, SaltReturnAssertsMixin): """ def setUp(self): - """ - """ + """ """ self.run_function("beacons.reset", f_timeout=300) self.wait_for_all_jobs() diff --git a/tests/integration/states/test_docker_network.py b/tests/integration/states/test_docker_network.py index 4a683fdebb9..a136abf07f2 100644 --- a/tests/integration/states/test_docker_network.py +++ b/tests/integration/states/test_docker_network.py @@ -267,7 +267,11 @@ class DockerNetworkTestCase(ModuleCase, SaltReturnAssertsMixin): @pytest.mark.slow_test def test_present_internal(self, net): self.assertSaltTrueReturn( - self.run_state("docker_network.present", name=net.name, internal=True,) + self.run_state( + "docker_network.present", + name=net.name, + internal=True, + ) ) net_info = self.run_function("docker.inspect_network", [net.name]) self.assertIs(net_info["Internal"], True) @@ -285,7 +289,8 @@ class DockerNetworkTestCase(ModuleCase, SaltReturnAssertsMixin): ) net_info = self.run_function("docker.inspect_network", [net.name]) self.assertEqual( - net_info["Labels"], {"foo": "", "bar": "baz", "hello": "world"}, + net_info["Labels"], + {"foo": "", "bar": "baz", "hello": "world"}, ) @with_network(subnet="fe3f:2180:26:1::/123") @@ -312,7 +317,11 @@ class DockerNetworkTestCase(ModuleCase, SaltReturnAssertsMixin): self.skipTest("Cannot reliably manage attachable on RHEL <= 7") self.assertSaltTrueReturn( - self.run_state("docker_network.present", name=net.name, attachable=True,) + self.run_state( + "docker_network.present", + name=net.name, + attachable=True, + ) ) net_info = self.run_function("docker.inspect_network", [net.name]) self.assertIs(net_info["Attachable"], True) @@ -321,7 +330,11 @@ class DockerNetworkTestCase(ModuleCase, SaltReturnAssertsMixin): @with_network() def test_present_scope(self, net): self.assertSaltTrueReturn( - self.run_state("docker_network.present", name=net.name, scope="global",) + self.run_state( + "docker_network.present", + name=net.name, + scope="global", + ) ) net_info = self.run_function("docker.inspect_network", [net.name]) self.assertIs(net_info["Scope"], "global") @@ -330,7 +343,11 @@ class DockerNetworkTestCase(ModuleCase, SaltReturnAssertsMixin): @with_network() def test_present_ingress(self, net): self.assertSaltTrueReturn( - self.run_state("docker_network.present", name=net.name, ingress=True,) + self.run_state( + "docker_network.present", + name=net.name, + ingress=True, + ) ) net_info = self.run_function("docker.inspect_network", [net.name]) self.assertIs(net_info["Ingress"], True) diff --git a/tests/integration/states/test_file.py b/tests/integration/states/test_file.py index c5d8fd4cf3c..3f11dac217a 100644 --- a/tests/integration/states/test_file.py +++ b/tests/integration/states/test_file.py @@ -87,7 +87,10 @@ def _test_managed_file_mode_keep_helper(testcase, local=False): # to "keep", we're actually changing the permissions of the file to the # new mode. ret = testcase.run_state( - "file.managed", name=str(name), mode=oct(initial_mode), source=grail, + "file.managed", + name=str(name), + mode=oct(initial_mode), + source=grail, ) if IS_WINDOWS: @@ -100,7 +103,10 @@ def _test_managed_file_mode_keep_helper(testcase, local=False): # Update the mode on the fileserver (pass 1) os.chmod(grail_fs_path, new_mode_1) ret = testcase.run_state( - "file.managed", name=str(name), mode="keep", source=grail, + "file.managed", + name=str(name), + mode="keep", + source=grail, ) testcase.assertSaltTrueReturn(ret) managed_mode = stat.S_IMODE(name.stat().st_mode) @@ -111,7 +117,10 @@ def _test_managed_file_mode_keep_helper(testcase, local=False): # this time. os.chmod(grail_fs_path, new_mode_2) ret = testcase.run_state( - "file.managed", name=str(name), mode="keep", source=grail, + "file.managed", + name=str(name), + mode="keep", + source=grail, ) testcase.assertSaltTrueReturn(ret) managed_mode = stat.S_IMODE(name.stat().st_mode) @@ -467,7 +476,9 @@ class FileTest(ModuleCase, SaltReturnAssertsMixin): name.write_bytes(b"test_managed_show_changes_false\n") ret = self.run_state( - "file.managed", name=str(name), source="salt://grail/scene33", + "file.managed", + name=str(name), + source="salt://grail/scene33", ) changes = next(iter(ret.values()))["changes"] @@ -981,7 +992,10 @@ class FileTest(ModuleCase, SaltReturnAssertsMixin): ret = self.repack_state_returns( self.run_function( - "state.apply", mods="onchanges_prereq", pillar=pillar, test=True, + "state.apply", + mods="onchanges_prereq", + pillar=pillar, + test=True, ) ) # The file states should both exit with None @@ -1019,7 +1033,10 @@ class FileTest(ModuleCase, SaltReturnAssertsMixin): ret = self.repack_state_returns( self.run_function( - "state.apply", mods="onchanges_prereq", pillar=pillar, test=True, + "state.apply", + mods="onchanges_prereq", + pillar=pillar, + test=True, ) ) # The file states should both exit with None @@ -1490,7 +1507,10 @@ class FileTest(ModuleCase, SaltReturnAssertsMixin): file.recurse test interface """ ret = self.run_state( - "file.recurse", test=True, name=name, source="salt://grail", + "file.recurse", + test=True, + name=name, + source="salt://grail", ) self.assertSaltNoneReturn(ret) self.assertFalse(os.path.isfile(os.path.join(name, "36", "scene"))) @@ -1617,7 +1637,8 @@ class FileTest(ModuleCase, SaltReturnAssertsMixin): self.assertSaltTrueReturn(ret) files = salt.utils.data.decode(os.listdir(name), normalize=True) self.assertEqual( - sorted(files), sorted(["foo.txt", "спам.txt", "яйца.txt"]), + sorted(files), + sorted(["foo.txt", "спам.txt", "яйца.txt"]), ) @with_tempfile() @@ -2072,7 +2093,10 @@ class FileTest(ModuleCase, SaltReturnAssertsMixin): merged = {"foo": {"abc": 123, "bar": "%(x)s"}} ret = self.run_state( - "file.serialize", name=name, dataset=data1, formatter="plist", + "file.serialize", + name=name, + dataset=data1, + formatter="plist", ) ret = ret[next(iter(ret))] assert ret["result"], ret @@ -2193,7 +2217,12 @@ class FileTest(ModuleCase, SaltReturnAssertsMixin): """ with salt.utils.files.fopen(name, "w+") as fp_: fp_.write("comment_me") - ret = self.run_state("file.comment", test=True, name=name, regex=".*comment.*",) + ret = self.run_state( + "file.comment", + test=True, + name=name, + regex=".*comment.*", + ) with salt.utils.files.fopen(name, "r") as fp_: self.assertNotIn("#comment", fp_.read()) self.assertSaltNoneReturn(ret) @@ -2962,7 +2991,11 @@ class FileTest(ModuleCase, SaltReturnAssertsMixin): # Run the state ret = self.run_state( - "file.managed", name=tempfile, user=user, group=group, mode="4750", + "file.managed", + name=tempfile, + user=user, + group=group, + mode="4750", ) self.assertSaltTrueReturn(ret) @@ -4537,7 +4570,11 @@ class BlockreplaceTest(ModuleCase, SaltReturnAssertsMixin): @with_tempfile() def test_issue_49043(self, name): - ret = self.run_function("state.sls", mods="issue-49043", pillar={"name": name},) + ret = self.run_function( + "state.sls", + mods="issue-49043", + pillar={"name": name}, + ) log.error("ret = %s", repr(ret)) diff = "--- \n+++ \n@@ -0,0 +1,3 @@\n" diff += dedent( @@ -4758,7 +4795,9 @@ class PatchTest(ModuleCase, SaltReturnAssertsMixin): Test file.patch using a patch applied to a single file """ ret = self.run_state( - "file.patch", name=self.numbers_file, source=self.numbers_patch, + "file.patch", + name=self.numbers_file, + source=self.numbers_patch, ) self.assertSaltTrueReturn(ret) ret = ret[next(iter(ret))] @@ -4767,7 +4806,9 @@ class PatchTest(ModuleCase, SaltReturnAssertsMixin): # Re-run the state, should succeed and there should be a message about # a partially-applied hunk. ret = self.run_state( - "file.patch", name=self.numbers_file, source=self.numbers_patch, + "file.patch", + name=self.numbers_file, + source=self.numbers_patch, ) self.assertSaltTrueReturn(ret) ret = ret[next(iter(ret))] @@ -4781,7 +4822,10 @@ class PatchTest(ModuleCase, SaltReturnAssertsMixin): """ self._check_patch_version("2.6") ret = self.run_state( - "file.patch", name=self.base_dir, source=self.all_patch, strip=1, + "file.patch", + name=self.base_dir, + source=self.all_patch, + strip=1, ) self.assertSaltTrueReturn(ret) ret = ret[next(iter(ret))] @@ -4790,7 +4834,10 @@ class PatchTest(ModuleCase, SaltReturnAssertsMixin): # Re-run the state, should succeed and there should be a message about # a partially-applied hunk. ret = self.run_state( - "file.patch", name=self.base_dir, source=self.all_patch, strip=1, + "file.patch", + name=self.base_dir, + source=self.all_patch, + strip=1, ) self.assertSaltTrueReturn(ret) ret = ret[next(iter(ret))] @@ -4804,7 +4851,10 @@ class PatchTest(ModuleCase, SaltReturnAssertsMixin): self._check_patch_version("2.6") # Run the state using -p1 ret = self.run_state( - "file.patch", name=self.base_dir, source=self.all_patch, options="-p1", + "file.patch", + name=self.base_dir, + source=self.all_patch, + options="-p1", ) self.assertSaltTrueReturn(ret) ret = ret[next(iter(ret))] @@ -4842,7 +4892,10 @@ class PatchTest(ModuleCase, SaltReturnAssertsMixin): # environment, but that is OK, we just want to test that we're looking # in an environment other than base. ret = self.run_state( - "file.patch", name=self.math_file, source=self.math_patch, saltenv="prod", + "file.patch", + name=self.math_file, + source=self.math_patch, + saltenv="prod", ) self.assertSaltFalseReturn(ret) ret = ret[next(iter(ret))] @@ -4861,7 +4914,9 @@ class PatchTest(ModuleCase, SaltReturnAssertsMixin): pass ret = self.run_state( - "file.patch", name=self.numbers_file, source=self.numbers_patch, + "file.patch", + name=self.numbers_file, + source=self.numbers_patch, ) self.assertSaltFalseReturn(ret) ret = ret[next(iter(ret))] @@ -4894,7 +4949,10 @@ class PatchTest(ModuleCase, SaltReturnAssertsMixin): pass ret = self.run_state( - "file.patch", name=self.base_dir, source=self.all_patch, strip=1, + "file.patch", + name=self.base_dir, + source=self.all_patch, + strip=1, ) self.assertSaltFalseReturn(ret) ret = ret[next(iter(ret))] @@ -4925,7 +4983,9 @@ class PatchTest(ModuleCase, SaltReturnAssertsMixin): # Try without a source_hash and without skip_verify=True, this should # fail with a message about the source_hash ret = self.run_state( - "file.patch", name=self.math_file, source=self.math_patch_http, + "file.patch", + name=self.math_file, + source=self.math_patch_http, ) self.assertSaltFalseReturn(ret) ret = ret[next(iter(ret))] @@ -4965,7 +5025,10 @@ class PatchTest(ModuleCase, SaltReturnAssertsMixin): # Try without a source_hash and without skip_verify=True, this should # fail with a message about the source_hash ret = self.run_state( - "file.patch", name=self.base_dir, source=self.all_patch_http, strip=1, + "file.patch", + name=self.base_dir, + source=self.all_patch_http, + strip=1, ) self.assertSaltFalseReturn(ret) ret = ret[next(iter(ret))] @@ -5165,7 +5228,10 @@ class PatchTest(ModuleCase, SaltReturnAssertsMixin): # Try without a source_hash and without skip_verify=True, this should # fail with a message about the source_hash ret = self.run_state( - "file.patch", name=self.numbers_file, source=self.numbers_patch, test=True, + "file.patch", + name=self.numbers_file, + source=self.numbers_patch, + test=True, ) self.assertSaltNoneReturn(ret) ret = ret[next(iter(ret))] @@ -5176,7 +5242,9 @@ class PatchTest(ModuleCase, SaltReturnAssertsMixin): # exit with a True rather than a None result if test=True is used on an # already-applied patch. ret = self.run_state( - "file.patch", name=self.numbers_file, source=self.numbers_patch, + "file.patch", + name=self.numbers_file, + source=self.numbers_patch, ) self.assertSaltTrueReturn(ret) ret = ret[next(iter(ret))] @@ -5188,7 +5256,10 @@ class PatchTest(ModuleCase, SaltReturnAssertsMixin): # the same as if we try to run this state on an already-patched file # *without* test=True. ret = self.run_state( - "file.patch", name=self.numbers_file, source=self.numbers_patch, test=True, + "file.patch", + name=self.numbers_file, + source=self.numbers_patch, + test=True, ) self.assertSaltTrueReturn(ret) ret = ret[next(iter(ret))] @@ -5204,7 +5275,10 @@ class PatchTest(ModuleCase, SaltReturnAssertsMixin): # case we should return a False result because we should already know # by this point that the patch will not apply cleanly. ret = self.run_state( - "file.patch", name=self.numbers_file, source=self.numbers_patch, test=True, + "file.patch", + name=self.numbers_file, + source=self.numbers_patch, + test=True, ) self.assertSaltFalseReturn(ret) ret = ret[next(iter(ret))] diff --git a/tests/integration/states/test_git.py b/tests/integration/states/test_git.py index a4706469b49..fdc8bf9a5f4 100644 --- a/tests/integration/states/test_git.py +++ b/tests/integration/states/test_git.py @@ -424,7 +424,11 @@ class GitTest(ModuleCase, SaltReturnAssertsMixin): ) # Run the state to clone the repo we just created - ret = self.run_state("git.latest", name=name, target=target,) + ret = self.run_state( + "git.latest", + name=name, + target=target, + ) self.assertSaltTrueReturn(ret) # Add another commit @@ -439,7 +443,11 @@ class GitTest(ModuleCase, SaltReturnAssertsMixin): # Run the state again. It should pass, if it doesn't then there was # a problem checking whether or not the change is a fast-forward. - ret = self.run_state("git.latest", name=name, target=target,) + ret = self.run_state( + "git.latest", + name=name, + target=target, + ) self.assertSaltTrueReturn(ret) @with_tempdir(create=False) @@ -943,7 +951,10 @@ class LocalRepoGitTest(ModuleCase, SaltReturnAssertsMixin): # Run git.latest state. This should successfully clone and fail with a # specific error in the comment field. ret = self.run_state( - "git.latest", name=self.repo, target=self.target, rev="develop", + "git.latest", + name=self.repo, + target=self.target, + rev="develop", ) self.assertSaltFalseReturn(ret) self.assertEqual( @@ -965,7 +976,10 @@ class LocalRepoGitTest(ModuleCase, SaltReturnAssertsMixin): # Run git.latest state again. This should fail again, with a different # error in the comment field, and should not change anything. ret = self.run_state( - "git.latest", name=self.repo, target=self.target, rev="develop", + "git.latest", + name=self.repo, + target=self.target, + rev="develop", ) self.assertSaltFalseReturn(ret) self.assertEqual( diff --git a/tests/integration/states/test_lxd_container.py b/tests/integration/states/test_lxd_container.py index 269d44ed007..3fc75805088 100644 --- a/tests/integration/states/test_lxd_container.py +++ b/tests/integration/states/test_lxd_container.py @@ -26,10 +26,12 @@ class LxdContainerTestCase(ModuleCase, SaltReturnAssertsMixin): def tearDown(self): self.run_state( - "lxd_image.absent", name="images:centos/7", + "lxd_image.absent", + name="images:centos/7", ) self.run_state( - "lxd_container.absent", name="test-container", + "lxd_container.absent", + name="test-container", ) def test_02__create_container(self): @@ -79,7 +81,10 @@ class LxdContainerTestCase(ModuleCase, SaltReturnAssertsMixin): running=True, source={"type": "image", "alias": "images:centos/7"}, ) - ret = self.run_state("lxd_container.running", name="test-container",) + ret = self.run_state( + "lxd_container.running", + name="test-container", + ) self.assertSaltTrueReturn(ret) name = "lxd_container_|-test-container_|-test-container_|-running" assert name in ret @@ -88,7 +93,9 @@ class LxdContainerTestCase(ModuleCase, SaltReturnAssertsMixin): ret[name]["comment"] == 'The container "test-container" is already running' ) ret = self.run_state( - "lxd_container.running", name="test-container", restart=True, + "lxd_container.running", + name="test-container", + restart=True, ) self.assertSaltTrueReturn(ret) assert name in ret @@ -104,13 +111,19 @@ class LxdContainerTestCase(ModuleCase, SaltReturnAssertsMixin): running=True, source={"type": "image", "alias": "images:centos/7"}, ) - ret = self.run_state("lxd_container.stopped", name="test-container",) + ret = self.run_state( + "lxd_container.stopped", + name="test-container", + ) name = "lxd_container_|-test-container_|-test-container_|-stopped" self.assertSaltTrueReturn(ret) assert ret[name]["changes"] == { "stopped": 'Stopped the container "test-container"' } - ret = self.run_state("lxd_container.stopped", name="test-container",) + ret = self.run_state( + "lxd_container.stopped", + name="test-container", + ) name = "lxd_container_|-test-container_|-test-container_|-stopped" self.assertSaltTrueReturn(ret) assert not ret[name]["changes"] @@ -122,15 +135,24 @@ class LxdContainerTestCase(ModuleCase, SaltReturnAssertsMixin): running=True, source={"type": "image", "alias": "images:centos/7"}, ) - ret = self.run_state("lxd_container.absent", name="test-container",) + ret = self.run_state( + "lxd_container.absent", + name="test-container", + ) name = "lxd_container_|-test-container_|-test-container_|-absent" assert name in ret assert ret[name]["result"] is False - ret = self.run_state("lxd_container.stopped", name="test-container",) + ret = self.run_state( + "lxd_container.stopped", + name="test-container", + ) name = "lxd_container_|-test-container_|-test-container_|-stopped" assert name in ret assert ret[name]["result"] is True - ret = self.run_state("lxd_container.absent", name="test-container",) + ret = self.run_state( + "lxd_container.absent", + name="test-container", + ) name = "lxd_container_|-test-container_|-test-container_|-absent" self.assertSaltTrueReturn(ret) assert name in ret diff --git a/tests/integration/states/test_lxd_image.py b/tests/integration/states/test_lxd_image.py index 9d3eff6d6e0..ac2ea1bf3e7 100644 --- a/tests/integration/states/test_lxd_image.py +++ b/tests/integration/states/test_lxd_image.py @@ -27,7 +27,10 @@ class LxdImageTestCase(ModuleCase, SaltReturnAssertsMixin): assert ret[name]["changes"]["aliases"] == ['Added alias "images:centos/7"'] def test_03__delete_image(self): - ret = self.run_state("lxd_image.absent", name="images:centos/7",) + ret = self.run_state( + "lxd_image.absent", + name="images:centos/7", + ) name = "lxd_image_|-images:centos/7_|-images:centos/7_|-absent" self.assertSaltTrueReturn(ret) assert name in ret diff --git a/tests/integration/states/test_lxd_profile.py b/tests/integration/states/test_lxd_profile.py index bb39b98e878..f149c98997c 100644 --- a/tests/integration/states/test_lxd_profile.py +++ b/tests/integration/states/test_lxd_profile.py @@ -13,12 +13,14 @@ from tests.support.mixins import SaltReturnAssertsMixin class LxdProfileTestCase(ModuleCase, SaltReturnAssertsMixin): def tearDown(self): self.run_state( - "lxd_profile.absent", name="test-profile", + "lxd_profile.absent", + name="test-profile", ) def test_02__create_profile(self): self.run_state( - "lxd_profile.absent", name="test-profile", + "lxd_profile.absent", + name="test-profile", ) ret = self.run_state( "lxd_profile.present", @@ -59,7 +61,10 @@ class LxdProfileTestCase(ModuleCase, SaltReturnAssertsMixin): name="test-profile", config=[{"key": "boot.autostart", "value": 1}], ) - ret = self.run_state("lxd_profile.absent", name="test-profile",) + ret = self.run_state( + "lxd_profile.absent", + name="test-profile", + ) name = "lxd_profile_|-test-profile_|-test-profile_|-absent" self.assertSaltTrueReturn(ret) assert name in ret diff --git a/tests/integration/states/test_mysql_grants.py b/tests/integration/states/test_mysql_grants.py index e03ef3b3247..655daefa127 100644 --- a/tests/integration/states/test_mysql_grants.py +++ b/tests/integration/states/test_mysql_grants.py @@ -106,7 +106,8 @@ class MysqlGrantsStateTest(ModuleCase, SaltReturnAssertsMixin): "CREATE TABLE {tblname} (" " id INT NOT NULL AUTO_INCREMENT PRIMARY KEY," " data VARCHAR(100)) ENGINE={engine};".format( - tblname=mysqlmod.quote_identifier(self.table1), engine="MYISAM", + tblname=mysqlmod.quote_identifier(self.table1), + engine="MYISAM", ) ) log.info("Adding table '%s'", self.table1) @@ -121,7 +122,8 @@ class MysqlGrantsStateTest(ModuleCase, SaltReturnAssertsMixin): "CREATE TABLE {tblname} (" " id INT NOT NULL AUTO_INCREMENT PRIMARY KEY," " data VARCHAR(100)) ENGINE={engine};".format( - tblname=mysqlmod.quote_identifier(self.table2), engine="MYISAM", + tblname=mysqlmod.quote_identifier(self.table2), + engine="MYISAM", ) ) log.info("Adding table '%s'", self.table2) diff --git a/tests/integration/states/test_pip_state.py b/tests/integration/states/test_pip_state.py index 75c1a5add8d..d00156e9098 100644 --- a/tests/integration/states/test_pip_state.py +++ b/tests/integration/states/test_pip_state.py @@ -338,10 +338,14 @@ class PipStateTest(ModuleCase, SaltReturnAssertsMixin): # Make sure we're calling a virtualenv and python # program that the user has access too. venv_kwargs["venv_bin"] = self._win_user_where( - username, "PassWord1!", "virtualenv", + username, + "PassWord1!", + "virtualenv", ) venv_kwargs["python"] = self._win_user_where( - username, "PassWord1!", "python", + username, + "PassWord1!", + "python", ) else: uid = self.run_function("file.user_to_uid", [username]) @@ -400,10 +404,14 @@ class PipStateTest(ModuleCase, SaltReturnAssertsMixin): # Make sure we're calling a virtualenv and python # program that the user has access too. venv_kwargs["venv_bin"] = self._win_user_where( - username, "PassWord1!", "virtualenv", + username, + "PassWord1!", + "virtualenv", ) venv_kwargs["python"] = self._win_user_where( - username, "PassWord1!", "python", + username, + "PassWord1!", + "python", ) else: uid = self.run_function("file.user_to_uid", [username]) diff --git a/tests/integration/states/test_pkg.py b/tests/integration/states/test_pkg.py index dbba1cc9a5c..483deaad9e5 100644 --- a/tests/integration/states/test_pkg.py +++ b/tests/integration/states/test_pkg.py @@ -265,7 +265,9 @@ class PkgTest(ModuleCase, SaltReturnAssertsMixin): This is a destructive test as it installs a package """ if not self._PKG_DOT_TARGETS: - self.skipTest('No packages with "." in their name have been specified',) + self.skipTest( + 'No packages with "." in their name have been specified', + ) target = self._PKG_DOT_TARGETS[0] @@ -422,11 +424,21 @@ class PkgTest(ModuleCase, SaltReturnAssertsMixin): # needs to not be installed before we run the states below self.assertFalse(version) - ret = self.run_state("pkg.installed", name=target, version="*", refresh=False,) + ret = self.run_state( + "pkg.installed", + name=target, + version="*", + refresh=False, + ) self.assertSaltTrueReturn(ret) # Repeat state, should pass - ret = self.run_state("pkg.installed", name=target, version="*", refresh=False,) + ret = self.run_state( + "pkg.installed", + name=target, + version="*", + refresh=False, + ) expected_comment = ( "All specified packages are already installed and are at the " @@ -437,7 +449,10 @@ class PkgTest(ModuleCase, SaltReturnAssertsMixin): # Repeat one more time with unavailable version, test should fail ret = self.run_state( - "pkg.installed", name=target, version="93413*", refresh=False, + "pkg.installed", + name=target, + version="93413*", + refresh=False, ) self.assertSaltFalseReturn(ret) @@ -467,7 +482,10 @@ class PkgTest(ModuleCase, SaltReturnAssertsMixin): try: ret = self.run_state( - "pkg.installed", name=target, version="<9999999", refresh=False, + "pkg.installed", + name=target, + version="<9999999", + refresh=False, ) self.assertSaltTrueReturn(ret) @@ -543,11 +561,20 @@ class PkgTest(ModuleCase, SaltReturnAssertsMixin): target = self._PKG_TARGETS[0] # First we ensure that the package is installed - ret = self.run_state("pkg.installed", name=target, refresh=False,) + ret = self.run_state( + "pkg.installed", + name=target, + refresh=False, + ) self.assertSaltTrueReturn(ret) # Then we check that the package is now held - ret = self.run_state("pkg.installed", name=target, hold=True, refresh=False,) + ret = self.run_state( + "pkg.installed", + name=target, + hold=True, + refresh=False, + ) if versionlock_pkg and "-versionlock is not installed" in str(ret): self.skipTest("{} `{}` is installed".format(ret, versionlock_pkg)) @@ -663,7 +690,10 @@ class PkgTest(ModuleCase, SaltReturnAssertsMixin): # First we ensure that the package is installed target_ret = self.run_state( - "pkg.installed", name=target, hold=False, refresh=False, + "pkg.installed", + name=target, + hold=False, + refresh=False, ) self.assertSaltTrueReturn(target_ret) diff --git a/tests/integration/states/test_x509.py b/tests/integration/states/test_x509.py index 2321689ef58..3664f6a6af4 100644 --- a/tests/integration/states/test_x509.py +++ b/tests/integration/states/test_x509.py @@ -184,8 +184,10 @@ class x509Test(ModuleCase, SaltReturnAssertsMixin): assert "Certificate" in ret[first_key]["changes"] assert "New" in ret[first_key]["changes"]["Certificate"] # check whether the second defined cert is considered to match the first one - second_key = "x509_|-second_test_crt_|-{}/pki/test.crt_|-certificate_managed".format( - RUNTIME_VARS.TMP + second_key = ( + "x509_|-second_test_crt_|-{}/pki/test.crt_|-certificate_managed".format( + RUNTIME_VARS.TMP + ) ) assert second_key in ret assert "changes" in ret[second_key] diff --git a/tests/integration/utils/test_smb.py b/tests/integration/utils/test_smb.py index ab92daff1c9..3f89f067dba 100644 --- a/tests/integration/utils/test_smb.py +++ b/tests/integration/utils/test_smb.py @@ -68,7 +68,8 @@ def which_smbd(): @skipIf(not which_smbd(), reason="smbd binary not found") @skipIf( - not salt.utils.smb.HAS_SMBPROTOCOL, '"smbprotocol" needs to be installed.', + not salt.utils.smb.HAS_SMBPROTOCOL, + '"smbprotocol" needs to be installed.', ) class TestSmb(TestCase): diff --git a/tests/minionswarm.py b/tests/minionswarm.py index 055873517e3..887e0ac8d48 100644 --- a/tests/minionswarm.py +++ b/tests/minionswarm.py @@ -213,7 +213,9 @@ class Swarm: subprocess.call( "salt-key -c {0} --gen-keys minion --gen-keys-dir {0} " "--log-file {1} --user {2}".format( - path, os.path.join(path, "keys.log"), self.opts["user"], + path, + os.path.join(path, "keys.log"), + self.opts["user"], ), shell=True, ) diff --git a/tests/pytests/conftest.py b/tests/pytests/conftest.py index bb0f5e54a20..31ed1de4186 100644 --- a/tests/pytests/conftest.py +++ b/tests/pytests/conftest.py @@ -326,7 +326,8 @@ def salt_proxy_factory(salt_master_factory): @pytest.fixture def temp_salt_master( - request, salt_factories, + request, + salt_factories, ): config_defaults = { "open_mode": True, diff --git a/tests/pytests/functional/modules/test_saltutil.py b/tests/pytests/functional/modules/test_saltutil.py index ecd1294d8b2..cf65593836a 100644 --- a/tests/pytests/functional/modules/test_saltutil.py +++ b/tests/pytests/functional/modules/test_saltutil.py @@ -10,7 +10,8 @@ from tests.support.mock import patch def opts(salt_master_factory): config_overrides = {"master_uri": "tcp://127.0.0.1:11111"} factory = salt_master_factory.salt_minion_daemon( - "get-tops-minion", overrides=config_overrides, + "get-tops-minion", + overrides=config_overrides, ) yield factory.config.copy() diff --git a/tests/pytests/functional/states/rabbitmq/conftest.py b/tests/pytests/functional/states/rabbitmq/conftest.py index dfdb3e321a6..70f7e5f1366 100644 --- a/tests/pytests/functional/states/rabbitmq/conftest.py +++ b/tests/pytests/functional/states/rabbitmq/conftest.py @@ -66,7 +66,8 @@ def rabbitmq_container(request, salt_factories, modules): rabbitmq_image = request.param combo = RabbitMQCombo( - rabbitmq_name=rabbitmq_image.name, rabbitmq_version=rabbitmq_image.tag, + rabbitmq_name=rabbitmq_image.name, + rabbitmq_version=rabbitmq_image.tag, ) container = salt_factories.get_container( rabbitmq_image.container_id, diff --git a/tests/pytests/functional/states/test_docker_container.py b/tests/pytests/functional/states/test_docker_container.py index 86949a6ea2e..33a6854fdb5 100644 --- a/tests/pytests/functional/states/test_docker_container.py +++ b/tests/pytests/functional/states/test_docker_container.py @@ -305,7 +305,10 @@ def test_running_start_false_without_replace( modules.docker.stop(container_name, force=True) # Re-run the state with start=False ret = docker_container.running( - name=container_name, image=image, start=False, shutdown_timeout=1, + name=container_name, + image=image, + start=False, + shutdown_timeout=1, ) assert ret.result is True # Check to make sure that the container was not replaced @@ -385,7 +388,10 @@ def test_running_start_true(docker_container, container_name, image, modules): modules.docker.stop(container_name, force=True) # Re-run the state with start=True ret = docker_container.running( - name=container_name, image=image, start=True, shutdown_timeout=1, + name=container_name, + image=image, + start=True, + shutdown_timeout=1, ) assert ret.result is True # Check to make sure that the container was not replaced @@ -405,7 +411,10 @@ def test_running_with_invalid_input(docker_container, container_name, image): """ # Try to create a container with invalid input ret = docker_container.running( - name=container_name, image=image, ulimits="nofile:2048", shutdown_timeout=1, + name=container_name, + image=image, + ulimits="nofile:2048", + shutdown_timeout=1, ) assert ret.result is False # Check to make sure that the container was not created @@ -483,7 +492,10 @@ def test_running_with_removed_argument( """ # Create the container ret = docker_container.running( - name=container_name, image=image, command="sleep 600", shutdown_timeout=1, + name=container_name, + image=image, + command="sleep 600", + shutdown_timeout=1, ) assert ret.result is True # Run the state again with the "command" argument removed @@ -538,13 +550,17 @@ def test_absent_with_stopped_container( # Create the container modules.docker.create(image, name=container_name) # Remove the container - ret = docker_container.absent(name=container_name,) + ret = docker_container.absent( + name=container_name, + ) assert ret.result is True # Check that we have a removed container ID in the changes dict assert "removed" in ret.changes # Run the state again to confirm it changes nothing - ret = docker_container.absent(name=container_name,) + ret = docker_container.absent( + name=container_name, + ) assert ret.result is True # Nothing should have changed assert ret.changes == {} @@ -559,13 +575,18 @@ def test_absent_with_running_container(docker_container, container_name, image): """ # Create the container ret = docker_container.running( - name=container_name, image=image, command="sleep 600", shutdown_timeout=1, + name=container_name, + image=image, + command="sleep 600", + shutdown_timeout=1, ) assert ret.result is True # Try to remove the container. This should fail because force=True # is needed to remove a container that is running. - ret = docker_container.absent(name=container_name,) + ret = docker_container.absent( + name=container_name, + ) assert ret.result is False # Nothing should have changed assert ret.changes == {} @@ -575,7 +596,10 @@ def test_absent_with_running_container(docker_container, container_name, image): ) # Try again with force=True. This should succeed. - ret = docker_container.absent(name=container_name, force=True,) + ret = docker_container.absent( + name=container_name, + force=True, + ) assert ret.result is True # Check that we have a removed container ID in the changes dict assert "removed" in ret.changes @@ -837,7 +861,9 @@ def test_running_explicit_networks( # Create a container with no specific network configuration. The only # networks connected will be the default ones. ret = docker_container.running( - name=container_name, image=image, shutdown_timeout=1, + name=container_name, + image=image, + shutdown_timeout=1, ) assert ret.result is True @@ -848,7 +874,10 @@ def test_running_explicit_networks( # Re-run the state with an explicit network configuration. All of the # default networks should be disconnected. ret = docker_container.running( - name=container_name, image=image, networks=[net.name], shutdown_timeout=1, + name=container_name, + image=image, + networks=[net.name], + shutdown_timeout=1, ) assert ret.result is True net_changes = ret.changes["container"]["Networks"] @@ -891,7 +920,10 @@ def test_run_with_onlyif(docker_container, container_name, image, modules): for cmd in test_cmds: log.debug("Trying %s", cmd) ret = docker_container.run( - name=container_name, image=image, command="whoami", onlyif=cmd, + name=container_name, + image=image, + command="whoami", + onlyif=cmd, ) try: assert ret.result is True @@ -904,7 +936,10 @@ def test_run_with_onlyif(docker_container, container_name, image, modules): for cmd in ("/bin/true", ["/bin/true", "ls /"]): log.debug("Trying %s", cmd) ret = docker_container.run( - name=container_name, image=image, command="whoami", onlyif=cmd, + name=container_name, + image=image, + command="whoami", + onlyif=cmd, ) assert ret.result is True assert ret.changes["Logs"] == "root\n" @@ -924,7 +959,10 @@ def test_run_with_unless(docker_container, container_name, image, modules): for cmd in ("/bin/true", ["/bin/true", "/bin/true"]): log.debug("Trying %s", cmd) ret = docker_container.run( - name=container_name, image=image, command="whoami", unless=cmd, + name=container_name, + image=image, + command="whoami", + unless=cmd, ) try: assert ret.result is True @@ -943,7 +981,10 @@ def test_run_with_unless(docker_container, container_name, image, modules): for cmd in test_cmds: log.debug("Trying %s", cmd) ret = docker_container.run( - name=container_name, image=image, command="whoami", unless=cmd, + name=container_name, + image=image, + command="whoami", + unless=cmd, ) assert ret.result is True assert ret.changes["Logs"] == "root\n" @@ -972,7 +1013,10 @@ def test_run_with_creates( try: log.debug("Trying %s", good_file1) ret = docker_container.run( - name=container_name, image=image, command="whoami", creates=good_file1, + name=container_name, + image=image, + command="whoami", + creates=good_file1, ) assert ret.result is True assert not ret.changes @@ -989,7 +1033,10 @@ def test_run_with_creates( try: log.debug("Trying %s", path) ret = docker_container.run( - name=container_name, image=image, command="whoami", creates=path, + name=container_name, + image=image, + command="whoami", + creates=path, ) assert ret.result is True assert not ret.changes @@ -1006,7 +1053,10 @@ def test_run_with_creates( try: log.debug("Trying %s", path) ret = docker_container.run( - name=container_name, image=image, command="whoami", creates=path, + name=container_name, + image=image, + command="whoami", + creates=path, ) assert ret.result is True assert ret.changes["Logs"] == "root\n" @@ -1031,7 +1081,10 @@ def test_run_replace(docker_container, container_name, image): # Run again with replace=False, this should fail ret = docker_container.run( - name=container_name, image=image, command="whoami", replace=False, + name=container_name, + image=image, + command="whoami", + replace=False, ) assert ret.result is False assert not ret.changes @@ -1044,7 +1097,10 @@ def test_run_replace(docker_container, container_name, image): # a "Replaces" key in the changes dict to show that a container was # replaced. ret = docker_container.run( - name=container_name, image=image, command="whoami", replace=True, + name=container_name, + image=image, + command="whoami", + replace=True, ) assert ret.result is True assert ret.changes["Logs"] == "root\n" @@ -1063,7 +1119,11 @@ def test_run_force(docker_container, container_name, image): # Run again with replace=True, this should fail because the container # is still running ret = docker_container.run( - name=container_name, image=image, command="whoami", replace=True, force=False, + name=container_name, + image=image, + command="whoami", + replace=True, + force=False, ) assert ret.result is False assert not ret.changes @@ -1076,7 +1136,11 @@ def test_run_force(docker_container, container_name, image): # there should be a "Replaces" key in the changes dict to show that a # container was replaced. ret = docker_container.run( - name=container_name, image=image, command="whoami", replace=True, force=True, + name=container_name, + image=image, + command="whoami", + replace=True, + force=True, ) assert ret.result is True assert ret.changes["Logs"] == "root\n" @@ -1097,7 +1161,10 @@ def test_run_failhard(docker_container, container_name, image, modules): Engine API will cause an exception to be raised. """ ret = docker_container.run( - name=container_name, image=image, command="/bin/false", failhard=True, + name=container_name, + image=image, + command="/bin/false", + failhard=True, ) assert ret.result is False assert ret.changes["Logs"] == "" @@ -1105,7 +1172,10 @@ def test_run_failhard(docker_container, container_name, image, modules): modules.docker.rm(container_name, force=True) ret = docker_container.run( - name=container_name, image=image, command="/bin/false", failhard=False, + name=container_name, + image=image, + command="/bin/false", + failhard=False, ) assert ret.result is True assert ret.changes["Logs"] == "" @@ -1120,7 +1190,10 @@ def test_run_bg(docker_container, container_name, image, modules): for the container to ensure that it ran as expected. """ ret = docker_container.run( - name=container_name, image=image, command='sh -c "sleep 5 && whoami"', bg=True, + name=container_name, + image=image, + command='sh -c "sleep 5 && whoami"', + bg=True, ) assert ret.result is True assert "Logs" not in ret.changes diff --git a/tests/pytests/functional/states/test_user.py b/tests/pytests/functional/states/test_user.py index 12b5a988c3a..e2d8ed7f50f 100644 --- a/tests/pytests/functional/states/test_user.py +++ b/tests/pytests/functional/states/test_user.py @@ -144,7 +144,10 @@ def test_user_present_nondefault(grains, modules, states, username, user_home): @pytest.mark.skip_on_windows(reason="windows minion does not support 'usergroup'") def test_user_present_usergroup_false(modules, states, username, group_1, user_home): ret = states.user.present( - name=username, gid=group_1.info.gid, usergroup=False, home=str(user_home), + name=username, + gid=group_1.info.gid, + usergroup=False, + home=str(user_home), ) assert ret.result is True @@ -161,7 +164,10 @@ def test_user_present_usergroup_false(modules, states, username, group_1, user_h @pytest.mark.skip_on_windows(reason="windows minion does not support 'usergroup'") def test_user_present_usergroup_true(modules, states, username, user_home, group_1): ret = states.user.present( - name=username, gid=group_1.info.gid, usergroup=True, home=str(user_home), + name=username, + gid=group_1.info.gid, + usergroup=True, + home=str(user_home), ) assert ret.result is True diff --git a/tests/pytests/functional/states/win_lgpo/test_rights_assignment.py b/tests/pytests/functional/states/win_lgpo/test_rights_assignment.py index 0cc9948c8f8..6b709833762 100644 --- a/tests/pytests/functional/states/win_lgpo/test_rights_assignment.py +++ b/tests/pytests/functional/states/win_lgpo/test_rights_assignment.py @@ -28,7 +28,8 @@ def configure_loader_modules(minion_opts, modules): @pytest.fixture(scope="function") def stage_single(): current_setting = win_lgpo_module.get_policy( - policy_name="SeTakeOwnershipPrivilege", policy_class="machine", + policy_name="SeTakeOwnershipPrivilege", + policy_class="machine", ) try: win_lgpo_module.set_computer_policy( @@ -48,7 +49,8 @@ def stage_single(): @pytest.fixture(scope="function") def stage_multiple(): current_setting = win_lgpo_module.get_policy( - policy_name="SeTakeOwnershipPrivilege", policy_class="machine", + policy_name="SeTakeOwnershipPrivilege", + policy_class="machine", ) try: win_lgpo_module.set_computer_policy( @@ -74,7 +76,8 @@ def test_cumulative_rights_assignments(stage_single): cumulative_rights_assignments=True, ) result = win_lgpo_module.get_policy( - policy_name="SeTakeOwnershipPrivilege", policy_class="machine", + policy_name="SeTakeOwnershipPrivilege", + policy_class="machine", ) assert sorted(result) == sorted(expected) @@ -139,7 +142,8 @@ def test_non_cumulative_rights_assignments(stage_multiple): cumulative_rights_assignments=False, ) result = win_lgpo_module.get_policy( - policy_name="SeTakeOwnershipPrivilege", policy_class="machine", + policy_name="SeTakeOwnershipPrivilege", + policy_class="machine", ) assert sorted(result) == sorted(expected) @@ -204,7 +208,8 @@ def test_cumulative_rights_assignments_resolve_name(stage_single): cumulative_rights_assignments=True, ) result = win_lgpo_module.get_policy( - policy_name="SeTakeOwnershipPrivilege", policy_class="machine", + policy_name="SeTakeOwnershipPrivilege", + policy_class="machine", ) assert sorted(result) == sorted(expected) @@ -269,7 +274,8 @@ def test_non_cumulative_rights_assignments_resolve_name(stage_multiple): cumulative_rights_assignments=False, ) result = win_lgpo_module.get_policy( - policy_name="SeTakeOwnershipPrivilege", policy_class="machine", + policy_name="SeTakeOwnershipPrivilege", + policy_class="machine", ) assert sorted(result) == sorted(expected) diff --git a/tests/pytests/functional/transport/ipc/test_client.py b/tests/pytests/functional/transport/ipc/test_client.py index 0f9cab4b3c7..08590664cbf 100644 --- a/tests/pytests/functional/transport/ipc/test_client.py +++ b/tests/pytests/functional/transport/ipc/test_client.py @@ -43,13 +43,16 @@ class IPCTester: @server.default def _server_default(self): return salt.transport.ipc.IPCMessageServer( - self.socket_path, io_loop=self.io_loop, payload_handler=self.handle_payload, + self.socket_path, + io_loop=self.io_loop, + payload_handler=self.handle_payload, ) @client.default def _client_default(self): return salt.transport.ipc.IPCMessageClient( - self.socket_path, io_loop=self.io_loop, + self.socket_path, + io_loop=self.io_loop, ) async def handle_payload(self, payload, reply_func): diff --git a/tests/pytests/functional/transport/ipc/test_subscriber.py b/tests/pytests/functional/transport/ipc/test_subscriber.py index 3ab05cc10eb..0ec0b4bfa8a 100644 --- a/tests/pytests/functional/transport/ipc/test_subscriber.py +++ b/tests/pytests/functional/transport/ipc/test_subscriber.py @@ -44,13 +44,16 @@ class IPCTester: @subscriber.default def _subscriber_default(self): return salt.transport.ipc.IPCMessageSubscriber( - self.socket_path, io_loop=self.io_loop, + self.socket_path, + io_loop=self.io_loop, ) @publisher.default def _publisher_default(self): return salt.transport.ipc.IPCMessagePublisher( - {"ipc_write_buffer": 0}, self.socket_path, io_loop=self.io_loop, + {"ipc_write_buffer": 0}, + self.socket_path, + io_loop=self.io_loop, ) async def handle_payload(self, payload, reply_func): diff --git a/tests/pytests/functional/transport/server/conftest.py b/tests/pytests/functional/transport/server/conftest.py index c096865e7ab..3ed15c015e4 100644 --- a/tests/pytests/functional/transport/server/conftest.py +++ b/tests/pytests/functional/transport/server/conftest.py @@ -19,7 +19,8 @@ def salt_master(salt_factories, transport): "sign_pub_messages": False, } factory = salt_factories.salt_master_daemon( - random_string("server-{}-master-".format(transport)), defaults=config_defaults, + random_string("server-{}-master-".format(transport)), + defaults=config_defaults, ) return factory @@ -35,6 +36,7 @@ def salt_minion(salt_master, transport): "master_uri": "tcp://127.0.0.1:{}".format(salt_master.config["ret_port"]), } factory = salt_master.salt_minion_daemon( - random_string("server-{}-minion-".format(transport)), defaults=config_defaults, + random_string("server-{}-minion-".format(transport)), + defaults=config_defaults, ) return factory diff --git a/tests/pytests/integration/logging/test_jid_logging.py b/tests/pytests/integration/logging/test_jid_logging.py index 4f35a130552..cc6ad82ed78 100644 --- a/tests/pytests/integration/logging/test_jid_logging.py +++ b/tests/pytests/integration/logging/test_jid_logging.py @@ -22,8 +22,10 @@ def test_jid_in_logs(caplog, salt_call_cli): assert ret.exitcode == 0 assert ret.json is True - assert_error_msg = "'{}' not found in log messages:\n>>>>>>>>>{}\n<<<<<<<<<".format( - jid_formatted_str, caplog.text + assert_error_msg = ( + "'{}' not found in log messages:\n>>>>>>>>>{}\n<<<<<<<<<".format( + jid_formatted_str, caplog.text + ) ) assert jid_formatted_str in caplog.text, assert_error_msg finally: diff --git a/tests/pytests/integration/modules/saltutil/test_pillar.py b/tests/pytests/integration/modules/saltutil/test_pillar.py index 29f358b82da..c1c3bb80528 100644 --- a/tests/pytests/integration/modules/saltutil/test_pillar.py +++ b/tests/pytests/integration/modules/saltutil/test_pillar.py @@ -32,7 +32,11 @@ def refresh_pillar(salt_call_cli, salt_minion): @pytest.mark.slow_test @pytest.mark.parametrize("sync_refresh", [False, True]) def test_pillar_refresh( - salt_master, salt_minion, salt_call_cli, event_listener, sync_refresh, + salt_master, + salt_minion, + salt_call_cli, + event_listener, + sync_refresh, ): """ test pillar refresh module @@ -70,7 +74,9 @@ def test_pillar_refresh( start_time = time.time() ret = salt_call_cli.run( - "--retcode-passthrough", "saltutil.refresh_pillar", wait=sync_refresh, + "--retcode-passthrough", + "saltutil.refresh_pillar", + wait=sync_refresh, ) assert ret.exitcode == 0 diff --git a/tests/pytests/integration/modules/test_mysql.py b/tests/pytests/integration/modules/test_mysql.py index 154d02ed7ef..18e80f18694 100644 --- a/tests/pytests/integration/modules/test_mysql.py +++ b/tests/pytests/integration/modules/test_mysql.py @@ -90,7 +90,10 @@ def test_user_exists(salt_call_cli_wrapper): assert ret.json ret = salt_call_cli_wrapper( - "mysql.user_exists", "george", "hostname", "badpassword", + "mysql.user_exists", + "george", + "hostname", + "badpassword", ) assert not ret.json @@ -139,12 +142,18 @@ def test_user_info(salt_call_cli_wrapper): def test_user_create_chpass_delete(salt_call_cli_wrapper): ret = salt_call_cli_wrapper( - "mysql.user_create", "george", host="localhost", password="badpassword", + "mysql.user_create", + "george", + host="localhost", + password="badpassword", ) assert ret.json ret = salt_call_cli_wrapper( - "mysql.user_chpass", "george", host="localhost", password="different_password", + "mysql.user_chpass", + "george", + host="localhost", + password="different_password", ) assert ret.json @@ -164,7 +173,10 @@ def test_grant_add_revoke(salt_call_cli_wrapper): # Create a user ret = salt_call_cli_wrapper( - "mysql.user_create", "george", host="localhost", password="badpassword", + "mysql.user_create", + "george", + host="localhost", + password="badpassword", ) assert ret.json diff --git a/tests/pytests/integration/modules/test_rpmbuild_pkgbuild.py b/tests/pytests/integration/modules/test_rpmbuild_pkgbuild.py index 7ae1331dc21..a4148fa85f7 100644 --- a/tests/pytests/integration/modules/test_rpmbuild_pkgbuild.py +++ b/tests/pytests/integration/modules/test_rpmbuild_pkgbuild.py @@ -306,8 +306,10 @@ def gpg_agent(request, gpghome): gpg_agent_cmd = "gpg-agent --homedir {} --allow-preset-passphrase --max-cache-ttl 600 --daemon".format( gpghome ) - echo_gpg_tty_cmd = "GPG_TTY=$(tty) ; export GPG_TTY ; echo $GPG_TTY=$(tty) > {}".format( - gpg_tty_info_path + echo_gpg_tty_cmd = ( + "GPG_TTY=$(tty) ; export GPG_TTY ; echo $GPG_TTY=$(tty) > {}".format( + gpg_tty_info_path + ) ) subprocess.run( # nosec "{}; {}".format(gpg_agent_cmd, echo_gpg_tty_cmd), shell=True, check=True diff --git a/tests/pytests/integration/modules/test_sysmod.py b/tests/pytests/integration/modules/test_sysmod.py index 77686132082..82dcd72f7af 100644 --- a/tests/pytests/integration/modules/test_sysmod.py +++ b/tests/pytests/integration/modules/test_sysmod.py @@ -81,11 +81,15 @@ def test_valid_docs(salt_call_cli): elif isinstance(docstring, dict) and not example_regex.search(docstring): missing_example.add(fun) - missing_docstring_error = "The following functions do not have a docstring: {}".format( - ",".join([repr(func) for func in sorted(missing_docstring)]) + missing_docstring_error = ( + "The following functions do not have a docstring: {}".format( + ",".join([repr(func) for func in sorted(missing_docstring)]) + ) ) assert not missing_docstring, missing_docstring_error - missing_example_error = "The following functions do not have a CLI example: {}".format( - ",".join([repr(func) for func in sorted(missing_example)]) + missing_example_error = ( + "The following functions do not have a CLI example: {}".format( + ",".join([repr(func) for func in sorted(missing_example)]) + ) ) assert not missing_example, missing_example_error diff --git a/tests/pytests/integration/states/test_file.py b/tests/pytests/integration/states/test_file.py index fbb7611d80f..9003c79bfc3 100644 --- a/tests/pytests/integration/states/test_file.py +++ b/tests/pytests/integration/states/test_file.py @@ -201,7 +201,11 @@ def test_issue_50221( def test_issue_60426( - salt_master, salt_call_cli, pillar_tree, tmp_path, salt_minion, + salt_master, + salt_call_cli, + pillar_tree, + tmp_path, + salt_minion, ): target_path = tmp_path / "/etc/foo/bar" jinja_name = "foo_bar" diff --git a/tests/pytests/integration/states/test_mysql.py b/tests/pytests/integration/states/test_mysql.py index 603fdeb38de..7aef4e98128 100644 --- a/tests/pytests/integration/states/test_mysql.py +++ b/tests/pytests/integration/states/test_mysql.py @@ -51,7 +51,9 @@ def salt_call_cli_wrapper(salt_call_cli, mysql_container): def test_database_present_absent(salt_cli_wrapper): ret = salt_cli_wrapper( - "state.single", "mysql_database.present", name="test_database", + "state.single", + "mysql_database.present", + name="test_database", ) state = ret.json["mysql_database_|-test_database_|-test_database_|-present"] assert ret.exitcode == 0, ret @@ -63,7 +65,9 @@ def test_database_present_absent(salt_cli_wrapper): assert state["comment"] == "The database test_database has been created" ret = salt_cli_wrapper( - "state.single", "mysql_database.absent", name="test_database", + "state.single", + "mysql_database.absent", + name="test_database", ) state = ret.json["mysql_database_|-test_database_|-test_database_|-absent"] @@ -84,7 +88,10 @@ def test_grants_present_absent(salt_cli_wrapper, salt_call_cli_wrapper): # Create a user ret = salt_call_cli_wrapper( - "mysql.user_create", "george", host="localhost", password="badpassword", + "mysql.user_create", + "george", + host="localhost", + password="badpassword", ) assert ret.json @@ -158,7 +165,10 @@ def test_user_present_absent(salt_cli_wrapper): assert state["comment"] == "The user george@localhost has been added" ret = salt_cli_wrapper( - "state.single", "mysql_user.absent", name="george", host="localhost", + "state.single", + "mysql_user.absent", + name="george", + host="localhost", ) state = ret.json["mysql_user_|-george_|-george_|-absent"] assert ret.exitcode == 0, ret diff --git a/tests/pytests/integration/utils/test_templates.py b/tests/pytests/integration/utils/test_templates.py index d427157fbc4..784e0893a91 100644 --- a/tests/pytests/integration/utils/test_templates.py +++ b/tests/pytests/integration/utils/test_templates.py @@ -7,7 +7,9 @@ import pytest def test_issue_60083( - salt_call_cli, tmp_path, base_env_state_tree_root_dir, + salt_call_cli, + tmp_path, + base_env_state_tree_root_dir, ): """ Validate that we can serialize pillars to json in states. diff --git a/tests/pytests/scenarios/compat/conftest.py b/tests/pytests/scenarios/compat/conftest.py index 0a87499d2f6..3854f671b64 100644 --- a/tests/pytests/scenarios/compat/conftest.py +++ b/tests/pytests/scenarios/compat/conftest.py @@ -110,7 +110,11 @@ def pillar_tree(integration_files_dir): @pytest.fixture(scope="package") def salt_master( - request, salt_factories, host_docker_network_ip_address, state_tree, pillar_tree, + request, + salt_factories, + host_docker_network_ip_address, + state_tree, + pillar_tree, ): master_id = random_string("master-compat-", uppercase=False) root_dir = salt_factories.get_root_dir_for_daemon(master_id) @@ -145,7 +149,9 @@ def salt_master( } ) factory = salt_factories.salt_master_daemon( - master_id, defaults=config_defaults, overrides=config_overrides, + master_id, + defaults=config_defaults, + overrides=config_overrides, ) with factory.started(): yield factory diff --git a/tests/pytests/scenarios/compat/test_with_versions.py b/tests/pytests/scenarios/compat/test_with_versions.py index 3e6080f9604..5c38d83afe0 100644 --- a/tests/pytests/scenarios/compat/test_with_versions.py +++ b/tests/pytests/scenarios/compat/test_with_versions.py @@ -94,7 +94,9 @@ def minion_image( log.warning("GENERATED Dockerfile:\n%s", dockerfile_contents) dockerfile_fh = io.BytesIO(dockerfile_contents.encode("utf-8")) _, logs = docker_client.images.build( - fileobj=dockerfile_fh, tag=minion_image_name, pull=True, + fileobj=dockerfile_fh, + tag=minion_image_name, + pull=True, ) log.warning("Image %s built. Logs:\n%s", minion_image_name, list(logs)) return minion_image_name @@ -197,11 +199,15 @@ def populated_state_tree(pysaltcombo, minion_id, package_name, state_tree, unico - name: {{ salt.pkgnames.get_test_package_name() }} """ with pytest.helpers.temp_file( - "_modules/pkgnames.py", module_contents, state_tree, + "_modules/pkgnames.py", + module_contents, + state_tree, ), pytest.helpers.temp_file( "top.sls", top_file_contents, state_tree ), pytest.helpers.temp_file( - "install-package.sls", install_package_sls_contents, state_tree, + "install-package.sls", + install_package_sls_contents, + state_tree, ): # Run the test yield diff --git a/tests/pytests/scenarios/setup/test_install.py b/tests/pytests/scenarios/setup/test_install.py index ed5d1ddf9b0..8313bcc755f 100644 --- a/tests/pytests/scenarios/setup/test_install.py +++ b/tests/pytests/scenarios/setup/test_install.py @@ -121,7 +121,9 @@ def test_egg(virtualenv, cache_dir, use_static_requirements, src_dir): # Let's create the testing virtualenv with virtualenv as venv: ret = venv.run( - venv.venv_python, "-c", "import setuptools; print(setuptools.__version__)", + venv.venv_python, + "-c", + "import setuptools; print(setuptools.__version__)", ) setuptools_version = ret.stdout.strip() ret = venv.run(venv.venv_python, "-m", "easy_install", "--version", check=False) @@ -165,7 +167,9 @@ def test_egg(virtualenv, cache_dir, use_static_requirements, src_dir): # Looks like, at least on windows, setuptools also get's downloaded as a salt dependency. # Let's check and see if this newly installed version also has easy_install ret = venv.run( - venv.venv_python, "-c", "import setuptools; print(setuptools.__version__)", + venv.venv_python, + "-c", + "import setuptools; print(setuptools.__version__)", ) setuptools_version = ret.stdout.strip() ret = venv.run(venv.venv_python, "-m", "easy_install", "--version", check=False) diff --git a/tests/pytests/unit/beacons/test_swapusage.py b/tests/pytests/unit/beacons/test_swapusage.py index f05347a496a..db1df72f422 100644 --- a/tests/pytests/unit/beacons/test_swapusage.py +++ b/tests/pytests/unit/beacons/test_swapusage.py @@ -19,7 +19,12 @@ def configure_loader_modules(): @pytest.fixture def stub_swap_usage(): return namedtuple("sswap", "total used free percent sin sout")( - 17179865088, 1674412032, 15505453056, 9.7, 1572110336, 3880046592, + 17179865088, + 1674412032, + 15505453056, + 9.7, + 1572110336, + 3880046592, ) diff --git a/tests/pytests/unit/client/ssh/test_shell.py b/tests/pytests/unit/client/ssh/test_shell.py index 0fab956d053..858e8d82a6d 100644 --- a/tests/pytests/unit/client/ssh/test_shell.py +++ b/tests/pytests/unit/client/ssh/test_shell.py @@ -23,6 +23,7 @@ def test_ssh_shell_key_gen(keys): assert keys.pub_key.exists() # verify there is not a passphrase set on key ret = subprocess.check_output( - ["ssh-keygen", "-f", str(keys.priv_key), "-y"], timeout=30, + ["ssh-keygen", "-f", str(keys.priv_key), "-y"], + timeout=30, ) assert ret.decode().startswith("ssh-rsa") diff --git a/tests/pytests/unit/cloud/clouds/test_hetzner.py b/tests/pytests/unit/cloud/clouds/test_hetzner.py index 36c4aaa100d..4f3f6ad15ff 100644 --- a/tests/pytests/unit/cloud/clouds/test_hetzner.py +++ b/tests/pytests/unit/cloud/clouds/test_hetzner.py @@ -167,7 +167,7 @@ def test_list_ssh_keys(ssh_keys): def test_list_nodes_full(): - """ Test the list_nodes_full function by using a mock """ + """Test the list_nodes_full function by using a mock""" with patch( "salt.cloud.clouds.hetzner._connect_client", return_value=MagicMock() ) as connect: @@ -200,7 +200,7 @@ def test_list_nodes_full(): def test_list_nodes(): - """ Test the list_nodes function by using a mock """ + """Test the list_nodes function by using a mock""" with patch( "salt.cloud.clouds.hetzner._connect_client", return_value=MagicMock() ) as connect: @@ -233,7 +233,7 @@ def test_list_nodes(): def test_show_instance(): - """ Test the show_instance function by using a mock """ + """Test the show_instance function by using a mock""" with patch( "salt.cloud.clouds.hetzner._connect_client", return_value=MagicMock() ) as connect: @@ -257,7 +257,7 @@ def test_show_instance(): def test_wait_until(): - """ Test the wait_until function """ + """Test the wait_until function""" with patch("salt.cloud.clouds.hetzner.show_instance") as show_instance: show_instance.side_effect = [{"state": "done"}, IndexError()] @@ -272,7 +272,7 @@ def test_wait_until(): def test_create(images, sizes, vm): - """ Test the overall creation and the required parameters """ + """Test the overall creation and the required parameters""" with patch( "salt.cloud.clouds.hetzner._connect_client", return_value=MagicMock() ) as connect: @@ -304,7 +304,7 @@ def test_create(images, sizes, vm): def test_create_location(vm): - """ Test the locations during the creation """ + """Test the locations during the creation""" vm["location"] = "abc" with patch( @@ -328,7 +328,7 @@ def test_create_location(vm): def test_ssh_keys(vm): - """ Test the locations during the creation """ + """Test the locations during the creation""" vm["ssh_keys"] = ["me"] with patch( @@ -351,7 +351,7 @@ def test_ssh_keys(vm): def test_create_datacenter(vm): - """ Test the datacenters during the creation """ + """Test the datacenters during the creation""" vm["datacenter"] = "abc" with patch( @@ -374,7 +374,7 @@ def test_create_datacenter(vm): def test_create_volumes(vm): - """ Test the volumes during the creation """ + """Test the volumes during the creation""" vm["volumes"] = ["a", "b"] with patch( @@ -393,7 +393,7 @@ def test_create_volumes(vm): def test_create_networks(vm): - """ Test the networks during the creation """ + """Test the networks during the creation""" vm["networks"] = ["a", "b"] with patch( @@ -412,7 +412,7 @@ def test_create_networks(vm): def test_start(): - """ Test the start action """ + """Test the start action""" with patch( "salt.cloud.clouds.hetzner._connect_client", return_value=MagicMock() ) as connect: @@ -433,7 +433,7 @@ def test_start(): def test_stop(): - """ Test the stop action """ + """Test the stop action""" with patch( "salt.cloud.clouds.hetzner._connect_client", return_value=MagicMock() ) as connect: @@ -454,7 +454,7 @@ def test_stop(): def test_reboot(): - """ Test the reboot action """ + """Test the reboot action""" with patch( "salt.cloud.clouds.hetzner._connect_client", return_value=MagicMock() ) as connect: @@ -475,7 +475,7 @@ def test_reboot(): def test_destroy(): - """ Test the destroy action """ + """Test the destroy action""" with patch( "salt.cloud.clouds.hetzner._connect_client", return_value=MagicMock() ) as connect: @@ -510,7 +510,7 @@ def test_destroy(): def test_resize(): - """ Test the resize action """ + """Test the resize action""" kwargs = {"size": "cpx21"} with patch( diff --git a/tests/pytests/unit/cloud/clouds/test_xen.py b/tests/pytests/unit/cloud/clouds/test_xen.py index 5b8e58da37b..d8ee7af9b91 100644 --- a/tests/pytests/unit/cloud/clouds/test_xen.py +++ b/tests/pytests/unit/cloud/clouds/test_xen.py @@ -45,9 +45,7 @@ def test_get_configured_provider_auth(): config = { "url": "https://127.0.0.2", } - with patch.dict( - xen.__opts__, {"providers": {"my-xen-cloud": {"xen": config}}}, - ): + with patch.dict(xen.__opts__, {"providers": {"my-xen-cloud": {"xen": config}}}): result = xen.get_configured_provider() assert config == result @@ -66,7 +64,7 @@ def test_get_dependencies_no_xenapi(): def test_get_vm(): XenAPI = MagicMock(name="mock_session") - XenAPI.xenapi.VM.get_by_name_label = MagicMock(return_value=["0000"],) + XenAPI.xenapi.VM.get_by_name_label = MagicMock(return_value=["0000"]) XenAPI.xenapi.VM.get_is_a_template = MagicMock(return_value=False) with patch("salt.cloud.clouds.xen._get_session", MagicMock(return_value=XenAPI)): result = xen._get_vm(name="test") @@ -77,7 +75,7 @@ def test_get_vm_multiple(): """Verify correct behavior if VM and template is returned""" vms = {"0000": False, "0001": True} XenAPI = MagicMock(name="mock_session") - XenAPI.xenapi.VM.get_by_name_label = MagicMock(return_value=vms.keys(),) + XenAPI.xenapi.VM.get_by_name_label = MagicMock(return_value=vms.keys()) XenAPI.xenapi.VM.get_is_a_template = MagicMock(side_effect=lambda x: vms[x]) with patch("salt.cloud.clouds.xen._get_session", MagicMock(return_value=XenAPI)): result = xen._get_vm(name="test") diff --git a/tests/pytests/unit/grains/test_core.py b/tests/pytests/unit/grains/test_core.py index d1892416809..850c8a3a285 100644 --- a/tests/pytests/unit/grains/test_core.py +++ b/tests/pytests/unit/grains/test_core.py @@ -29,7 +29,7 @@ log = logging.getLogger(__name__) @pytest.fixture def ipv4_tuple(): """ - return tuple of IPv4 local, addr1, addr2 + return tuple of IPv4 local, addr1, addr2 """ return ("127.0.0.1", "10.0.0.1", "10.0.0.2") @@ -37,7 +37,7 @@ def ipv4_tuple(): @pytest.fixture def ipv6_tuple(): """ - return tuple of IPv6 local, addr1, addr2, scope + return tuple of IPv6 local, addr1, addr2, scope """ return ( "::1", @@ -784,7 +784,7 @@ def test_rocky_8_os_grains(os_release_dir): "oscodename": "Rocky Linux 8.4 (Green Obsidian)", "osfullname": "Rocky Linux", "osrelease": "8.4", - "osrelease_info": (8, 4,), + "osrelease_info": (8, 4), "osmajorrelease": 8, "osfinger": "Rocky Linux-8", } @@ -836,7 +836,7 @@ def test_almalinux_8_os_grains(os_release_dir): "oscodename": "AlmaLinux 8", "osfullname": "AlmaLinux", "osrelease": "8.3", - "osrelease_info": (8, 3,), + "osrelease_info": (8, 3), "osmajorrelease": 8, "osfinger": "AlmaLinux-8", } @@ -1426,7 +1426,7 @@ def test_illumos_fallback_virtual(): return False with patch.dict( - core.__salt__, {"cmd.run_all": MagicMock(side_effect=_cmd_all_side_effect)}, + core.__salt__, {"cmd.run_all": MagicMock(side_effect=_cmd_all_side_effect)} ): with patch("salt.utils.path.which", MagicMock(side_effect=_which_side_effect)): with patch("os.path.isdir", MagicMock(side_effect=_isdir_side_effect)): @@ -1454,9 +1454,7 @@ def test_if_virtual_subtype_exists_virtual_should_fallback_to_virtual(): isfile=MagicMock(return_value=False), isdir=MagicMock(side_effect=lambda x: x == "/proc"), ): - with patch.multiple( - os, stat=MagicMock(side_effect=mockstat), - ): + with patch.multiple(os, stat=MagicMock(side_effect=mockstat)): grains = core._virtual({"kernel": "Linux"}) assert grains.get("virtual_subtype") is not None assert grains.get("virtual") == "virtual" @@ -1596,9 +1594,9 @@ def _run_fqdn_tests( with patch.object( salt.utils.network, "ip_addrs", MagicMock(return_value=net_ip4_mock) ), patch.object( - salt.utils.network, "ip_addrs6", MagicMock(return_value=net_ip6_mock), + salt.utils.network, "ip_addrs6", MagicMock(return_value=net_ip6_mock) ), patch.object( - core.socket, "getaddrinfo", side_effect=_getaddrinfo, + core.socket, "getaddrinfo", side_effect=_getaddrinfo ): get_fqdn = core.ip_fqdn() ret_keys = ["fqdn_ip4", "fqdn_ip6", "ipv4", "ipv6"] @@ -2029,15 +2027,8 @@ def test_core_virtual_unicode(mock_file, mock_dir): ) }, ): - with patch( - "salt.utils.files.fopen", mock_open(read_data="嗨".encode()), - ): - osdata = { - "kernel": "Linux", - } - osdata = { - "kernel": "Linux", - } + with patch("salt.utils.files.fopen", mock_open(read_data="嗨".encode())): + osdata = {"kernel": "Linux"} ret = core._virtual(osdata) assert ret["virtual"] == virt @@ -2161,7 +2152,7 @@ def test_locale_info_unicode_error_tzname(): # mock tzname[0].decode() decode = Mock(return_value="CST_FAKE") - tzname2 = (Mock(decode=decode,),) + tzname2 = Mock(decode=decode) with patch.object(core, "datetime", datetime=datetime) as datetime_module: with patch.object( diff --git a/tests/pytests/unit/loader/test_lazy.py b/tests/pytests/unit/loader/test_lazy.py index 026ca60b4ba..f2bad17d72a 100644 --- a/tests/pytests/unit/loader/test_lazy.py +++ b/tests/pytests/unit/loader/test_lazy.py @@ -48,8 +48,8 @@ def test_loaders_have_uniq_context(loader_dir): Loaded functions run in the LazyLoader's context. """ opts = {"optimization_order": [0, 1, 2]} - loader_1 = salt.loader.lazy.LazyLoader([loader_dir], opts,) - loader_2 = salt.loader.lazy.LazyLoader([loader_dir], opts,) + loader_1 = salt.loader.lazy.LazyLoader([loader_dir], opts) + loader_2 = salt.loader.lazy.LazyLoader([loader_dir], opts) loader_1._load_all() loader_2._load_all() assert loader_1.pack["__context__"] == {} @@ -67,7 +67,7 @@ def test_loaded_methods_are_loaded_func(loader_dir): Functions loaded from LazyLoader's item lookups are LoadedFunc objects """ opts = {"optimization_order": [0, 1, 2]} - loader_1 = salt.loader.lazy.LazyLoader([loader_dir], opts,) + loader_1 = salt.loader.lazy.LazyLoader([loader_dir], opts) fun = loader_1["mod_a.get_context"] assert isinstance(fun, salt.loader.lazy.LoadedFunc) @@ -77,7 +77,7 @@ def test_loaded_modules_are_loaded_mods(loader_dir): Modules looked up as attributes of LazyLoaders are LoadedMod objects. """ opts = {"optimization_order": [0, 1, 2]} - loader_1 = salt.loader.lazy.LazyLoader([loader_dir], opts,) + loader_1 = salt.loader.lazy.LazyLoader([loader_dir], opts) mod = loader_1.mod_a assert isinstance(mod, salt.loader.lazy.LoadedMod) @@ -87,7 +87,7 @@ def test_loaders_create_named_loader_contexts(loader_dir): LazyLoader's create NamedLoaderContexts on the modules the load. """ opts = {"optimization_order": [0, 1, 2]} - loader_1 = salt.loader.lazy.LazyLoader([loader_dir], opts,) + loader_1 = salt.loader.lazy.LazyLoader([loader_dir], opts) mod = loader_1.mod_a assert isinstance(mod.mod, dict) func = mod.set_context @@ -112,7 +112,7 @@ def test_loaders_convert_context_to_values(loader_dir): "optimization_order": [0, 1, 2], "grains": grains, } - loader_1 = salt.loader.lazy.LazyLoader([loader_dir], opts,) + loader_1 = salt.loader.lazy.LazyLoader([loader_dir], opts) assert loader_1.opts["grains"] == grains_default # The loader's opts is a copy assert opts["grains"] == grains diff --git a/tests/pytests/unit/modules/state/test_state.py b/tests/pytests/unit/modules/state/test_state.py index 4e959fa1789..6aaa68cf962 100644 --- a/tests/pytests/unit/modules/state/test_state.py +++ b/tests/pytests/unit/modules/state/test_state.py @@ -28,7 +28,7 @@ log = logging.getLogger(__name__) class MockState: """ - Mock class + Mock class """ def __init__(self): @@ -36,7 +36,7 @@ class MockState: class State: """ - Mock state class + Mock state class """ flag = None @@ -48,7 +48,7 @@ class MockState: def verify_data(self, data): """ - Mock verify_data method + Mock verify_data method """ if self.flag: return True @@ -58,34 +58,34 @@ class MockState: @staticmethod def call(data): """ - Mock call method + Mock call method """ return list @staticmethod def call_high(data, orchestration_jid=None): """ - Mock call_high method + Mock call_high method """ return True @staticmethod def call_template_str(data): """ - Mock call_template_str method + Mock call_template_str method """ return True @staticmethod def _mod_init(data): """ - Mock _mod_init method + Mock _mod_init method """ return True def verify_high(self, data): """ - Mock verify_high method + Mock verify_high method """ if self.flag: return True @@ -95,28 +95,28 @@ class MockState: @staticmethod def compile_high_data(data): """ - Mock compile_high_data + Mock compile_high_data """ return [{"__id__": "ABC"}] @staticmethod def call_chunk(data, data1, data2): """ - Mock call_chunk method + Mock call_chunk method """ return {"": "ABC"} @staticmethod def call_chunks(data): """ - Mock call_chunks method + Mock call_chunks method """ return True @staticmethod def call_listen(data, ret): """ - Mock call_listen method + Mock call_listen method """ return True @@ -125,7 +125,7 @@ class MockState: class HighState: """ - Mock HighState class + Mock HighState class """ flag = False @@ -137,7 +137,7 @@ class MockState: def render_state(self, sls, saltenv, mods, matches, local=False): """ - Mock render_state method + Mock render_state method """ if self.flag: return {}, True @@ -147,13 +147,13 @@ class MockState: @staticmethod def get_top(): """ - Mock get_top method + Mock get_top method """ return "_top" def verify_tops(self, data): """ - Mock verify_tops method + Mock verify_tops method """ if self.flag: return ["a", "b"] @@ -163,48 +163,48 @@ class MockState: @staticmethod def top_matches(data): """ - Mock top_matches method + Mock top_matches method """ return ["a", "b", "c"] @staticmethod def push_active(): """ - Mock push_active method + Mock push_active method """ return True @staticmethod def compile_highstate(): """ - Mock compile_highstate method + Mock compile_highstate method """ return "A" @staticmethod def compile_state_usage(): """ - Mock compile_state_usage method + Mock compile_state_usage method """ return "A" @staticmethod def pop_active(): """ - Mock pop_active method + Mock pop_active method """ return True @staticmethod def compile_low_chunks(): """ - Mock compile_low_chunks method + Mock compile_low_chunks method """ return [{"__id__": "ABC", "__sls__": "abc"}] def render_highstate(self, data): """ - Mock render_highstate method + Mock render_highstate method """ if self.flag: return ["a", "b"], True @@ -221,7 +221,7 @@ class MockState: orchestration_jid=None, ): """ - Mock call_highstate method + Mock call_highstate method """ return True @@ -234,7 +234,7 @@ class MockState: class MockSerial: """ - Mock Class + Mock Class """ def __init__(self): @@ -242,7 +242,7 @@ class MockSerial: class Serial: """ - Mock Serial class + Mock Serial class """ def __init__(self, data): @@ -251,21 +251,21 @@ class MockSerial: @staticmethod def load(data): """ - Mock load method + Mock load method """ return {"A": "B"} @staticmethod def dump(data, data1): """ - Mock dump method + Mock dump method """ return True class MockTarFile: """ - Mock tarfile class + Mock tarfile class """ path = os.sep + "tmp" @@ -276,28 +276,28 @@ class MockTarFile: @staticmethod def open(data, data1): """ - Mock open method + Mock open method """ return MockTarFile @staticmethod def getmembers(): """ - Mock getmembers method + Mock getmembers method """ return [MockTarFile] @staticmethod def extractall(data): """ - Mock extractall method + Mock extractall method """ return True @staticmethod def close(): """ - Mock close method + Mock close method """ return True @@ -330,7 +330,7 @@ def configure_loader_modules(salt_minion_factory): def test_running(): """ - Test of checking i fthe state function is already running + Test of checking i fthe state function is already running """ assert state.running(True) == [] @@ -353,7 +353,7 @@ def test_running(): def test_low(): """ - Test of executing a single low data call + Test of executing a single low data call """ with patch.object(state, "_check_queue", side_effect=[False, None, None]): assert not state.low({"state": "pkg", "fun": "installed", "name": "vi"}) @@ -367,7 +367,7 @@ def test_low(): def test_high(): """ - Test for checking the state system + Test for checking the state system """ with patch.object(state, "_check_queue", side_effect=[False, None]): assert not state.high({"vim": {"pkg": ["installed"]}}) @@ -380,8 +380,8 @@ def test_high(): def test_template(): """ - Test of executing the information - stored in a template file on the minion + Test of executing the information + stored in a template file on the minion """ with patch.object(state, "_check_queue", side_effect=[False, None, None]): assert not state.template("/home/salt/salt.sls") @@ -395,8 +395,8 @@ def test_template(): def test_template_str(): """ - Test for Executing the information - stored in a string from an sls template + Test for Executing the information + stored in a string from an sls template """ with patch.object(state, "_check_queue", side_effect=[False, None]): assert not state.template_str("Template String") @@ -406,7 +406,7 @@ def test_template_str(): def test_apply_(): """ - Test to apply states + Test to apply states """ with patch.object(state, "sls", return_value=True): assert state.apply_(True) @@ -417,7 +417,7 @@ def test_apply_(): def test_test(): """ - Test to apply states in test mode + Test to apply states in test mode """ with patch.dict(state.__opts__, {"test": False}): with patch.object(state, "sls", return_value=True) as mock: @@ -433,7 +433,7 @@ def test_test(): def test_list_disabled(): """ - Test to list disabled states + Test to list disabled states """ mock = MagicMock(return_value=["A", "B", "C"]) with patch.dict(state.__salt__, {"grains.get": mock}): @@ -442,7 +442,7 @@ def test_list_disabled(): def test_enable(): """ - Test to Enable state function or sls run + Test to Enable state function or sls run """ mock = MagicMock(return_value=["A", "B"]) with patch.dict(state.__salt__, {"grains.get": mock}): @@ -463,7 +463,7 @@ def test_enable(): def test_disable(): """ - Test to disable state run + Test to disable state run """ mock = MagicMock(return_value=["C", "D"]) with patch.dict(state.__salt__, {"grains.get": mock}): @@ -484,7 +484,7 @@ def test_disable(): def test_clear_cache(): """ - Test to clear out cached state file + Test to clear out cached state file """ mock = MagicMock(return_value=["A.cache.p", "B.cache.p", "C"]) with patch.object(os, "listdir", mock): @@ -497,7 +497,7 @@ def test_clear_cache(): def test_single(): """ - Test to execute single state function + Test to execute single state function """ ret = {"pkg_|-name=vim_|-name=vim_|-installed": list} mock = MagicMock(side_effect=["A", None, None, None, None]) @@ -528,7 +528,7 @@ def test_single(): def test_show_top(): """ - Test to return the top data that the minion will use for a highstate + Test to return the top data that the minion will use for a highstate """ mock = MagicMock(side_effect=["A", None, None]) with patch.object(state, "_check_queue", mock): @@ -543,7 +543,7 @@ def test_show_top(): def test_run_request(): """ - Test to Execute the pending state request + Test to Execute the pending state request """ mock = MagicMock( side_effect=[{}, {"name": "A"}, {"name": {"mods": "A", "kwargs": {}}}] @@ -562,7 +562,7 @@ def test_run_request(): def test_show_highstate(): """ - Test to retrieve the highstate data from the salt master + Test to retrieve the highstate data from the salt master """ mock = MagicMock(side_effect=["A", None, None]) with patch.object(state, "_check_queue", mock): @@ -575,7 +575,7 @@ def test_show_highstate(): def test_show_lowstate(): """ - Test to list out the low data that will be applied to this minion + Test to list out the low data that will be applied to this minion """ mock = MagicMock(side_effect=["A", None]) with patch.object(state, "_check_queue", mock): @@ -586,7 +586,7 @@ def test_show_lowstate(): def test_show_state_usage(): """ - Test to list out the state usage that will be applied to this minion + Test to list out the state usage that will be applied to this minion """ mock = MagicMock(side_effect=["A", None, None]) @@ -600,7 +600,7 @@ def test_show_state_usage(): def test_show_states(): """ - Test to display the low data from a specific sls + Test to display the low data from a specific sls """ mock = MagicMock(side_effect=["A", None]) with patch.object(state, "_check_queue", mock): @@ -626,8 +626,8 @@ def test_show_states_missing_sls(): def test_sls_id(): """ - Test to call a single ID from the - named module(s) and handle all requisites + Test to call a single ID from the + named module(s) and handle all requisites """ mock = MagicMock(side_effect=["A", None, None, None]) with patch.object(state, "_check_queue", mock): @@ -649,7 +649,7 @@ def test_sls_id(): def test_show_low_sls(): """ - Test to display the low data from a specific sls + Test to display the low data from a specific sls """ mock = MagicMock(side_effect=["A", None, None]) with patch.object(state, "_check_queue", mock): @@ -668,7 +668,7 @@ def test_show_low_sls(): def test_show_sls(): """ - Test to display the state data from a specific sls + Test to display the state data from a specific sls """ mock = MagicMock(side_effect=["A", None, None, None]) with patch.object(state, "_check_queue", mock): @@ -692,7 +692,7 @@ def test_show_sls(): def test_sls_exists(): """ - Test of sls_exists + Test of sls_exists """ test_state = {} test_missing_state = [] @@ -707,7 +707,7 @@ def test_sls_exists(): def test_id_exists(): """ - Test of id_exists + Test of id_exists """ test_state = [ { @@ -739,7 +739,7 @@ def test_id_exists(): def test_top(): """ - Test to execute a specific top file + Test to execute a specific top file """ ret = ["Pillar failed to render with the following messages:", "E"] mock = MagicMock(side_effect=["A", None, None, None]) @@ -774,8 +774,8 @@ def test_top(): def test_highstate(): """ - Test to retrieve the state data from the - salt master for the minion and execute it + Test to retrieve the state data from the + salt master for the minion and execute it """ arg = "whitelist=sls1.sls" mock = MagicMock(side_effect=[True, False, False, False]) @@ -814,7 +814,7 @@ def test_highstate(): def test_clear_request(): """ - Test to clear out the state execution request without executing it + Test to clear out the state execution request without executing it """ mock = MagicMock(return_value=True) with patch.object(salt.payload, "Serial", mock): @@ -833,7 +833,7 @@ def test_clear_request(): def test_check_request(): """ - Test to return the state request information + Test to return the state request information """ with patch("salt.modules.state.salt.payload", MockSerial): mock = MagicMock(side_effect=[True, True, False]) @@ -849,7 +849,7 @@ def test_check_request(): def test_request(): """ - Test to request the local admin execute a state run + Test to request the local admin execute a state run """ mock = MagicMock(return_value=True) with patch.object(state, "apply_", mock): @@ -1090,7 +1090,7 @@ def test_sls_sync(subtests): def test_pkg(): """ - Test to execute a packaged state run + Test to execute a packaged state run """ tar_file = os.sep + os.path.join("tmp", "state_pkg.tgz") mock = MagicMock( diff --git a/tests/pytests/unit/modules/test_alternatives.py b/tests/pytests/unit/modules/test_alternatives.py index aa05c3f0f42..6443013f05c 100644 --- a/tests/pytests/unit/modules/test_alternatives.py +++ b/tests/pytests/unit/modules/test_alternatives.py @@ -133,7 +133,10 @@ def test_remove(): with patch.dict(alternatives.__grains__, {"os_family": "RedHat"}): mock = MagicMock(return_value={"retcode": 0, "stdout": "salt"}) with patch.dict(alternatives.__salt__, {"cmd.run_all": mock}): - solution = alternatives.remove("better-world", "/usr/bin/better-world",) + solution = alternatives.remove( + "better-world", + "/usr/bin/better-world", + ) assert "salt" == solution mock.assert_called_once_with( ["alternatives", "--remove", "better-world", "/usr/bin/better-world"], @@ -143,7 +146,10 @@ def test_remove(): with patch.dict(alternatives.__grains__, {"os_family": "Debian"}): mock = MagicMock(return_value={"retcode": 0, "stdout": "salt"}) with patch.dict(alternatives.__salt__, {"cmd.run_all": mock}): - solution = alternatives.remove("better-world", "/usr/bin/better-world",) + solution = alternatives.remove( + "better-world", + "/usr/bin/better-world", + ) assert "salt" == solution mock.assert_called_once_with( [ @@ -160,7 +166,10 @@ def test_remove(): return_value={"retcode": 1, "stdout": "salt-out", "stderr": "salt-err"} ) with patch.dict(alternatives.__salt__, {"cmd.run_all": mock}): - solution = alternatives.remove("better-world", "/usr/bin/better-world",) + solution = alternatives.remove( + "better-world", + "/usr/bin/better-world", + ) assert "salt-err" == solution mock.assert_called_once_with( ["alternatives", "--remove", "better-world", "/usr/bin/better-world"], diff --git a/tests/pytests/unit/modules/test_ansiblegate.py b/tests/pytests/unit/modules/test_ansiblegate.py index b05d5dc59e7..44c9b12acb5 100644 --- a/tests/pytests/unit/modules/test_ansiblegate.py +++ b/tests/pytests/unit/modules/test_ansiblegate.py @@ -49,7 +49,8 @@ def test_virtual_function(subtests): with subtests.test("missing ansible-doc binary"): with patch( - "salt.utils.path.which", side_effect=["/path/to/ansible", None], + "salt.utils.path.which", + side_effect=["/path/to/ansible", None], ): assert ansiblegate.__virtual__() == ( False, diff --git a/tests/pytests/unit/modules/test_aptpkg.py b/tests/pytests/unit/modules/test_aptpkg.py index 52091058019..09210a0b45d 100644 --- a/tests/pytests/unit/modules/test_aptpkg.py +++ b/tests/pytests/unit/modules/test_aptpkg.py @@ -675,10 +675,13 @@ def test_mod_repo_match(): with patch("salt.modules.aptpkg.refresh_db", MagicMock(return_value={})): with patch("salt.utils.data.is_true", MagicMock(return_value=True)): with patch( - "salt.modules.aptpkg._check_apt", MagicMock(return_value=True), + "salt.modules.aptpkg._check_apt", + MagicMock(return_value=True), ): with patch( - "salt.modules.aptpkg.sourceslist", MagicMock(), create=True, + "salt.modules.aptpkg.sourceslist", + MagicMock(), + create=True, ): with patch( "salt.modules.aptpkg.sourceslist.SourcesList", @@ -898,7 +901,8 @@ def test_list_pkgs(): aptpkg.__salt__, {"cmd.run_stdout": MagicMock(return_value=os.linesep.join(apt_out))}, ), patch.dict(aptpkg.__salt__, {"pkg_resource.add_pkg": _add_data}), patch.dict( - aptpkg.__salt__, {"pkg_resource.format_pkg_list": pkg_resource.format_pkg_list}, + aptpkg.__salt__, + {"pkg_resource.format_pkg_list": pkg_resource.format_pkg_list}, ), patch.dict( aptpkg.__salt__, {"pkg_resource.sort_pkglist": pkg_resource.sort_pkglist} ): @@ -946,7 +950,8 @@ def test_list_pkgs_no_context(): aptpkg.__salt__, {"cmd.run_stdout": MagicMock(return_value=os.linesep.join(apt_out))}, ), patch.dict(aptpkg.__salt__, {"pkg_resource.add_pkg": _add_data}), patch.dict( - aptpkg.__salt__, {"pkg_resource.format_pkg_list": pkg_resource.format_pkg_list}, + aptpkg.__salt__, + {"pkg_resource.format_pkg_list": pkg_resource.format_pkg_list}, ), patch.dict( aptpkg.__salt__, {"pkg_resource.sort_pkglist": pkg_resource.sort_pkglist} ), patch.object( diff --git a/tests/pytests/unit/modules/test_archive.py b/tests/pytests/unit/modules/test_archive.py index 033e03274bd..f4c3f04a1ab 100644 --- a/tests/pytests/unit/modules/test_archive.py +++ b/tests/pytests/unit/modules/test_archive.py @@ -511,7 +511,8 @@ def test_unrar_raises_exception_if_not_found(): with patch.dict(archive.__salt__, {"cmd.run": mock}): with pytest.raises(CommandNotFoundError): archive.unrar( - "/tmp/rarfile.rar", "/home/strongbad/", + "/tmp/rarfile.rar", + "/home/strongbad/", ) assert not mock.called diff --git a/tests/pytests/unit/modules/test_cmdmod.py b/tests/pytests/unit/modules/test_cmdmod.py index 89c675c5768..1cc47d641f1 100644 --- a/tests/pytests/unit/modules/test_cmdmod.py +++ b/tests/pytests/unit/modules/test_cmdmod.py @@ -191,7 +191,11 @@ def test_run_invalid_umask(): with patch("os.path.isfile", MagicMock(return_value=True)): with patch("os.access", MagicMock(return_value=True)): pytest.raises( - CommandExecutionError, cmdmod._run, "foo", "bar", umask="baz", + CommandExecutionError, + cmdmod._run, + "foo", + "bar", + umask="baz", ) diff --git a/tests/pytests/unit/modules/test_gpg.py b/tests/pytests/unit/modules/test_gpg.py index 33b76cf365b..b8dee925b4c 100644 --- a/tests/pytests/unit/modules/test_gpg.py +++ b/tests/pytests/unit/modules/test_gpg.py @@ -502,7 +502,9 @@ def test_export_key_without_passphrase(gpghome): ret = gpg.export_key("xxxxxxxxxxxxxxxx") assert ret == GPG_TEST_PUB_KEY gnupg_export_keys.assert_called_with( - ["xxxxxxxxxxxxxxxx"], False, expect_passphrase=False, + ["xxxxxxxxxxxxxxxx"], + False, + expect_passphrase=False, ) @@ -609,7 +611,9 @@ def test_export_key_with_passphrase_with_gpg_passphrase_in_pillar(gpghome): ret = gpg.export_key("xxxxxxxxxxxxxxxx", use_passphrase=True) assert ret == GPG_TEST_PUB_KEY gnupg_export_keys.assert_called_with( - ["xxxxxxxxxxxxxxxx"], False, passphrase=GPG_TEST_KEY_PASSPHRASE, + ["xxxxxxxxxxxxxxxx"], + False, + passphrase=GPG_TEST_KEY_PASSPHRASE, ) diff --git a/tests/pytests/unit/modules/test_mysql.py b/tests/pytests/unit/modules/test_mysql.py index 88380b45d5e..3bda1d92584 100644 --- a/tests/pytests/unit/modules/test_mysql.py +++ b/tests/pytests/unit/modules/test_mysql.py @@ -154,7 +154,9 @@ def test_user_exists(): with patch.object(mysql, "version", return_value="8.0.11"): with patch.object( - mysql, "__get_auth_plugin", MagicMock(return_value="mysql_native_password"), + mysql, + "__get_auth_plugin", + MagicMock(return_value="mysql_native_password"), ): _test_call( mysql.user_exists, @@ -245,7 +247,9 @@ def test_user_create(): """ with patch.object(mysql, "version", return_value="8.0.10"): with patch.object( - mysql, "__get_auth_plugin", MagicMock(return_value="mysql_native_password"), + mysql, + "__get_auth_plugin", + MagicMock(return_value="mysql_native_password"), ): _test_call( mysql.user_create, @@ -263,7 +267,9 @@ def test_user_create(): with patch.object(mysql, "version", return_value="8.0.11"): with patch.object( - mysql, "__get_auth_plugin", MagicMock(return_value="mysql_native_password"), + mysql, + "__get_auth_plugin", + MagicMock(return_value="mysql_native_password"), ): _test_call( mysql.user_create, @@ -311,7 +317,9 @@ def test_user_create(): with patch.object( mysql, "user_exists", MagicMock(return_value=False) ), patch.object( - mysql, "__get_auth_plugin", MagicMock(return_value="mysql_native_password"), + mysql, + "__get_auth_plugin", + MagicMock(return_value="mysql_native_password"), ): _test_call( mysql.user_create, @@ -501,7 +509,9 @@ def test_db_create(): Test MySQL db_create function in mysql exec module """ _test_call( - mysql.db_create, "CREATE DATABASE IF NOT EXISTS `test``'\" db`;", "test`'\" db", + mysql.db_create, + "CREATE DATABASE IF NOT EXISTS `test``'\" db`;", + "test`'\" db", ) @@ -646,7 +656,12 @@ def test_grant_add(): Test grant_add function in mysql exec module """ _test_call( - mysql.grant_add, "", "SELECT,INSERT,UPDATE", "database.*", "frank", "localhost", + mysql.grant_add, + "", + "SELECT,INSERT,UPDATE", + "database.*", + "frank", + "localhost", ) @@ -742,7 +757,9 @@ def test_plugin_remove(): """ with patch.object(mysql, "plugin_status", MagicMock(return_value="ACTIVE")): _test_call( - mysql.plugin_remove, "UNINSTALL PLUGIN auth_socket", "auth_socket", + mysql.plugin_remove, + "UNINSTALL PLUGIN auth_socket", + "auth_socket", ) diff --git a/tests/pytests/unit/modules/test_pkgng.py b/tests/pytests/unit/modules/test_pkgng.py index 3f34577f16b..5c68e3128ca 100644 --- a/tests/pytests/unit/modules/test_pkgng.py +++ b/tests/pytests/unit/modules/test_pkgng.py @@ -274,7 +274,9 @@ def test_upgrade_without_fromrepo(pkgs): } assert result == expected pkg_cmd.assert_called_with( - ["pkg", "upgrade", "-y"], output_loglevel="trace", python_shell=False, + ["pkg", "upgrade", "-y"], + output_loglevel="trace", + python_shell=False, ) @@ -316,7 +318,9 @@ def test_upgrade_with_fetchonly(pkgs): } assert result == expected pkg_cmd.assert_called_with( - ["pkg", "upgrade", "-Fy"], output_loglevel="trace", python_shell=False, + ["pkg", "upgrade", "-Fy"], + output_loglevel="trace", + python_shell=False, ) @@ -337,7 +341,9 @@ def test_upgrade_with_local(pkgs): } assert result == expected pkg_cmd.assert_called_with( - ["pkg", "upgrade", "-Uy"], output_loglevel="trace", python_shell=False, + ["pkg", "upgrade", "-Uy"], + output_loglevel="trace", + python_shell=False, ) @@ -351,7 +357,9 @@ def test_stats_with_local(): result = pkgng.stats(local=True) assert result == [] pkg_cmd.assert_called_with( - ["pkg", "stats", "-l"], output_loglevel="trace", python_shell=False, + ["pkg", "stats", "-l"], + output_loglevel="trace", + python_shell=False, ) @@ -365,7 +373,9 @@ def test_stats_with_remote(): result = pkgng.stats(remote=True) assert result == [] pkg_cmd.assert_called_with( - ["pkg", "stats", "-r"], output_loglevel="trace", python_shell=False, + ["pkg", "stats", "-r"], + output_loglevel="trace", + python_shell=False, ) @@ -379,7 +389,9 @@ def test_stats_with_bytes_remote(): result = pkgng.stats(remote=True, bytes=True) assert result == [] pkg_cmd.assert_called_with( - ["pkg", "stats", "-rb"], output_loglevel="trace", python_shell=False, + ["pkg", "stats", "-rb"], + output_loglevel="trace", + python_shell=False, ) @@ -393,7 +405,9 @@ def test_stats_with_bytes_local(): result = pkgng.stats(local=True, bytes=True) assert result == [] pkg_cmd.assert_called_with( - ["pkg", "stats", "-lb"], output_loglevel="trace", python_shell=False, + ["pkg", "stats", "-lb"], + output_loglevel="trace", + python_shell=False, ) @@ -685,7 +699,9 @@ def test_check_depends(): result = pkgng.check(depends=True) assert result == "" pkg_cmd.assert_called_with( - ["pkg", "check", "-dy"], output_loglevel="trace", python_shell=False, + ["pkg", "check", "-dy"], + output_loglevel="trace", + python_shell=False, ) @@ -699,7 +715,9 @@ def test_check_checksum(): result = pkgng.check(checksum=True) assert result == "" pkg_cmd.assert_called_with( - ["pkg", "check", "-s"], output_loglevel="trace", python_shell=False, + ["pkg", "check", "-s"], + output_loglevel="trace", + python_shell=False, ) @@ -713,7 +731,9 @@ def test_check_recompute(): result = pkgng.check(recompute=True) assert result == "" pkg_cmd.assert_called_with( - ["pkg", "check", "-r"], output_loglevel="trace", python_shell=False, + ["pkg", "check", "-r"], + output_loglevel="trace", + python_shell=False, ) @@ -727,7 +747,9 @@ def test_check_checklibs(): result = pkgng.check(checklibs=True) assert result == "" pkg_cmd.assert_called_with( - ["pkg", "check", "-B"], output_loglevel="trace", python_shell=False, + ["pkg", "check", "-B"], + output_loglevel="trace", + python_shell=False, ) @@ -741,7 +763,9 @@ def test_autoremove_with_dryrun(): result = pkgng.autoremove(dryrun=True) assert result == "" pkg_cmd.assert_called_with( - ["pkg", "autoremove", "-n"], output_loglevel="trace", python_shell=False, + ["pkg", "autoremove", "-n"], + output_loglevel="trace", + python_shell=False, ) @@ -756,7 +780,9 @@ def test_autoremove(): result = pkgng.autoremove() assert result == "" pkg_cmd.assert_called_with( - ["pkg", "autoremove", "-y"], output_loglevel="trace", python_shell=False, + ["pkg", "autoremove", "-y"], + output_loglevel="trace", + python_shell=False, ) @@ -771,7 +797,9 @@ def test_audit(): result = pkgng.audit() assert result == "" pkg_cmd.assert_called_with( - ["pkg", "audit", "-F"], output_loglevel="trace", python_shell=False, + ["pkg", "audit", "-F"], + output_loglevel="trace", + python_shell=False, ) @@ -798,7 +826,8 @@ def test_refresh_db_without_forced_flag(): result = pkgng.refresh_db() assert result is True pkg_cmd.assert_called_with( - ["pkg", "update"], python_shell=False, + ["pkg", "update"], + python_shell=False, ) @@ -813,7 +842,8 @@ def test_refresh_db_with_forced_flag(): result = pkgng.refresh_db(force=True) assert result is True pkg_cmd.assert_called_with( - ["pkg", "update", "-f"], python_shell=False, + ["pkg", "update", "-f"], + python_shell=False, ) diff --git a/tests/pytests/unit/modules/test_rabbitmq.py b/tests/pytests/unit/modules/test_rabbitmq.py index fa2affaf57f..f54ec3a8bef 100644 --- a/tests/pytests/unit/modules/test_rabbitmq.py +++ b/tests/pytests/unit/modules/test_rabbitmq.py @@ -207,7 +207,9 @@ def test_add_user(): mock_run = MagicMock(return_value="Error") with patch.dict(rabbitmq.__salt__, {"cmd.run_all": mock_run}): with patch.object( - rabbitmq, "clear_password", return_value={"Error": "Error", "retcode": 1}, + rabbitmq, + "clear_password", + return_value={"Error": "Error", "retcode": 1}, ): pytest.raises(CommandExecutionError, rabbitmq.add_user, "saltstack") diff --git a/tests/pytests/unit/modules/test_restartcheck.py b/tests/pytests/unit/modules/test_restartcheck.py index 8b4dc01bca4..8c540634216 100644 --- a/tests/pytests/unit/modules/test_restartcheck.py +++ b/tests/pytests/unit/modules/test_restartcheck.py @@ -189,7 +189,8 @@ def test_when_nilinuxrt_and_not_kernel_modules_changed_or_sysapi_files_changed_a { "cmd.run": create_autospec(cmdmod.run, return_value=current_kernel), "system.get_reboot_required_witnessed": create_autospec( - system.get_reboot_required_witnessed, return_value=restart_required, + system.get_reboot_required_witnessed, + return_value=restart_required, ), "service.get_running": create_autospec( service.get_running, return_value=[] @@ -207,7 +208,9 @@ def test_when_nilinuxrt_and_not_kernel_modules_changed_or_sysapi_files_changed_a return_value=False, ) patch_del_files = patch( - "salt.modules.restartcheck._deleted_files", autospec=True, return_value=[], + "salt.modules.restartcheck._deleted_files", + autospec=True, + return_value=[], ) with patch_grains, patch_kernel_versions, patch_salt, patch_sysapi_changed, patch_kernel_mod_changed, patch_del_files: @@ -231,7 +234,8 @@ def test_when_nilinuxrt_and_not_kernel_modules_changed_or_sysapi_files_changed_a { "cmd.run": create_autospec(cmdmod.run, return_value=current_kernel), "system.get_reboot_required_witnessed": create_autospec( - system.get_reboot_required_witnessed, return_value=restart_required, + system.get_reboot_required_witnessed, + return_value=restart_required, ), "service.get_running": create_autospec( service.get_running, return_value=[] @@ -249,7 +253,9 @@ def test_when_nilinuxrt_and_not_kernel_modules_changed_or_sysapi_files_changed_a return_value=False, ) patch_del_files = patch( - "salt.modules.restartcheck._deleted_files", autospec=True, return_value=[], + "salt.modules.restartcheck._deleted_files", + autospec=True, + return_value=[], ) with patch_grains, patch_kernel_versions, patch_salt, patch_sysapi_changed, patch_kernel_mod_changed, patch_del_files: diff --git a/tests/pytests/unit/modules/test_solaris_shadow.py b/tests/pytests/unit/modules/test_solaris_shadow.py index 41651745539..0044b3988e0 100644 --- a/tests/pytests/unit/modules/test_solaris_shadow.py +++ b/tests/pytests/unit/modules/test_solaris_shadow.py @@ -79,13 +79,19 @@ def has_not_spwd(): @pytest.fixture def fake_spnam(): - with patch("spwd.getspnam", autospec=True,) as fake_spnam: + with patch( + "spwd.getspnam", + autospec=True, + ) as fake_spnam: yield fake_spnam @pytest.fixture def fake_pwnam(): - with patch("pwd.getpwnam", autospec=True,) as fake_pwnam: + with patch( + "pwd.getpwnam", + autospec=True, + ) as fake_pwnam: yield fake_pwnam diff --git a/tests/pytests/unit/modules/test_solarisipspkg.py b/tests/pytests/unit/modules/test_solarisipspkg.py index 6bd8b5372f1..1dd54eaf34a 100644 --- a/tests/pytests/unit/modules/test_solarisipspkg.py +++ b/tests/pytests/unit/modules/test_solarisipspkg.py @@ -335,7 +335,9 @@ def test_get_fmri_single_named(): assert added == expected expected_calls = [ - call(["/bin/pkg", "list", "-aHv", install_target],), + call( + ["/bin/pkg", "list", "-aHv", install_target], + ), ] run_stdout_mock.assert_has_calls(expected_calls, any_order=True) assert run_stdout_mock.call_count == 1 @@ -383,7 +385,10 @@ def test_remove_single_named_package(): assert added == expected expected_calls = [ - call(["/bin/pkg", "uninstall", "-v", install_target], output_loglevel="trace",), + call( + ["/bin/pkg", "uninstall", "-v", install_target], + output_loglevel="trace", + ), ] run_all_mock.assert_has_calls(expected_calls, any_order=True) assert run_all_mock.call_count == 1 diff --git a/tests/pytests/unit/modules/test_yumpkg.py b/tests/pytests/unit/modules/test_yumpkg.py index c8994058b4d..de1e75b1729 100644 --- a/tests/pytests/unit/modules/test_yumpkg.py +++ b/tests/pytests/unit/modules/test_yumpkg.py @@ -97,9 +97,11 @@ def test_list_pkgs(): "virt-what_|-(none)_|-1.13_|-8.el7_|-x86_64_|-(none)_|-1487838486", ] with patch.dict(yumpkg.__grains__, {"osarch": "x86_64"}), patch.dict( - yumpkg.__salt__, {"cmd.run": MagicMock(return_value=os.linesep.join(rpm_out))}, + yumpkg.__salt__, + {"cmd.run": MagicMock(return_value=os.linesep.join(rpm_out))}, ), patch.dict(yumpkg.__salt__, {"pkg_resource.add_pkg": _add_data}), patch.dict( - yumpkg.__salt__, {"pkg_resource.format_pkg_list": pkg_resource.format_pkg_list}, + yumpkg.__salt__, + {"pkg_resource.format_pkg_list": pkg_resource.format_pkg_list}, ), patch.dict( yumpkg.__salt__, {"pkg_resource.stringify": MagicMock()} ), patch.dict( @@ -151,9 +153,11 @@ def test_list_pkgs_no_context(): "virt-what_|-(none)_|-1.13_|-8.el7_|-x86_64_|-(none)_|-1487838486", ] with patch.dict(yumpkg.__grains__, {"osarch": "x86_64"}), patch.dict( - yumpkg.__salt__, {"cmd.run": MagicMock(return_value=os.linesep.join(rpm_out))}, + yumpkg.__salt__, + {"cmd.run": MagicMock(return_value=os.linesep.join(rpm_out))}, ), patch.dict(yumpkg.__salt__, {"pkg_resource.add_pkg": _add_data}), patch.dict( - yumpkg.__salt__, {"pkg_resource.format_pkg_list": pkg_resource.format_pkg_list}, + yumpkg.__salt__, + {"pkg_resource.format_pkg_list": pkg_resource.format_pkg_list}, ), patch.dict( yumpkg.__salt__, {"pkg_resource.stringify": MagicMock()} ), patch.dict( @@ -196,9 +200,11 @@ def test_list_pkgs_with_attr(): "virt-what_|-(none)_|-1.13_|-8.el7_|-x86_64_|-(none)_|-1487838486", ] with patch.dict(yumpkg.__grains__, {"osarch": "x86_64"}), patch.dict( - yumpkg.__salt__, {"cmd.run": MagicMock(return_value=os.linesep.join(rpm_out))}, + yumpkg.__salt__, + {"cmd.run": MagicMock(return_value=os.linesep.join(rpm_out))}, ), patch.dict(yumpkg.__salt__, {"pkg_resource.add_pkg": _add_data}), patch.dict( - yumpkg.__salt__, {"pkg_resource.format_pkg_list": pkg_resource.format_pkg_list}, + yumpkg.__salt__, + {"pkg_resource.format_pkg_list": pkg_resource.format_pkg_list}, ), patch.dict( yumpkg.__salt__, {"pkg_resource.stringify": MagicMock()} ), patch.dict( @@ -322,9 +328,11 @@ def test_list_pkgs_with_attr_multiple_versions(): "virt-what_|-(none)_|-1.10_|-2.el7_|-x86_64_|-(none)_|-1387838486", ] with patch.dict(yumpkg.__grains__, {"osarch": "x86_64"}), patch.dict( - yumpkg.__salt__, {"cmd.run": MagicMock(return_value=os.linesep.join(rpm_out))}, + yumpkg.__salt__, + {"cmd.run": MagicMock(return_value=os.linesep.join(rpm_out))}, ), patch.dict(yumpkg.__salt__, {"pkg_resource.add_pkg": _add_data}), patch.dict( - yumpkg.__salt__, {"pkg_resource.format_pkg_list": pkg_resource.format_pkg_list}, + yumpkg.__salt__, + {"pkg_resource.format_pkg_list": pkg_resource.format_pkg_list}, ), patch.dict( yumpkg.__salt__, {"pkg_resource.stringify": MagicMock()} ), patch.dict( @@ -823,7 +831,10 @@ def test_refresh_db_with_options(): {"cmd.run_all": yum_call, "config.get": MagicMock(return_value=False)}, ): yumpkg.refresh_db( - check_update=True, enablerepo="good", disablerepo="bad", branch="foo", + check_update=True, + enablerepo="good", + disablerepo="bad", + branch="foo", ) assert yum_call.call_count == 2 yum_call.assert_any_call( @@ -893,7 +904,10 @@ def test_refresh_db_with_options(): {"cmd.run_all": yum_call, "config.get": MagicMock(return_value=False)}, ): yumpkg.refresh_db( - check_update=False, enablerepo="good", disablerepo="bad", branch="foo", + check_update=False, + enablerepo="good", + disablerepo="bad", + branch="foo", ) assert yum_call.call_count == 1 yum_call.assert_called_once_with( @@ -1785,7 +1799,10 @@ def test_get_repo_with_existent_repo(list_repos_var): yumpkg, "list_repos", autospec=True, return_value=list_repos_var ) patch_parse_repo_file = patch.object( - yumpkg, "_parse_repo_file", autospec=True, return_value=parse_repo_file_return, + yumpkg, + "_parse_repo_file", + autospec=True, + return_value=parse_repo_file_return, ) with patch_list_repos, patch_parse_repo_file: diff --git a/tests/pytests/unit/modules/test_zypperpkg.py b/tests/pytests/unit/modules/test_zypperpkg.py index b0f6eb291d3..4a0055e11cd 100644 --- a/tests/pytests/unit/modules/test_zypperpkg.py +++ b/tests/pytests/unit/modules/test_zypperpkg.py @@ -40,9 +40,11 @@ def test_list_pkgs_no_context(): "perseus-dummy_|-(none)_|-1.1_|-1.1_|-i586_|-(none)_|-1529936062", ] with patch.dict(zypper.__grains__, {"osarch": "x86_64"}), patch.dict( - zypper.__salt__, {"cmd.run": MagicMock(return_value=os.linesep.join(rpm_out))}, + zypper.__salt__, + {"cmd.run": MagicMock(return_value=os.linesep.join(rpm_out))}, ), patch.dict(zypper.__salt__, {"pkg_resource.add_pkg": _add_data}), patch.dict( - zypper.__salt__, {"pkg_resource.format_pkg_list": pkg_resource.format_pkg_list}, + zypper.__salt__, + {"pkg_resource.format_pkg_list": pkg_resource.format_pkg_list}, ), patch.dict( zypper.__salt__, {"pkg_resource.stringify": MagicMock()} ), patch.object( diff --git a/tests/pytests/unit/modules/virt/test_domain.py b/tests/pytests/unit/modules/virt/test_domain.py index 993d5bf1ed4..d96beb32dc7 100644 --- a/tests/pytests/unit/modules/virt/test_domain.py +++ b/tests/pytests/unit/modules/virt/test_domain.py @@ -1636,7 +1636,8 @@ def test_update_mem(make_mock_vm): domain_mock = make_mock_vm() ret = virt.update( - "my_vm", mem={"boot": "0.5g", "current": "2g", "max": "1g", "slots": 12}, + "my_vm", + mem={"boot": "0.5g", "current": "2g", "max": "1g", "slots": 12}, ) assert ret["definition"] assert ret["mem"] diff --git a/tests/pytests/unit/modules/virt/test_network.py b/tests/pytests/unit/modules/virt/test_network.py index 5ab4e0a4493..ccb579aad7d 100644 --- a/tests/pytests/unit/modules/virt/test_network.py +++ b/tests/pytests/unit/modules/virt/test_network.py @@ -188,7 +188,11 @@ def test_gen_xml_passthrough_interfaces(): Test the virt._gen_net_xml() function for a passthrough forward mode """ xml_data = virt._gen_net_xml( - "network", "virbr0", "passthrough", None, interfaces="eth10 eth11 eth12", + "network", + "virbr0", + "passthrough", + None, + interfaces="eth10 eth11 eth12", ) root = ET.fromstring(xml_data) assert root.find("forward").get("mode") == "passthrough" @@ -204,7 +208,11 @@ def test_gen_xml_hostdev_addresses(): Test the virt._gen_net_xml() function for a hostdev forward mode with PCI addresses """ xml_data = virt._gen_net_xml( - "network", "virbr0", "hostdev", None, addresses="0000:04:00.1 0000:e3:01.2", + "network", + "virbr0", + "hostdev", + None, + addresses="0000:04:00.1 0000:e3:01.2", ) root = ET.fromstring(xml_data) expected_forward = ET.fromstring( @@ -274,7 +282,8 @@ def test_gen_xml_openvswitch(): @pytest.mark.parametrize( - "autostart, start", [(True, True), (False, True), (False, False)], + "autostart, start", + [(True, True), (False, True), (False, False)], ) def test_define(make_mock_network, autostart, start): """ diff --git a/tests/pytests/unit/output/test_highstate.py b/tests/pytests/unit/output/test_highstate.py index 53eaf6fde75..0536efd75dc 100644 --- a/tests/pytests/unit/output/test_highstate.py +++ b/tests/pytests/unit/output/test_highstate.py @@ -37,7 +37,8 @@ def test_when_data_is_dict_with_return_key_and_return_value_has_data_key_and_dat @pytest.mark.parametrize( - "return_value", [42, "fnord"], + "return_value", + [42, "fnord"], ) def test_when_data_is_dict_with_return_key_and_return_value_has_data_key_and_data_dict_has_one_dict_element_with_jid_and_fun_keys_and_return_value_is_int_or_str_that_value_should_be_returned( return_value, diff --git a/tests/pytests/unit/states/mysql/test_grants.py b/tests/pytests/unit/states/mysql/test_grants.py index 880578e9d6b..c797af2011a 100644 --- a/tests/pytests/unit/states/mysql/test_grants.py +++ b/tests/pytests/unit/states/mysql/test_grants.py @@ -25,7 +25,8 @@ def test_present(): mock_str = MagicMock(return_value="salt") mock_none = MagicMock(return_value=None) with patch.dict( - mysql_grants.__salt__, {"mysql.grant_exists": mock, "mysql.grant_add": mock_t}, + mysql_grants.__salt__, + {"mysql.grant_exists": mock, "mysql.grant_add": mock_t}, ): comt = "Grant None on None to None@localhost is already present" ret.update({"comment": comt}) diff --git a/tests/pytests/unit/states/mysql/test_query.py b/tests/pytests/unit/states/mysql/test_query.py index b272cdc1d0b..06a6dbf1774 100644 --- a/tests/pytests/unit/states/mysql/test_query.py +++ b/tests/pytests/unit/states/mysql/test_query.py @@ -74,7 +74,12 @@ def test_run(): ret.update({"comment": comt, "result": True}) assert ( mysql_query.run( - name, database, query, output="grain", grain="grain", overwrite=False, + name, + database, + query, + output="grain", + grain="grain", + overwrite=False, ) == ret ) diff --git a/tests/pytests/unit/states/mysql/test_user.py b/tests/pytests/unit/states/mysql/test_user.py index a6c4ea427e3..08685522a20 100644 --- a/tests/pytests/unit/states/mysql/test_user.py +++ b/tests/pytests/unit/states/mysql/test_user.py @@ -53,7 +53,8 @@ def test_present(): assert mysql_user.present(name) == ret with patch.dict( - mysql_user.__salt__, {"mysql.user_exists": mock, "mysql.user_chpass": mock_t}, + mysql_user.__salt__, + {"mysql.user_exists": mock, "mysql.user_chpass": mock_t}, ): with patch.object(salt.utils.data, "is_true", mock_t): comt = "User frank@localhost is already present with passwordless login" @@ -110,7 +111,8 @@ def test_absent(): mock_str = MagicMock(return_value="salt") mock_none = MagicMock(return_value=None) with patch.dict( - mysql_user.__salt__, {"mysql.user_exists": mock, "mysql.user_remove": mock_t}, + mysql_user.__salt__, + {"mysql.user_exists": mock, "mysql.user_remove": mock_t}, ): with patch.dict(mysql_user.__opts__, {"test": True}): comt = "User frank_exampledb@localhost is set to be removed" diff --git a/tests/pytests/unit/states/postgresql/test_language.py b/tests/pytests/unit/states/postgresql/test_language.py index 9b713ab2090..5c10f52dd83 100644 --- a/tests/pytests/unit/states/postgresql/test_language.py +++ b/tests/pytests/unit/states/postgresql/test_language.py @@ -20,7 +20,8 @@ def test_present_existing(): ret = {"name": name, "changes": {}, "result": False, "comment": ""} mock_language_list = MagicMock(return_value={"plpgsql": name}) with patch.dict( - postgres_language.__salt__, {"postgres.language_list": mock_language_list}, + postgres_language.__salt__, + {"postgres.language_list": mock_language_list}, ): comt = "Language {} is already installed".format(name) ret.update({"comment": comt, "result": True}) diff --git a/tests/pytests/unit/states/test_archive.py b/tests/pytests/unit/states/test_archive.py index b724dd2a111..ed27511f2c2 100644 --- a/tests/pytests/unit/states/test_archive.py +++ b/tests/pytests/unit/states/test_archive.py @@ -101,7 +101,8 @@ def test_extracted_tar(): isfile_mock = MagicMock(side_effect=_isfile_side_effect) with patch.dict( - archive.__opts__, {"test": False, "cachedir": tmp_dir, "hash_type": "sha256"}, + archive.__opts__, + {"test": False, "cachedir": tmp_dir, "hash_type": "sha256"}, ), patch.dict( archive.__salt__, { diff --git a/tests/pytests/unit/states/test_boto_asg.py b/tests/pytests/unit/states/test_boto_asg.py index c45e0fc8bcb..646cc468d56 100644 --- a/tests/pytests/unit/states/test_boto_asg.py +++ b/tests/pytests/unit/states/test_boto_asg.py @@ -73,7 +73,8 @@ def test_present(): boto_asg.__salt__, {"config.option": MagicMock(return_value={})} ): with patch.dict( - boto_asg.__utils__, {"boto3.ordered": MagicMock(return_value="")}, + boto_asg.__utils__, + {"boto3.ordered": MagicMock(return_value="")}, ): comt = "Autoscale group present. " ret.update({"comment": comt, "result": True}) diff --git a/tests/pytests/unit/states/test_boto_cloudwatch_event.py b/tests/pytests/unit/states/test_boto_cloudwatch_event.py index b477872de9f..6b0ed4ef5ef 100644 --- a/tests/pytests/unit/states/test_boto_cloudwatch_event.py +++ b/tests/pytests/unit/states/test_boto_cloudwatch_event.py @@ -56,7 +56,9 @@ def configure_loader_modules(): opts["grains"] = salt.loader.grains(opts) ctx = {} utils = salt.loader.utils( - opts, whitelist=["boto3", "args", "systemd", "path", "platform"], context=ctx, + opts, + whitelist=["boto3", "args", "systemd", "path", "platform"], + context=ctx, ) serializers = salt.loader.serializers(opts) funcs = funcs = salt.loader.minion_mods( diff --git a/tests/pytests/unit/states/test_boto_elasticsearch_domain.py b/tests/pytests/unit/states/test_boto_elasticsearch_domain.py index e4b860c6ad0..423d53b0a64 100644 --- a/tests/pytests/unit/states/test_boto_elasticsearch_domain.py +++ b/tests/pytests/unit/states/test_boto_elasticsearch_domain.py @@ -55,7 +55,9 @@ def configure_loader_modules(): opts["grains"] = salt.loader.grains(opts) ctx = {} utils = salt.loader.utils( - opts, whitelist=["boto3", "args", "systemd", "path", "platform"], context=ctx, + opts, + whitelist=["boto3", "args", "systemd", "path", "platform"], + context=ctx, ) serializers = salt.loader.serializers(opts) funcs = funcs = salt.loader.minion_mods( diff --git a/tests/pytests/unit/states/test_boto_iot.py b/tests/pytests/unit/states/test_boto_iot.py index 0bdc80d0b22..e0d0179a9fc 100644 --- a/tests/pytests/unit/states/test_boto_iot.py +++ b/tests/pytests/unit/states/test_boto_iot.py @@ -96,7 +96,9 @@ def configure_loader_modules(): opts["grains"] = salt.loader.grains(opts) ctx = {} utils = salt.loader.utils( - opts, whitelist=["boto3", "args", "systemd", "path", "platform"], context=ctx, + opts, + whitelist=["boto3", "args", "systemd", "path", "platform"], + context=ctx, ) serializers = salt.loader.serializers(opts) funcs = funcs = salt.loader.minion_mods( diff --git a/tests/pytests/unit/states/test_boto_sqs.py b/tests/pytests/unit/states/test_boto_sqs.py index bae38e4dcb7..e54b7efc5f1 100644 --- a/tests/pytests/unit/states/test_boto_sqs.py +++ b/tests/pytests/unit/states/test_boto_sqs.py @@ -29,7 +29,9 @@ def test_present(): attributes = {"DelaySeconds": 20} base_ret = {"name": name, "changes": {}} - mock = MagicMock(side_effect=[{"result": b} for b in [False, False, True, True]],) + mock = MagicMock( + side_effect=[{"result": b} for b in [False, False, True, True]], + ) mock_bool = MagicMock(return_value={"error": "create error"}) mock_attr = MagicMock(return_value={"result": {}}) with patch.dict( @@ -41,7 +43,11 @@ def test_present(): }, ): with patch.dict(boto_sqs.__opts__, {"test": False}): - comt = ["Failed to create SQS queue {}: create error".format(name,)] + comt = [ + "Failed to create SQS queue {}: create error".format( + name, + ) + ] ret = base_ret.copy() ret.update({"result": False, "comment": comt}) assert boto_sqs.present(name) == ret @@ -73,7 +79,9 @@ def test_present(): comt = [ "SQS queue mysqs present.", - "Attribute(s) DelaySeconds set to be updated:\n{}".format(diff,), + "Attribute(s) DelaySeconds set to be updated:\n{}".format( + diff, + ), ] ret.update({"comment": comt, "changes": {"attributes": {"diff": diff}}}) assert boto_sqs.present(name, attributes) == ret diff --git a/tests/pytests/unit/states/test_btrfs.py b/tests/pytests/unit/states/test_btrfs.py index 27fb24c95ba..75fff65190d 100644 --- a/tests/pytests/unit/states/test_btrfs.py +++ b/tests/pytests/unit/states/test_btrfs.py @@ -348,7 +348,10 @@ def test_subvolume_created_exists_set_default_no_force( } with patch.dict(btrfs.__salt__, salt_mock), patch.dict(btrfs.__opts__, opts_mock): assert btrfs.subvolume_created( - name="@/var", device="/dev/sda1", set_default=True, force_set_default=False, + name="@/var", + device="/dev/sda1", + set_default=True, + force_set_default=False, ) == { "name": "@/var", "result": True, diff --git a/tests/pytests/unit/states/test_cloud.py b/tests/pytests/unit/states/test_cloud.py index 81273d9dd6a..117135fab26 100644 --- a/tests/pytests/unit/states/test_cloud.py +++ b/tests/pytests/unit/states/test_cloud.py @@ -265,7 +265,9 @@ def test_volume_attached(): cloud.__salt__, {"cloud.volume_list": mock_dict, "cloud.action": mock} ): with patch.object( - salt.utils.cloud, "check_name", MagicMock(side_effect=[True, False, True]), + salt.utils.cloud, + "check_name", + MagicMock(side_effect=[True, False, True]), ): comt = "Invalid characters in name." ret.update({"comment": comt}) @@ -334,7 +336,9 @@ def test_volume_detached(): cloud.__salt__, {"cloud.volume_list": mock_dict, "cloud.action": mock} ): with patch.object( - salt.utils.cloud, "check_name", MagicMock(side_effect=[True, False, True]), + salt.utils.cloud, + "check_name", + MagicMock(side_effect=[True, False, True]), ): comt = "Invalid characters in name." ret.update({"comment": comt}) diff --git a/tests/pytests/unit/states/test_docker_volume.py b/tests/pytests/unit/states/test_docker_volume.py index 8d31db44f10..4dbe49bc0bd 100644 --- a/tests/pytests/unit/states/test_docker_volume.py +++ b/tests/pytests/unit/states/test_docker_volume.py @@ -114,7 +114,11 @@ def test_present_with_another_driver(): ), } with patch.dict(docker_state.__dict__, {"__salt__": __salt__}): - ret = docker_state.present("volume_foo", driver="bar", force=True,) + ret = docker_state.present( + "volume_foo", + driver="bar", + force=True, + ) docker_remove_volume.assert_called_with("volume_foo") docker_create_volume.assert_called_with( "volume_foo", driver="bar", driver_opts=None @@ -139,7 +143,11 @@ def test_present_wo_existing_volumes(): "docker.volumes": Mock(return_value={"Volumes": None}), } with patch.dict(docker_state.__dict__, {"__salt__": __salt__}): - ret = docker_state.present("volume_foo", driver="bar", force=True,) + ret = docker_state.present( + "volume_foo", + driver="bar", + force=True, + ) docker_create_volume.assert_called_with( "volume_foo", driver="bar", driver_opts=None ) @@ -161,7 +169,9 @@ def test_absent(): "docker.volumes": Mock(return_value={"Volumes": [{"Name": "volume_foo"}]}), } with patch.dict(docker_state.__dict__, {"__salt__": __salt__}): - ret = docker_state.absent("volume_foo",) + ret = docker_state.absent( + "volume_foo", + ) docker_remove_volume.assert_called_with("volume_foo") assert ret == { "name": "volume_foo", diff --git a/tests/pytests/unit/states/test_drac.py b/tests/pytests/unit/states/test_drac.py index 2016afc450a..c94ba207459 100644 --- a/tests/pytests/unit/states/test_drac.py +++ b/tests/pytests/unit/states/test_drac.py @@ -76,7 +76,8 @@ def test_network(): mock_info = MagicMock(return_value=net_info) mock_bool = MagicMock(side_effect=[True, False]) with patch.dict( - drac.__salt__, {"drac.network_info": mock_info, "drac.set_network": mock_bool}, + drac.__salt__, + {"drac.network_info": mock_info, "drac.set_network": mock_bool}, ): with patch.dict(drac.__opts__, {"test": True}): assert drac.network(ip_, netmask, gateway) == ret diff --git a/tests/pytests/unit/states/test_event.py b/tests/pytests/unit/states/test_event.py index d43d48e1835..bfbf93b0310 100644 --- a/tests/pytests/unit/states/test_event.py +++ b/tests/pytests/unit/states/test_event.py @@ -14,7 +14,7 @@ def configure_loader_modules(): def test_send(): """ - Test to send an event to the Salt Master + Test to send an event to the Salt Master """ with patch.dict(event.__opts__, {"test": True}): assert event.send("salt") == { @@ -37,7 +37,7 @@ def test_send(): def test_wait(): """ - Test to fire an event on the Salt master + Test to fire an event on the Salt master """ assert event.wait("salt") == { "changes": {}, diff --git a/tests/pytests/unit/states/test_host.py b/tests/pytests/unit/states/test_host.py index 3ed4124ab3f..2656e738fed 100644 --- a/tests/pytests/unit/states/test_host.py +++ b/tests/pytests/unit/states/test_host.py @@ -346,12 +346,17 @@ def test_host_present_should_return_True_if_test_and_no_changes(): add_host_mock = MagicMock(return_value=True) rm_host_mock = MagicMock(return_value=True) expected = { - "comment": "Host {} ({}) already present".format(hostname, ip_list[0],), + "comment": "Host {} ({}) already present".format( + hostname, + ip_list[0], + ), "changes": {}, "name": hostname, "result": True, } - list_hosts = MagicMock(return_value={ip_list[0]: {"aliases": [hostname]}},) + list_hosts = MagicMock( + return_value={ip_list[0]: {"aliases": [hostname]}}, + ) with patch.dict( host.__salt__, { @@ -372,12 +377,19 @@ def test_host_present_should_return_None_if_test_and_adding(): expected = { "comment": "\n".join( ["Host {} ({}) already present", "Host {} ({}) would be added"] - ).format(hostname, ip_list[0], hostname, ip_list[1],), + ).format( + hostname, + ip_list[0], + hostname, + ip_list[1], + ), "changes": {"added": {ip_list[1]: [hostname]}}, "name": hostname, "result": None, } - list_hosts = MagicMock(return_value={ip_list[0]: {"aliases": [hostname]}},) + list_hosts = MagicMock( + return_value={ip_list[0]: {"aliases": [hostname]}}, + ) with patch.dict( host.__salt__, { @@ -398,7 +410,12 @@ def test_host_present_should_return_None_if_test_and_removing(): expected = { "comment": "\n".join( ["Host {} ({}) already present", "Host {} ({}) would be removed"] - ).format(hostname, ip_list[0], hostname, ip_list[1],), + ).format( + hostname, + ip_list[0], + hostname, + ip_list[1], + ), "changes": {"removed": {ip_list[1]: [hostname]}}, "name": hostname, "result": None, diff --git a/tests/pytests/unit/states/test_lvm.py b/tests/pytests/unit/states/test_lvm.py index 6631ec6e8cb..72e77509a6f 100644 --- a/tests/pytests/unit/states/test_lvm.py +++ b/tests/pytests/unit/states/test_lvm.py @@ -230,7 +230,11 @@ def test_lv_present_with_invalid_suffixes(lv02): with patch.dict(lvm.__opts__, {"test": True}): for size in sizes_list: pytest.raises( - ArgumentValueError, lvm.lv_present, name, vgname=vgname, size=size, + ArgumentValueError, + lvm.lv_present, + name, + vgname=vgname, + size=size, ) diff --git a/tests/pytests/unit/states/test_mac_keychain.py b/tests/pytests/unit/states/test_mac_keychain.py index 454e2972e15..4c8959fbbfe 100644 --- a/tests/pytests/unit/states/test_mac_keychain.py +++ b/tests/pytests/unit/states/test_mac_keychain.py @@ -241,7 +241,9 @@ def test_install_cert_salt_fileserver(): list_mock.assert_called_once_with("/Library/Keychains/System.keychain") friendly_mock.assert_called_once_with("/tmp/path/to/cert.p12", "passw0rd") install_mock.assert_called_once_with( - "/tmp/path/to/cert.p12", "passw0rd", "/Library/Keychains/System.keychain", + "/tmp/path/to/cert.p12", + "passw0rd", + "/Library/Keychains/System.keychain", ) assert out == expected diff --git a/tests/pytests/unit/states/test_pkg.py b/tests/pytests/unit/states/test_pkg.py index a572c4c192b..3d2377fdae1 100644 --- a/tests/pytests/unit/states/test_pkg.py +++ b/tests/pytests/unit/states/test_pkg.py @@ -86,13 +86,21 @@ def test_uptodate_with_pkgs_with_changes(pkgs): ): # Run state with test=false with patch.dict(pkg.__opts__, {"test": False}): - ret = pkg.uptodate("dummy", test=True, pkgs=[pkgname for pkgname in pkgs],) + ret = pkg.uptodate( + "dummy", + test=True, + pkgs=[pkgname for pkgname in pkgs], + ) assert ret["result"] assert ret["changes"] == pkgs # Run state with test=true with patch.dict(pkg.__opts__, {"test": True}): - ret = pkg.uptodate("dummy", test=True, pkgs=[pkgname for pkgname in pkgs],) + ret = pkg.uptodate( + "dummy", + test=True, + pkgs=[pkgname for pkgname in pkgs], + ) assert ret["result"] is None assert ret["changes"] == pkgs @@ -135,13 +143,21 @@ def test_uptodate_with_pkgs_no_changes(pkgs): ): # Run state with test=false with patch.dict(pkg.__opts__, {"test": False}): - ret = pkg.uptodate("dummy", test=True, pkgs=[pkgname for pkgname in pkgs],) + ret = pkg.uptodate( + "dummy", + test=True, + pkgs=[pkgname for pkgname in pkgs], + ) assert ret["result"] assert ret["changes"] == {} # Run state with test=true with patch.dict(pkg.__opts__, {"test": True}): - ret = pkg.uptodate("dummy", test=True, pkgs=[pkgname for pkgname in pkgs],) + ret = pkg.uptodate( + "dummy", + test=True, + pkgs=[pkgname for pkgname in pkgs], + ) assert ret["result"] assert ret["changes"] == {} @@ -167,13 +183,21 @@ def test_uptodate_with_failed_changes(pkgs): ): # Run state with test=false with patch.dict(pkg.__opts__, {"test": False}): - ret = pkg.uptodate("dummy", test=True, pkgs=[pkgname for pkgname in pkgs],) + ret = pkg.uptodate( + "dummy", + test=True, + pkgs=[pkgname for pkgname in pkgs], + ) assert not ret["result"] assert ret["changes"] == {} # Run state with test=true with patch.dict(pkg.__opts__, {"test": True}): - ret = pkg.uptodate("dummy", test=True, pkgs=[pkgname for pkgname in pkgs],) + ret = pkg.uptodate( + "dummy", + test=True, + pkgs=[pkgname for pkgname in pkgs], + ) assert ret["result"] is None assert ret["changes"] == pkgs @@ -215,7 +239,11 @@ def test_parse_version_string(version_string, expected_version_conditions): ("> 1.0.0, < 15.0.0, != 14.0.1", ["14.0.1"], False), ("> 1.0.0, < 15.0.0, != 14.0.1", ["16.0.0"], False), ("> 1.0.0, < 15.0.0, != 14.0.1", ["2.0.0"], True), - ("> 1.0.0, < 15.0.0, != 14.0.1", ["1.0.0", "14.0.1", "16.0.0", "2.0.0"], True,), + ( + "> 1.0.0, < 15.0.0, != 14.0.1", + ["1.0.0", "14.0.1", "16.0.0", "2.0.0"], + True, + ), ("> 15.0.0", [], False), ("> 15.0.0", ["1.0.0"], False), ("> 15.0.0", ["16.0.0"], True), @@ -251,8 +279,10 @@ def test_fulfills_version_string(version_string, installed_versions, expected_re ], ) def test_fulfills_version_spec(installed_versions, operator, version, expected_result): - msg = "installed_versions: {}, operator: {}, version: {}, expected_result: {}".format( - installed_versions, operator, version, expected_result + msg = ( + "installed_versions: {}, operator: {}, version: {}, expected_result: {}".format( + installed_versions, operator, version, expected_result + ) ) assert expected_result == pkg._fulfills_version_spec( installed_versions, operator, version diff --git a/tests/pytests/unit/states/test_service.py b/tests/pytests/unit/states/test_service.py index 3f43baaa68d..7a140d0a9f7 100644 --- a/tests/pytests/unit/states/test_service.py +++ b/tests/pytests/unit/states/test_service.py @@ -17,7 +17,7 @@ log = logging.getLogger(__name__) def func(name): """ - Mock func method + Mock func method """ return name @@ -178,7 +178,8 @@ def test_running(): with patch.object(service, "_available", tmock): with patch.dict(service.__opts__, {"test": False}): with patch.dict( - service.__salt__, {"service.enabled": tmock, "service.status": tmock}, + service.__salt__, + {"service.enabled": tmock, "service.status": tmock}, ): assert service.running("salt") == ret[1] diff --git a/tests/pytests/unit/states/test_slack.py b/tests/pytests/unit/states/test_slack.py index ed21444ceef..13d842d54d1 100644 --- a/tests/pytests/unit/states/test_slack.py +++ b/tests/pytests/unit/states/test_slack.py @@ -74,7 +74,11 @@ def test_post_message_apikey(): ret.update({"comment": comt, "result": False}) assert ( slack.post_message( - name, channel=channel, from_name=None, message=message, api_key=api_key, + name, + channel=channel, + from_name=None, + message=message, + api_key=api_key, ) == ret ) @@ -167,7 +171,11 @@ def test_post_message_webhook(): ret.update({"comment": comt, "result": False}) assert ( slack.post_message( - name, channel=channel, username=username, message=None, webhook=webhook, + name, + channel=channel, + username=username, + message=None, + webhook=webhook, ) == ret ) diff --git a/tests/pytests/unit/states/test_user.py b/tests/pytests/unit/states/test_user.py index 23b25e14d44..f8fb96185c9 100644 --- a/tests/pytests/unit/states/test_user.py +++ b/tests/pytests/unit/states/test_user.py @@ -208,7 +208,8 @@ def test_absent(): mock = MagicMock(side_effect=[True, True, False]) mock1 = MagicMock(return_value=False) with patch.dict( - user.__salt__, {"user.info": mock, "user.delete": mock1, "group.info": mock1}, + user.__salt__, + {"user.info": mock, "user.delete": mock1, "group.info": mock1}, ): with patch.dict(user.__opts__, {"test": True}): ret.update({"comment": "User salt set for removal"}) diff --git a/tests/pytests/unit/states/test_win_network.py b/tests/pytests/unit/states/test_win_network.py index 99667d9f683..12c2bd23299 100644 --- a/tests/pytests/unit/states/test_win_network.py +++ b/tests/pytests/unit/states/test_win_network.py @@ -280,7 +280,10 @@ def test_managed_static_dns(): win_network, "_validate", mock_validate ): ret = win_network.managed( - "salt", dns_proto="static", dns_servers=["192.168.0.10"], ip_proto="dhcp", + "salt", + dns_proto="static", + dns_servers=["192.168.0.10"], + ip_proto="dhcp", ) assert ret == expected diff --git a/tests/pytests/unit/states/test_win_powercfg.py b/tests/pytests/unit/states/test_win_powercfg.py index 450e23c91cd..567037f7f5b 100644 --- a/tests/pytests/unit/states/test_win_powercfg.py +++ b/tests/pytests/unit/states/test_win_powercfg.py @@ -60,7 +60,8 @@ def test_set_monitor_test_true_with_change(): } get_monitor_return_value = MagicMock(return_value={"ac": 45, "dc": 22}) with patch.dict( - powercfg.__salt__, {"powercfg.get_monitor_timeout": get_monitor_return_value}, + powercfg.__salt__, + {"powercfg.get_monitor_timeout": get_monitor_return_value}, ): with patch.dict(powercfg.__opts__, {"test": True}): assert powercfg.set_timeout("monitor", 0) == ret diff --git a/tests/pytests/unit/states/test_zfs.py b/tests/pytests/unit/states/test_zfs.py index aff5f5195e5..b0715ab8584 100644 --- a/tests/pytests/unit/states/test_zfs.py +++ b/tests/pytests/unit/states/test_zfs.py @@ -521,7 +521,8 @@ def test_filesystem_present_update(utils_patch): zfs.__utils__, utils_patch ): assert ret == zfs.filesystem_present( - name="myzpool/filesystem", properties={"compression": "lz4"}, + name="myzpool/filesystem", + properties={"compression": "lz4"}, ) @@ -641,7 +642,9 @@ def test_volume_present_update(utils_patch): zfs.__utils__, utils_patch ): assert ret == zfs.volume_present( - name="myzpool/volume", volume_size="1G", properties={"compression": "lz4"}, + name="myzpool/volume", + volume_size="1G", + properties={"compression": "lz4"}, ) @@ -793,7 +796,10 @@ def test_snapshot_present_fail(utils_patch): return_value=OrderedDict( [ ("snapshotted", False), - ("error", "cannot open 'myzpool/filesystem': dataset does not exist",), + ( + "error", + "cannot open 'myzpool/filesystem': dataset does not exist", + ), ] ) ) diff --git a/tests/pytests/unit/states/test_zpool.py b/tests/pytests/unit/states/test_zpool.py index df64feb51ab..6913b59d35e 100644 --- a/tests/pytests/unit/states/test_zpool.py +++ b/tests/pytests/unit/states/test_zpool.py @@ -403,7 +403,10 @@ def test_present_update_success(utils_patch): ): assert ( zpool.present( - "myzpool", config=config, layout=layout, properties=properties, + "myzpool", + config=config, + layout=layout, + properties=properties, ) == ret ) @@ -485,7 +488,10 @@ def test_present_update_nochange_success(utils_patch): with patch.dict(zpool.__utils__, utils_patch): assert ( zpool.present( - "myzpool", config=config, layout=layout, properties=properties, + "myzpool", + config=config, + layout=layout, + properties=properties, ) == ret ) diff --git a/tests/pytests/unit/states/virt/test_domain.py b/tests/pytests/unit/states/virt/test_domain.py index 0f9326033dc..86cb1cbd39f 100644 --- a/tests/pytests/unit/states/virt/test_domain.py +++ b/tests/pytests/unit/states/virt/test_domain.py @@ -550,7 +550,10 @@ def test_stopped(test, running): changes = {"stopped": [{"domain": "myvm", "shutdown": True}]} comment = "Machine has been shut down" assert virt.stopped( - "myvm", connection="myconnection", username="user", password="secret", + "myvm", + connection="myconnection", + username="user", + password="secret", ) == { "name": "myvm", "changes": changes, @@ -598,7 +601,8 @@ def test_stopped_not_existing(test): with patch.dict(virt.__opts__, {"test": test}): shutdown_mock = MagicMock(return_value=True) with patch.dict( - virt.__salt__, {"virt.list_domains": MagicMock(return_value=[])}, + virt.__salt__, + {"virt.list_domains": MagicMock(return_value=[])}, ): assert virt.stopped("myvm") == { "name": "myvm", @@ -629,7 +633,10 @@ def test_powered_off(test, running): changes = {"unpowered": [{"domain": "myvm", "stop": True}]} comment = "Machine has been powered off" assert virt.powered_off( - "myvm", connection="myconnection", username="user", password="secret", + "myvm", + connection="myconnection", + username="user", + password="secret", ) == { "name": "myvm", "result": True if not test or running == "shutdown" else None, @@ -780,7 +787,10 @@ def test_rebooted(test): }, ): assert virt.rebooted( - "myvm", connection="myconnection", username="user", password="secret", + "myvm", + connection="myconnection", + username="user", + password="secret", ) == { "name": "myvm", "result": True if not test else None, diff --git a/tests/pytests/unit/test_version.py b/tests/pytests/unit/test_version.py index 284e9dc55ee..9a49d449fdf 100644 --- a/tests/pytests/unit/test_version.py +++ b/tests/pytests/unit/test_version.py @@ -467,7 +467,8 @@ def test_system_version_osx(): """ with patch( - "platform.mac_ver", MagicMock(return_value=("10.15.2", ("", "", ""), "x86_64")), + "platform.mac_ver", + MagicMock(return_value=("10.15.2", ("", "", ""), "x86_64")), ): versions = [item for item in system_information()] version = ("version", "10.15.2 x86_64") diff --git a/tests/pytests/unit/transport/test_tcp.py b/tests/pytests/unit/transport/test_tcp.py index 123f688d91d..d003797d29c 100644 --- a/tests/pytests/unit/transport/test_tcp.py +++ b/tests/pytests/unit/transport/test_tcp.py @@ -20,7 +20,8 @@ def message_client_pool(): 0, # port ) with patch( - "salt.transport.tcp.SaltMessageClient.__init__", MagicMock(return_value=None), + "salt.transport.tcp.SaltMessageClient.__init__", + MagicMock(return_value=None), ): message_client_pool = salt.transport.tcp.SaltMessageClientPool( opts, args=message_client_args diff --git a/tests/pytests/unit/transport/test_zeromq.py b/tests/pytests/unit/transport/test_zeromq.py index ce830ab32ba..e0382f4fe6a 100644 --- a/tests/pytests/unit/transport/test_zeromq.py +++ b/tests/pytests/unit/transport/test_zeromq.py @@ -166,7 +166,9 @@ def test_zeromq_async_pub_channel_publish_port(temp_salt_master): assert str(opts["publish_port"]) in patch_socket.mock_calls[0][1][0] -def test_zeromq_async_pub_channel_filtering_decode_message_no_match(temp_salt_master,): +def test_zeromq_async_pub_channel_filtering_decode_message_no_match( + temp_salt_master, +): """ test AsyncZeroMQPubChannel _decode_messages when zmq_filtering enabled and minion does not match diff --git a/tests/pytests/unit/utils/test_cloud.py b/tests/pytests/unit/utils/test_cloud.py index 7c8f954f60f..8fa875cb081 100644 --- a/tests/pytests/unit/utils/test_cloud.py +++ b/tests/pytests/unit/utils/test_cloud.py @@ -98,10 +98,12 @@ def test__save_password_in_keyring(create_class): "fake_password_c8231", ) stored_pw = keyring.get_password( - "salt.cloud.provider.test_case_provider", "fake_username", + "salt.cloud.provider.test_case_provider", + "fake_username", ) keyring.delete_password( - "salt.cloud.provider.test_case_provider", "fake_username", + "salt.cloud.provider.test_case_provider", + "fake_username", ) assert stored_pw == "fake_password_c8231" @@ -151,21 +153,26 @@ def test_deploy_windows_default_port(): """ mock_true = MagicMock(return_value=True) mock_tuple = MagicMock(return_value=(0, 0, 0)) - # fmt: off - with patch("salt.utils.smb.get_conn", MagicMock()) as mock,\ - patch("salt.utils.smb.mkdirs", MagicMock()), \ - patch("salt.utils.smb.put_file", MagicMock()), \ - patch("salt.utils.smb.delete_file", MagicMock()), \ - patch("salt.utils.smb.delete_directory", MagicMock()), \ - patch("time.sleep", MagicMock()),\ - patch.object(cloud, "wait_for_port", mock_true), \ - patch.object(cloud, "fire_event", MagicMock()), \ - patch.object(cloud, "wait_for_psexecsvc", mock_true),\ - patch.object(cloud, "run_psexec_command", mock_tuple): + with patch("salt.utils.smb.get_conn", MagicMock()) as mock, patch( + "salt.utils.smb.mkdirs", MagicMock() + ), patch("salt.utils.smb.put_file", MagicMock()), patch( + "salt.utils.smb.delete_file", MagicMock() + ), patch( + "salt.utils.smb.delete_directory", MagicMock() + ), patch( + "time.sleep", MagicMock() + ), patch.object( + cloud, "wait_for_port", mock_true + ), patch.object( + cloud, "fire_event", MagicMock() + ), patch.object( + cloud, "wait_for_psexecsvc", mock_true + ), patch.object( + cloud, "run_psexec_command", mock_tuple + ): cloud.deploy_windows(host="test", win_installer="") mock.assert_called_once_with("test", "Administrator", None, 445) - # fmt: on @pytest.mark.skip_unless_on_windows(reason="Only applicable for Windows.") @@ -175,21 +182,26 @@ def test_deploy_windows_custom_port(): """ mock_true = MagicMock(return_value=True) mock_tuple = MagicMock(return_value=(0, 0, 0)) - # fmt: off - with patch("salt.utils.smb.get_conn", MagicMock()) as mock, \ - patch("salt.utils.smb.mkdirs", MagicMock()), \ - patch("salt.utils.smb.put_file", MagicMock()), \ - patch("salt.utils.smb.delete_file", MagicMock()), \ - patch("salt.utils.smb.delete_directory", MagicMock()), \ - patch("time.sleep", MagicMock()), \ - patch.object(cloud, "wait_for_port", mock_true), \ - patch.object(cloud, "fire_event", MagicMock()), \ - patch.object(cloud, "wait_for_psexecsvc", mock_true), \ - patch.object(cloud, "run_psexec_command", mock_tuple): + with patch("salt.utils.smb.get_conn", MagicMock()) as mock, patch( + "salt.utils.smb.mkdirs", MagicMock() + ), patch("salt.utils.smb.put_file", MagicMock()), patch( + "salt.utils.smb.delete_file", MagicMock() + ), patch( + "salt.utils.smb.delete_directory", MagicMock() + ), patch( + "time.sleep", MagicMock() + ), patch.object( + cloud, "wait_for_port", mock_true + ), patch.object( + cloud, "fire_event", MagicMock() + ), patch.object( + cloud, "wait_for_psexecsvc", mock_true + ), patch.object( + cloud, "run_psexec_command", mock_tuple + ): cloud.deploy_windows(host="test", port=1234, win_installer="") mock.assert_called_once_with("test", "Administrator", None, 1234) - # fmt: on @pytest.mark.skip_unless_on_windows(reason="Only applicable for Windows.") @@ -199,17 +211,23 @@ def test_winrm_pinnned_version(): """ mock_true = MagicMock(return_value=True) mock_tuple = MagicMock(return_value=(0, 0, 0)) - # fmt: off - with patch("salt.utils.smb.get_conn", MagicMock()),\ - patch("salt.utils.smb.mkdirs", MagicMock()), \ - patch("salt.utils.smb.put_file", MagicMock()), \ - patch("salt.utils.smb.delete_file", MagicMock()), \ - patch("salt.utils.smb.delete_directory", MagicMock()), \ - patch("time.sleep", MagicMock()),\ - patch.object(cloud, "wait_for_port", mock_true), \ - patch.object(cloud, "fire_event", MagicMock()), \ - patch.object(cloud, "wait_for_psexecsvc", mock_true),\ - patch.object(cloud, "run_psexec_command", mock_tuple): + with patch("salt.utils.smb.get_conn", MagicMock()), patch( + "salt.utils.smb.mkdirs", MagicMock() + ), patch("salt.utils.smb.put_file", MagicMock()), patch( + "salt.utils.smb.delete_file", MagicMock() + ), patch( + "salt.utils.smb.delete_directory", MagicMock() + ), patch( + "time.sleep", MagicMock() + ), patch.object( + cloud, "wait_for_port", mock_true + ), patch.object( + cloud, "fire_event", MagicMock() + ), patch.object( + cloud, "wait_for_psexecsvc", mock_true + ), patch.object( + cloud, "run_psexec_command", mock_tuple + ): try: import winrm @@ -217,6 +235,6 @@ def test_winrm_pinnned_version(): raise pytest.skip('The "winrm" python module is not installed in this env.') else: import pkg_resources + winrm_pkg = pkg_resources.get_distribution("pywinrm") - assert winrm_pkg.version >= '0.3.0' - # fmt: on + assert winrm_pkg.version >= "0.3.0" diff --git a/tests/pytests/unit/utils/test_stringutils.py b/tests/pytests/unit/utils/test_stringutils.py index fce145e8544..72b05ecd348 100644 --- a/tests/pytests/unit/utils/test_stringutils.py +++ b/tests/pytests/unit/utils/test_stringutils.py @@ -223,7 +223,10 @@ def test_to_str(unicode): ) assert salt.utils.stringutils.to_str(ut2, "utf-8", "replace") == "\ufffd" assert pytest.raises( - UnicodeDecodeError, salt.utils.stringutils.to_str, bytearray(ut2), "utf-8", + UnicodeDecodeError, + salt.utils.stringutils.to_str, + bytearray(ut2), + "utf-8", ) assert salt.utils.stringutils.to_str(bytearray(ut2), "utf-8", "replace") == "\ufffd" @@ -370,69 +373,89 @@ def test_check_whitelist_blacklist(): # Tests with string whitelist/blacklist assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web_one", whitelist=whitelist[1], blacklist=None, + "web_one", + whitelist=whitelist[1], + blacklist=None, ) is False ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web_one", whitelist=whitelist[1], blacklist=[], + "web_one", + whitelist=whitelist[1], + blacklist=[], ) is False ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web1", whitelist=whitelist[1], blacklist=None, + "web1", + whitelist=whitelist[1], + blacklist=None, ) is True ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web1", whitelist=whitelist[1], blacklist=[], + "web1", + whitelist=whitelist[1], + blacklist=[], ) is True ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web5", whitelist=None, blacklist=blacklist[1], + "web5", + whitelist=None, + blacklist=blacklist[1], ) is False ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web5", whitelist=[], blacklist=blacklist[1], + "web5", + whitelist=[], + blacklist=blacklist[1], ) is False ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web_five", whitelist=None, blacklist=blacklist[1], + "web_five", + whitelist=None, + blacklist=blacklist[1], ) is True ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web_five", whitelist=[], blacklist=blacklist[1], + "web_five", + whitelist=[], + blacklist=blacklist[1], ) is True ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web5", whitelist=whitelist[1], blacklist=blacklist[1], + "web5", + whitelist=whitelist[1], + blacklist=blacklist[1], ) is False ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web4", whitelist=whitelist[1], blacklist=blacklist[1], + "web4", + whitelist=whitelist[1], + blacklist=blacklist[1], ) is True ) @@ -440,67 +463,87 @@ def test_check_whitelist_blacklist(): # Tests with list whitelist/blacklist assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web_one", whitelist=whitelist, blacklist=None, + "web_one", + whitelist=whitelist, + blacklist=None, ) is False ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web_one", whitelist=whitelist, blacklist=[], + "web_one", + whitelist=whitelist, + blacklist=[], ) is False ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web1", whitelist=whitelist, blacklist=None, + "web1", + whitelist=whitelist, + blacklist=None, ) is True ) assert salt.utils.stringutils.check_whitelist_blacklist( - "web1", whitelist=whitelist, blacklist=[], + "web1", + whitelist=whitelist, + blacklist=[], ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web5", whitelist=None, blacklist=blacklist, + "web5", + whitelist=None, + blacklist=blacklist, ) is False ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web5", whitelist=[], blacklist=blacklist, + "web5", + whitelist=[], + blacklist=blacklist, ) is False ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web_five", whitelist=None, blacklist=blacklist, + "web_five", + whitelist=None, + blacklist=blacklist, ) is True ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web_five", whitelist=[], blacklist=blacklist, + "web_five", + whitelist=[], + blacklist=blacklist, ) is True ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web5", whitelist=whitelist, blacklist=blacklist, + "web5", + whitelist=whitelist, + blacklist=blacklist, ) is False ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web4", whitelist=whitelist, blacklist=blacklist, + "web4", + whitelist=whitelist, + blacklist=blacklist, ) is True ) @@ -508,70 +551,90 @@ def test_check_whitelist_blacklist(): # Tests with set whitelist/blacklist assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web_one", whitelist=set(whitelist), blacklist=None, + "web_one", + whitelist=set(whitelist), + blacklist=None, ) is False ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web_one", whitelist=set(whitelist), blacklist=set(), + "web_one", + whitelist=set(whitelist), + blacklist=set(), ) is False ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web1", whitelist=set(whitelist), blacklist=None, + "web1", + whitelist=set(whitelist), + blacklist=None, ) is True ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web1", whitelist=set(whitelist), blacklist=set(), + "web1", + whitelist=set(whitelist), + blacklist=set(), ) is True ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web5", whitelist=None, blacklist=set(blacklist), + "web5", + whitelist=None, + blacklist=set(blacklist), ) is False ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web5", whitelist=set(), blacklist=set(blacklist), + "web5", + whitelist=set(), + blacklist=set(blacklist), ) is False ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web_five", whitelist=None, blacklist=set(blacklist), + "web_five", + whitelist=None, + blacklist=set(blacklist), ) is True ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web_five", whitelist=set(), blacklist=set(blacklist), + "web_five", + whitelist=set(), + blacklist=set(blacklist), ) is True ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web5", whitelist=set(whitelist), blacklist=set(blacklist), + "web5", + whitelist=set(whitelist), + blacklist=set(blacklist), ) is False ) assert ( salt.utils.stringutils.check_whitelist_blacklist( - "web4", whitelist=set(whitelist), blacklist=set(blacklist), + "web4", + whitelist=set(whitelist), + blacklist=set(blacklist), ) is True ) diff --git a/tests/pytests/unit/utils/test_versions.py b/tests/pytests/unit/utils/test_versions.py index f22db05a163..73218765ab8 100644 --- a/tests/pytests/unit/utils/test_versions.py +++ b/tests/pytests/unit/utils/test_versions.py @@ -91,7 +91,13 @@ def test_compare(): @pytest.mark.parametrize( - "version", ("Chlorine", 3007, (3007, 0), salt.version.SaltVersionsInfo.CHLORINE,) + "version", + ( + "Chlorine", + 3007, + (3007, 0), + salt.version.SaltVersionsInfo.CHLORINE, + ), ) def test_warn_until_good_version_argument(version): with pytest.raises( @@ -192,7 +198,7 @@ def test_warn_until_warning_raised(subtests): r"([\d.]+). Please remove the warning." ), ): - raise_named_version_warning(_version_info_=(sys.maxsize, 16, 0,)) + raise_named_version_warning(_version_info_=(sys.maxsize, 16, 0)) with subtests.test( "Even though we're calling warn_until, we pass _dont_call_warnings " @@ -222,7 +228,7 @@ def test_warn_until_warning_raised(subtests): "Hydrogen", "Foo", _dont_call_warnings=True, - _version_info_=(sys.maxsize, 16, 0,), + _version_info_=(sys.maxsize, 16, 0), ) with subtests.test("version on the deprecation message gets properly formatted"): diff --git a/tests/pytests/unit/utils/test_win_functions.py b/tests/pytests/unit/utils/test_win_functions.py index e609a7d2f52..75a52982237 100644 --- a/tests/pytests/unit/utils/test_win_functions.py +++ b/tests/pytests/unit/utils/test_win_functions.py @@ -72,7 +72,7 @@ def test_escape_argument_path_with_space(): @pytest.mark.skip_unless_on_windows(reason="Test is only applicable to Windows.") def test_broadcast_setting_change(): """ - Test to rehash the Environment variables + Test to rehash the Environment variables """ assert win_functions.broadcast_setting_change() diff --git a/tests/saltsh.py b/tests/saltsh.py index b88625c4379..f490de6b93c 100644 --- a/tests/saltsh.py +++ b/tests/saltsh.py @@ -81,7 +81,10 @@ def get_salt_vars(): if __opts__["file_client"] == "local": __pillar__ = salt.pillar.get_pillar( - __opts__, __grains__, __opts__.get("id"), __opts__.get("saltenv"), + __opts__, + __grains__, + __opts__.get("id"), + __opts__.get("saltenv"), ).compile_pillar() else: __pillar__ = {} diff --git a/tests/support/case.py b/tests/support/case.py index 9e2d3f41ccf..e185a113d74 100644 --- a/tests/support/case.py +++ b/tests/support/case.py @@ -149,7 +149,9 @@ class ShellCase(TestCase, AdaptedConfigurationTestCaseMixin, ScriptPathMixin): timeout = self.RUN_TIMEOUT asynchronous = kwargs.get("async", asynchronous) arg_str = "{async_flag} -t {timeout} {}".format( - arg_str, timeout=timeout, async_flag=" --async" if asynchronous else "", + arg_str, + timeout=timeout, + async_flag=" --async" if asynchronous else "", ) ret = self.run_script( "salt-run", diff --git a/tests/support/gitfs.py b/tests/support/gitfs.py index d96cab260ca..cdb3b0b6571 100644 --- a/tests/support/gitfs.py +++ b/tests/support/gitfs.py @@ -375,10 +375,12 @@ def webserver_pillar_tests_prep_authenticated(request, webserver_pillar_tests_pr password=request.cls.password, port=request.cls.nginx_port, ) - url_extra_repo = "http://{username}:{password}@127.0.0.1:{port}/extra_repo.git".format( - username=request.cls.username, - password=request.cls.password, - port=request.cls.nginx_port, + url_extra_repo = ( + "http://{username}:{password}@127.0.0.1:{port}/extra_repo.git".format( + username=request.cls.username, + password=request.cls.password, + port=request.cls.nginx_port, + ) ) request.cls.ext_opts["url"] = url request.cls.ext_opts["url_extra_repo"] = url_extra_repo @@ -476,7 +478,11 @@ class GitPillarTestBase(GitTestBase, LoaderModuleMockMixin): git_opts=self.git_opts, ) self.run_function( - "git.push", [self.admin_repo], remote="origin", ref=branch, user=user, + "git.push", + [self.admin_repo], + remote="origin", + ref=branch, + user=user, ) with salt.utils.files.fopen( diff --git a/tests/support/helpers.py b/tests/support/helpers.py index e77c77ed9af..4c289a363e4 100644 --- a/tests/support/helpers.py +++ b/tests/support/helpers.py @@ -739,7 +739,7 @@ def with_system_user( return func(cls, username) except Exception as exc: # pylint: disable=W0703 log.error( - "Running %r raised an exception: %s", func, exc, exc_info=True, + "Running %r raised an exception: %s", func, exc, exc_info=True ) # Store the original exception details which will be raised # a little further down the code @@ -833,7 +833,7 @@ def with_system_group(group, on_existing="delete", delete=True): return func(cls, group) except Exception as exc: # pylint: disable=W0703 log.error( - "Running %r raised an exception: %s", func, exc, exc_info=True, + "Running %r raised an exception: %s", func, exc, exc_info=True ) # Store the original exception details which will be raised # a little further down the code @@ -957,7 +957,7 @@ def with_system_user_and_group(username, group, on_existing="delete", delete=Tru return func(cls, username, group) except Exception as exc: # pylint: disable=W0703 log.error( - "Running %r raised an exception: %s", func, exc, exc_info=True, + "Running %r raised an exception: %s", func, exc, exc_info=True ) # Store the original exception details which will be raised # a little further down the code diff --git a/tests/support/pytest/loader.py b/tests/support/pytest/loader.py index d814b743600..9af714a1e1f 100644 --- a/tests/support/pytest/loader.py +++ b/tests/support/pytest/loader.py @@ -42,7 +42,10 @@ class LoaderModuleMock: ) # These dunders might exist at the module global scope salt_module_dunders_optional = attr.ib( - init=True, repr=False, kw_only=True, default=("__proxy__",), + init=True, + repr=False, + kw_only=True, + default=("__proxy__",), ) # These dunders might exist at the function global scope salt_module_dunder_attributes = attr.ib( @@ -110,7 +113,10 @@ class LoaderModuleMock: func(*args, **kwargs) except Exception as exc: # pylint: disable=broad-except log.error( - "Failed to run finalizer %s: %s", func_repr, exc, exc_info=True, + "Failed to run finalizer %s: %s", + func_repr, + exc, + exc_info=True, ) def addfinalizer(self, func, *args, **kwargs): @@ -154,13 +160,15 @@ class LoaderModuleMock: if key in ("__init__", "__virtual__"): raise RuntimeError( "No need to patch {!r}. Passed loader module dict: {}".format( - key, self.setup_loader_modules, + key, + self.setup_loader_modules, ) ) elif key not in allowed_salt_dunders: raise RuntimeError( "Don't know how to handle {!r}. Passed loader module dict: {}".format( - key, self.setup_loader_modules, + key, + self.setup_loader_modules, ) ) elif key in salt_dunder_dicts and not hasattr(module, key): diff --git a/tests/unit/beacons/test_journald.py b/tests/unit/beacons/test_journald.py index f067ffd4404..b7ad2e9ff25 100644 --- a/tests/unit/beacons/test_journald.py +++ b/tests/unit/beacons/test_journald.py @@ -49,7 +49,7 @@ _STUB_JOURNALD_ENTRY = { class SystemdJournaldMock(Mock): - """ Request Mock""" + """Request Mock""" returned_once = False diff --git a/tests/unit/beacons/test_salt_monitor.py b/tests/unit/beacons/test_salt_monitor.py index 59275cd98fe..56691a6c476 100644 --- a/tests/unit/beacons/test_salt_monitor.py +++ b/tests/unit/beacons/test_salt_monitor.py @@ -17,7 +17,18 @@ TEST_CONFIG = [ }, { "config": [ - {"salt_fun": [{"cmd.run": {"args": ["echo hello world",]}}, "test.version"]} + { + "salt_fun": [ + { + "cmd.run": { + "args": [ + "echo hello world", + ] + } + }, + "test.version", + ] + } ], # *args behaves weird on list with single string, does it happen in yaml? "expected_validate": (True, "valid config"), "expected_beacon": [ @@ -35,7 +46,9 @@ TEST_CONFIG = [ "salt_fun": [ { "cmd.run": { - "args": ["echo hello world",], + "args": [ + "echo hello world", + ], "kwargs": [{"shell": "ps"}], } } diff --git a/tests/unit/beacons/test_telegram_bot_msg.py b/tests/unit/beacons/test_telegram_bot_msg.py index eb21ecec430..abc9d269edf 100644 --- a/tests/unit/beacons/test_telegram_bot_msg.py +++ b/tests/unit/beacons/test_telegram_bot_msg.py @@ -35,21 +35,28 @@ class TelegramBotMsgBeaconTestCase(TestCase, LoaderModuleMockMixin): def test_validate_empty_config(self, *args, **kwargs): ret = telegram_bot_msg.validate(None) self.assertEqual( - ret, (False, ("Configuration for telegram_bot_msg beacon must be a list.")), + ret, + (False, ("Configuration for telegram_bot_msg beacon must be a list.")), ) def test_validate_missing_accept_from_config(self, *args, **kwargs): ret = telegram_bot_msg.validate([{"token": "bcd"}]) self.assertEqual( ret, - (False, ("Not all required configuration for telegram_bot_msg are set."),), + ( + False, + ("Not all required configuration for telegram_bot_msg are set."), + ), ) def test_validate_missing_token_config(self, *args, **kwargs): ret = telegram_bot_msg.validate([{"accept_from": []}]) self.assertEqual( ret, - (False, ("Not all required configuration for telegram_bot_msg are set."),), + ( + False, + ("Not all required configuration for telegram_bot_msg are set."), + ), ) def test_validate_config_not_list_in_accept_from(self, *args, **kwargs): diff --git a/tests/unit/client/test_ssh.py b/tests/unit/client/test_ssh.py index 24f6752a4e5..6f3d87d493c 100644 --- a/tests/unit/client/test_ssh.py +++ b/tests/unit/client/test_ssh.py @@ -177,8 +177,7 @@ class SSHSingleTests(TestCase): } def test_single_opts(self): - """ Sanity check for ssh.Single options - """ + """Sanity check for ssh.Single options""" single = ssh.Single( self.opts, diff --git a/tests/unit/cloud/clouds/test_digitalocean.py b/tests/unit/cloud/clouds/test_digitalocean.py index 4763627d852..5ebcc493101 100644 --- a/tests/unit/cloud/clouds/test_digitalocean.py +++ b/tests/unit/cloud/clouds/test_digitalocean.py @@ -26,7 +26,9 @@ class DigitalOceanTestCase(TestCase): kwargs that are provided do not include an action. """ self.assertRaises( - SaltCloudSystemExit, digitalocean.reboot, name="fake_name", + SaltCloudSystemExit, + digitalocean.reboot, + name="fake_name", ) with self.assertRaises(SaltCloudSystemExit) as excinfo: diff --git a/tests/unit/cloud/clouds/test_openstack.py b/tests/unit/cloud/clouds/test_openstack.py index cdcd6ef1d58..e17d21b5bc2 100644 --- a/tests/unit/cloud/clouds/test_openstack.py +++ b/tests/unit/cloud/clouds/test_openstack.py @@ -265,7 +265,8 @@ class OpenstackTestCase(TestCase, LoaderModuleMockMixin): "thisgetsdropped": "yup", } patch_utils = patch.dict( - openstack.__utils__, {"dictupdate.update": dictupdate.update}, + openstack.__utils__, + {"dictupdate.update": dictupdate.update}, ) with patch_utils: ret = openstack._clean_create_kwargs(**params) diff --git a/tests/unit/cloud/clouds/test_proxmox.py b/tests/unit/cloud/clouds/test_proxmox.py index c0f27a13628..a86227ed23b 100644 --- a/tests/unit/cloud/clouds/test_proxmox.py +++ b/tests/unit/cloud/clouds/test_proxmox.py @@ -122,7 +122,9 @@ class ProxmoxTest(TestCase, LoaderModuleMockMixin): # CASE 1: Numeric ID result = proxmox.create_node(vm_, ANY) mock_query.assert_called_once_with( - "post", "nodes/myhost/qemu/123/clone", {"newid": ANY}, + "post", + "nodes/myhost/qemu/123/clone", + {"newid": ANY}, ) assert result == {} @@ -131,7 +133,9 @@ class ProxmoxTest(TestCase, LoaderModuleMockMixin): vm_["clone_from"] = "otherhost:123" result = proxmox.create_node(vm_, ANY) mock_query.assert_called_once_with( - "post", "nodes/otherhost/qemu/123/clone", {"newid": ANY}, + "post", + "nodes/otherhost/qemu/123/clone", + {"newid": ANY}, ) assert result == {} diff --git a/tests/unit/fileserver/test_gitfs.py b/tests/unit/fileserver/test_gitfs.py index 58d323a4540..70e663ee35c 100644 --- a/tests/unit/fileserver/test_gitfs.py +++ b/tests/unit/fileserver/test_gitfs.py @@ -556,7 +556,9 @@ class GitFSTestBase: raise shutil.copytree( - str(RUNTIME_VARS.BASE_FILES), str(cls.tmp_repo_dir + "/"), symlinks=True, + str(RUNTIME_VARS.BASE_FILES), + str(cls.tmp_repo_dir + "/"), + symlinks=True, ) repo = git.Repo.init(cls.tmp_repo_dir) diff --git a/tests/unit/modules/nxos/nxos_n36k.py b/tests/unit/modules/nxos/nxos_n36k.py index a956e46ed49..0c299f9176e 100644 --- a/tests/unit/modules/nxos/nxos_n36k.py +++ b/tests/unit/modules/nxos/nxos_n36k.py @@ -20,7 +20,7 @@ from tests.unit.modules.nxos.nxos_platform import NXOSPlatform class N36KPlatform(NXOSPlatform): - """ Cisco Systems N36K Platform Unit Test Object """ + """Cisco Systems N36K Platform Unit Test Object""" chassis = "Nexus3000 N3K-C36180YC-R Chassis" diff --git a/tests/unit/modules/nxos/nxos_n3k.py b/tests/unit/modules/nxos/nxos_n3k.py index c0e81e54503..80a714cbba5 100644 --- a/tests/unit/modules/nxos/nxos_n3k.py +++ b/tests/unit/modules/nxos/nxos_n3k.py @@ -20,7 +20,7 @@ from tests.unit.modules.nxos.nxos_platform import NXOSPlatform class N3KPlatform(NXOSPlatform): - """ Cisco Systems N3K Platform Unit Test Object """ + """Cisco Systems N3K Platform Unit Test Object""" chassis = "Nexus 3172 Chassis" diff --git a/tests/unit/modules/nxos/nxos_n5k.py b/tests/unit/modules/nxos/nxos_n5k.py index 43d8739c399..97c96dccc37 100644 --- a/tests/unit/modules/nxos/nxos_n5k.py +++ b/tests/unit/modules/nxos/nxos_n5k.py @@ -20,7 +20,7 @@ from tests.unit.modules.nxos.nxos_platform import NXOSPlatform class N5KPlatform(NXOSPlatform): - """ Cisco Systems N5K Platform Unit Test Object """ + """Cisco Systems N5K Platform Unit Test Object""" chassis = "cisco Nexus 5672UP 16G-FC Chassis" diff --git a/tests/unit/modules/nxos/nxos_n7k.py b/tests/unit/modules/nxos/nxos_n7k.py index 1c94f73caab..23fce54d99b 100644 --- a/tests/unit/modules/nxos/nxos_n7k.py +++ b/tests/unit/modules/nxos/nxos_n7k.py @@ -20,7 +20,7 @@ from tests.unit.modules.nxos.nxos_platform import NXOSPlatform class N7KPlatform(NXOSPlatform): - """ Cisco Systems N7K Platform Unit Test Object """ + """Cisco Systems N7K Platform Unit Test Object""" chassis = "Nexus7000 C7010 (10 Slot) Chassis" diff --git a/tests/unit/modules/nxos/nxos_n93k.py b/tests/unit/modules/nxos/nxos_n93k.py index da78a369524..ed44ab3a06d 100644 --- a/tests/unit/modules/nxos/nxos_n93k.py +++ b/tests/unit/modules/nxos/nxos_n93k.py @@ -20,7 +20,7 @@ from tests.unit.modules.nxos.nxos_platform import NXOSPlatform class N93KPlatform(NXOSPlatform): - """ Cisco Systems N93K Platform Unit Test Object """ + """Cisco Systems N93K Platform Unit Test Object""" chassis = "Nexus9000 C9396PX Chassis" diff --git a/tests/unit/modules/nxos/nxos_n93klxc.py b/tests/unit/modules/nxos/nxos_n93klxc.py index 2b9f5c0a2fb..949c88d8eae 100644 --- a/tests/unit/modules/nxos/nxos_n93klxc.py +++ b/tests/unit/modules/nxos/nxos_n93klxc.py @@ -20,7 +20,7 @@ from tests.unit.modules.nxos.nxos_platform import NXOSPlatform class N93KLXCPlatform(NXOSPlatform): - """ Cisco Systems N93K (boot mode lxc) Platform Unit Test Object """ + """Cisco Systems N93K (boot mode lxc) Platform Unit Test Object""" chassis = "Nexus9000 C9396PX (LXC) Chassis" diff --git a/tests/unit/modules/nxos/nxos_n95k.py b/tests/unit/modules/nxos/nxos_n95k.py index 31f99303ee0..9fa3300ecfb 100644 --- a/tests/unit/modules/nxos/nxos_n95k.py +++ b/tests/unit/modules/nxos/nxos_n95k.py @@ -22,7 +22,7 @@ from tests.unit.modules.nxos.nxos_platform import NXOSPlatform class N95KPlatform(NXOSPlatform): - """ Cisco Systems N9K Platform Unit Test Object """ + """Cisco Systems N9K Platform Unit Test Object""" chassis = "Nexus9000 C9508 (8 Slot) Chassis" diff --git a/tests/unit/modules/nxos/nxos_platform.py b/tests/unit/modules/nxos/nxos_platform.py index a238d8ee14b..05795c23b26 100644 --- a/tests/unit/modules/nxos/nxos_platform.py +++ b/tests/unit/modules/nxos/nxos_platform.py @@ -26,7 +26,7 @@ from string import Template class NXOSPlatform: - """ Cisco Systems Base Platform Unit Test Object """ + """Cisco Systems Base Platform Unit Test Object""" chassis = "Unknown NXOS Chassis" @@ -108,10 +108,10 @@ Module Image Running-Version(pri:alt) New-Versi def __init__(self, *args, **kwargs): """ - ckimage - current kickstart image - cimage - current system image - nkimage - new kickstart image - nimage - new system image + ckimage - current kickstart image + cimage - current system image + nkimage - new kickstart image + nimage - new system image """ self.ckimage = kwargs.get("ckimage", None) @@ -164,14 +164,14 @@ Module Image Running-Version(pri:alt) New-Versi @staticmethod def templatize(template, values): - """ Substitute variables in template with their corresponding values """ + """Substitute variables in template with their corresponding values""" return Template(template).substitute(values) @staticmethod def version_from_image(image): - """ Given a NXOS image named image decompose to appropriate image version """ + """Given a NXOS image named image decompose to appropriate image version""" ver = None if image: diff --git a/tests/unit/modules/test_artifactory.py b/tests/unit/modules/test_artifactory.py index 5ac7f2dfbec..b82cd2c8968 100644 --- a/tests/unit/modules/test_artifactory.py +++ b/tests/unit/modules/test_artifactory.py @@ -304,7 +304,8 @@ class ArtifactoryTestCase(TestCase, LoaderModuleMockMixin): def test_get_latest_release_username_password(self): with patch( - "salt.modules.artifactory.__find_latest_version", return_value="1.1", + "salt.modules.artifactory.__find_latest_version", + return_value="1.1", ), patch( "salt.modules.artifactory._get_release_url", return_value=( diff --git a/tests/unit/modules/test_at.py b/tests/unit/modules/test_at.py index bb6e32ceafd..3bfb005d28c 100644 --- a/tests/unit/modules/test_at.py +++ b/tests/unit/modules/test_at.py @@ -233,7 +233,7 @@ class AtTestCase(TestCase, LoaderModuleMockMixin): def test_atc(self): """ - Tests for atc + Tests for atc """ with patch.object(at, "_cmd", return_value=None): self.assertEqual(at.atc(101), "'at.atc' is not available.") diff --git a/tests/unit/modules/test_bluez_bluetooth.py b/tests/unit/modules/test_bluez_bluetooth.py index 3cf53748966..ed5cf5b0a43 100644 --- a/tests/unit/modules/test_bluez_bluetooth.py +++ b/tests/unit/modules/test_bluez_bluetooth.py @@ -13,7 +13,7 @@ from tests.support.unit import TestCase class MockBluetooth: """ - Mock class for bluetooth + Mock class for bluetooth """ def __init__(self): @@ -22,14 +22,14 @@ class MockBluetooth: @staticmethod def discover_devices(lookup_names): """ - Mock method to return all Discoverable devices + Mock method to return all Discoverable devices """ return [["a", "b", "c"], ["d", "e", "f"]] class BluezTestCase(TestCase, LoaderModuleMockMixin): """ - Test cases for salt.modules.bluez + Test cases for salt.modules.bluez """ def setup_loader_modules(self): @@ -37,7 +37,7 @@ class BluezTestCase(TestCase, LoaderModuleMockMixin): def test_version(self): """ - Test if return bluetooth version + Test if return bluetooth version """ mock = MagicMock(return_value="5.7") with patch.dict(bluez.__salt__, {"cmd.run": mock}): @@ -48,7 +48,7 @@ class BluezTestCase(TestCase, LoaderModuleMockMixin): def test_address_(self): """ - Test of getting address of bluetooth adapter + Test of getting address of bluetooth adapter """ mock = MagicMock(return_value="hci : hci0") with patch.dict(bluez.__salt__, {"cmd.run": mock}): @@ -59,7 +59,7 @@ class BluezTestCase(TestCase, LoaderModuleMockMixin): def test_power(self): """ - Test of getting address of bluetooth adapter + Test of getting address of bluetooth adapter """ mock = MagicMock(return_value={}) with patch.object(bluez, "address_", mock): @@ -79,7 +79,7 @@ class BluezTestCase(TestCase, LoaderModuleMockMixin): def test_discoverable(self): """ - Test of enabling bluetooth device + Test of enabling bluetooth device """ mock = MagicMock( side_effect=[ @@ -101,7 +101,7 @@ class BluezTestCase(TestCase, LoaderModuleMockMixin): def test_noscan(self): """ - Test of turning off of scanning modes + Test of turning off of scanning modes """ mock = MagicMock( side_effect=[ @@ -123,13 +123,13 @@ class BluezTestCase(TestCase, LoaderModuleMockMixin): def test_scan(self): """ - Test of scanning of bluetooth devices + Test of scanning of bluetooth devices """ self.assertListEqual(bluez.scan(), [{"a": "b"}, {"d": "e"}]) def test_block(self): """ - Test of blocking specific bluetooth device + Test of blocking specific bluetooth device """ mock = MagicMock(side_effect=[False, True]) with patch.object(salt.utils.validate.net, "mac", mock): @@ -141,7 +141,7 @@ class BluezTestCase(TestCase, LoaderModuleMockMixin): def test_unblock(self): """ - Test to unblock specific bluetooth device + Test to unblock specific bluetooth device """ mock = MagicMock(side_effect=[False, True]) with patch.object(salt.utils.validate.net, "mac", mock): @@ -153,7 +153,7 @@ class BluezTestCase(TestCase, LoaderModuleMockMixin): def test_pair(self): """ - Test to pair bluetooth adapter with a device + Test to pair bluetooth adapter with a device """ mock = MagicMock(side_effect=[False, True, True]) with patch.object(salt.utils.validate.net, "mac", mock): @@ -175,7 +175,7 @@ class BluezTestCase(TestCase, LoaderModuleMockMixin): def test_unpair(self): """ - Test to unpair bluetooth adaptor with a device + Test to unpair bluetooth adaptor with a device """ mock = MagicMock(side_effect=[False, True]) with patch.object(salt.utils.validate.net, "mac", mock): @@ -187,7 +187,7 @@ class BluezTestCase(TestCase, LoaderModuleMockMixin): def test_start(self): """ - Test to start bluetooth service + Test to start bluetooth service """ mock = MagicMock(return_value="Ok") with patch.dict(bluez.__salt__, {"service.start": mock}): @@ -195,7 +195,7 @@ class BluezTestCase(TestCase, LoaderModuleMockMixin): def test_stop(self): """ - Test to stop bluetooth service + Test to stop bluetooth service """ mock = MagicMock(return_value="Ok") with patch.dict(bluez.__salt__, {"service.stop": mock}): diff --git a/tests/unit/modules/test_boto3_elasticsearch.py b/tests/unit/modules/test_boto3_elasticsearch.py index 9e568c14446..2d75d2a8bb9 100644 --- a/tests/unit/modules/test_boto3_elasticsearch.py +++ b/tests/unit/modules/test_boto3_elasticsearch.py @@ -761,8 +761,10 @@ class Boto3ElasticsearchTestCase(TestCase, LoaderModuleMockMixin): ERROR_CONTENT, "describe_reserved_elasticsearch_instance_offerings" ), ): - result = boto3_elasticsearch.describe_reserved_elasticsearch_instance_offerings( - reserved_elasticsearch_instance_offering_id="foo", **CONN_PARAMETERS + result = ( + boto3_elasticsearch.describe_reserved_elasticsearch_instance_offerings( + reserved_elasticsearch_instance_offering_id="foo", **CONN_PARAMETERS + ) ) self.assertFalse(result["result"]) self.assertEqual( @@ -1134,10 +1136,12 @@ class Boto3ElasticsearchTestCase(TestCase, LoaderModuleMockMixin): ERROR_CONTENT, "purchase_reserved_elasticsearch_instance_offering" ), ): - result = boto3_elasticsearch.purchase_reserved_elasticsearch_instance_offering( - reserved_elasticsearch_instance_offering_id="foo", - reservation_name="bar", - **CONN_PARAMETERS + result = ( + boto3_elasticsearch.purchase_reserved_elasticsearch_instance_offering( + reserved_elasticsearch_instance_offering_id="foo", + reservation_name="bar", + **CONN_PARAMETERS + ) ) self.assertFalse(result["result"]) self.assertEqual( diff --git a/tests/unit/modules/test_boto_cloudwatch_event.py b/tests/unit/modules/test_boto_cloudwatch_event.py index 0cd885a4a1c..98bc3b98fd3 100644 --- a/tests/unit/modules/test_boto_cloudwatch_event.py +++ b/tests/unit/modules/test_boto_cloudwatch_event.py @@ -71,8 +71,12 @@ if _has_required_boto(): ScheduleExpression=rule_sched, State="ENABLED", ) - create_rule_ret = dict(Name=rule_name,) - target_ret = dict(Id="target1",) + create_rule_ret = dict( + Name=rule_name, + ) + target_ret = dict( + Id="target1", + ) class BotoCloudWatchEventTestCaseBase(TestCase, LoaderModuleMockMixin): diff --git a/tests/unit/modules/test_boto_route53.py b/tests/unit/modules/test_boto_route53.py index 382465eae49..1d3d1393a93 100644 --- a/tests/unit/modules/test_boto_route53.py +++ b/tests/unit/modules/test_boto_route53.py @@ -193,7 +193,10 @@ class BotoRoute53RetryTestCase(TestCase, LoaderModuleMockMixin): # Retryable error (max retries reached) conn = DummyConn(get_zone=[self._retryable_error, self._retryable_error]) with patch.object(boto_route53, "_get_conn", MagicMock(return_value=conn)): - result = boto_route53.zone_exists("foo", error_retries=2,) + result = boto_route53.zone_exists( + "foo", + error_retries=2, + ) assert conn.get_zone.call_count == 2 assert result is False @@ -225,7 +228,10 @@ class BotoRoute53RetryTestCase(TestCase, LoaderModuleMockMixin): create_health_check=[self._retryable_error, self._retryable_error] ) with patch.object(boto_route53, "_get_conn", MagicMock(return_value=conn)): - result = boto_route53.create_healthcheck("foo", error_retries=2,) + result = boto_route53.create_healthcheck( + "foo", + error_retries=2, + ) assert conn.create_health_check.call_count == 2 assert result is False @@ -250,7 +256,12 @@ class BotoRoute53RetryTestCase(TestCase, LoaderModuleMockMixin): # Retryable error (max retries reached) conn = DummyConn(get_zone=[self._retryable_error, self._retryable_error]) with patch.object(boto_route53, "_get_conn", MagicMock(return_value=conn)): - result = boto_route53.get_record("foo", "bar", "baz", error_retries=2,) + result = boto_route53.get_record( + "foo", + "bar", + "baz", + error_retries=2, + ) assert conn.get_zone.call_count == 2 assert not result @@ -287,7 +298,13 @@ class BotoRoute53RetryTestCase(TestCase, LoaderModuleMockMixin): zone.id = "foo" conn = DummyConn(get_zone=[zone]) with patch.object(boto_route53, "_get_conn", MagicMock(return_value=conn)): - result = boto_route53.add_record("a", "b", "c", "d", error_retries=2,) + result = boto_route53.add_record( + "a", + "b", + "c", + "d", + error_retries=2, + ) assert zone.add_record.call_count == 2 assert not result @@ -322,7 +339,13 @@ class BotoRoute53RetryTestCase(TestCase, LoaderModuleMockMixin): zone = DummyConn(find_records=[self._retryable_error, self._retryable_error]) conn = DummyConn(get_zone=[zone]) with patch.object(boto_route53, "_get_conn", MagicMock(return_value=conn)): - result = boto_route53.update_record("a", "b", "c", "d", error_retries=2,) + result = boto_route53.update_record( + "a", + "b", + "c", + "d", + error_retries=2, + ) assert zone.find_records.call_count == 2 assert not result @@ -358,7 +381,13 @@ class BotoRoute53RetryTestCase(TestCase, LoaderModuleMockMixin): zone = DummyConn(find_records=[self._retryable_error, self._retryable_error]) conn = DummyConn(get_zone=[zone]) with patch.object(boto_route53, "_get_conn", MagicMock(return_value=conn)): - result = boto_route53.delete_record("a", "b", "c", "d", error_retries=2,) + result = boto_route53.delete_record( + "a", + "b", + "c", + "d", + error_retries=2, + ) assert zone.find_records.call_count == 2 assert not result diff --git a/tests/unit/modules/test_boto_vpc.py b/tests/unit/modules/test_boto_vpc.py index 2924df3df27..e18c70538db 100644 --- a/tests/unit/modules/test_boto_vpc.py +++ b/tests/unit/modules/test_boto_vpc.py @@ -1787,8 +1787,10 @@ class BotoVpcNetworkACLTestCase(BotoVpcTestCaseBase, BotoVpcTestCaseMixin): vpc = self._create_vpc() subnet = self._create_subnet(vpc.id) - network_acl_creation_and_association_result = boto_vpc.associate_new_network_acl_to_subnet( - vpc.id, subnet.id, **conn_parameters + network_acl_creation_and_association_result = ( + boto_vpc.associate_new_network_acl_to_subnet( + vpc.id, subnet.id, **conn_parameters + ) ) self.assertTrue(network_acl_creation_and_association_result) @@ -1804,8 +1806,10 @@ class BotoVpcNetworkACLTestCase(BotoVpcTestCaseBase, BotoVpcTestCaseMixin): vpc = self._create_vpc() subnet = self._create_subnet(vpc.id) - network_acl_creation_and_association_result = boto_vpc.associate_new_network_acl_to_subnet( - vpc.id, subnet.id, network_acl_name="test", **conn_parameters + network_acl_creation_and_association_result = ( + boto_vpc.associate_new_network_acl_to_subnet( + vpc.id, subnet.id, network_acl_name="test", **conn_parameters + ) ) self.assertTrue(network_acl_creation_and_association_result) @@ -1821,8 +1825,10 @@ class BotoVpcNetworkACLTestCase(BotoVpcTestCaseBase, BotoVpcTestCaseMixin): vpc = self._create_vpc() subnet = self._create_subnet(vpc.id) - network_acl_creation_and_association_result = boto_vpc.associate_new_network_acl_to_subnet( - vpc.id, subnet.id, tags={"test": "testvalue"}, **conn_parameters + network_acl_creation_and_association_result = ( + boto_vpc.associate_new_network_acl_to_subnet( + vpc.id, subnet.id, tags={"test": "testvalue"}, **conn_parameters + ) ) self.assertTrue(network_acl_creation_and_association_result) @@ -1837,8 +1843,10 @@ class BotoVpcNetworkACLTestCase(BotoVpcTestCaseBase, BotoVpcTestCaseMixin): """ vpc = self._create_vpc() - network_acl_creation_and_association_result = boto_vpc.associate_new_network_acl_to_subnet( - vpc.id, "fake", **conn_parameters + network_acl_creation_and_association_result = ( + boto_vpc.associate_new_network_acl_to_subnet( + vpc.id, "fake", **conn_parameters + ) ) self.assertFalse(network_acl_creation_and_association_result) diff --git a/tests/unit/modules/test_dockermod.py b/tests/unit/modules/test_dockermod.py index fcedaf92728..85c8ff58507 100644 --- a/tests/unit/modules/test_dockermod.py +++ b/tests/unit/modules/test_dockermod.py @@ -64,10 +64,12 @@ class DockerUnitTestCase(TestCase, LoaderModuleMockMixin): extra_pillar_data = {"some": "extras"} fake_trans_tar = MagicMock(return_value=b"hi") patch_trans_tar = patch( - "salt.modules.dockermod._prepare_trans_tar", fake_trans_tar, + "salt.modules.dockermod._prepare_trans_tar", + fake_trans_tar, ) patch_call = patch( - "salt.modules.dockermod.call", MagicMock(return_value=expected_grains), + "salt.modules.dockermod.call", + MagicMock(return_value=expected_grains), ) fake_get_pillar = MagicMock() fake_get_pillar.compile_pillar.return_value = expected_pillars @@ -619,8 +621,12 @@ class DockerTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(docker_mod.__dict__, {"__salt__": __salt__}): with patch.object(docker_mod, "_get_client", get_client_mock): - docker_mod.volumes(filters={"dangling": [True]},) - client.volumes.assert_called_once_with(filters={"dangling": [True]},) + docker_mod.volumes( + filters={"dangling": [True]}, + ) + client.volumes.assert_called_once_with( + filters={"dangling": [True]}, + ) @skipIf( docker_version < (1, 5, 0), @@ -641,10 +647,14 @@ class DockerTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(docker_mod.__dict__, {"__salt__": __salt__}): with patch.object(docker_mod, "_get_client", get_client_mock): docker_mod.create_volume( - "foo", driver="bridge", driver_opts={}, + "foo", + driver="bridge", + driver_opts={}, ) client.create_volume.assert_called_once_with( - "foo", driver="bridge", driver_opts={}, + "foo", + driver="bridge", + driver_opts={}, ) @skipIf( diff --git a/tests/unit/modules/test_file.py b/tests/unit/modules/test_file.py index 966c304ef66..99700ac21b7 100644 --- a/tests/unit/modules/test_file.py +++ b/tests/unit/modules/test_file.py @@ -1473,14 +1473,16 @@ class FilemodLineTests(TestCase, LoaderModuleMockMixin): with self.assertRaises(CommandExecutionError) as err: filemod._set_line(lines=[], mode=None) self.assertEqual( - err.exception.args[0], "Mode was not defined. How to process the file?", + err.exception.args[0], + "Mode was not defined. How to process the file?", ) def test_set_line_should_raise_command_execution_error_with_unknown_mode(self): with self.assertRaises(CommandExecutionError) as err: filemod._set_line(lines=[], mode="fnord") self.assertEqual( - err.exception.args[0], "Unknown mode: fnord", + err.exception.args[0], + "Unknown mode: fnord", ) def test_if_content_is_none_and_mode_is_valid_but_not_delete_it_should_raise_command_execution_error( @@ -1491,7 +1493,8 @@ class FilemodLineTests(TestCase, LoaderModuleMockMixin): with self.assertRaises(CommandExecutionError) as err: filemod._set_line(lines=[], mode=mode) self.assertEqual( - err.exception.args[0], "Content can only be empty if mode is delete", + err.exception.args[0], + "Content can only be empty if mode is delete", ) def test_if_delete_or_replace_is_called_with_empty_lines_it_should_warn_and_return_empty_body( @@ -1537,7 +1540,10 @@ class FilemodLineTests(TestCase, LoaderModuleMockMixin): expected_lines = ["foo", replacement, "bar"] actual_lines = filemod._set_line( - mode="replace", lines=original_lines, content=replacement, match=to_replace, + mode="replace", + lines=original_lines, + content=replacement, + match=to_replace, ) self.assertEqual(actual_lines, expected_lines) @@ -1607,7 +1613,10 @@ class FilemodLineTests(TestCase, LoaderModuleMockMixin): with patch("os.linesep", ""): actual_lines = filemod._set_line( - lines=lines, content=content, mode="insert", location="start", + lines=lines, + content=content, + mode="insert", + location="start", ) self.assertEqual(actual_lines, expected_lines) @@ -1621,7 +1630,10 @@ class FilemodLineTests(TestCase, LoaderModuleMockMixin): expected_lines = [content + linesep] + lines actual_lines = filemod._set_line( - lines=lines, content=content, mode="insert", location="start", + lines=lines, + content=content, + mode="insert", + location="start", ) self.assertEqual(actual_lines, expected_lines) @@ -1635,7 +1647,10 @@ class FilemodLineTests(TestCase, LoaderModuleMockMixin): with patch("os.linesep", fake_linesep): actual_lines = filemod._set_line( - lines=[], content=content, mode="insert", location="start", + lines=[], + content=content, + mode="insert", + location="start", ) self.assertEqual(actual_lines, expected_lines) @@ -1645,7 +1660,10 @@ class FilemodLineTests(TestCase, LoaderModuleMockMixin): expected_lines = [content] actual_lines = filemod._set_line( - lines=[], content=content, mode="insert", location="end", + lines=[], + content=content, + mode="insert", + location="end", ) self.assertEqual(actual_lines, expected_lines) @@ -1834,7 +1852,8 @@ class FilemodLineTests(TestCase, LoaderModuleMockMixin): after=after, ) self.assertEqual( - err.exception.args[0], "Neither before or after was found in file", + err.exception.args[0], + "Neither before or after was found in file", ) def test_if_not_location_or_before_and_no_after_in_lines_it_should_CommandExecutionError( @@ -1855,7 +1874,8 @@ class FilemodLineTests(TestCase, LoaderModuleMockMixin): after=after, ) self.assertEqual( - err.exception.args[0], "Neither before or after was found in file", + err.exception.args[0], + "Neither before or after was found in file", ) def test_if_not_location_or_before_but_after_then_line_should_be_inserted_after_after( @@ -1886,7 +1906,10 @@ class FilemodLineTests(TestCase, LoaderModuleMockMixin): original_lines = [after, content + line_endings] actual_lines = filemod._set_line( - lines=original_lines[:], content=content, mode="insert", after=after, + lines=original_lines[:], + content=content, + mode="insert", + after=after, ) self.assertEqual(actual_lines, original_lines) @@ -1898,7 +1921,10 @@ class FilemodLineTests(TestCase, LoaderModuleMockMixin): original_lines = [content + line_endings, before] actual_lines = filemod._set_line( - lines=original_lines[:], content=content, mode="insert", before=before, + lines=original_lines[:], + content=content, + mode="insert", + before=before, ) self.assertEqual(actual_lines, original_lines) @@ -1997,7 +2023,10 @@ class FilemodLineTests(TestCase, LoaderModuleMockMixin): original_lines = [content, before] actual_lines = filemod._set_line( - lines=original_lines[:], content=content, mode="insert", before=before, + lines=original_lines[:], + content=content, + mode="insert", + before=before, ) self.assertEqual(actual_lines, original_lines) @@ -2069,7 +2098,10 @@ class FilemodLineTests(TestCase, LoaderModuleMockMixin): with self.assertRaises(CommandExecutionError) as err: filemod._set_line( - lines=bad_lines, content="asdf", after=after, mode="ensure", + lines=bad_lines, + content="asdf", + after=after, + mode="ensure", ) self.assertEqual( err.exception.args[0], @@ -2104,7 +2136,10 @@ class FilemodLineTests(TestCase, LoaderModuleMockMixin): with self.assertRaises(CommandExecutionError) as err: filemod._set_line( - lines=bad_lines, content="asdf", before=before, mode="ensure", + lines=bad_lines, + content="asdf", + before=before, + mode="ensure", ) self.assertEqual( err.exception.args[0], @@ -2232,7 +2267,10 @@ class FilemodLineTests(TestCase, LoaderModuleMockMixin): original_lines = [after, content + "\n"] actual_lines = filemod._set_line( - lines=original_lines, content=content, after=after, mode="ensure", + lines=original_lines, + content=content, + after=after, + mode="ensure", ) self.assertEqual(actual_lines, original_lines) @@ -2369,7 +2407,8 @@ class FilemodLineTests(TestCase, LoaderModuleMockMixin): with pytest.raises(CommandExecutionError) as exc_info: filemod.line("foo", mode=mode) self.assertIn( - 'Content can only be empty if mode is "delete"', str(exc_info.value), + 'Content can only be empty if mode is "delete"', + str(exc_info.value), ) @patch("os.path.realpath", MagicMock(wraps=lambda x: x)) @@ -3318,20 +3357,35 @@ class LsattrTests(TestCase, LoaderModuleMockMixin): } def run(self, result=None): - patch_aix = patch("salt.utils.platform.is_aix", Mock(return_value=False),) - patch_exists = patch("os.path.exists", Mock(return_value=True),) - patch_which = patch("salt.utils.path.which", Mock(return_value="fnord"),) + patch_aix = patch( + "salt.utils.platform.is_aix", + Mock(return_value=False), + ) + patch_exists = patch( + "os.path.exists", + Mock(return_value=True), + ) + patch_which = patch( + "salt.utils.path.which", + Mock(return_value="fnord"), + ) with patch_aix, patch_exists, patch_which: super().run(result) def test_if_lsattr_is_missing_it_should_return_None(self): - patch_which = patch("salt.utils.path.which", Mock(return_value=None),) + patch_which = patch( + "salt.utils.path.which", + Mock(return_value=None), + ) with patch_which: actual = filemod.lsattr("foo") assert actual is None, actual def test_on_aix_lsattr_should_be_None(self): - patch_aix = patch("salt.utils.platform.is_aix", Mock(return_value=True),) + patch_aix = patch( + "salt.utils.platform.is_aix", + Mock(return_value=True), + ) with patch_aix: # SaltInvocationError will be raised if filemod.lsattr # doesn't early exit @@ -3339,7 +3393,10 @@ class LsattrTests(TestCase, LoaderModuleMockMixin): self.assertIsNone(actual) def test_SaltInvocationError_should_be_raised_when_file_is_missing(self): - patch_exists = patch("os.path.exists", Mock(return_value=False),) + patch_exists = patch( + "os.path.exists", + Mock(return_value=False), + ) with patch_exists, self.assertRaises(SaltInvocationError): filemod.lsattr("foo") @@ -3356,10 +3413,12 @@ class LsattrTests(TestCase, LoaderModuleMockMixin): ) expected = set("acdijstuADST") patch_has_ext = patch( - "salt.modules.file._chattr_has_extended_attrs", Mock(return_value=False), + "salt.modules.file._chattr_has_extended_attrs", + Mock(return_value=False), ) patch_run = patch.dict( - filemod.__salt__, {"cmd.run": Mock(return_value=with_extended)}, + filemod.__salt__, + {"cmd.run": Mock(return_value=with_extended)}, ) with patch_has_ext, patch_run: actual = set(filemod.lsattr(fname)[fname]) @@ -3383,10 +3442,12 @@ class LsattrTests(TestCase, LoaderModuleMockMixin): ) expected = set("aAcCdDeijPsStTu") patch_has_ext = patch( - "salt.modules.file._chattr_has_extended_attrs", Mock(return_value=True), + "salt.modules.file._chattr_has_extended_attrs", + Mock(return_value=True), ) patch_run = patch.dict( - filemod.__salt__, {"cmd.run": Mock(return_value=with_extended)}, + filemod.__salt__, + {"cmd.run": Mock(return_value=with_extended)}, ) with patch_has_ext, patch_run: actual = set(filemod.lsattr(fname)[fname]) @@ -3410,10 +3471,12 @@ class LsattrTests(TestCase, LoaderModuleMockMixin): ) expected = set("") patch_has_ext = patch( - "salt.modules.file._chattr_has_extended_attrs", Mock(return_value=True), + "salt.modules.file._chattr_has_extended_attrs", + Mock(return_value=True), ) patch_run = patch.dict( - filemod.__salt__, {"cmd.run": Mock(return_value=with_extended)}, + filemod.__salt__, + {"cmd.run": Mock(return_value=with_extended)}, ) with patch_has_ext, patch_run: actual = set(filemod.lsattr(fname)[fname]) @@ -3438,21 +3501,39 @@ class ChattrTests(TestCase, LoaderModuleMockMixin): } def run(self, result=None): - patch_aix = patch("salt.utils.platform.is_aix", Mock(return_value=False),) - patch_exists = patch("os.path.exists", Mock(return_value=True),) - patch_which = patch("salt.utils.path.which", Mock(return_value="some/tune2fs"),) + patch_aix = patch( + "salt.utils.platform.is_aix", + Mock(return_value=False), + ) + patch_exists = patch( + "os.path.exists", + Mock(return_value=True), + ) + patch_which = patch( + "salt.utils.path.which", + Mock(return_value="some/tune2fs"), + ) with patch_aix, patch_exists, patch_which: super().run(result) def test_chattr_version_returns_None_if_no_tune2fs_exists(self): - patch_which = patch("salt.utils.path.which", Mock(return_value=""),) + patch_which = patch( + "salt.utils.path.which", + Mock(return_value=""), + ) with patch_which: actual = filemod._chattr_version() self.assertIsNone(actual) def test_on_aix_chattr_version_should_be_None_even_if_tune2fs_exists(self): - patch_which = patch("salt.utils.path.which", Mock(return_value="fnord"),) - patch_aix = patch("salt.utils.platform.is_aix", Mock(return_value=True),) + patch_which = patch( + "salt.utils.path.which", + Mock(return_value="fnord"), + ) + patch_aix = patch( + "salt.utils.platform.is_aix", + Mock(return_value=True), + ) mock_run = MagicMock(return_value="fnord") patch_run = patch.dict(filemod.__salt__, {"cmd.run": mock_run}) with patch_which, patch_aix, patch_run: @@ -3475,18 +3556,26 @@ class ChattrTests(TestCase, LoaderModuleMockMixin): [-I new_inode_size] [-z undo_file] device """ ) - patch_which = patch("salt.utils.path.which", Mock(return_value="fnord"),) + patch_which = patch( + "salt.utils.path.which", + Mock(return_value="fnord"), + ) patch_run = patch.dict( - filemod.__salt__, {"cmd.run": MagicMock(return_value=sample_output)}, + filemod.__salt__, + {"cmd.run": MagicMock(return_value=sample_output)}, ) with patch_which, patch_run: actual = filemod._chattr_version() self.assertEqual(actual, expected) def test_if_tune2fs_has_no_version_version_should_be_None(self): - patch_which = patch("salt.utils.path.which", Mock(return_value="fnord"),) + patch_which = patch( + "salt.utils.path.which", + Mock(return_value="fnord"), + ) patch_run = patch.dict( - filemod.__salt__, {"cmd.run": MagicMock(return_value="fnord")}, + filemod.__salt__, + {"cmd.run": MagicMock(return_value="fnord")}, ) with patch_which, patch_run: actual = filemod._chattr_version() @@ -3496,7 +3585,8 @@ class ChattrTests(TestCase, LoaderModuleMockMixin): self, ): patch_chattr = patch( - "salt.modules.file._chattr_version", Mock(return_value=None), + "salt.modules.file._chattr_version", + Mock(return_value=None), ) with patch_chattr: actual = filemod._chattr_has_extended_attrs() @@ -3505,7 +3595,8 @@ class ChattrTests(TestCase, LoaderModuleMockMixin): def test_chattr_has_extended_attrs_should_return_False_if_version_is_too_low(self): below_expected = "0.1.1" patch_chattr = patch( - "salt.modules.file._chattr_version", Mock(return_value=below_expected), + "salt.modules.file._chattr_version", + Mock(return_value=below_expected), ) with patch_chattr: actual = filemod._chattr_has_extended_attrs() @@ -3516,7 +3607,8 @@ class ChattrTests(TestCase, LoaderModuleMockMixin): ): threshold = "1.41.12" patch_chattr = patch( - "salt.modules.file._chattr_version", Mock(return_value=threshold), + "salt.modules.file._chattr_version", + Mock(return_value=threshold), ) with patch_chattr: actual = filemod._chattr_has_extended_attrs() @@ -3527,7 +3619,8 @@ class ChattrTests(TestCase, LoaderModuleMockMixin): ): higher_than = "1.41.13" patch_chattr = patch( - "salt.modules.file._chattr_version", Mock(return_value=higher_than), + "salt.modules.file._chattr_version", + Mock(return_value=higher_than), ) with patch_chattr: actual = filemod._chattr_has_extended_attrs() @@ -3543,9 +3636,13 @@ class ChattrTests(TestCase, LoaderModuleMockMixin): higher_than = "1.41.13" patch_chattr = patch( - "salt.modules.file._chattr_version", Mock(return_value=higher_than), + "salt.modules.file._chattr_version", + Mock(return_value=higher_than), + ) + patch_exists = patch( + "os.path.exists", + Mock(return_value=True), ) - patch_exists = patch("os.path.exists", Mock(return_value=True),) patch_stats = patch( "salt.modules.file.stats", Mock(return_value={"user": "foo", "group": "bar", "mode": "123"}), @@ -3580,7 +3677,8 @@ class ChattrTests(TestCase, LoaderModuleMockMixin): higher_than = "1.41.13" patch_chattr = patch( - "salt.modules.file._chattr_version", Mock(return_value=higher_than), + "salt.modules.file._chattr_version", + Mock(return_value=higher_than), ) patch_stats = patch( "salt.modules.file.stats", @@ -3590,12 +3688,21 @@ class ChattrTests(TestCase, LoaderModuleMockMixin): "salt.modules.file._cmp_attrs", MagicMock( side_effect=[ - filemod.AttrChanges(added="aAcCdDeijPsStTu", removed="",), - filemod.AttrChanges(None, None,), + filemod.AttrChanges( + added="aAcCdDeijPsStTu", + removed="", + ), + filemod.AttrChanges( + None, + None, + ), ] ), ) - patch_chattr = patch("salt.modules.file.chattr", MagicMock(),) + patch_chattr = patch( + "salt.modules.file.chattr", + MagicMock(), + ) def fake_cmd(cmd, *args, **kwargs): if cmd == ["lsattr", "/path/to/fnord"]: @@ -3610,7 +3717,8 @@ class ChattrTests(TestCase, LoaderModuleMockMixin): assert False, "not sure how to handle {}".format(cmd) patch_run = patch.dict( - filemod.__salt__, {"cmd.run": MagicMock(side_effect=fake_cmd)}, + filemod.__salt__, + {"cmd.run": MagicMock(side_effect=fake_cmd)}, ) patch_ver = patch( "salt.modules.file._chattr_has_extended_attrs", @@ -3666,24 +3774,24 @@ class FileSelinuxTestCase(TestCase, LoaderModuleMockMixin): def test_selinux_getcontext(self): """ - Test get selinux context - Assumes default selinux attributes on temporary files + Test get selinux context + Assumes default selinux attributes on temporary files """ result = filemod.get_selinux_context(self.tfile1.name) self.assertEqual(result, "unconfined_u:object_r:user_tmp_t:s0") def test_selinux_setcontext(self): """ - Test set selinux context - Assumes default selinux attributes on temporary files + Test set selinux context + Assumes default selinux attributes on temporary files """ result = filemod.set_selinux_context(self.tfile2.name, user="system_u") self.assertEqual(result, "system_u:object_r:user_tmp_t:s0") def test_selinux_setcontext_persist(self): """ - Test set selinux context with persist=True - Assumes default selinux attributes on temporary files + Test set selinux context with persist=True + Assumes default selinux attributes on temporary files """ result = filemod.set_selinux_context( self.tfile2.name, user="system_u", persist=True diff --git a/tests/unit/modules/test_freebsd_sysctl.py b/tests/unit/modules/test_freebsd_sysctl.py index ee60d59d013..a4ff0d4423c 100644 --- a/tests/unit/modules/test_freebsd_sysctl.py +++ b/tests/unit/modules/test_freebsd_sysctl.py @@ -102,10 +102,12 @@ class FreeBSDSysctlTestCase(TestCase, LoaderModuleMockMixin): with patch("salt.utils.files.fopen", mock_open()): with patch.dict( - freebsd_sysctl.__salt__, {"cmd.run_all": mock_cmd}, + freebsd_sysctl.__salt__, + {"cmd.run_all": mock_cmd}, ): self.assertEqual( - freebsd_sysctl.persist("vfs.usermount", 1), "Updated", + freebsd_sysctl.persist("vfs.usermount", 1), + "Updated", ) def test_persist_updated_tunable(self): diff --git a/tests/unit/modules/test_glusterfs.py b/tests/unit/modules/test_glusterfs.py index 7d5206f7c7b..b06743bbdb8 100644 --- a/tests/unit/modules/test_glusterfs.py +++ b/tests/unit/modules/test_glusterfs.py @@ -12,13 +12,13 @@ from tests.support.unit import TestCase class GlusterResults: - """ This class holds the xml results from gluster cli transactions """ + """This class holds the xml results from gluster cli transactions""" class v34: - """ This is for version 3.4 results """ + """This is for version 3.4 results""" class list_peers: - """ results from "peer status" """ + """results from "peer status" """ class peer_probe: fail_cant_connect = fail_bad_hostname = "\n".join( @@ -112,9 +112,9 @@ class GlusterResults: ), } success_first_hostname_from_second_first_time = success_other - success_first_hostname_from_second_second_time = success_reverse_already_peer[ - "hostname" - ] + success_first_hostname_from_second_second_time = ( + success_reverse_already_peer["hostname"] + ) success_first_ip_from_second_first_time = success_reverse_already_peer["ip"] class v37: @@ -208,9 +208,9 @@ class GlusterResults: ] ), } - success_first_hostname_from_second_first_time = success_reverse_already_peer[ - "hostname" - ] + success_first_hostname_from_second_first_time = ( + success_reverse_already_peer["hostname"] + ) success_first_ip_from_second_first_time = success_other success_first_ip_from_second_second_time = success_reverse_already_peer[ "ip" diff --git a/tests/unit/modules/test_helm.py b/tests/unit/modules/test_helm.py index 2d54296502a..ea80da17f58 100644 --- a/tests/unit/modules/test_helm.py +++ b/tests/unit/modules/test_helm.py @@ -23,13 +23,22 @@ class HelmTestCase(TestCase, LoaderModuleMockMixin): def test__prepare_cmd_commands(self): self.assertEqual( - helm._prepare_cmd(commands=["com1", "com2"]), ("helm", "com1", "com2",) + helm._prepare_cmd(commands=["com1", "com2"]), + ( + "helm", + "com1", + "com2", + ), ) def test__prepare_cmd_flags(self): self.assertEqual( helm._prepare_cmd(flags=["flag1", "--flag2"]), - ("helm", "--flag1", "--flag2",), + ( + "helm", + "--flag1", + "--flag2", + ), ) def test__prepare_cmd_kvflags(self): diff --git a/tests/unit/modules/test_hosts.py b/tests/unit/modules/test_hosts.py index 1ebc9fa8252..5b9ca6e1041 100644 --- a/tests/unit/modules/test_hosts.py +++ b/tests/unit/modules/test_hosts.py @@ -205,7 +205,12 @@ class HostsTestCase(TestCase, LoaderModuleMockMixin): self.write(line) expected = ( - "\n".join(("2.2.2.2 bar.barbar bar", "3.3.3.3 asdf.asdfadsf asdf",)) + "\n".join( + ( + "2.2.2.2 bar.barbar bar", + "3.3.3.3 asdf.asdfadsf asdf", + ) + ) + "\n" ) diff --git a/tests/unit/modules/test_influxdb08mod.py b/tests/unit/modules/test_influxdb08mod.py index d0a09254adf..d58d99da138 100644 --- a/tests/unit/modules/test_influxdb08mod.py +++ b/tests/unit/modules/test_influxdb08mod.py @@ -300,7 +300,10 @@ class InfluxTestCase(TestCase): client.create_retention_policy = MagicMock() self.assertTrue( influx08.retention_policy_add( - database="db", name="name", duration="30d", replication=1, + database="db", + name="name", + duration="30d", + replication=1, ) ) client.create_retention_policy.assert_called_once_with( @@ -313,7 +316,10 @@ class InfluxTestCase(TestCase): client.alter_retention_policy = MagicMock() self.assertTrue( influx08.retention_policy_alter( - database="db", name="name", duration="30d", replication=1, + database="db", + name="name", + duration="30d", + replication=1, ) ) client.alter_retention_policy.assert_called_once_with( diff --git a/tests/unit/modules/test_k8s.py b/tests/unit/modules/test_k8s.py index 5081dbc16f2..1d82d6870bd 100644 --- a/tests/unit/modules/test_k8s.py +++ b/tests/unit/modules/test_k8s.py @@ -113,7 +113,9 @@ class TestK8SSecrets(TestCase): res = k8s.get_secrets( "default", name, apiserver_url="http://127.0.0.1:8080", decode=True ) - a = res.get("data", {}).get("testsecret",) + a = res.get("data", {}).get( + "testsecret", + ) self.assertEqual(a, "teststring") def test_create_secret(self): diff --git a/tests/unit/modules/test_kubeadm.py b/tests/unit/modules/test_kubeadm.py index 2d2d211e2e2..9e3dee2fa7c 100644 --- a/tests/unit/modules/test_kubeadm.py +++ b/tests/unit/modules/test_kubeadm.py @@ -638,13 +638,16 @@ class KubeAdmTestCase(TestCase, LoaderModuleMockMixin): "cmd.run_all": MagicMock(return_value=result), } with patch.dict(kubeadm.__salt__, salt_mock): - assert kubeadm.config_images_list( - config="/kubeadm.cfg", - feature_gates="k=v", - kubernetes_version="version", - kubeconfig="/kube.cfg", - rootfs="/mnt", - ) == ["image1", "image2"] + assert ( + kubeadm.config_images_list( + config="/kubeadm.cfg", + feature_gates="k=v", + kubernetes_version="version", + kubeconfig="/kube.cfg", + rootfs="/mnt", + ) + == ["image1", "image2"] + ) salt_mock["cmd.run_all"].assert_called_with( [ "kubeadm", @@ -707,14 +710,17 @@ class KubeAdmTestCase(TestCase, LoaderModuleMockMixin): "cmd.run_all": MagicMock(return_value=result), } with patch.dict(kubeadm.__salt__, salt_mock): - assert kubeadm.config_images_pull( - config="/kubeadm.cfg", - cri_socket="socket", - feature_gates="k=v", - kubernetes_version="version", - kubeconfig="/kube.cfg", - rootfs="/mnt", - ) == ["image1", "image2"] + assert ( + kubeadm.config_images_pull( + config="/kubeadm.cfg", + cri_socket="socket", + feature_gates="k=v", + kubernetes_version="version", + kubeconfig="/kube.cfg", + rootfs="/mnt", + ) + == ["image1", "image2"] + ) salt_mock["cmd.run_all"].assert_called_with( [ "kubeadm", diff --git a/tests/unit/modules/test_kubernetesmod.py b/tests/unit/modules/test_kubernetesmod.py index 51ff0ec9292..f354f211543 100644 --- a/tests/unit/modules/test_kubernetesmod.py +++ b/tests/unit/modules/test_kubernetesmod.py @@ -218,7 +218,8 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): mock_kubernetes_lib.config.load_kube_config = Mock() config = kubernetes._setup_conn() self.assertEqual( - self.settings("kubernetes.kubeconfig"), config["kubeconfig"], + self.settings("kubernetes.kubeconfig"), + config["kubeconfig"], ) def test_setup_kubeconfig_data_overwrite(self): @@ -301,5 +302,6 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): 2: 2, } self.assertEqual( - {"unicode": "1", "2": "2"}, func(data), + {"unicode": "1", "2": "2"}, + func(data), ) diff --git a/tests/unit/modules/test_mac_keychain.py b/tests/unit/modules/test_mac_keychain.py index e4559997f56..32ae920baef 100644 --- a/tests/unit/modules/test_mac_keychain.py +++ b/tests/unit/modules/test_mac_keychain.py @@ -10,7 +10,7 @@ class KeychainTestCase(TestCase, LoaderModuleMockMixin): def test_install_cert(self): """ - Test installing a certificate into the macOS keychain + Test installing a certificate into the macOS keychain """ mock = MagicMock() with patch.dict(keychain.__salt__, {"cmd.run": mock}): @@ -22,7 +22,7 @@ class KeychainTestCase(TestCase, LoaderModuleMockMixin): def test_install_cert_extras(self): """ - Test installing a certificate into the macOS keychain with extras + Test installing a certificate into the macOS keychain with extras """ mock = MagicMock() with patch.dict(keychain.__salt__, {"cmd.run": mock}), patch( @@ -42,7 +42,7 @@ class KeychainTestCase(TestCase, LoaderModuleMockMixin): def test_uninstall_cert(self): """ - Test uninstalling a certificate from the macOS keychain + Test uninstalling a certificate from the macOS keychain """ mock = MagicMock() with patch.dict(keychain.__salt__, {"cmd.run": mock}): @@ -53,7 +53,7 @@ class KeychainTestCase(TestCase, LoaderModuleMockMixin): def test_list_certs(self): """ - Test listing available certificates in a keychain + Test listing available certificates in a keychain """ expected = ["com.apple.systemdefault", "com.apple.kerberos.kdc"] mock = MagicMock( @@ -71,7 +71,7 @@ class KeychainTestCase(TestCase, LoaderModuleMockMixin): def test_get_friendly_name(self): """ - Test getting the friendly name of a certificate + Test getting the friendly name of a certificate """ expected = "ID Installer Salt" mock = MagicMock(return_value="friendlyName: ID Installer Salt") @@ -87,7 +87,7 @@ class KeychainTestCase(TestCase, LoaderModuleMockMixin): def test_get_default_keychain(self): """ - Test getting the default keychain + Test getting the default keychain """ mock = MagicMock() with patch.dict(keychain.__salt__, {"cmd.run": mock}): @@ -98,7 +98,7 @@ class KeychainTestCase(TestCase, LoaderModuleMockMixin): def test_set_default_keychain(self): """ - Test setting the default keychain + Test setting the default keychain """ mock = MagicMock() with patch.dict(keychain.__salt__, {"cmd.run": mock}): @@ -110,7 +110,7 @@ class KeychainTestCase(TestCase, LoaderModuleMockMixin): def test_unlock_keychain(self): """ - Test unlocking the keychain + Test unlocking the keychain """ mock = MagicMock() with patch.dict(keychain.__salt__, {"cmd.run": mock}): diff --git a/tests/unit/modules/test_macdefaults.py b/tests/unit/modules/test_macdefaults.py index 29d7422f082..affa3ea95ea 100644 --- a/tests/unit/modules/test_macdefaults.py +++ b/tests/unit/modules/test_macdefaults.py @@ -10,7 +10,7 @@ class MacDefaultsTestCase(TestCase, LoaderModuleMockMixin): def test_write_default(self): """ - Test writing a default setting + Test writing a default setting """ mock = MagicMock() with patch.dict(macdefaults.__salt__, {"cmd.run_all": mock}): @@ -22,7 +22,7 @@ class MacDefaultsTestCase(TestCase, LoaderModuleMockMixin): def test_write_with_user(self): """ - Test writing a default setting with a specific user + Test writing a default setting with a specific user """ mock = MagicMock() with patch.dict(macdefaults.__salt__, {"cmd.run_all": mock}): @@ -36,7 +36,7 @@ class MacDefaultsTestCase(TestCase, LoaderModuleMockMixin): def test_write_default_boolean(self): """ - Test writing a default setting + Test writing a default setting """ mock = MagicMock() with patch.dict(macdefaults.__salt__, {"cmd.run_all": mock}): @@ -48,7 +48,7 @@ class MacDefaultsTestCase(TestCase, LoaderModuleMockMixin): def test_read_default(self): """ - Test reading a default setting + Test reading a default setting """ mock = MagicMock() with patch.dict(macdefaults.__salt__, {"cmd.run": mock}): @@ -59,7 +59,7 @@ class MacDefaultsTestCase(TestCase, LoaderModuleMockMixin): def test_read_default_with_user(self): """ - Test reading a default setting as a specific user + Test reading a default setting as a specific user """ mock = MagicMock() with patch.dict(macdefaults.__salt__, {"cmd.run": mock}): @@ -70,7 +70,7 @@ class MacDefaultsTestCase(TestCase, LoaderModuleMockMixin): def test_delete_default(self): """ - Test delete a default setting + Test delete a default setting """ mock = MagicMock() with patch.dict(macdefaults.__salt__, {"cmd.run_all": mock}): @@ -83,7 +83,7 @@ class MacDefaultsTestCase(TestCase, LoaderModuleMockMixin): def test_delete_default_with_user(self): """ - Test delete a default setting as a specific user + Test delete a default setting as a specific user """ mock = MagicMock() with patch.dict(macdefaults.__salt__, {"cmd.run_all": mock}): diff --git a/tests/unit/modules/test_macpackage.py b/tests/unit/modules/test_macpackage.py index ff5f6cf1ad0..5109f69d8c9 100644 --- a/tests/unit/modules/test_macpackage.py +++ b/tests/unit/modules/test_macpackage.py @@ -10,7 +10,7 @@ class MacPackageTestCase(TestCase, LoaderModuleMockMixin): def test_install(self): """ - Test installing a PKG file + Test installing a PKG file """ mock = MagicMock() with patch.dict(macpackage.__salt__, {"cmd.run_all": mock}): @@ -22,7 +22,7 @@ class MacPackageTestCase(TestCase, LoaderModuleMockMixin): def test_install_wildcard(self): """ - Test installing a PKG file with a wildcard + Test installing a PKG file with a wildcard """ mock = MagicMock() with patch.dict(macpackage.__salt__, {"cmd.run_all": mock}): @@ -33,7 +33,7 @@ class MacPackageTestCase(TestCase, LoaderModuleMockMixin): def test_install_with_extras(self): """ - Test installing a PKG file with extra options + Test installing a PKG file with extra options """ mock = MagicMock() with patch.dict(macpackage.__salt__, {"cmd.run_all": mock}): @@ -45,7 +45,7 @@ class MacPackageTestCase(TestCase, LoaderModuleMockMixin): def test_install_app(self): """ - Test installing an APP package + Test installing an APP package """ mock = MagicMock() with patch.dict(macpackage.__salt__, {"cmd.run": mock}): @@ -56,7 +56,7 @@ class MacPackageTestCase(TestCase, LoaderModuleMockMixin): def test_install_app_specify_target(self): """ - Test installing an APP package with a specific target + Test installing an APP package with a specific target """ mock = MagicMock() with patch.dict(macpackage.__salt__, {"cmd.run": mock}): @@ -67,7 +67,7 @@ class MacPackageTestCase(TestCase, LoaderModuleMockMixin): def test_install_app_with_slash(self): """ - Test installing an APP package with a specific target + Test installing an APP package with a specific target """ mock = MagicMock() with patch.dict(macpackage.__salt__, {"cmd.run": mock}): @@ -78,7 +78,7 @@ class MacPackageTestCase(TestCase, LoaderModuleMockMixin): def test_uninstall(self): """ - Test Uninstalling an APP package with a specific target + Test Uninstalling an APP package with a specific target """ mock = MagicMock() with patch.dict(macpackage.__salt__, {"file.remove": mock}): @@ -87,7 +87,7 @@ class MacPackageTestCase(TestCase, LoaderModuleMockMixin): def test_mount(self): """ - Test mounting an dmg file to a temporary location + Test mounting an dmg file to a temporary location """ cmd_mock = MagicMock() temp_mock = MagicMock(return_value="dmg-ABCDEF") @@ -103,7 +103,7 @@ class MacPackageTestCase(TestCase, LoaderModuleMockMixin): def test_unmount(self): """ - Test Unmounting an dmg file to a temporary location + Test Unmounting an dmg file to a temporary location """ mock = MagicMock() with patch.dict(macpackage.__salt__, {"cmd.run": mock}): @@ -112,7 +112,7 @@ class MacPackageTestCase(TestCase, LoaderModuleMockMixin): def test_installed_pkgs(self): """ - Test getting a list of the installed packages + Test getting a list of the installed packages """ expected = ["com.apple.this", "com.salt.that"] mock = MagicMock(return_value="com.apple.this\ncom.salt.that") @@ -123,7 +123,7 @@ class MacPackageTestCase(TestCase, LoaderModuleMockMixin): def test_get_pkg_id_with_files(self): """ - Test getting a the id for a package + Test getting a the id for a package """ with patch( "salt.modules.macpackage._get_pkg_id_from_pkginfo" @@ -176,7 +176,7 @@ class MacPackageTestCase(TestCase, LoaderModuleMockMixin): def test_get_pkg_id_with_dir(self): """ - Test getting a the id for a package with a directory + Test getting a the id for a package with a directory """ with patch("salt.modules.macpackage._get_pkg_id_dir") as pkg_id_dir_mock: expected = ["com.apple.this"] @@ -208,7 +208,7 @@ class MacPackageTestCase(TestCase, LoaderModuleMockMixin): def test_get_mpkg_ids(self): """ - Test getting the ids of a mpkg file + Test getting the ids of a mpkg file """ with patch("salt.modules.macpackage.get_pkg_id") as get_pkg_id_mock: expected = ["com.apple.this", "com.salt.other"] @@ -229,7 +229,7 @@ class MacPackageTestCase(TestCase, LoaderModuleMockMixin): def test_get_pkg_id_from_pkginfo(self): """ - Test getting a package id from pkginfo files + Test getting a package id from pkginfo files """ expected = ["com.apple.this", "com.apple.that"] mock = MagicMock(return_value="com.apple.this\ncom.apple.that") @@ -244,7 +244,7 @@ class MacPackageTestCase(TestCase, LoaderModuleMockMixin): def test_get_pkg_id_from_pkginfo_no_file(self): """ - Test getting a package id from pkginfo file when it doesn't exist + Test getting a package id from pkginfo file when it doesn't exist """ expected = [] mock = MagicMock(return_value="No such file") @@ -259,7 +259,7 @@ class MacPackageTestCase(TestCase, LoaderModuleMockMixin): def test_get_pkg_id_dir(self): """ - Test getting a package id from a directory + Test getting a package id from a directory """ expected = ["com.apple.this"] mock = MagicMock(return_value="com.apple.this") @@ -271,7 +271,7 @@ class MacPackageTestCase(TestCase, LoaderModuleMockMixin): def test_get_pkg_id_dir_wildcard(self): """ - Test getting a package id from a directory with a wildcard + Test getting a package id from a directory with a wildcard """ expected = ["com.apple.this"] mock = MagicMock(return_value="com.apple.this") diff --git a/tests/unit/modules/test_mandrill.py b/tests/unit/modules/test_mandrill.py index 1103f31c32c..16449beee96 100644 --- a/tests/unit/modules/test_mandrill.py +++ b/tests/unit/modules/test_mandrill.py @@ -77,5 +77,6 @@ class MandrillModuleTest(TestCase, LoaderModuleMockMixin): ) except TypeError as no_async: self.assertEqual( - str(no_async), "send() got an unexpected keyword argument 'async'", + str(no_async), + "send() got an unexpected keyword argument 'async'", ) diff --git a/tests/unit/modules/test_nova.py b/tests/unit/modules/test_nova.py index 192d377c105..f9cb3db9490 100644 --- a/tests/unit/modules/test_nova.py +++ b/tests/unit/modules/test_nova.py @@ -195,7 +195,7 @@ class NovaTestCase(TestCase, LoaderModuleMockMixin): Test for To maintain the feel of the nova command line, this function simply calls the server_list function. - """ + """ with patch.object(nova, "server_list", return_value=["A"]): self.assertEqual(nova.list_(), ["A"]) @@ -212,7 +212,7 @@ class NovaTestCase(TestCase, LoaderModuleMockMixin): Test for To maintain the feel of the nova command line, this function simply calls the server_show function. - """ + """ with patch.object(nova, "server_show", return_value=["A"]): self.assertEqual(nova.show("server_id"), ["A"]) diff --git a/tests/unit/modules/test_nxos.py b/tests/unit/modules/test_nxos.py index 6e2c356f6ef..bd74da771f3 100644 --- a/tests/unit/modules/test_nxos.py +++ b/tests/unit/modules/test_nxos.py @@ -44,7 +44,7 @@ from tests.unit.modules.nxos.nxos_show_run import ( class NxosTestCase(TestCase, LoaderModuleMockMixin): - """ Test cases for salt.modules.nxos """ + """Test cases for salt.modules.nxos""" COPY_RS = "copy running-config startup-config" @@ -57,14 +57,14 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): @staticmethod def test_check_virtual(): - """ UT: nxos module:check_virtual method - return value """ + """UT: nxos module:check_virtual method - return value""" result = nxos_module.__virtual__() assert "nxos" in result def test_ping_proxy(self): - """ UT: nxos module:ping method - proxy """ + """UT: nxos module:ping method - proxy""" with patch("salt.utils.platform.is_proxy", return_value=True, autospec=True): with patch.dict( nxos_module.__proxy__, {"nxos.ping": MagicMock(return_value=True)} @@ -74,7 +74,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_ping_native_minion(self): - """ UT: nxos module:ping method - proxy """ + """UT: nxos module:ping method - proxy""" with patch("salt.utils.platform.is_proxy", return_value=False, autospec=True): with patch.dict( @@ -85,7 +85,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_check_password_return_none(self): - """ UT: nxos module:check_password method - return None """ + """UT: nxos module:check_password method - return None""" username = "admin" password = "foo" @@ -96,7 +96,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_check_password_password_nxos_comment(self): - """ UT: nxos module:check_password method - password_line has '!' """ + """UT: nxos module:check_password method - password_line has '!'""" username = "admin" password = "foo" @@ -111,7 +111,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): ) def test_check_password_password_encrypted_false(self): - """ UT: nxos module:check_password method - password is not encrypted """ + """UT: nxos module:check_password method - password is not encrypted""" username = "salt_test" password = "foobar123&" @@ -126,7 +126,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_check_password_password_encrypted_true(self): - """ UT: nxos module:check_password method - password is encrypted """ + """UT: nxos module:check_password method - password is encrypted""" username = "salt_test" password = "$5$mkXh6O4T$YUVtA89HbXCnue63kgghPlaqPHyaXhdtxPBbPEHhbRC" @@ -141,7 +141,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_check_password_password_encrypted_true_negative(self): - """ UT: nxos module:check_password method - password is not encrypted """ + """UT: nxos module:check_password method - password is not encrypted""" username = "salt_test" password = "foobar123&" @@ -154,7 +154,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_check_role_true(self): - """ UT: nxos module:check_role method - Role configured """ + """UT: nxos module:check_role method - Role configured""" username = "salt_test" roles = ["network-admin", "dev-ops"] @@ -165,7 +165,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_check_role_false(self): - """ UT: nxos module:check_role method - Role not configured """ + """UT: nxos module:check_role method - Role not configured""" username = "salt_test" roles = ["network-admin", "dev-ops"] @@ -176,7 +176,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_cmd_any_function(self): - """ UT: nxos module:cmd method - check_role function """ + """UT: nxos module:cmd method - check_role function""" with patch.dict( nxos_module.__salt__, @@ -197,7 +197,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_cmd_function_absent(self): - """ UT: nxos module:cmd method - non existent function """ + """UT: nxos module:cmd method - non existent function""" result = nxos_module.cmd( "cool_new_function", "salt_test", "network-admin", encrypted=True @@ -206,7 +206,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_find_single_match(self): - """ UT: nxos module:test_find method - Find single match in running config """ + """UT: nxos module:test_find method - Find single match in running config""" find_pattern = "^vrf context testing$" find_string = "vrf context testing" @@ -219,7 +219,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_find_multiple_matches(self): - """ UT: nxos module:test_find method - Find multiple matches in running config """ + """UT: nxos module:test_find method - Find multiple matches in running config""" find_pattern = "^no logging.*$" find_string = "no logging event link-status enable" @@ -233,7 +233,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_get_roles_user_not_configured(self): - """ UT: nxos module:get_roles method - User not configured """ + """UT: nxos module:get_roles method - User not configured""" username = "salt_does_not_exist" user_info = "" @@ -244,7 +244,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_get_roles_user_configured(self): - """ UT: nxos module:get_roles method - User configured """ + """UT: nxos module:get_roles method - User configured""" username = "salt_test" expected_result = ["network-operator", "network-admin", "dev-ops"] @@ -257,7 +257,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_get_roles_user_configured_no_role(self): - """ UT: nxos module:get_roles method - User configured no roles""" + """UT: nxos module:get_roles method - User configured no roles""" username = "salt_test" @@ -268,7 +268,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_get_user_configured(self): - """ UT: nxos module:get_user method - User configured """ + """UT: nxos module:get_user method - User configured""" username = "salt_test" expected_output = n9k_show_running_inc_username_list[0] @@ -283,7 +283,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_grains(self): - """ UT: nxos module:grains method """ + """UT: nxos module:grains method""" nxos_module.DEVICE_DETAILS["grains_cache"] = {} expected_grains = { @@ -313,7 +313,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_grains_get_cache(self): - """ UT: nxos module:grains method """ + """UT: nxos module:grains method""" expected_grains = { "software": { @@ -343,7 +343,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_grains_refresh(self): - """ UT: nxos module:grains_refresh method """ + """UT: nxos module:grains_refresh method""" expected_grains = { "software": { @@ -365,7 +365,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_system_info(self): - """ UT: nxos module:system_info method """ + """UT: nxos module:system_info method""" expected_grains = { "software": { @@ -394,7 +394,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_sendline_invalid_method(self): - """ UT: nxos module:sendline method - invalid method """ + """UT: nxos module:sendline method - invalid method""" command = "show version" method = "invalid" @@ -406,7 +406,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_sendline_valid_method_proxy(self): - """ UT: nxos module:sendline method - valid method over proxy """ + """UT: nxos module:sendline method - valid method over proxy""" command = "show version" method = "cli_show_ascii" @@ -421,7 +421,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_sendline_valid_method_nxapi_uds(self): - """ UT: nxos module:sendline method - valid method over nxapi uds """ + """UT: nxos module:sendline method - valid method over nxapi uds""" command = "show version" method = "cli_show_ascii" @@ -437,7 +437,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_show_raw_text_invalid(self): - """ UT: nxos module:show method - invalid argument """ + """UT: nxos module:show method - invalid argument""" command = "show version" raw_text = "invalid" @@ -447,7 +447,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_show_raw_text_true(self): - """ UT: nxos module:show method - raw_test true """ + """UT: nxos module:show method - raw_test true""" command = "show version" raw_text = True @@ -460,7 +460,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_show_raw_text_true_multiple_commands(self): - """ UT: nxos module:show method - raw_test true multiple commands """ + """UT: nxos module:show method - raw_test true multiple commands""" command = "show bgp sessions ; show processes" raw_text = True @@ -472,7 +472,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_show_nxapi(self): - """ UT: nxos module:show method - nxapi returns info as list """ + """UT: nxos module:show method - nxapi returns info as list""" command = "show version; show interface eth1/1" raw_text = True @@ -488,7 +488,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_show_nxapi_structured(self): - """ UT: nxos module:show method - nxapi returns info as list """ + """UT: nxos module:show method - nxapi returns info as list""" command = "show version; show interface eth1/1" raw_text = False @@ -504,7 +504,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_show_run(self): - """ UT: nxos module:show_run method """ + """UT: nxos module:show_run method""" expected_output = n9k_show_running_config_list[0] @@ -515,7 +515,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_show_ver(self): - """ UT: nxos module:show_ver method """ + """UT: nxos module:show_ver method""" expected_output = n9k_show_ver_list[0] @@ -526,7 +526,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_add_config(self): - """ UT: nxos module:add_config method """ + """UT: nxos module:add_config method""" expected_output = "COMMAND_LIST: feature bgp" @@ -538,7 +538,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_config_commands(self): - """ UT: nxos module:config method - Using commands arg""" + """UT: nxos module:config method - Using commands arg""" commands = ["no feature ospf", ["no feature ospf"]] expected_output = "COMMAND_LIST: no feature ospf\n\n--- \n+++ \n@@ -19,7 +19,6 @@\n feature bash-shell\n cfs eth distribute\n feature ngmvpn\n-feature ospf\n feature pim\n feature lldp\n \n" @@ -566,7 +566,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_config_commands_template_none(self): - """ UT: nxos module:config method - Template engine is None""" + """UT: nxos module:config method - Template engine is None""" commands = ["no feature ospf", ["no feature ospf"]] expected_output = "COMMAND_LIST: no feature ospf\n\n--- \n+++ \n@@ -19,7 +19,6 @@\n feature bash-shell\n cfs eth distribute\n feature ngmvpn\n-feature ospf\n feature pim\n feature lldp\n \n" @@ -594,7 +594,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_config_commands_string(self): - """ UT: nxos module:config method - Using commands arg and output is string""" + """UT: nxos module:config method - Using commands arg and output is string""" commands = "no feature ospf" expected_output = "COMMAND_LIST: no feature ospf\n\n--- \n+++ \n@@ -19,7 +19,6 @@\n feature bash-shell\n cfs eth distribute\n feature ngmvpn\n-feature ospf\n feature pim\n feature lldp\n \n" @@ -621,7 +621,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_config_file(self): - """ UT: nxos module:config method - Using config_file arg""" + """UT: nxos module:config method - Using config_file arg""" config_file = "salt://bgp_config.txt" expected_output = "COMMAND_LIST: feature bgp ; ! ; router bgp 55 ; address-family ipv4 unicast ; no client-to-client reflection ; additional-paths send\n\n--- \n+++ \n@@ -19,6 +19,7 @@\n feature bash-shell\n cfs eth distribute\n feature ngmvpn\n+feature bgp\n feature pim\n feature lldp\n \n@@ -233,6 +234,10 @@\n line console\n line vty\n boot nxos bootflash:/nxos.9.2.4.bin \n+router bgp 55\n+ address-family ipv4 unicast\n+ no client-to-client reflection\n+ additional-paths send\n \n no logging logfile\n no logging monitor\n" @@ -652,7 +652,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_config_file_error1(self): - """ UT: nxos module:config method - Error file not found """ + """UT: nxos module:config method - Error file not found""" config_file = "salt://bgp_config.txt" @@ -680,7 +680,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_config_nxos_error_ssh(self): - """ UT: nxos module:config method - nxos device error over ssh transport """ + """UT: nxos module:config method - nxos device error over ssh transport""" commands = ["feature bgp", "router bgp 57"] config_result = [ @@ -711,7 +711,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_commands_error(self): - """ UT: nxos module:config method - Mandatory arg commands not specified """ + """UT: nxos module:config method - Mandatory arg commands not specified""" commands = None @@ -739,7 +739,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_config_file_error2(self): - """ UT: nxos module:config method - Mandatory arg config_file not specified """ + """UT: nxos module:config method - Mandatory arg config_file not specified""" config_file = None @@ -767,7 +767,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_delete_config(self): - """ UT: nxos module:delete_config method """ + """UT: nxos module:delete_config method""" for lines in ["feature bgp", ["feature bgp"]]: with patch("salt.modules.nxos.config", autospec=True): @@ -777,7 +777,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_remove_user(self): - """ UT: nxos module:remove_user method """ + """UT: nxos module:remove_user method""" with patch("salt.modules.nxos.config", autospec=True): result = nxos_module.remove_user("salt_test") @@ -786,7 +786,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_replace(self): - """ UT: nxos module:replace method """ + """UT: nxos module:replace method""" old_value = "feature bgp" new_value = "feature ospf" @@ -808,7 +808,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_replace_full_match_true(self): - """ UT: nxos module:replace method - full match true""" + """UT: nxos module:replace method - full match true""" old_value = "feature bgp" new_value = "feature ospf" @@ -830,7 +830,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_replace_no_match(self): - """ UT: nxos module:replace method - no match """ + """UT: nxos module:replace method - no match""" old_value = "feature does_not_exist" new_value = "feature ospf" @@ -852,7 +852,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_save_running_config(self): - """ UT: nxos module:save_running_config method """ + """UT: nxos module:save_running_config method""" with patch( "salt.modules.nxos.config", autospec=True, return_value=save_running_config @@ -862,7 +862,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_set_password_enc_false_cs_none(self): - """ UT: nxos module:set_password method - encrypted False, crypt_salt None """ + """UT: nxos module:set_password method - encrypted False, crypt_salt None""" username = "devops" password = "test123TMM^&" @@ -884,7 +884,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_set_password_enc_false_cs_set(self): - """ UT: nxos module:set_password method - encrypted False, crypt_salt set """ + """UT: nxos module:set_password method - encrypted False, crypt_salt set""" username = "devops" password = "test123TMM^&" @@ -909,7 +909,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_set_password_enc_true(self): - """ UT: nxos module:set_password method - encrypted True """ + """UT: nxos module:set_password method - encrypted True""" username = "devops" password = "test123TMM^&" @@ -933,7 +933,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_set_password_role_none(self): - """ UT: nxos module:set_password method - role none """ + """UT: nxos module:set_password method - role none""" username = "devops" password = "test123TMM^&" @@ -958,7 +958,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_set_password_blowfish_crypt(self): - """ UT: nxos module:set_password method - role none """ + """UT: nxos module:set_password method - role none""" with self.assertRaises(SaltInvocationError): nxos_module.set_password( @@ -967,7 +967,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_set_role(self): - """ UT: nxos module:save_running_config method """ + """UT: nxos module:save_running_config method""" username = "salt_test" role = "vdc-admin" @@ -978,7 +978,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_unset_role(self): - """ UT: nxos module:save_running_config method """ + """UT: nxos module:save_running_config method""" username = "salt_test" role = "vdc-admin" @@ -989,7 +989,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_configure_device(self): - """ UT: nxos module:_configure_device method """ + """UT: nxos module:_configure_device method""" with patch("salt.utils.platform.is_proxy", autospec=True, return_value=True): with patch.dict( @@ -1008,7 +1008,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_nxapi_config(self): - """ UT: nxos module:_nxapi_config method """ + """UT: nxos module:_nxapi_config method""" mock_cmd = MagicMock(return_value={"nxos": {"save_config": False}}) with patch.dict(nxos_module.__salt__, {"config.get": mock_cmd}): @@ -1022,7 +1022,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_nxapi_config_failure(self): - """ UT: nxos module:_nxapi_config method """ + """UT: nxos module:_nxapi_config method""" side_effect = ["Failure", "saved_data"] @@ -1038,7 +1038,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_nxapi_request_proxy(self): - """ UT: nxos module:_nxapi_request method - proxy""" + """UT: nxos module:_nxapi_request method - proxy""" with patch("salt.utils.platform.is_proxy", autospec=True, return_value=True): mock_request = create_autospec( @@ -1052,7 +1052,7 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): def test_nxapi_request_no_proxy(self): - """ UT: nxos module:_nxapi_request method - no proxy""" + """UT: nxos module:_nxapi_request method - no proxy""" with patch("salt.utils.platform.is_proxy", autospec=True, return_value=False): mock_cmd = MagicMock(return_value={"nxos": {"save_config": False}}) diff --git a/tests/unit/modules/test_nxos_upgrade.py b/tests/unit/modules/test_nxos_upgrade.py index 59197a83a72..1b6be938ef4 100644 --- a/tests/unit/modules/test_nxos_upgrade.py +++ b/tests/unit/modules/test_nxos_upgrade.py @@ -36,14 +36,14 @@ from tests.unit.modules.nxos.nxos_n95k import N95KPlatform class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): - """ Test cases for salt.modules.nxos_upgrade """ + """Test cases for salt.modules.nxos_upgrade""" platform_list = None @staticmethod def assert_platform_upgrade(condition, platform): - """ Assert platform upgrade condition and display appropriate chassis & images upon assertion failure """ + """Assert platform upgrade condition and display appropriate chassis & images upon assertion failure""" assert bool(condition), "{}: Upgrade {} -> {}".format( platform.chassis, platform.cimage, platform.nimage @@ -51,7 +51,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def setup_loader_modules(self): - """ Define list of platforms for Unit Test """ + """Define list of platforms for Unit Test""" self.platform_list = [ N3KPlatform(cimage="nxos.7.0.3.F3.3.bin", nimage="nxos.9.2.1.255.bin"), @@ -82,7 +82,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): @staticmethod def test_check_upgrade_impact_input_validation(): - """ UT: nxos_upgrade module:check_upgrade_impact method - input validation """ + """UT: nxos_upgrade module:check_upgrade_impact method - input validation""" result = nxos_upgrade.check_upgrade_impact("dummy-platform-image.bin", issu=1) assert "Input Error" in result @@ -90,14 +90,14 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): @staticmethod def test_upgrade_input_validation(): - """ UT: nxos_upgrade module:upgrade method - input validation """ + """UT: nxos_upgrade module:upgrade method - input validation""" result = nxos_upgrade.upgrade("dummy-platform-image.bin", issu=1) assert "Input Error" in result def test_check_upgrade_impact_backend_processing_error_500(self): - """ UT: nxos_upgrade module:check_upgrade_impact method - error HTTP code 500 """ + """UT: nxos_upgrade module:check_upgrade_impact method - error HTTP code 500""" for platform in self.platform_list: if platform.backend_processing_error_500: @@ -117,7 +117,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def test_check_upgrade_impact_internal_server_error_400_invalid_command(self): - """ UT: nxos_upgrade module:check_upgrade_impact method - invalid command error HTTP code 400 """ + """UT: nxos_upgrade module:check_upgrade_impact method - invalid command error HTTP code 400""" for platform in self.platform_list: if platform.bad_request_client_error_400_invalid_command_dict: @@ -135,7 +135,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def test_check_upgrade_impact_internal_server_error_400_in_progress(self): - """ UT: nxos_upgrade module:check_upgrade_impact method - in-progress error HTTP code 400 """ + """UT: nxos_upgrade module:check_upgrade_impact method - in-progress error HTTP code 400""" for platform in self.platform_list: if platform.bad_request_client_error_400_in_progress_dict: @@ -153,7 +153,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def test_check_upgrade_impact_internal_server_error_500(self): - """ UT: nxos_upgrade module:check_upgrade_impact method - internal server error HTTP code 500 """ + """UT: nxos_upgrade module:check_upgrade_impact method - internal server error HTTP code 500""" for platform in self.platform_list: if platform.internal_server_error_500: @@ -177,7 +177,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def test_check_upgrade_impact_non_disruptive_success(self): - """ UT: nxos_upgrade module:check_upgrade_impact method - non-disruptive success """ + """UT: nxos_upgrade module:check_upgrade_impact method - non-disruptive success""" for platform in self.platform_list: if platform.install_all_non_disruptive_success: @@ -198,7 +198,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def test_check_upgrade_impact_disruptive_success(self): - """ UT: nxos_upgrade module:check_upgrade_impact method - disruptive success """ + """UT: nxos_upgrade module:check_upgrade_impact method - disruptive success""" for platform in self.platform_list: if platform.install_all_disruptive_success: @@ -226,7 +226,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def test_upgrade_show_install_all_impact_no_module_data(self): - """ UT: nxos_upgrade module: upgrade method - no module data """ + """UT: nxos_upgrade module: upgrade method - no module data""" for platform in self.platform_list: if platform.show_install_all_impact_no_module_data: @@ -246,7 +246,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def test_upgrade_invalid_command(self): - """ UT: nxos_upgrade module:upgrade method - invalid command """ + """UT: nxos_upgrade module:upgrade method - invalid command""" for platform in self.platform_list: if platform.invalid_command: @@ -260,7 +260,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def test_upgrade_install_in_progress(self): - """ UT: nxos_upgrade module:upgrade method - in-progress """ + """UT: nxos_upgrade module:upgrade method - in-progress""" for platform in self.platform_list: if platform.show_install_all_impact_in_progress: @@ -278,7 +278,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def test_upgrade_install_in_progress_terminal_dont_ask(self): - """ UT: nxos_upgrade module:upgrade method - in-progress (terminal don't-ask) """ + """UT: nxos_upgrade module:upgrade method - in-progress (terminal don't-ask)""" for platform in self.platform_list: if platform.invalid_command: @@ -299,7 +299,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def test_upgrade_install_in_progress_sans_terminal_dont_ask(self): - """ UT: nxos_upgrade module:upgrade method - in-progress (sans terminal don't-ask) """ + """UT: nxos_upgrade module:upgrade method - in-progress (sans terminal don't-ask)""" for platform in self.platform_list: if platform.invalid_command: @@ -317,7 +317,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def test_upgrade_internal_server_error_500(self): - """ UT: nxos_upgrade module:upgrade method - internal server error 500 """ + """UT: nxos_upgrade module:upgrade method - internal server error 500""" for platform in self.platform_list: if platform.backend_processing_error_500: @@ -338,7 +338,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def test_upgrade_install_all_disruptive(self): - """ UT: nxos_upgrade module:upgrade method - install all disruptive """ + """UT: nxos_upgrade module:upgrade method - install all disruptive""" for platform in self.platform_list: if platform.show_install_all_impact: @@ -368,7 +368,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def test_upgrade_install_all_non_disruptive(self): - """ UT: nxos_upgrade module:upgrade method - install all non-disruptive """ + """UT: nxos_upgrade module:upgrade method - install all non-disruptive""" for platform in self.platform_list: if platform.show_install_all_impact_non_disruptive: @@ -391,7 +391,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def test_upgrade_CommandExecutionError_Exception(self): - """ UT: nxos_upgrade module:upgrade method - raise CommandExecutionError exception #1 """ + """UT: nxos_upgrade module:upgrade method - raise CommandExecutionError exception #1""" for platform in self.platform_list: if platform.invalid_command: @@ -419,7 +419,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def test_upgrade_CommandExecutionError_Exception2(self): - """ UT: nxos_upgrade module:upgrade method - raise CommandExecutionError exception #2 """ + """UT: nxos_upgrade module:upgrade method - raise CommandExecutionError exception #2""" for platform in self.platform_list: if platform.invalid_command: @@ -455,7 +455,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def test_upgrade_NxosError_Exception(self): - """ UT: nxos_upgrade module:upgrade method - raise NxosError exception """ + """UT: nxos_upgrade module:upgrade method - raise NxosError exception""" for platform in self.platform_list: if platform.internal_server_error_500: @@ -486,7 +486,7 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): def test_upgrade_NxosError_Exception2(self): - """ UT: nxos_upgrade module:upgrade method - raise NxosError exception #2 """ + """UT: nxos_upgrade module:upgrade method - raise NxosError exception #2""" for platform in self.platform_list: if platform.internal_server_error_500: diff --git a/tests/unit/modules/test_pillar.py b/tests/unit/modules/test_pillar.py index b3c0fbb55a4..9e3b051b051 100644 --- a/tests/unit/modules/test_pillar.py +++ b/tests/unit/modules/test_pillar.py @@ -127,7 +127,8 @@ class PillarModuleTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pillarmod.__pillar__, {"foo": "bar"}): self.assertEqual( - pillarmod.get(key="foo", default=None, merge=True), "bar", + pillarmod.get(key="foo", default=None, merge=True), + "bar", ) def test_pillar_get_int_key(self): @@ -137,7 +138,8 @@ class PillarModuleTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pillarmod.__pillar__, {12345: "luggage_code"}): self.assertEqual( - pillarmod.get(key=12345, default=None, merge=True), "luggage_code", + pillarmod.get(key=12345, default=None, merge=True), + "luggage_code", ) with patch.dict( diff --git a/tests/unit/modules/test_pip.py b/tests/unit/modules/test_pip.py index de5d55fba7a..e908a6f0ae4 100644 --- a/tests/unit/modules/test_pip.py +++ b/tests/unit/modules/test_pip.py @@ -116,7 +116,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pip.__salt__, {"cmd.run_all": mock}): pip.install(editable=editables) mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) # Passing editables as a comma separated list @@ -124,7 +128,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pip.__salt__, {"cmd.run_all": mock}): pip.install(editable=",".join(editables)) mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_multiple_pkgs_and_editables(self): @@ -144,7 +152,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pip.__salt__, {"cmd.run_all": mock}): pip.install(pkgs=pkgs, editable=editables) mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) # Passing editables as a comma separated list @@ -152,7 +164,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pip.__salt__, {"cmd.run_all": mock}): pip.install(pkgs=",".join(pkgs), editable=",".join(editables)) mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) # As single string (just use the first element from pkgs and editables) @@ -169,7 +185,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): editables[0], ] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_issue5940_install_multiple_pip_mirrors(self): @@ -253,7 +273,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pip.__salt__, {"cmd.run_all": mock}): pip.install(pkg, find_links=find_links) mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) # Passing mirrors as a comma separated list @@ -261,7 +285,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pip.__salt__, {"cmd.run_all": mock}): pip.install(pkg, find_links=",".join(find_links)) mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) # Valid protos work? @@ -269,7 +297,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pip.__salt__, {"cmd.run_all": mock}): pip.install(pkg, find_links=find_links) mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) expected = [ @@ -287,7 +319,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pip.__salt__, {"cmd.run_all": mock}): pip.install(pkg, find_links=find_links[0]) mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) # Invalid proto raises exception @@ -467,7 +503,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): pkg, ] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_extra_index_url_argument_in_resulting_command(self): @@ -486,7 +526,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): pkg, ] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_no_index_argument_in_resulting_command(self): @@ -496,7 +540,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): pip.install(pkg, no_index=True) expected = [sys.executable, "-m", "pip", "install", "--no-index", pkg] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_build_argument_in_resulting_command(self): @@ -507,7 +555,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): pip.install(pkg, build=build) expected = [sys.executable, "-m", "pip", "install", "--build", build, pkg] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_target_argument_in_resulting_command(self): @@ -518,7 +570,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): pip.install(pkg, target=target) expected = [sys.executable, "-m", "pip", "install", "--target", target, pkg] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_download_argument_in_resulting_command(self): @@ -537,7 +593,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): pkg, ] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_no_download_argument_in_resulting_command(self): @@ -547,7 +607,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): pip.install(pkg, no_download=True) expected = [sys.executable, "-m", "pip", "install", "--no-download", pkg] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_download_cache_dir_arguments_in_resulting_command(self): @@ -601,7 +665,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): pip.install(pkg, source=source) expected = [sys.executable, "-m", "pip", "install", "--source", source, pkg] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_exists_action_argument_in_resulting_command(self): @@ -648,7 +716,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pip.__salt__, {"cmd.run_all": mock}): pip.install(pkg, install_options=install_options) mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) # Passing mirrors as a comma separated list @@ -656,7 +728,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pip.__salt__, {"cmd.run_all": mock}): pip.install(pkg, install_options=",".join(install_options)) mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) # Passing mirrors as a single string entry @@ -673,7 +749,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): pkg, ] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_global_options_argument_in_resulting_command(self): @@ -690,7 +770,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pip.__salt__, {"cmd.run_all": mock}): pip.install(pkg, global_options=global_options) mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) # Passing mirrors as a comma separated list @@ -698,7 +782,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pip.__salt__, {"cmd.run_all": mock}): pip.install(pkg, global_options=",".join(global_options)) mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) # Passing mirrors as a single string entry @@ -715,7 +803,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): pkg, ] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_upgrade_argument_in_resulting_command(self): @@ -725,7 +817,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): pip.install(pkg, upgrade=True) expected = [sys.executable, "-m", "pip", "install", "--upgrade", pkg] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_force_reinstall_argument_in_resulting_command(self): @@ -742,7 +838,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): pkg, ] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_ignore_installed_argument_in_resulting_command(self): @@ -759,7 +859,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): pkg, ] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_no_deps_argument_in_resulting_command(self): @@ -769,7 +873,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): pip.install(pkg, no_deps=True) expected = [sys.executable, "-m", "pip", "install", "--no-deps", pkg] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_no_install_argument_in_resulting_command(self): @@ -779,7 +887,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): pip.install(pkg, no_install=True) expected = [sys.executable, "-m", "pip", "install", "--no-install", pkg] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_proxy_argument_in_resulting_command(self): @@ -790,7 +902,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): pip.install(pkg, proxy=proxy) expected = [sys.executable, "-m", "pip", "install", "--proxy", proxy, pkg] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_proxy_false_argument_in_resulting_command(self): @@ -928,7 +1044,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): "--latest-pip-arg", ] mock.assert_called_with( - expected, saltenv="base", runas=None, use_vt=False, python_shell=False, + expected, + saltenv="base", + runas=None, + use_vt=False, + python_shell=False, ) def test_install_extra_args_arguments_recursion_error(self): @@ -1155,7 +1275,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): with patch("salt.modules.pip.version", MagicMock(return_value="6.1.1")): ret = pip.freeze() mock.assert_called_with( - expected, cwd=None, runas=None, use_vt=False, python_shell=False, + expected, + cwd=None, + runas=None, + use_vt=False, + python_shell=False, ) self.assertEqual(ret, eggs) @@ -1179,7 +1303,8 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pip.__salt__, {"cmd.run_all": mock}): with patch("salt.modules.pip.version", MagicMock(return_value="6.1.1")): self.assertRaises( - CommandExecutionError, pip.freeze, + CommandExecutionError, + pip.freeze, ) def test_freeze_command_with_all(self): @@ -1198,7 +1323,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): ret = pip.freeze() expected = [sys.executable, "-m", "pip", "freeze", "--all"] mock.assert_called_with( - expected, cwd=None, runas=None, use_vt=False, python_shell=False, + expected, + cwd=None, + runas=None, + use_vt=False, + python_shell=False, ) self.assertEqual(ret, eggs) @@ -1207,7 +1336,8 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pip.__salt__, {"cmd.run_all": mock}): with patch("salt.modules.pip.version", MagicMock(return_value="9.0.1")): self.assertRaises( - CommandExecutionError, pip.freeze, + CommandExecutionError, + pip.freeze, ) def test_list_command(self): @@ -1227,7 +1357,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): ret = pip.list_() expected = [sys.executable, "-m", "pip", "freeze"] mock.assert_called_with( - expected, cwd=None, runas=None, python_shell=False, use_vt=False, + expected, + cwd=None, + runas=None, + python_shell=False, + use_vt=False, ) self.assertEqual( ret, @@ -1246,7 +1380,8 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pip.__salt__, {"cmd.run_all": mock}): with patch("salt.modules.pip.version", MagicMock(return_value="6.1.1")): self.assertRaises( - CommandExecutionError, pip.list_, + CommandExecutionError, + pip.list_, ) def test_list_command_with_all(self): @@ -1271,7 +1406,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): ret = pip.list_() expected = [sys.executable, "-m", "pip", "freeze", "--all"] mock.assert_called_with( - expected, cwd=None, runas=None, python_shell=False, use_vt=False, + expected, + cwd=None, + runas=None, + python_shell=False, + use_vt=False, ) self.assertEqual( ret, @@ -1291,7 +1430,8 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(pip.__salt__, {"cmd.run_all": mock}): with patch("salt.modules.pip.version", MagicMock(return_value="6.1.1")): self.assertRaises( - CommandExecutionError, pip.list_, + CommandExecutionError, + pip.list_, ) def test_list_command_with_prefix(self): @@ -1308,7 +1448,11 @@ class PipTestCase(TestCase, LoaderModuleMockMixin): ret = pip.list_(prefix="bb") expected = [sys.executable, "-m", "pip", "freeze"] mock.assert_called_with( - expected, cwd=None, runas=None, python_shell=False, use_vt=False, + expected, + cwd=None, + runas=None, + python_shell=False, + use_vt=False, ) self.assertEqual(ret, {"bbfreeze-loader": "1.1.0", "bbfreeze": "1.1.0"}) diff --git a/tests/unit/modules/test_pkg_resource.py b/tests/unit/modules/test_pkg_resource.py index 537142e3512..dae0efe689f 100644 --- a/tests/unit/modules/test_pkg_resource.py +++ b/tests/unit/modules/test_pkg_resource.py @@ -22,8 +22,8 @@ class PkgresTestCase(TestCase, LoaderModuleMockMixin): def test_pack_sources(self): """ - Test to accepts list of dicts (or a string representing a - list of dicts) and packs the key/value pairs into a single dict. + Test to accepts list of dicts (or a string representing a + list of dicts) and packs the key/value pairs into a single dict. """ with patch.object( salt.utils.yaml, @@ -39,10 +39,10 @@ class PkgresTestCase(TestCase, LoaderModuleMockMixin): def test_parse_targets(self): """ - Test to parses the input to pkg.install and - returns back the package(s) to be installed. Returns a - list of packages, as well as a string noting whether the - packages are to come from a repository or a binary package. + Test to parses the input to pkg.install and + returns back the package(s) to be installed. Returns a + list of packages, as well as a string noting whether the + packages are to come from a repository or a binary package. """ with patch.dict(pkg_resource.__grains__, {"os": "A"}): self.assertEqual( @@ -84,8 +84,8 @@ class PkgresTestCase(TestCase, LoaderModuleMockMixin): def test_version(self): """ - Test to Common interface for obtaining the version - of installed packages. + Test to Common interface for obtaining the version + of installed packages. """ with patch.object(salt.utils.data, "is_true", return_value=True): mock = MagicMock(return_value={"A": "B"}) @@ -102,22 +102,22 @@ class PkgresTestCase(TestCase, LoaderModuleMockMixin): def test_add_pkg(self): """ - Test to add a package to a dict of installed packages. + Test to add a package to a dict of installed packages. """ self.assertIsNone(pkg_resource.add_pkg({"pkgs": []}, "name", "version")) def test_sort_pkglist(self): """ - Test to accepts a dict obtained from pkg.list_pkgs() and sorts - in place the list of versions for any packages that have multiple - versions installed, so that two package lists can be compared - to one another. + Test to accepts a dict obtained from pkg.list_pkgs() and sorts + in place the list of versions for any packages that have multiple + versions installed, so that two package lists can be compared + to one another. """ self.assertIsNone(pkg_resource.sort_pkglist({})) def test_format_pkg_list_no_attr(self): """ - Test to output format of the package list with no attr parameter. + Test to output format of the package list with no attr parameter. """ packages = { "glibc": [ @@ -160,9 +160,9 @@ class PkgresTestCase(TestCase, LoaderModuleMockMixin): def test_format_pkg_list_with_attr(self): """ - Test to output format of the package list with attr parameter. - In this case, any redundant "arch" reference will be removed from the package name since it's - include as part of the requested attr. + Test to output format of the package list with attr parameter. + In this case, any redundant "arch" reference will be removed from the package name since it's + include as part of the requested attr. """ NAME_ARCH_MAPPING = { "glibc": {"name": "glibc", "arch": None}, @@ -237,15 +237,15 @@ class PkgresTestCase(TestCase, LoaderModuleMockMixin): def test_stringify(self): """ - Test to takes a dict of package name/version information - and joins each list of - installed versions into a string. + Test to takes a dict of package name/version information + and joins each list of + installed versions into a string. """ self.assertIsNone(pkg_resource.stringify({})) def test_version_clean(self): """ - Test to clean the version string removing extra data. + Test to clean the version string removing extra data. """ with patch.dict( pkg_resource.__salt__, {"pkg.version_clean": MagicMock(return_value="A")} @@ -256,8 +256,8 @@ class PkgresTestCase(TestCase, LoaderModuleMockMixin): def test_check_extra_requirements(self): """ - Test to check if the installed package already - has the given requirements. + Test to check if the installed package already + has the given requirements. """ with patch.dict( pkg_resource.__salt__, diff --git a/tests/unit/modules/test_proxy.py b/tests/unit/modules/test_proxy.py index 862abe70279..b5179434420 100644 --- a/tests/unit/modules/test_proxy.py +++ b/tests/unit/modules/test_proxy.py @@ -14,8 +14,8 @@ class ProxyTestCase(TestCase, LoaderModuleMockMixin): def test_get_http_proxy_macos(self): """ - Test to make sure that we correctly get the current proxy info - on macOS + Test to make sure that we correctly get the current proxy info + on macOS """ mock = MagicMock( return_value="Enabled: Yes\nServer: 192.168.0.1\nPort: 3128\nAuthenticated Proxy Enabled: 0" @@ -29,8 +29,8 @@ class ProxyTestCase(TestCase, LoaderModuleMockMixin): def test_get_https_proxy_macos(self): """ - Test to make sure that we correctly get the current proxy info - on macOS + Test to make sure that we correctly get the current proxy info + on macOS """ mock = MagicMock( return_value="Enabled: Yes\nServer: 192.168.0.1\nPort: 3128\nAuthenticated Proxy Enabled: 0" @@ -44,8 +44,8 @@ class ProxyTestCase(TestCase, LoaderModuleMockMixin): def test_get_ftp_proxy_macos(self): """ - Test to make sure that we correctly get the current proxy info - on macOS + Test to make sure that we correctly get the current proxy info + on macOS """ mock = MagicMock( return_value="Enabled: Yes\nServer: 192.168.0.1\nPort: 3128\nAuthenticated Proxy Enabled: 0" @@ -59,7 +59,7 @@ class ProxyTestCase(TestCase, LoaderModuleMockMixin): def test_get_http_proxy_macos_none(self): """ - Test to make sure that we correctly return when there's no proxy set + Test to make sure that we correctly return when there's no proxy set """ mock = MagicMock( return_value="Enabled: No\nServer:\nPort: 0\nAuthenticated Proxy Enabled: 0" @@ -72,8 +72,8 @@ class ProxyTestCase(TestCase, LoaderModuleMockMixin): def test_set_http_proxy_macos(self): """ - Test to make sure that we correctly set the proxy info - on macOS + Test to make sure that we correctly set the proxy info + on macOS """ mock = MagicMock() @@ -92,8 +92,8 @@ class ProxyTestCase(TestCase, LoaderModuleMockMixin): def test_set_https_proxy_macos(self): """ - Test to make sure that we correctly set the proxy info - on macOS + Test to make sure that we correctly set the proxy info + on macOS """ mock = MagicMock() @@ -112,8 +112,8 @@ class ProxyTestCase(TestCase, LoaderModuleMockMixin): def test_set_ftp_proxy_macos(self): """ - Test to make sure that we correctly set the proxy info - on macOS + Test to make sure that we correctly set the proxy info + on macOS """ mock = MagicMock() @@ -302,7 +302,9 @@ class ProxyTestCase(TestCase, LoaderModuleMockMixin): proxy.__utils__, {"reg.set_value": mock_reg} ), patch.dict(proxy.__salt__, {"cmd.run": mock_cmd}): out = proxy.set_http_proxy( - server="192.168.0.1", port=3128, bypass_hosts=[".moo.com", ".salt.com"], + server="192.168.0.1", + port=3128, + bypass_hosts=[".moo.com", ".salt.com"], ) mock_reg.assert_has_calls(calls) mock_cmd.assert_called_once_with("netsh winhttp import proxy source=ie") @@ -339,7 +341,9 @@ class ProxyTestCase(TestCase, LoaderModuleMockMixin): proxy.__utils__, {"reg.set_value": mock_reg} ), patch.dict(proxy.__salt__, {"cmd.run": mock_cmd}): out = proxy.set_https_proxy( - server="192.168.0.1", port=3128, bypass_hosts=[".moo.com", ".salt.com"], + server="192.168.0.1", + port=3128, + bypass_hosts=[".moo.com", ".salt.com"], ) mock_reg.assert_has_calls(calls) mock_cmd.assert_called_once_with("netsh winhttp import proxy source=ie") @@ -376,7 +380,9 @@ class ProxyTestCase(TestCase, LoaderModuleMockMixin): proxy.__utils__, {"reg.set_value": mock_reg} ), patch.dict(proxy.__salt__, {"cmd.run": mock_cmd}): out = proxy.set_ftp_proxy( - server="192.168.0.1", port=3128, bypass_hosts=[".moo.com", ".salt.com"], + server="192.168.0.1", + port=3128, + bypass_hosts=[".moo.com", ".salt.com"], ) mock_reg.assert_has_calls(calls) mock_cmd.assert_called_once_with("netsh winhttp import proxy source=ie") @@ -413,7 +419,9 @@ class ProxyTestCase(TestCase, LoaderModuleMockMixin): proxy.__utils__, {"reg.set_value": mock_reg} ), patch.dict(proxy.__salt__, {"cmd.run": mock_cmd}): out = proxy.set_proxy_win( - server="192.168.0.1", port=3128, bypass_hosts=[".moo.com", ".salt.com"], + server="192.168.0.1", + port=3128, + bypass_hosts=[".moo.com", ".salt.com"], ) mock_reg.assert_has_calls(calls) mock_cmd.assert_called_once_with("netsh winhttp import proxy source=ie") diff --git a/tests/unit/modules/test_reg.py b/tests/unit/modules/test_reg.py index edb177821ab..0b345b83cad 100644 --- a/tests/unit/modules/test_reg.py +++ b/tests/unit/modules/test_reg.py @@ -385,7 +385,12 @@ class WinFunctionsTestCase(TestCase, LoaderModuleMockMixin): "vtype": "REG_MULTI_SZ", } self.assertEqual( - reg.read_value(hive="HKLM", key=FAKE_KEY, vname="empty_list",), expected + reg.read_value( + hive="HKLM", + key=FAKE_KEY, + vname="empty_list", + ), + expected, ) finally: reg.delete_key_recursive(hive="HKLM", key=FAKE_KEY) diff --git a/tests/unit/modules/test_rh_ip.py b/tests/unit/modules/test_rh_ip.py index d3dcf910084..016aee93b78 100644 --- a/tests/unit/modules/test_rh_ip.py +++ b/tests/unit/modules/test_rh_ip.py @@ -76,7 +76,8 @@ class RhipTestCase(TestCase, LoaderModuleMockMixin): for osrelease in range(7, 8): with patch.dict( - rh_ip.__grains__, {"os": "RedHat", "osrelease": str(osrelease)}, + rh_ip.__grains__, + {"os": "RedHat", "osrelease": str(osrelease)}, ): with patch.object(rh_ip, "_raise_error_iface", return_value=None): with patch.object(rh_ip, "_parse_settings_bond", MagicMock()): @@ -392,7 +393,10 @@ class RhipTestCase(TestCase, LoaderModuleMockMixin): kwargs["downdelay"] = 201 try: rh_ip.build_interface( - "bond0", "bond", enabled=True, **kwargs, + "bond0", + "bond", + enabled=True, + **kwargs, ) except AttributeError as exc: assert "multiple of miimon" in str(exc) @@ -414,7 +418,10 @@ class RhipTestCase(TestCase, LoaderModuleMockMixin): # Leaving out miimon should raise an error try: rh_ip.build_interface( - "bond0", "bond", enabled=True, **kwargs, + "bond0", + "bond", + enabled=True, + **kwargs, ) except AttributeError as exc: assert "miimon" in str(exc) @@ -424,7 +431,12 @@ class RhipTestCase(TestCase, LoaderModuleMockMixin): self._validate_miimon_downdelay(kwargs) def _get_bonding_opts(self, kwargs): - results = rh_ip.build_interface("bond0", "bond", enabled=True, **kwargs,) + results = rh_ip.build_interface( + "bond0", + "bond", + enabled=True, + **kwargs, + ) self._check_common_opts_bond(results) for line in results: @@ -781,7 +793,11 @@ class RhipTestCase(TestCase, LoaderModuleMockMixin): ): results = sorted( rh_ip.build_interface( - "eth1", "slave", enabled=True, test=True, master="bond0", + "eth1", + "slave", + enabled=True, + test=True, + master="bond0", ) ) expected = [ diff --git a/tests/unit/modules/test_saltcloudmod.py b/tests/unit/modules/test_saltcloudmod.py index a1ac29df4cb..561451877c9 100644 --- a/tests/unit/modules/test_saltcloudmod.py +++ b/tests/unit/modules/test_saltcloudmod.py @@ -12,7 +12,7 @@ from tests.support.unit import TestCase class SaltcloudmodTestCase(TestCase, LoaderModuleMockMixin): """ - Test cases for salt.modules.saltcloudmod + Test cases for salt.modules.saltcloudmod """ def setup_loader_modules(self): @@ -23,7 +23,7 @@ class SaltcloudmodTestCase(TestCase, LoaderModuleMockMixin): def test_create(self): """ - Test if create the named vm + Test if create the named vm """ mock = MagicMock(return_value="""{"foo": "bar"}""") with patch.dict(saltcloudmod.__salt__, {"cmd.run_stdout": mock}): diff --git a/tests/unit/modules/test_systemd_service.py b/tests/unit/modules/test_systemd_service.py index 65ca30e42d9..a387383c500 100644 --- a/tests/unit/modules/test_systemd_service.py +++ b/tests/unit/modules/test_systemd_service.py @@ -81,7 +81,7 @@ class SystemdTestCase(TestCase, LoaderModuleMockMixin): def test_systemctl_reload(self): """ - Test to Reloads systemctl + Test to Reloads systemctl """ mock = MagicMock( side_effect=[ @@ -263,7 +263,7 @@ class SystemdTestCase(TestCase, LoaderModuleMockMixin): def test_missing(self): """ - Test to the inverse of service.available. + Test to the inverse of service.available. """ mock = MagicMock(side_effect=lambda x: _SYSTEMCTL_STATUS[x]) @@ -318,8 +318,8 @@ class SystemdTestCase(TestCase, LoaderModuleMockMixin): class SystemdScopeTestCase(TestCase, LoaderModuleMockMixin): """ - Test case for salt.modules.systemd, for functions which use systemd - scopes + Test case for salt.modules.systemd, for functions which use systemd + scopes """ def setup_loader_modules(self): diff --git a/tests/unit/modules/test_timezone.py b/tests/unit/modules/test_timezone.py index ff7cf3f8ae3..adbfb240c04 100644 --- a/tests/unit/modules/test_timezone.py +++ b/tests/unit/modules/test_timezone.py @@ -69,8 +69,8 @@ class TimezoneTestCase(TestCase, LoaderModuleMockMixin): class TimezoneModuleTestCase(TestCase, LoaderModuleMockMixin): """ - Timezone test case - """ + Timezone test case + """ TEST_TZ = "UTC" diff --git a/tests/unit/modules/test_tuned.py b/tests/unit/modules/test_tuned.py index c2435b1613f..394aac0274e 100644 --- a/tests/unit/modules/test_tuned.py +++ b/tests/unit/modules/test_tuned.py @@ -124,8 +124,7 @@ No SMBIOS nor DMI entry point found, sorry. ) def test_none(self): - """ - """ + """ """ ret = { "pid": 12345, "retcode": 1, diff --git a/tests/unit/modules/test_virt.py b/tests/unit/modules/test_virt.py index 00a31d148e6..b9a62a7b558 100644 --- a/tests/unit/modules/test_virt.py +++ b/tests/unit/modules/test_virt.py @@ -787,13 +787,16 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): "1-4,^2", ) self.assertEqual( - root.find("cputune").find("vcpupin[@vcpu='1']").attrib.get("cpuset"), "0,1", + root.find("cputune").find("vcpupin[@vcpu='1']").attrib.get("cpuset"), + "0,1", ) self.assertEqual( - root.find("cputune").find("vcpupin[@vcpu='2']").attrib.get("cpuset"), "2,3", + root.find("cputune").find("vcpupin[@vcpu='2']").attrib.get("cpuset"), + "2,3", ) self.assertEqual( - root.find("cputune").find("vcpupin[@vcpu='3']").attrib.get("cpuset"), "0,4", + root.find("cputune").find("vcpupin[@vcpu='3']").attrib.get("cpuset"), + "0,4", ) self.assertEqual( root.find("cputune").find("emulatorpin").attrib.get("cpuset"), "1-3" @@ -1068,7 +1071,15 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): diskp = virt._disk_profile(self.mock_conn, "default", "kvm", [], "hello") nicp = virt._nic_profile("default", "kvm") xml_data = virt._gen_xml( - self.mock_conn, "hello", 1, 512, diskp, nicp, "kvm", "hvm", "x86_64", + self.mock_conn, + "hello", + 1, + 512, + diskp, + nicp, + "kvm", + "hvm", + "x86_64", ) root = ET.fromstring(xml_data) self.assertEqual(root.attrib["type"], "kvm") @@ -1101,7 +1112,15 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): diskp = virt._disk_profile(self.mock_conn, "default", "vmware", [], "hello") nicp = virt._nic_profile("default", "vmware") xml_data = virt._gen_xml( - self.mock_conn, "hello", 1, 512, diskp, nicp, "vmware", "hvm", "x86_64", + self.mock_conn, + "hello", + 1, + 512, + diskp, + nicp, + "vmware", + "hvm", + "x86_64", ) root = ET.fromstring(xml_data) self.assertEqual(root.attrib["type"], "vmware") @@ -1150,7 +1169,15 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): ) nicp = virt._nic_profile("noeffect", "vmware") xml_data = virt._gen_xml( - self.mock_conn, "hello", 1, 512, diskp, nicp, "vmware", "hvm", "x86_64", + self.mock_conn, + "hello", + 1, + 512, + diskp, + nicp, + "vmware", + "hvm", + "x86_64", ) root = ET.fromstring(xml_data) self.assertEqual(root.attrib["type"], "vmware") @@ -1183,7 +1210,15 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): diskp = virt._disk_profile(self.mock_conn, "noeffect", "kvm", [], "hello") nicp = virt._nic_profile("noeffect", "kvm") xml_data = virt._gen_xml( - self.mock_conn, "hello", 1, 512, diskp, nicp, "kvm", "hvm", "x86_64", + self.mock_conn, + "hello", + 1, + 512, + diskp, + nicp, + "kvm", + "hvm", + "x86_64", ) root = ET.fromstring(xml_data) self.assertEqual(root.attrib["type"], "kvm") @@ -1366,7 +1401,15 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): ) nicp = virt._nic_profile(None, "kvm") xml_data = virt._gen_xml( - self.mock_conn, "hello", 1, 512, diskp, nicp, "kvm", "hvm", "x86_64", + self.mock_conn, + "hello", + 1, + 512, + diskp, + nicp, + "kvm", + "hvm", + "x86_64", ) root = ET.fromstring(xml_data) disk = root.findall(".//disk")[0] @@ -1415,7 +1458,15 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): "test-vm", ) xml_data = virt._gen_xml( - self.mock_conn, "hello", 1, 512, diskp, nicp, "kvm", "hvm", "x86_64", + self.mock_conn, + "hello", + 1, + 512, + diskp, + nicp, + "kvm", + "hvm", + "x86_64", ) root = ET.fromstring(xml_data) disk = root.findall(".//disk")[0] @@ -1475,7 +1526,15 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): "test-vm", ) xml_data = virt._gen_xml( - self.mock_conn, "hello", 1, 512, diskp, nicp, "kvm", "hvm", "x86_64", + self.mock_conn, + "hello", + 1, + 512, + diskp, + nicp, + "kvm", + "hvm", + "x86_64", ) root = ET.fromstring(xml_data) self.assertDictEqual( @@ -1523,7 +1582,15 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): "test-vm", ) xml_data = virt._gen_xml( - self.mock_conn, "hello", 1, 512, diskp, nicp, "kvm", "hvm", "x86_64", + self.mock_conn, + "hello", + 1, + 512, + diskp, + nicp, + "kvm", + "hvm", + "x86_64", ) root = ET.fromstring(xml_data) disk = root.findall(".//disk")[0] @@ -1553,7 +1620,15 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): "hello", ) xml_data = virt._gen_xml( - self.mock_conn, "hello", 1, 512, diskp, [], "xen", "hvm", "x86_64", + self.mock_conn, + "hello", + 1, + 512, + diskp, + [], + "xen", + "hvm", + "x86_64", ) root = ET.fromstring(xml_data) disk = root.findall(".//disk")[0] @@ -1585,7 +1660,15 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): "hello", ) xml_data = virt._gen_xml( - self.mock_conn, "hello", 1, 512, diskp, [], "xen", "hvm", "x86_64", + self.mock_conn, + "hello", + 1, + 512, + diskp, + [], + "xen", + "hvm", + "x86_64", ) root = ET.fromstring(xml_data) disk = root.findall(".//disk")[0] @@ -1622,7 +1705,15 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): ) nicp = virt._nic_profile(None, "kvm") xml_data = virt._gen_xml( - self.mock_conn, "hello", 1, 512, diskp, nicp, "kvm", "hvm", "x86_64", + self.mock_conn, + "hello", + 1, + 512, + diskp, + nicp, + "kvm", + "hvm", + "x86_64", ) root = ET.fromstring(xml_data) disk = root.findall(".//disk")[1] @@ -1651,7 +1742,15 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): diskp = virt._disk_profile(self.mock_conn, "default", "vmware", [], "hello") nicp = virt._nic_profile("default", "vmware") xml_data = virt._gen_xml( - self.mock_conn, "hello", 1, 512, diskp, nicp, "vmware", "hvm", "x86_64", + self.mock_conn, + "hello", + 1, + 512, + diskp, + nicp, + "vmware", + "hvm", + "x86_64", ) root = ET.fromstring(xml_data) controllers = root.findall(".//devices/controller") @@ -1666,7 +1765,15 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): diskp = virt._disk_profile(self.mock_conn, "default", "kvm", [], "hello") nicp = virt._nic_profile("default", "kvm") xml_data = virt._gen_xml( - self.mock_conn, "hello", 1, 512, diskp, nicp, "kvm", "hvm", "x86_64", + self.mock_conn, + "hello", + 1, + 512, + diskp, + nicp, + "kvm", + "hvm", + "x86_64", ) root = ET.fromstring(xml_data) controllers = root.findall(".//devices/controller") @@ -1953,7 +2060,8 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(virt.__dict__, {"CACHE_DIR": cache_dir}): with patch( - "urllib.request.urlopen", MagicMock(return_value=mock_response), + "urllib.request.urlopen", + MagicMock(return_value=mock_response), ): with patch( "salt.utils.files.fopen", return_value=mock_response @@ -2090,7 +2198,8 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): for call in create_calls ] self.assertEqual( - ["test vm_system", "test vm_test"], vol_names, + ["test vm_system", "test vm_test"], + vol_names, ) stream_mock.sendAll.assert_called_once() @@ -3144,7 +3253,8 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): str(512 * 1024 ** 2), ) self.assertEqual( - setxml.find("./cpu/numa/cell/[@id='0']").get("unit"), "bytes", + setxml.find("./cpu/numa/cell/[@id='0']").get("unit"), + "bytes", ) self.assertEqual( setxml.find("./cpu/numa/cell/[@id='0']").attrib["discard"], "yes" @@ -3182,7 +3292,8 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): str(int(2 * 1024 ** 3)), ) self.assertEqual( - setxml.find("./cpu/numa/cell/[@id='1']").get("unit"), "bytes", + setxml.find("./cpu/numa/cell/[@id='1']").get("unit"), + "bytes", ) self.assertEqual( setxml.find("./cpu/numa/cell/[@id='1']").attrib["discard"], "yes" @@ -3249,7 +3360,8 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): str(512 * 1024 ** 2), ) self.assertEqual( - setxml.find("./cpu/numa/cell/[@id='0']").get("unit"), "bytes", + setxml.find("./cpu/numa/cell/[@id='0']").get("unit"), + "bytes", ) self.assertEqual( setxml.find("./cpu/numa/cell/[@id='0']").attrib.get("discard"), "no" @@ -3338,7 +3450,8 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): "25", ) self.assertEqual( - setxml.find("./cpu/numa/cell/[@id='1']/distances/sibling/[@id='3']"), None, + setxml.find("./cpu/numa/cell/[@id='1']/distances/sibling/[@id='3']"), + None, ) def test_update_memtune_params(self): @@ -3405,7 +3518,8 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): str(int(2.5 * 1024 ** 2)), ) self.assertEqual( - setxml.find("memtune").find("swap_hard_limit").get("unit"), "KiB", + setxml.find("memtune").find("swap_hard_limit").get("unit"), + "KiB", ) self.assertEqual( setxml.find("memtune").find("min_guarantee").text, str(1 * 1024 ** 3) @@ -5074,7 +5188,8 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): "44454c4c-3400-105a-8033-b3c04f4b344a", caps["host"]["host"]["uuid"] ) self.assertEqual( - {"qemu", "kvm"}, {domainCaps["domain"] for domainCaps in caps["domains"]}, + {"qemu", "kvm"}, + {domainCaps["domain"] for domainCaps in caps["domains"]}, ) self.assertEqual( diff --git a/tests/unit/modules/test_virtualenv_mod.py b/tests/unit/modules/test_virtualenv_mod.py index 1c562a3432e..358cb37b2a4 100644 --- a/tests/unit/modules/test_virtualenv_mod.py +++ b/tests/unit/modules/test_virtualenv_mod.py @@ -217,7 +217,9 @@ class VirtualenvTestCase(TestCase, LoaderModuleMockMixin): mock = MagicMock(return_value={"retcode": 0, "stdout": ""}) with patch.dict(virtualenv_mod.__salt__, {"cmd.run_all": mock}): self.assertRaises( - CommandExecutionError, virtualenv_mod.create, "/tmp/foo", + CommandExecutionError, + virtualenv_mod.create, + "/tmp/foo", ) # <---- virtualenv binary not available -------------------------- @@ -272,7 +274,8 @@ class VirtualenvTestCase(TestCase, LoaderModuleMockMixin): with patch.dict(virtualenv_mod.__salt__, {"cmd.run_all": mock}): virtualenv_mod.create( - "/tmp/foo", python=sys.executable, + "/tmp/foo", + python=sys.executable, ) mock.assert_called_once_with( ["virtualenv", "--python={}".format(sys.executable), "/tmp/foo"], diff --git a/tests/unit/modules/test_win_certutil.py b/tests/unit/modules/test_win_certutil.py index 78dfec44f76..031889a11a4 100644 --- a/tests/unit/modules/test_win_certutil.py +++ b/tests/unit/modules/test_win_certutil.py @@ -10,7 +10,7 @@ class CertUtilTestCase(TestCase, LoaderModuleMockMixin): def test_get_serial(self): """ - Test getting the serial number from a certificate + Test getting the serial number from a certificate """ expected = "180720d39cd2db3244ba037417241e90" mock = MagicMock( @@ -30,7 +30,7 @@ class CertUtilTestCase(TestCase, LoaderModuleMockMixin): def test_get_serials(self): """ - Test getting all the serial numbers from a store + Test getting all the serial numbers from a store """ expected = [ "180720d39cd2db3244ba037417241e90", @@ -55,7 +55,7 @@ class CertUtilTestCase(TestCase, LoaderModuleMockMixin): def test_add_store(self): """ - Test adding a certificate to a specific store + Test adding a certificate to a specific store """ cmd_mock = MagicMock( return_value=( @@ -77,7 +77,7 @@ class CertUtilTestCase(TestCase, LoaderModuleMockMixin): def test_del_store(self): """ - Test removing a certificate to a specific store + Test removing a certificate to a specific store """ with patch("salt.modules.win_certutil.get_cert_serial") as cert_serial_mock: cmd_mock = MagicMock( diff --git a/tests/unit/modules/test_win_dism.py b/tests/unit/modules/test_win_dism.py index 241917c6a98..360580e5b39 100644 --- a/tests/unit/modules/test_win_dism.py +++ b/tests/unit/modules/test_win_dism.py @@ -10,7 +10,7 @@ class WinDismTestCase(TestCase, LoaderModuleMockMixin): def test_add_capability(self): """ - Test installing a capability with DISM + Test installing a capability with DISM """ mock = MagicMock() with patch.dict(dism.__salt__, {"cmd.run_all": mock}): @@ -29,7 +29,7 @@ class WinDismTestCase(TestCase, LoaderModuleMockMixin): def test_add_capability_with_extras(self): """ - Test installing a capability with DISM + Test installing a capability with DISM """ mock = MagicMock() with patch.dict(dism.__salt__, {"cmd.run_all": mock}): @@ -50,7 +50,7 @@ class WinDismTestCase(TestCase, LoaderModuleMockMixin): def test_remove_capability(self): """ - Test uninstalling a capability with DISM + Test uninstalling a capability with DISM """ mock = MagicMock() with patch.dict(dism.__salt__, {"cmd.run_all": mock}): @@ -69,7 +69,7 @@ class WinDismTestCase(TestCase, LoaderModuleMockMixin): def test_get_capabilities(self): """ - Test getting all the capabilities + Test getting all the capabilities """ capabilties = ( "Capability Identity : Capa1\r\n State : Installed\r\n" @@ -87,7 +87,7 @@ class WinDismTestCase(TestCase, LoaderModuleMockMixin): def test_installed_capabilities(self): """ - Test getting all the installed capabilities + Test getting all the installed capabilities """ capabilties = ( "Capability Identity : Capa1\r\n State : Installed\r\n" @@ -105,7 +105,7 @@ class WinDismTestCase(TestCase, LoaderModuleMockMixin): def test_available_capabilities(self): """ - Test getting all the available capabilities + Test getting all the available capabilities """ capabilties = ( "Capability Identity : Capa1\r\n State : Installed\r\n" @@ -123,7 +123,7 @@ class WinDismTestCase(TestCase, LoaderModuleMockMixin): def test_add_feature(self): """ - Test installing a feature with DISM + Test installing a feature with DISM """ mock = MagicMock() with patch.dict(dism.__salt__, {"cmd.run_all": mock}): @@ -141,7 +141,7 @@ class WinDismTestCase(TestCase, LoaderModuleMockMixin): def test_add_feature_with_extras(self): """ - Test installing a feature with DISM + Test installing a feature with DISM """ mock = MagicMock() with patch.dict(dism.__salt__, {"cmd.run_all": mock}): @@ -163,7 +163,7 @@ class WinDismTestCase(TestCase, LoaderModuleMockMixin): def test_remove_feature(self): """ - Test uninstalling a capability with DISM + Test uninstalling a capability with DISM """ mock = MagicMock() with patch.dict(dism.__salt__, {"cmd.run_all": mock}): @@ -181,7 +181,7 @@ class WinDismTestCase(TestCase, LoaderModuleMockMixin): def test_remove_feature_with_extras(self): """ - Test uninstalling a capability with DISM + Test uninstalling a capability with DISM """ mock = MagicMock() with patch.dict(dism.__salt__, {"cmd.run_all": mock}): @@ -200,7 +200,7 @@ class WinDismTestCase(TestCase, LoaderModuleMockMixin): def test_get_features(self): """ - Test getting all the features + Test getting all the features """ features = ( "Feature Name : Capa1\r\n State : Enabled\r\n" @@ -217,7 +217,7 @@ class WinDismTestCase(TestCase, LoaderModuleMockMixin): def test_installed_features(self): """ - Test getting all the installed features + Test getting all the installed features """ features = ( "Feature Name : Capa1\r\n State : Enabled\r\n" @@ -234,7 +234,7 @@ class WinDismTestCase(TestCase, LoaderModuleMockMixin): def test_available_features(self): """ - Test getting all the available features + Test getting all the available features """ features = ( "Feature Name : Capa1\r\n State : Enabled\r\n" @@ -251,7 +251,7 @@ class WinDismTestCase(TestCase, LoaderModuleMockMixin): def test_add_package(self): """ - Test installing a package with DISM + Test installing a package with DISM """ mock = MagicMock() with patch.dict(dism.__salt__, {"cmd.run_all": mock}): @@ -269,7 +269,7 @@ class WinDismTestCase(TestCase, LoaderModuleMockMixin): def test_add_package_with_extras(self): """ - Test installing a package with DISM + Test installing a package with DISM """ mock = MagicMock() with patch.dict(dism.__salt__, {"cmd.run_all": mock}): @@ -289,7 +289,7 @@ class WinDismTestCase(TestCase, LoaderModuleMockMixin): def test_remove_package(self): """ - Test uninstalling a package with DISM + Test uninstalling a package with DISM """ mock = MagicMock() with patch.dict(dism.__salt__, {"cmd.run_all": mock}): @@ -307,7 +307,7 @@ class WinDismTestCase(TestCase, LoaderModuleMockMixin): def test_installed_packages(self): """ - Test getting all the installed features + Test getting all the installed features """ features = ( "Package Identity : Capa1\r\n State : Installed\r\n" diff --git a/tests/unit/modules/test_win_file.py b/tests/unit/modules/test_win_file.py index 5350254aae2..5aa571a01a3 100644 --- a/tests/unit/modules/test_win_file.py +++ b/tests/unit/modules/test_win_file.py @@ -39,7 +39,7 @@ class DummyStat: class WinFileTestCase(TestCase, LoaderModuleMockMixin): """ - Test cases for salt.modules.win_file + Test cases for salt.modules.win_file """ FAKE_RET = {"fake": "ret data"} diff --git a/tests/unit/modules/test_win_license.py b/tests/unit/modules/test_win_license.py index 76812947a7d..d11310cb4da 100644 --- a/tests/unit/modules/test_win_license.py +++ b/tests/unit/modules/test_win_license.py @@ -10,7 +10,7 @@ class LicenseTestCase(TestCase, LoaderModuleMockMixin): def test_installed(self): """ - Test to see if the given license key is installed + Test to see if the given license key is installed """ mock = MagicMock(return_value="Partial Product Key: ABCDE") with patch.dict(win_license.__salt__, {"cmd.run": mock}): @@ -20,7 +20,7 @@ class LicenseTestCase(TestCase, LoaderModuleMockMixin): def test_installed_diff(self): """ - Test to see if the given license key is installed when the key is different + Test to see if the given license key is installed when the key is different """ mock = MagicMock(return_value="Partial Product Key: 12345") with patch.dict(win_license.__salt__, {"cmd.run": mock}): @@ -30,7 +30,7 @@ class LicenseTestCase(TestCase, LoaderModuleMockMixin): def test_install(self): """ - Test installing the given product key + Test installing the given product key """ mock = MagicMock() with patch.dict(win_license.__salt__, {"cmd.run": mock}): @@ -42,7 +42,7 @@ class LicenseTestCase(TestCase, LoaderModuleMockMixin): def test_uninstall(self): """ - Test uninstalling the given product key + Test uninstalling the given product key """ mock = MagicMock() with patch.dict(win_license.__salt__, {"cmd.run": mock}): @@ -51,7 +51,7 @@ class LicenseTestCase(TestCase, LoaderModuleMockMixin): def test_activate(self): """ - Test activating the current product key + Test activating the current product key """ mock = MagicMock() with patch.dict(win_license.__salt__, {"cmd.run": mock}): @@ -60,7 +60,7 @@ class LicenseTestCase(TestCase, LoaderModuleMockMixin): def test_licensed(self): """ - Test checking if the minion is licensed + Test checking if the minion is licensed """ mock = MagicMock(return_value="License Status: Licensed") with patch.dict(win_license.__salt__, {"cmd.run": mock}): @@ -69,7 +69,7 @@ class LicenseTestCase(TestCase, LoaderModuleMockMixin): def test_info(self): """ - Test getting the info about the current license key + Test getting the info about the current license key """ expected = { "description": "Prof", diff --git a/tests/unit/modules/test_win_pkg.py b/tests/unit/modules/test_win_pkg.py index 8e8abc3f435..f57e456626f 100644 --- a/tests/unit/modules/test_win_pkg.py +++ b/tests/unit/modules/test_win_pkg.py @@ -308,7 +308,10 @@ class WinPkgInstallTestCase(TestCase, LoaderModuleMockMixin): "cp.cache_file": mock_minion_error, }, ): - ret = win_pkg.install(name="firebox", version="3.03",) + ret = win_pkg.install( + name="firebox", + version="3.03", + ) expected = ( "Failed to cache https://repo.test.com/runme.exe\n" "Error: [Errno 11001] getaddrinfo failed reading https://repo.test.com/runme.exe" @@ -349,7 +352,10 @@ class WinPkgInstallTestCase(TestCase, LoaderModuleMockMixin): "cp.cache_file": mock_minion_error, }, ): - ret = win_pkg.install(name="firebox", version="3.03",) + ret = win_pkg.install( + name="firebox", + version="3.03", + ) expected = ( "Failed to cache salt://software/runme.exe\n" "Error: [Errno 1] failed reading salt://software/runme.exe" @@ -384,9 +390,13 @@ class WinPkgInstallTestCase(TestCase, LoaderModuleMockMixin): ), patch.object( win_pkg, "_get_package_info", MagicMock(return_value=ret__get_package_info) ), patch.dict( - win_pkg.__salt__, {"cp.cache_dir": mock_minion_error}, + win_pkg.__salt__, + {"cp.cache_dir": mock_minion_error}, ): - ret = win_pkg.install(name="firebox", version="3.03",) + ret = win_pkg.install( + name="firebox", + version="3.03", + ) expected = ( "Failed to cache salt://software\n" "Error: [Errno 1] failed reading salt://software" diff --git a/tests/unit/modules/test_win_service.py b/tests/unit/modules/test_win_service.py index 92dff1166d9..9b12e6029a5 100644 --- a/tests/unit/modules/test_win_service.py +++ b/tests/unit/modules/test_win_service.py @@ -19,7 +19,7 @@ except ImportError: class WinServiceTestCase(TestCase, LoaderModuleMockMixin): """ - Test cases for salt.modules.win_service + Test cases for salt.modules.win_service """ def setup_loader_modules(self): @@ -27,7 +27,7 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): def test_get_enabled(self): """ - Test to return the enabled services + Test to return the enabled services """ mock = MagicMock( return_value=[ @@ -49,7 +49,7 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): def test_get_disabled(self): """ - Test to return the disabled services + Test to return the disabled services """ mock = MagicMock( return_value=[ @@ -73,8 +73,8 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): def test_available(self): """ - Test to Returns ``True`` if the specified service - is available, otherwise returns ``False`` + Test to Returns ``True`` if the specified service + is available, otherwise returns ``False`` """ mock = MagicMock(return_value=["c", "a", "b"]) with patch.object(win_service, "get_all", mock): @@ -82,7 +82,7 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): def test_missing(self): """ - Test to the inverse of service.available + Test to the inverse of service.available """ mock = MagicMock(return_value=["c", "a", "b"]) with patch.object(win_service, "get_all", mock): @@ -90,7 +90,7 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): def test_get_all(self): """ - Test to return all installed services + Test to return all installed services """ mock = MagicMock( return_value=[ @@ -106,8 +106,8 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): def test_get_service_name(self): """ - Test to the Display Name is what is displayed - in Windows when services.msc is executed. + Test to the Display Name is what is displayed + in Windows when services.msc is executed. """ mock = MagicMock( return_value=[ @@ -134,7 +134,7 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): @pytest.mark.slow_test def test_start(self): """ - Test to start the specified service + Test to start the specified service """ mock_true = MagicMock(return_value=True) mock_false = MagicMock(return_value=False) @@ -179,7 +179,7 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): @pytest.mark.slow_test def test_stop(self): """ - Test to stop the specified service + Test to stop the specified service """ mock_true = MagicMock(return_value=True) mock_false = MagicMock(return_value=False) @@ -219,7 +219,7 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): def test_restart(self): """ - Test to restart the named service + Test to restart the named service """ mock_true = MagicMock(return_value=True) with patch.object(win_service, "create_win_salt_restart_task", mock_true): @@ -232,8 +232,8 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): def test_createwin_saltrestart_task(self): """ - Test to create a task in Windows task - scheduler to enable restarting the salt-minion + Test to create a task in Windows task + scheduler to enable restarting the salt-minion """ cmd = salt.utils.path.which("cmd") mock = MagicMock() @@ -254,7 +254,7 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): def test_execute_salt_restart_task(self): """ - Test to run the Windows Salt restart task + Test to run the Windows Salt restart task """ mock_true = MagicMock(return_value=True) with patch.dict(win_service.__salt__, {"task.run": mock_true}): @@ -263,7 +263,7 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): @skipIf(not WINAPI, "win32serviceutil not available") def test_status(self): """ - Test to return the status for a service + Test to return the status for a service """ mock_info = MagicMock( side_effect=[ @@ -280,7 +280,7 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): def test_getsid(self): """ - Test to return the sid for this windows service + Test to return the sid for this windows service """ mock_info = MagicMock( side_effect=[{"sid": "S-1-5-80-1956725871..."}, {"sid": None}] @@ -291,7 +291,7 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): def test_enable(self): """ - Test to enable the named service to start at boot + Test to enable the named service to start at boot """ mock_modify = MagicMock(return_value=True) mock_info = MagicMock( @@ -303,7 +303,7 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): def test_disable(self): """ - Test to disable the named service to start at boot + Test to disable the named service to start at boot """ mock_modify = MagicMock(return_value=True) mock_info = MagicMock(return_value={"StartType": "Disabled"}) @@ -313,8 +313,8 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): def test_enabled(self): """ - Test to check to see if the named - service is enabled to start on boot + Test to check to see if the named + service is enabled to start on boot """ mock = MagicMock(side_effect=[{"StartType": "Auto"}, {"StartType": "Disabled"}]) with patch.object(win_service, "info", mock): @@ -323,9 +323,9 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): 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 + 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): @@ -334,8 +334,8 @@ class WinServiceTestCase(TestCase, LoaderModuleMockMixin): def test_disabled(self): """ - Test to check to see if the named - service is disabled to start on boot + Test to check to see if the named + service is disabled to start on boot """ mock = MagicMock(side_effect=[False, True]) with patch.object(win_service, "enabled", mock): diff --git a/tests/unit/modules/test_win_system.py b/tests/unit/modules/test_win_system.py index 3ba17793b37..a5c0828823e 100644 --- a/tests/unit/modules/test_win_system.py +++ b/tests/unit/modules/test_win_system.py @@ -126,7 +126,7 @@ class MockWMI_BIOS: @skipIf(not salt.utils.platform.is_windows(), "System is not Windows") class WinSystemTestCase(TestCase, LoaderModuleMockMixin): """ - Test cases for salt.modules.win_system + Test cases for salt.modules.win_system """ def setup_loader_modules(self): @@ -165,7 +165,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): def test_halt(self): """ - Test to halt a running system + Test to halt a running system """ mock = MagicMock(return_value="salt") with patch.object(win_system, "shutdown", mock): @@ -173,14 +173,14 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): def test_init(self): """ - Test to change the system runlevel on sysV compatible systems + Test to change the system runlevel on sysV compatible systems """ self.assertEqual(win_system.init(3), "Not implemented on Windows at this time.") @skipIf(not win_system.HAS_WIN32NET_MODS, "Missing win32 libraries") def test_poweroff(self): """ - Test to poweroff a running system + Test to poweroff a running system """ mock = MagicMock(return_value="salt") with patch.object(win_system, "shutdown", mock): @@ -189,7 +189,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): @skipIf(not win_system.HAS_WIN32NET_MODS, "Missing win32 libraries") def test_reboot(self): """ - Test to reboot the system + Test to reboot the system """ with patch("salt.modules.win_system.shutdown", MagicMock(return_value=True)): self.assertEqual(win_system.reboot(), True) @@ -197,7 +197,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): @skipIf(not win_system.HAS_WIN32NET_MODS, "Missing win32 libraries") def test_reboot_with_timeout_in_minutes(self): """ - Test to reboot the system with a timeout + Test to reboot the system with a timeout """ with patch( "salt.modules.win_system.shutdown", MagicMock(return_value=True) @@ -210,7 +210,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): @skipIf(not win_system.HAS_WIN32NET_MODS, "Missing win32 libraries") def test_reboot_with_timeout_in_seconds(self): """ - Test to reboot the system with a timeout + Test to reboot the system with a timeout """ with patch( "salt.modules.win_system.shutdown", MagicMock(return_value=True) @@ -223,8 +223,8 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): @skipIf(not win_system.HAS_WIN32NET_MODS, "Missing win32 libraries") def test_reboot_with_wait(self): """ - Test to reboot the system with a timeout and - wait for it to finish + Test to reboot the system with a timeout and + wait for it to finish """ with patch( "salt.modules.win_system.shutdown", MagicMock(return_value=True) @@ -235,7 +235,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): @skipIf(not win_system.HAS_WIN32NET_MODS, "Missing win32 libraries") def test_shutdown(self): """ - Test to shutdown a running system + Test to shutdown a running system """ with patch( "salt.modules.win_system.win32api.InitiateSystemShutdown", MagicMock() @@ -245,7 +245,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): @skipIf(not win_system.HAS_WIN32NET_MODS, "Missing win32 libraries") def test_shutdown_hard(self): """ - Test to shutdown a running system with no timeout or warning + Test to shutdown a running system with no timeout or warning """ with patch( "salt.modules.win_system.shutdown", MagicMock(return_value=True) @@ -256,7 +256,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): @skipIf(not win_system.HAS_WIN32NET_MODS, "Missing win32 libraries") def test_set_computer_name(self): """ - Test to set the Windows computer name + Test to set the Windows computer name """ with patch( "salt.modules.win_system.windll.kernel32.SetComputerNameExW", @@ -264,7 +264,9 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): ), patch.object( win_system, "get_computer_name", MagicMock(return_value="salt") ), patch.object( - win_system, "get_pending_computer_name", MagicMock(return_value="salt_new"), + win_system, + "get_pending_computer_name", + MagicMock(return_value="salt_new"), ): self.assertDictEqual( win_system.set_computer_name("salt_new"), @@ -280,7 +282,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): @skipIf(not win_system.HAS_WIN32NET_MODS, "Missing win32 libraries") def test_set_computer_desc(self): """ - Test to set the Windows computer description + Test to set the Windows computer description """ mock = MagicMock() mock_get_info = MagicMock(return_value={"comment": ""}) @@ -300,7 +302,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): @skipIf(not win_system.HAS_WIN32NET_MODS, "Missing win32 libraries") def test_get_computer_desc(self): """ - Test to get the Windows computer description + Test to get the Windows computer description """ with patch( "salt.modules.win_system.get_system_info", @@ -314,7 +316,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): @skipIf(not win_system.HAS_WIN32NET_MODS, "Missing win32 libraries") def test_join_domain(self): """ - Test to join a computer to an Active Directory domain + Test to join a computer to an Active Directory domain """ with patch( "salt.modules.win_system._join_domain", MagicMock(return_value=0) @@ -330,8 +332,8 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): @skipIf(not win_system.HAS_WIN32NET_MODS, "Missing win32 libraries") def test_join_domain_already_joined(self): """ - Test to join a computer to an Active Directory domain when it is - already joined + Test to join a computer to an Active Directory domain when it is + already joined """ with patch( "salt.modules.win_system._join_domain", MagicMock(return_value=0) @@ -347,7 +349,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): @skipIf(not win_system.HAS_WIN32NET_MODS, "Missing win32 libraries") def test_unjoin_domain(self): """ - Test unjoining a computer from an Active Directory domain + Test unjoining a computer from an Active Directory domain """ with patch("salt.utils.winapi.Com", MagicMock()), patch.object( self.WMI, "Win32_ComputerSystem", return_value=[MockWMI_ComputerSystem()] @@ -363,7 +365,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): @skipIf(not win_system.HAS_WIN32NET_MODS, "Missing win32 libraries") def test_unjoin_domain_already_unjoined(self): """ - Test unjoining a computer from an Active Directory domain + Test unjoining a computer from an Active Directory domain """ with patch("salt.utils.winapi.Com", MagicMock()), patch.object( self.WMI, "Win32_ComputerSystem", return_value=[MockWMI_ComputerSystem()] @@ -375,7 +377,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): def test_get_system_time(self): """ - Test to get system time + Test to get system time """ tm = datetime.strftime(datetime.now(), "%I:%M:%S %p") win_tm = win_system.get_system_time() @@ -390,7 +392,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): @skipIf(not win_system.HAS_WIN32NET_MODS, "Missing win32 libraries") def test_set_system_time(self): """ - Test to set system time + Test to set system time """ with patch( "salt.modules.win_system.set_system_date_time", @@ -401,7 +403,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): def test_get_system_date(self): """ - Test to get system date + Test to get system date """ date = datetime.strftime(datetime.now(), "%m/%d/%Y") self.assertEqual(win_system.get_system_date(), date) @@ -409,7 +411,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): @skipIf(not win_system.HAS_WIN32NET_MODS, "Missing win32 libraries") def test_set_system_date(self): """ - Test to set system date + Test to set system date """ with patch( "salt.modules.win_system.set_system_date_time", @@ -420,7 +422,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): def test_start_time_service(self): """ - Test to start the Windows time service + Test to start the Windows time service """ mock = MagicMock(return_value=True) with patch.dict(win_system.__salt__, {"service.start": mock}): @@ -428,7 +430,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): def test_stop_time_service(self): """ - Test to stop the windows time service + Test to stop the windows time service """ mock = MagicMock(return_value=True) with patch.dict(win_system.__salt__, {"service.stop": mock}): @@ -436,7 +438,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): def test_set_hostname(self): """ - Test setting a new hostname + Test setting a new hostname """ with patch("salt.utils.winapi.Com", MagicMock()), patch.object( self.WMI, "Win32_ComputerSystem", return_value=[MockWMI_ComputerSystem()] @@ -469,7 +471,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): def test_get_hostname(self): """ - Test getting a new hostname + Test getting a new hostname """ cmd_run_mock = MagicMock(return_value="MINION") with patch.dict(win_system.__salt__, {"cmd.run": cmd_run_mock}): diff --git a/tests/unit/modules/test_xapi_virt.py b/tests/unit/modules/test_xapi_virt.py index 7b0b19abb1e..c7e5b79316e 100644 --- a/tests/unit/modules/test_xapi_virt.py +++ b/tests/unit/modules/test_xapi_virt.py @@ -11,7 +11,7 @@ from tests.support.unit import TestCase class Mockxapi: """ - Mock xapi class + Mock xapi class """ def __init__(self): @@ -19,7 +19,7 @@ class Mockxapi: class Session: """ - Mock Session class + Mock Session class """ def __init__(self, xapi_uri): @@ -27,7 +27,7 @@ class Mockxapi: class xenapi: """ - Mock xenapi class + Mock xenapi class """ def __init__(self): @@ -36,13 +36,13 @@ class Mockxapi: @staticmethod def login_with_password(xapi_login, xapi_password): """ - Mock login_with_password method + Mock login_with_password method """ return xapi_login, xapi_password class session: """ - Mock session class + Mock session class """ def __init__(self): @@ -51,14 +51,14 @@ class Mockxapi: @staticmethod def logout(): """ - Mock logout method + Mock logout method """ return Mockxapi() class XapiTestCase(TestCase, LoaderModuleMockMixin): """ - Test cases for salt.modules.xapi + Test cases for salt.modules.xapi """ def setup_loader_modules(self): @@ -66,14 +66,14 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_list_domains(self): """ - Test to return a list of domain names on the minion + Test to return a list of domain names on the minion """ with patch.object(xapi, "_get_xapi_session", MagicMock()): self.assertListEqual(xapi.list_domains(), []) def test_vm_info(self): """ - Test to return detailed information about the vms + Test to return detailed information about the vms """ with patch.object(xapi, "_get_xapi_session", MagicMock()): mock = MagicMock(return_value=False) @@ -82,7 +82,7 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_vm_state(self): """ - Test to return list of all the vms and their state. + Test to return list of all the vms and their state. """ with patch.object(xapi, "_get_xapi_session", MagicMock()): mock = MagicMock(return_value={"power_state": "1"}) @@ -93,7 +93,7 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_get_nics(self): """ - Test to return info about the network interfaces of a named vm + Test to return info about the network interfaces of a named vm """ ret = {"Stack": {"device": "ETH0", "mac": "Stack", "mtu": 1}} with patch.object(xapi, "_get_xapi_session", MagicMock()): @@ -109,7 +109,7 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_get_macs(self): """ - Test to return a list off MAC addresses from the named vm + Test to return a list off MAC addresses from the named vm """ mock = MagicMock(side_effect=[None, ["a", "b", "c"]]) with patch.object(xapi, "get_nics", mock): @@ -119,7 +119,7 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_get_disks(self): """ - Test to return the disks of a named vm + Test to return the disks of a named vm """ with patch.object(xapi, "_get_xapi_session", MagicMock()): mock = MagicMock(side_effect=[False, ["a", "b", "c"]]) @@ -130,7 +130,7 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_setmem(self): """ - Test to changes the amount of memory allocated to VM. + Test to changes the amount of memory allocated to VM. """ with patch.object(xapi, "_get_xapi_session", MagicMock()): mock = MagicMock(side_effect=[False, ["a", "b", "c"]]) @@ -147,7 +147,7 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_setvcpus(self): """ - Test to changes the amount of vcpus allocated to VM. + Test to changes the amount of vcpus allocated to VM. """ with patch.object(xapi, "_get_xapi_session", MagicMock()): mock = MagicMock(side_effect=[False, ["a", "b", "c"]]) @@ -164,7 +164,7 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_vcpu_pin(self): """ - Test to Set which CPUs a VCPU can use. + Test to Set which CPUs a VCPU can use. """ with patch.object(xapi, "_get_xapi_session", MagicMock()): mock = MagicMock(side_effect=[False, ["a", "b", "c"]]) @@ -182,8 +182,8 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_freemem(self): """ - Test to return an int representing the amount of memory - that has not been given to virtual machines on this node + Test to return an int representing the amount of memory + that has not been given to virtual machines on this node """ mock = MagicMock(return_value={"free_memory": 1024}) with patch.object(xapi, "node_info", mock): @@ -191,8 +191,8 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_freecpu(self): """ - Test to return an int representing the number - of unallocated cpus on this hypervisor + Test to return an int representing the number + of unallocated cpus on this hypervisor """ mock = MagicMock(return_value={"free_cpus": 1024}) with patch.object(xapi, "node_info", mock): @@ -200,7 +200,7 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_full_info(self): """ - Test to return the node_info, vm_info and freemem + Test to return the node_info, vm_info and freemem """ mock = MagicMock(return_value="salt") with patch.object(xapi, "node_info", mock): @@ -212,7 +212,7 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_shutdown(self): """ - Test to send a soft shutdown signal to the named vm + Test to send a soft shutdown signal to the named vm """ with patch.object(xapi, "_get_xapi_session", MagicMock()): mock = MagicMock(side_effect=[False, ["a", "b", "c"]]) @@ -229,7 +229,7 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_pause(self): """ - Test to pause the named vm + Test to pause the named vm """ with patch.object(xapi, "_get_xapi_session", MagicMock()): mock = MagicMock(side_effect=[False, ["a", "b", "c"]]) @@ -246,7 +246,7 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_resume(self): """ - Test to resume the named vm + Test to resume the named vm """ with patch.object(xapi, "_get_xapi_session", MagicMock()): mock = MagicMock(side_effect=[False, ["a", "b", "c"]]) @@ -263,7 +263,7 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_start(self): """ - Test to reboot a domain via ACPI request + Test to reboot a domain via ACPI request """ mock = MagicMock(return_value=True) with patch.object(xapi, "start", mock): @@ -271,7 +271,7 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_reboot(self): """ - Test to reboot a domain via ACPI request + Test to reboot a domain via ACPI request """ with patch.object(xapi, "_get_xapi_session", MagicMock()): mock = MagicMock(side_effect=[False, ["a", "b", "c"]]) @@ -288,8 +288,8 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_reset(self): """ - Test to reset a VM by emulating the - reset button on a physical machine + Test to reset a VM by emulating the + reset button on a physical machine """ with patch.object(xapi, "_get_xapi_session", MagicMock()): mock = MagicMock(side_effect=[False, ["a", "b", "c"]]) @@ -306,7 +306,7 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_migrate(self): """ - Test to migrates the virtual machine to another hypervisor + Test to migrates the virtual machine to another hypervisor """ with patch.object(xapi, "_get_xapi_session", MagicMock()): mock = MagicMock(side_effect=[False, ["a", "b", "c"]]) @@ -323,8 +323,8 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_stop(self): """ - Test to Hard power down the virtual machine, - this is equivalent to pulling the power + Test to Hard power down the virtual machine, + this is equivalent to pulling the power """ with patch.object(xapi, "_get_xapi_session", MagicMock()): mock = MagicMock(side_effect=[False, ["a", "b", "c"]]) @@ -341,8 +341,8 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_is_hyper(self): """ - Test to returns a bool whether or not - this node is a hypervisor of any kind + Test to returns a bool whether or not + this node is a hypervisor of any kind """ with patch.dict(xapi.__grains__, {"virtual_subtype": "Dom0"}): self.assertFalse(xapi.is_hyper()) @@ -366,7 +366,7 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_vm_cputime(self): """ - Test to Return cputime used by the vms + Test to Return cputime used by the vms """ ret = {"1": {"cputime_percent": 0, "cputime": 1}} with patch.object(xapi, "_get_xapi_session", MagicMock()): @@ -384,14 +384,14 @@ class XapiTestCase(TestCase, LoaderModuleMockMixin): def test_vm_netstats(self): """ - Test to return combined network counters used by the vms + Test to return combined network counters used by the vms """ with patch.object(xapi, "_get_xapi_session", MagicMock()): self.assertDictEqual(xapi.vm_netstats(""), {}) def test_vm_diskstats(self): """ - Test to return disk usage counters used by the vms + Test to return disk usage counters used by the vms """ with patch.object(xapi, "_get_xapi_session", MagicMock()): self.assertDictEqual(xapi.vm_diskstats(""), {}) diff --git a/tests/unit/modules/test_xml.py b/tests/unit/modules/test_xml.py index ee43140f84f..a37779534e7 100644 --- a/tests/unit/modules/test_xml.py +++ b/tests/unit/modules/test_xml.py @@ -28,7 +28,7 @@ XML_STRING = """ class XmlTestCase(TestCase, LoaderModuleMockMixin): """ - Test cases for salt.modules.xml + Test cases for salt.modules.xml """ def setup_loader_modules(self): @@ -36,7 +36,7 @@ class XmlTestCase(TestCase, LoaderModuleMockMixin): def test_get_value(self): """ - Verify xml.get_value + Verify xml.get_value """ with tempfile.NamedTemporaryFile("w+", delete=False) as xml_file: xml_file.write(XML_STRING) @@ -49,7 +49,7 @@ class XmlTestCase(TestCase, LoaderModuleMockMixin): def test_set_value(self): """ - Verify xml.set_value + Verify xml.set_value """ with tempfile.NamedTemporaryFile("w+", delete=False) as xml_file: xml_file.write(XML_STRING) @@ -67,7 +67,7 @@ class XmlTestCase(TestCase, LoaderModuleMockMixin): def test_get_attribute(self): """ - Verify xml.get_attribute + Verify xml.get_attribute """ with tempfile.NamedTemporaryFile("w+", delete=False) as xml_file: xml_file.write(XML_STRING) @@ -80,7 +80,7 @@ class XmlTestCase(TestCase, LoaderModuleMockMixin): def test_set_attribute(self): """ - Verify xml.set_value + Verify xml.set_value """ with tempfile.NamedTemporaryFile("w+", delete=False) as xml_file: xml_file.write(XML_STRING) diff --git a/tests/unit/modules/test_zcbuildout.py b/tests/unit/modules/test_zcbuildout.py index 03bf563e648..7901ad49c3e 100644 --- a/tests/unit/modules/test_zcbuildout.py +++ b/tests/unit/modules/test_zcbuildout.py @@ -356,7 +356,8 @@ class BuildoutOnlineTestCase(Base): "/d/distribute/distribute-0.6.43.tar.gz" ) download_to( - url, os.path.join(cls.ppy_dis, "distribute-0.6.43.tar.gz"), + url, + os.path.join(cls.ppy_dis, "distribute-0.6.43.tar.gz"), ) subprocess.check_call( diff --git a/tests/unit/netapi/test_rest_tornado.py b/tests/unit/netapi/test_rest_tornado.py index 73a8f4bd8b4..0f932330036 100644 --- a/tests/unit/netapi/test_rest_tornado.py +++ b/tests/unit/netapi/test_rest_tornado.py @@ -65,7 +65,7 @@ class SaltnadoTestsBase(AsyncHTTPTestCase, AdaptedConfigurationTestCaseMixin): @property def token(self): - """ Mint and return a valid token for auth_creds """ + """Mint and return a valid token for auth_creds""" return self.auth.mk_token(self.auth_creds_dict) def setUp(self): @@ -956,7 +956,10 @@ class TestEventListener(AsyncTestCase): ) self._finished = False # fit to event_listener's behavior event_future = event_listener.get_event( - self, tag="evt", callback=self.stop, timeout=1, + self, + tag="evt", + callback=self.stop, + timeout=1, ) # get an event future me.fire_event({"data": "foo"}, "evt") # fire an event we do want self.wait() @@ -976,7 +979,10 @@ class TestEventListener(AsyncTestCase): ) self._finished = False # fit to event_listener's behavior event_future = event_listener.get_event( - self, tag="evt1", callback=self.stop, timeout=1, + self, + tag="evt1", + callback=self.stop, + timeout=1, ) # get an event future self.wait() self.assertTrue(event_future.done()) diff --git a/tests/unit/pillar/test_pepa.py b/tests/unit/pillar/test_pepa.py index 230393a1f25..078bfb74597 100644 --- a/tests/unit/pillar/test_pepa.py +++ b/tests/unit/pillar/test_pepa.py @@ -9,7 +9,6 @@ except ImportError: class PepaPillarTestCase(TestCase): def test_repeated_keys(self): - # fmt: off expected_result = { "foo": { "bar": { @@ -18,10 +17,11 @@ class PepaPillarTestCase(TestCase): }, }, } - data = OrderedDict([ - ('foo..bar..foo', True), - ('foo..bar..baz', True), - ]) - # fmt: on + data = OrderedDict( + [ + ("foo..bar..foo", True), + ("foo..bar..baz", True), + ] + ) result = pepa.key_value_to_tree(data) self.assertDictEqual(result, expected_result) diff --git a/tests/unit/proxy/test_nxos.py b/tests/unit/proxy/test_nxos.py index 3b7e921159b..396e8e3468a 100644 --- a/tests/unit/proxy/test_nxos.py +++ b/tests/unit/proxy/test_nxos.py @@ -33,14 +33,14 @@ class NxosNxapiProxyTestCase(TestCase, LoaderModuleMockMixin): def test_check_virtual(self): - """ UT: nxos module:check_virtual method - return value """ + """UT: nxos module:check_virtual method - return value""" result = nxos_proxy.__virtual__() self.assertIn("nxos", result) def test_init(self): - """ UT: nxos module:init method - nxapi proxy """ + """UT: nxos module:init method - nxapi proxy""" with patch.object(nxos_proxy, "__opts__", {"proxy": {"connection": "nxapi"}}): with patch("salt.proxy.nxos._init_nxapi", autospec=True) as init_nxapi: @@ -49,7 +49,7 @@ class NxosNxapiProxyTestCase(TestCase, LoaderModuleMockMixin): def test_init_opts_none(self): - """ UT: nxos module:init method - __opts__ connection is None """ + """UT: nxos module:init method - __opts__ connection is None""" with patch.object(nxos_proxy, "__opts__", {"proxy": {"connection": None}}): with patch("salt.proxy.nxos._init_nxapi", autospec=True) as init_nxapi: @@ -58,13 +58,13 @@ class NxosNxapiProxyTestCase(TestCase, LoaderModuleMockMixin): def test_init_bad_connection_type(self): - """ UT: nxos module:init method - bad CONNECTION type """ + """UT: nxos module:init method - bad CONNECTION type""" with patch.object(nxos_proxy, "__opts__", {"proxy": {"connection": "unknown"}}): self.assertFalse(nxos_proxy.init()) def test_initialized(self): - """ UT: nxos module:initialized method - nxapi proxy """ + """UT: nxos module:initialized method - nxapi proxy""" with patch( "salt.proxy.nxos._initialized_nxapi", autospec=True @@ -74,7 +74,7 @@ class NxosNxapiProxyTestCase(TestCase, LoaderModuleMockMixin): def test_ping(self): - """ UT: nxos module:ping method - nxapi proxy """ + """UT: nxos module:ping method - nxapi proxy""" with patch("salt.proxy.nxos._ping_nxapi", autospec=True) as ping_nxapi: result = nxos_proxy.ping() @@ -82,7 +82,7 @@ class NxosNxapiProxyTestCase(TestCase, LoaderModuleMockMixin): def test_grains(self): - """ UT: nxos module:grains method - nxapi grains """ + """UT: nxos module:grains method - nxapi grains""" with patch( "salt.proxy.nxos.sendline", autospec=True, return_value=n9k_show_ver_list @@ -92,7 +92,7 @@ class NxosNxapiProxyTestCase(TestCase, LoaderModuleMockMixin): def test_grains_cache_set(self): - """ UT: nxos module:grains method - nxapi grains cache set """ + """UT: nxos module:grains method - nxapi grains cache set""" with patch( "salt.proxy.nxos.DEVICE_DETAILS", {"grains_cache": n9k_grains["nxos"]} @@ -107,7 +107,7 @@ class NxosNxapiProxyTestCase(TestCase, LoaderModuleMockMixin): def test_grains_refresh(self): - """ UT: nxos module:grains_refresh method - nxapi grains """ + """UT: nxos module:grains_refresh method - nxapi grains""" device_details = {"grains_cache": None} @@ -119,7 +119,7 @@ class NxosNxapiProxyTestCase(TestCase, LoaderModuleMockMixin): def test_sendline(self): - """ UT: nxos module:sendline method - nxapi """ + """UT: nxos module:sendline method - nxapi""" command = "show version" @@ -129,7 +129,7 @@ class NxosNxapiProxyTestCase(TestCase, LoaderModuleMockMixin): def test_proxy_config(self): - """ UT: nxos module:proxy_config method - nxapi success path""" + """UT: nxos module:proxy_config method - nxapi success path""" commands = ["feature bgp", "router bgp 65535"] @@ -142,7 +142,7 @@ class NxosNxapiProxyTestCase(TestCase, LoaderModuleMockMixin): def test_proxy_config_save_config(self): - """ UT: nxos module:proxy_config method - nxapi success path""" + """UT: nxos module:proxy_config method - nxapi success path""" commands = ["feature bgp", "router bgp 65535"] @@ -155,7 +155,7 @@ class NxosNxapiProxyTestCase(TestCase, LoaderModuleMockMixin): def test__init_nxapi(self): - """ UT: nxos module:_init_nxapi method - successful connectinon """ + """UT: nxos module:_init_nxapi method - successful connectinon""" opts = {"proxy": {"arg1": None}} nxapi_request = create_autospec(nxos_utils.nxapi_request, return_value="data") @@ -189,7 +189,7 @@ class NxosNxapiProxyTestCase(TestCase, LoaderModuleMockMixin): def test__initialized_nxapi(self): - """ UT: nxos module:_initialized_nxapi method """ + """UT: nxos module:_initialized_nxapi method""" result = nxos_proxy._initialized_nxapi() self.assertFalse(result) @@ -200,7 +200,7 @@ class NxosNxapiProxyTestCase(TestCase, LoaderModuleMockMixin): def test__ping_nxapi(self): - """ UT: nxos module:_ping_nxapi method """ + """UT: nxos module:_ping_nxapi method""" result = nxos_proxy._ping_nxapi() self.assertFalse(result) @@ -211,7 +211,7 @@ class NxosNxapiProxyTestCase(TestCase, LoaderModuleMockMixin): def test__shutdown_nxapi(self): - """ UT: nxos module:_shutdown_nxapi method """ + """UT: nxos module:_shutdown_nxapi method""" opts = {"id": "value"} @@ -221,7 +221,7 @@ class NxosNxapiProxyTestCase(TestCase, LoaderModuleMockMixin): def test__nxapi_request_ssh_return(self): - """ UT: nxos module:_nxapi_request method - CONNECTION == 'ssh' """ + """UT: nxos module:_nxapi_request method - CONNECTION == 'ssh'""" commands = "show version" @@ -231,7 +231,7 @@ class NxosNxapiProxyTestCase(TestCase, LoaderModuleMockMixin): def test__nxapi_request_connect(self): - """ UT: nxos module:_nxapi_request method """ + """UT: nxos module:_nxapi_request method""" commands = "show version" nxapi_request = create_autospec(nxos_utils.nxapi_request, return_value="data") @@ -262,7 +262,7 @@ class NxosSSHProxyTestCase(TestCase, LoaderModuleMockMixin): def test_init(self): - """ UT: nxos module:init method - ssh proxy """ + """UT: nxos module:init method - ssh proxy""" with patch("salt.proxy.nxos._init_ssh", autospec=True) as init_ssh: result = nxos_proxy.init() @@ -270,7 +270,7 @@ class NxosSSHProxyTestCase(TestCase, LoaderModuleMockMixin): def test_init_opts_none(self): - """ UT: nxos module:init method - __opts__ connection is None """ + """UT: nxos module:init method - __opts__ connection is None""" with patch("salt.proxy.nxos.__opts__", {"proxy": {"connection": None}}): with patch("salt.proxy.nxos._init_ssh", autospec=True) as init_ssh: @@ -279,7 +279,7 @@ class NxosSSHProxyTestCase(TestCase, LoaderModuleMockMixin): def test_initialized(self): - """ UT: nxos module:initialized method - ssh proxy """ + """UT: nxos module:initialized method - ssh proxy""" with patch( "salt.proxy.nxos._initialized_ssh", autospec=True @@ -289,7 +289,7 @@ class NxosSSHProxyTestCase(TestCase, LoaderModuleMockMixin): def test_ping(self): - """ UT: nxos module:ping method - ssh proxy """ + """UT: nxos module:ping method - ssh proxy""" with patch("salt.proxy.nxos._ping_ssh", autospec=True) as ping_ssh: result = nxos_proxy.ping() @@ -297,7 +297,7 @@ class NxosSSHProxyTestCase(TestCase, LoaderModuleMockMixin): def test_grains(self): - """ UT: nxos module:grains method - ssh grains """ + """UT: nxos module:grains method - ssh grains""" with patch( "salt.proxy.nxos.sendline", autospec=True, return_value=n9k_show_ver_list[0] @@ -307,7 +307,7 @@ class NxosSSHProxyTestCase(TestCase, LoaderModuleMockMixin): def test_sendline(self): - """ UT: nxos module:sendline method - nxapi """ + """UT: nxos module:sendline method - nxapi""" command = "show version" @@ -317,7 +317,7 @@ class NxosSSHProxyTestCase(TestCase, LoaderModuleMockMixin): def test_proxy_config(self): - """ UT: nxos module:proxy_config method - ssh success path """ + """UT: nxos module:proxy_config method - ssh success path""" commands = ["feature bgp", "router bgp 65535"] @@ -328,7 +328,7 @@ class NxosSSHProxyTestCase(TestCase, LoaderModuleMockMixin): def test_proxy_config_save_config(self): - """ UT: nxos module:proxy_config method - ssh success path """ + """UT: nxos module:proxy_config method - ssh success path""" commands = ["feature bgp", "router bgp 65535"] @@ -339,7 +339,7 @@ class NxosSSHProxyTestCase(TestCase, LoaderModuleMockMixin): def test_proxy_config_error(self): - """ UT: nxos module:proxy_config method - CommandExecutionError """ + """UT: nxos module:proxy_config method - CommandExecutionError""" with patch( "salt.proxy.nxos._sendline_ssh", @@ -368,7 +368,7 @@ class NxosSSHProxyTestCase(TestCase, LoaderModuleMockMixin): def test__init_ssh_opts(self): - """ UT: nxos module:_init_ssh method - successful connectinon """ + """UT: nxos module:_init_ssh method - successful connectinon""" with patch("salt.proxy.nxos.DEVICE_DETAILS", {}): with patch("salt.proxy.nxos.SSHConnection", autospec=True) as SSHConnection: @@ -387,7 +387,7 @@ class NxosSSHProxyTestCase(TestCase, LoaderModuleMockMixin): def test__init_ssh_prompt(self): - """ UT: nxos module:_init_ssh method - prompt regex """ + """UT: nxos module:_init_ssh method - prompt regex""" with patch("salt.proxy.nxos.DEVICE_DETAILS", {}): with patch("salt.proxy.nxos.SSHConnection", autospec=True) as SSHConnection: @@ -414,7 +414,7 @@ class NxosSSHProxyTestCase(TestCase, LoaderModuleMockMixin): def test__initialized_ssh(self): - """ UT: nxos module:_initialized_ssh method """ + """UT: nxos module:_initialized_ssh method""" with patch("salt.proxy.nxos.DEVICE_DETAILS", {"initialized": True}): result = nxos_proxy._initialized_ssh() @@ -426,7 +426,7 @@ class NxosSSHProxyTestCase(TestCase, LoaderModuleMockMixin): def test__parse_output_for_errors(self): - """ UT: nxos module:_parse_output_for_errors method """ + """UT: nxos module:_parse_output_for_errors method""" data = "% Incomplete command at '^' marker." command = "show" @@ -462,7 +462,7 @@ class NxosSSHProxyTestCase(TestCase, LoaderModuleMockMixin): def test__init_ssh_raise_exception(self): - """ UT: nxos module:_init_ssh method - raise exception """ + """UT: nxos module:_init_ssh method - raise exception""" class SSHException(Exception): pass diff --git a/tests/unit/renderers/test_aws_kms.py b/tests/unit/renderers/test_aws_kms.py index fd398979243..f5450febc38 100644 --- a/tests/unit/renderers/test_aws_kms.py +++ b/tests/unit/renderers/test_aws_kms.py @@ -139,9 +139,11 @@ class AWSKMSTestCase(TestCase, LoaderModuleMockMixin): with an error_code of 'InvalidCiphertextException'. """ kms_client = MagicMock() - kms_client.decrypt.side_effect = botocore.exceptions.ClientError( # pylint: disable=no-member - error_response={"Error": {"Code": "InvalidCiphertextException"}}, - operation_name="Decrypt", + kms_client.decrypt.side_effect = ( + botocore.exceptions.ClientError( # pylint: disable=no-member + error_response={"Error": {"Code": "InvalidCiphertextException"}}, + operation_name="Decrypt", + ) ) with patch.object(aws_kms, "_kms") as kms_getter: kms_getter.return_value = kms_client diff --git a/tests/unit/renderers/test_gpg.py b/tests/unit/renderers/test_gpg.py index 7e599ddbbee..d5cfa728314 100644 --- a/tests/unit/renderers/test_gpg.py +++ b/tests/unit/renderers/test_gpg.py @@ -284,7 +284,8 @@ class GPGTestCase(TestCase, LoaderModuleMockMixin, AdaptedConfigurationTestCaseM MagicMock(return_value=key_dir), ): with patch( - "salt.utils.atomicfile.atomic_open", MagicMock(), + "salt.utils.atomicfile.atomic_open", + MagicMock(), ) as atomic_open_mock: self.assertEqual(gpg.render(crypted), expected) gpg_call = call( diff --git a/tests/unit/sdb/test_etcd_db.py b/tests/unit/sdb/test_etcd_db.py index c3b2f545ecf..35403d097bd 100644 --- a/tests/unit/sdb/test_etcd_db.py +++ b/tests/unit/sdb/test_etcd_db.py @@ -53,7 +53,8 @@ class TestEtcdSDB(LoaderModuleMockMixin, TestCase): ) self.assertEqual( - self.instance.get.call_args_list, [call("sdb://myetcd/path/to/foo/bar")], + self.instance.get.call_args_list, + [call("sdb://myetcd/path/to/foo/bar")], ) def test_get(self): @@ -64,5 +65,6 @@ class TestEtcdSDB(LoaderModuleMockMixin, TestCase): etcd_db.get("sdb://myetcd/path/to/foo/bar") self.assertEqual( - self.instance.get.call_args_list, [call("sdb://myetcd/path/to/foo/bar")], + self.instance.get.call_args_list, + [call("sdb://myetcd/path/to/foo/bar")], ) diff --git a/tests/unit/sdb/test_vault.py b/tests/unit/sdb/test_vault.py index 326f1967322..7f033597daa 100644 --- a/tests/unit/sdb/test_vault.py +++ b/tests/unit/sdb/test_vault.py @@ -119,7 +119,8 @@ class TestVaultSDB(LoaderModuleMockMixin, TestCase): self.assertEqual(vault.get("sdb://myvault/path/to/foo/bar"), "test") self.assertEqual( - mock_vault.call_args_list, [call("GET", "v1/sdb://myvault/path/to/foo")], + mock_vault.call_args_list, + [call("GET", "v1/sdb://myvault/path/to/foo")], ) def test_get_v2(self): @@ -160,7 +161,8 @@ class TestVaultSDB(LoaderModuleMockMixin, TestCase): ), patch.dict(vault.__utils__, {"vault.is_v2": mock_version}): self.assertEqual(vault.get("sdb://myvault/path/to/foo?bar"), "test") self.assertEqual( - mock_vault.call_args_list, [call("GET", "v1/sdb://myvault/path/to/foo")], + mock_vault.call_args_list, + [call("GET", "v1/sdb://myvault/path/to/foo")], ) def test_get_missing(self): diff --git a/tests/unit/states/test_file.py b/tests/unit/states/test_file.py index 1dbf5de4a10..06b8cca004e 100644 --- a/tests/unit/states/test_file.py +++ b/tests/unit/states/test_file.py @@ -2764,14 +2764,16 @@ class TestFileState(TestCase, LoaderModuleMockMixin): } if test: expected_ret["result"] = None - expected_ret["comment"] = ( - "{} backups would have been removed from {}.\n" - "".format(len(deleted_files), fake_name) + expected_ret[ + "comment" + ] = "{} backups would have been removed from {}.\n" "".format( + len(deleted_files), fake_name ) else: - expected_ret["comment"] = ( - "{} backups were removed from {}.\n" - "".format(len(deleted_files), fake_name) + expected_ret[ + "comment" + ] = "{} backups were removed from {}.\n" "".format( + len(deleted_files), fake_name ) mock_remove.assert_has_calls( [call(os.path.join(fake_name, x)) for x in deleted_files], diff --git a/tests/unit/states/test_git.py b/tests/unit/states/test_git.py index 81473d17613..9db4ba777ee 100644 --- a/tests/unit/states/test_git.py +++ b/tests/unit/states/test_git.py @@ -63,7 +63,9 @@ class GitTestCase(TestCase, LoaderModuleMockMixin): git_state.__salt__, dunder_salt ): result = git_state.latest( - name=name, target=target, mirror=True, # mirror=True implies bare=True + name=name, + target=target, + mirror=True, # mirror=True implies bare=True ) assert result["result"] is True, result git_diff.assert_not_called() diff --git a/tests/unit/states/test_group.py b/tests/unit/states/test_group.py index 77fb9452d8a..a68448391f2 100644 --- a/tests/unit/states/test_group.py +++ b/tests/unit/states/test_group.py @@ -12,7 +12,7 @@ from tests.support.unit import TestCase class GroupTestCase(TestCase, LoaderModuleMockMixin): """ - Validate the group state + Validate the group state """ def setup_loader_modules(self): @@ -20,7 +20,7 @@ class GroupTestCase(TestCase, LoaderModuleMockMixin): def test_present(self): """ - Test to ensure that a group is present + Test to ensure that a group is present """ ret = {"name": "salt", "changes": {}, "result": True, "comment": {}} @@ -82,7 +82,7 @@ class GroupTestCase(TestCase, LoaderModuleMockMixin): def test_absent(self): """ - Test to ensure that the named group is absent + Test to ensure that the named group is absent """ ret = {"name": "salt", "changes": {}, "result": True, "comment": {}} mock = MagicMock(side_effect=[True, True, True, False]) diff --git a/tests/unit/states/test_hg.py b/tests/unit/states/test_hg.py index 61dfbadf894..2293af90694 100644 --- a/tests/unit/states/test_hg.py +++ b/tests/unit/states/test_hg.py @@ -12,7 +12,7 @@ from tests.support.unit import TestCase class HgTestCase(TestCase, LoaderModuleMockMixin): """ - Validate the svn state + Validate the svn state """ def setup_loader_modules(self): @@ -20,8 +20,8 @@ class HgTestCase(TestCase, LoaderModuleMockMixin): def test_latest(self): """ - Test to Make sure the repository is cloned to - the given directory and is up to date + Test to Make sure the repository is cloned to + the given directory and is up to date """ ret = {"changes": {}, "comment": "", "name": "salt", "result": True} mock = MagicMock(return_value=True) @@ -46,7 +46,7 @@ class HgTestCase(TestCase, LoaderModuleMockMixin): def test_latest_update_changes(self): """ - Test to make sure we don't update even if we have changes + Test to make sure we don't update even if we have changes """ ret = {"changes": {}, "comment": "", "name": "salt", "result": True} revision_mock = MagicMock(return_value="abcdef") @@ -73,7 +73,7 @@ class HgTestCase(TestCase, LoaderModuleMockMixin): def test_latest_no_update_changes(self): """ - Test to make sure we don't update even if we have changes + Test to make sure we don't update even if we have changes """ ret = { "changes": {}, @@ -105,8 +105,8 @@ class HgTestCase(TestCase, LoaderModuleMockMixin): def test_latest_no_update_no_changes(self): """ - Test to Make sure the repository is cloned to - the given directory and is up to date + Test to Make sure the repository is cloned to + the given directory and is up to date """ ret = { "changes": {}, diff --git a/tests/unit/states/test_iptables.py b/tests/unit/states/test_iptables.py index 8f98c4a74d3..c5c9e519561 100644 --- a/tests/unit/states/test_iptables.py +++ b/tests/unit/states/test_iptables.py @@ -11,7 +11,7 @@ from tests.support.unit import TestCase class IptablesTestCase(TestCase, LoaderModuleMockMixin): """ - Validate the iptables state + Validate the iptables state """ def setup_loader_modules(self): @@ -19,7 +19,7 @@ class IptablesTestCase(TestCase, LoaderModuleMockMixin): def test_chain_present(self): """ - Test to verify the chain is exist. + Test to verify the chain is exist. """ ret = {"name": "salt", "changes": {}, "result": True, "comment": ""} @@ -68,7 +68,7 @@ class IptablesTestCase(TestCase, LoaderModuleMockMixin): def test_chain_absent(self): """ - Test to verify the chain is absent. + Test to verify the chain is absent. """ ret = {"name": "salt", "changes": {}, "result": True, "comment": ""} @@ -119,7 +119,7 @@ class IptablesTestCase(TestCase, LoaderModuleMockMixin): def test_append(self): """ - Test to append a rule to a chain + Test to append a rule to a chain """ ret = {"name": "salt", "changes": {}, "result": None, "comment": ""} @@ -243,7 +243,7 @@ class IptablesTestCase(TestCase, LoaderModuleMockMixin): def test_insert(self): """ - Test to insert a rule into a chain + Test to insert a rule into a chain """ ret = {"name": "salt", "changes": {}, "result": None, "comment": ""} @@ -374,7 +374,7 @@ class IptablesTestCase(TestCase, LoaderModuleMockMixin): def test_delete(self): """ - Test to delete a rule to a chain + Test to delete a rule to a chain """ ret = {"name": "salt", "changes": {}, "result": None, "comment": ""} @@ -495,7 +495,7 @@ class IptablesTestCase(TestCase, LoaderModuleMockMixin): def test_set_policy(self): """ - Test to sets the default policy for iptables firewall tables + Test to sets the default policy for iptables firewall tables """ ret = {"name": "salt", "changes": {}, "result": True, "comment": ""} @@ -561,7 +561,7 @@ class IptablesTestCase(TestCase, LoaderModuleMockMixin): def test_flush(self): """ - Test to flush current iptables state + Test to flush current iptables state """ ret = {"name": "salt", "changes": {}, "result": None, "comment": ""} @@ -604,7 +604,7 @@ class IptablesTestCase(TestCase, LoaderModuleMockMixin): def test_mod_aggregate(self): """ - Test to mod_aggregate function + Test to mod_aggregate function """ self.assertDictEqual( iptables.mod_aggregate({"fun": "salt"}, [], []), {"fun": "salt"} diff --git a/tests/unit/states/test_kubernetes.py b/tests/unit/states/test_kubernetes.py index 39ec50573ca..9499218b73d 100644 --- a/tests/unit/states/test_kubernetes.py +++ b/tests/unit/states/test_kubernetes.py @@ -39,12 +39,18 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): def make_configmap(self, name, namespace="default", data=None): return self.make_ret_dict( - kind="ConfigMap", name=name, namespace=namespace, data=data, + kind="ConfigMap", + name=name, + namespace=namespace, + data=data, ) def make_secret(self, name, namespace="default", data=None): secret_data = self.make_ret_dict( - kind="Secret", name=name, namespace=namespace, data=data, + kind="Secret", + name=name, + namespace=namespace, + data=data, ) # Base64 all of the values just like kubectl does for key, value in secret_data["data"].items(): @@ -114,7 +120,9 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): data = {} self_link = "/api/v1/namespaces/{namespace}/{kind}s/{name}".format( - namespace=namespace, kind=kind.lower(), name=name, + namespace=namespace, + kind=kind.lower(), + name=name, ) return_data = { @@ -133,7 +141,9 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): def test_configmap_present__fail(self): error = kubernetes.configmap_present( - name="testme", data={1: 1}, source="salt://beyond/oblivion.jinja", + name="testme", + data={1: 1}, + source="salt://beyond/oblivion.jinja", ) self.assertDictEqual( { @@ -149,7 +159,8 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): # Create a new configmap with test=True with self.mock_func("show_configmap", return_value=None, test=True): ret = kubernetes.configmap_present( - name="example", data={"example.conf": "# empty config file"}, + name="example", + data={"example.conf": "# empty config file"}, ) self.assertDictEqual( { @@ -165,10 +176,15 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): # Create a new configmap with self.mock_func("show_configmap", return_value=None): cm = self.make_configmap( - name="test", namespace="default", data={"foo": "bar"}, + name="test", + namespace="default", + data={"foo": "bar"}, ) with self.mock_func("create_configmap", return_value=cm): - actual = kubernetes.configmap_present(name="test", data={"foo": "bar"},) + actual = kubernetes.configmap_present( + name="test", + data={"foo": "bar"}, + ) self.assertDictEqual( { "comment": "", @@ -182,7 +198,10 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): def test_configmap_present__create_no_data(self): # Create a new configmap with no 'data' attribute with self.mock_func("show_configmap", return_value=None): - cm = self.make_configmap(name="test", namespace="default",) + cm = self.make_configmap( + name="test", + namespace="default", + ) with self.mock_func("create_configmap", return_value=cm): actual = kubernetes.configmap_present(name="test") self.assertDictEqual( @@ -225,7 +244,8 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): new_cm.update({"data": {"action": "make=peace"}}) with self.mock_func("replace_configmap", return_value=new_cm): actual = kubernetes.configmap_present( - name="settings", data={"action": "make=peace"}, + name="settings", + data={"action": "make=peace"}, ) self.assertDictEqual( { @@ -304,7 +324,9 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): def test_secret_present__fail(self): actual = kubernetes.secret_present( - name="sekret", data={"password": "monk3y"}, source="salt://nope.jinja", + name="sekret", + data={"password": "monk3y"}, + source="salt://nope.jinja", ) self.assertDictEqual( { @@ -324,7 +346,8 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): with self.mock_func("show_secret", return_value=secret): with self.mock_func("replace_secret", return_value=new_secret, test=True): actual = kubernetes.secret_present( - name="sekret", data={"password": "uncle"}, + name="sekret", + data={"password": "uncle"}, ) self.assertDictEqual( { @@ -342,7 +365,8 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): with self.mock_func("show_secret", return_value=secret): with self.mock_func("replace_secret", return_value=secret): actual = kubernetes.secret_present( - name="sekret", data={"password": "booyah"}, + name="sekret", + data={"password": "booyah"}, ) self.assertDictEqual( { @@ -360,7 +384,8 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): with self.mock_func("show_secret", return_value=None): with self.mock_func("create_secret", return_value=secret): actual = kubernetes.secret_present( - name="sekret", data={"password": "booyah"}, + name="sekret", + data={"password": "booyah"}, ) self.assertDictEqual( { @@ -479,7 +504,9 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): labels = self.make_node_labels() with self.mock_func("node_labels", return_value=labels, test=True): actual = kubernetes.node_label_present( - name="com.zoo-animal", node="minikube", value="monkey", + name="com.zoo-animal", + node="minikube", + value="monkey", ) self.assertDictEqual( { @@ -601,7 +628,8 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): labels = self.make_node_labels() with self.mock_func("node_labels", return_value=labels, test=True): actual = kubernetes.node_label_absent( - name="non-existent-label", node="minikube", + name="non-existent-label", + node="minikube", ) self.assertDictEqual( { @@ -617,7 +645,8 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): labels = self.make_node_labels() with self.mock_func("node_labels", return_value=labels): actual = kubernetes.node_label_absent( - name="non-existent-label", node="minikube", + name="non-existent-label", + node="minikube", ) self.assertDictEqual( { @@ -633,7 +662,8 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): labels = self.make_node_labels() with self.mock_func("node_labels", return_value=labels, test=True): actual = kubernetes.node_label_absent( - name="failure-domain.beta.kubernetes.io/region", node="minikube", + name="failure-domain.beta.kubernetes.io/region", + node="minikube", ) self.assertDictEqual( { @@ -654,7 +684,8 @@ class KubernetesTestCase(TestCase, LoaderModuleMockMixin): with self.mock_func("node_labels", return_value=labels): with self.mock_func("node_remove_label", return_value=node_data): actual = kubernetes.node_label_absent( - name="failure-domain.beta.kubernetes.io/region", node="minikube", + name="failure-domain.beta.kubernetes.io/region", + node="minikube", ) self.assertDictEqual( { diff --git a/tests/unit/states/test_ldap.py b/tests/unit/states/test_ldap.py index e75a2911849..0de1fff1fb9 100644 --- a/tests/unit/states/test_ldap.py +++ b/tests/unit/states/test_ldap.py @@ -30,11 +30,21 @@ def _init_db(newdb=None): def _complex_db(): return { "dnfoo": { - "attrfoo1": OrderedSet((b"valfoo1.1", b"valfoo1.2",)), + "attrfoo1": OrderedSet( + ( + b"valfoo1.1", + b"valfoo1.2", + ) + ), "attrfoo2": OrderedSet((b"valfoo2.1",)), }, "dnbar": { - "attrbar1": OrderedSet((b"valbar1.1", b"valbar1.2",)), + "attrbar1": OrderedSet( + ( + b"valbar1.1", + b"valbar1.2", + ) + ), "attrbar2": OrderedSet((b"valbar2.1",)), }, } diff --git a/tests/unit/states/test_module.py b/tests/unit/states/test_module.py index 7e10a7ef718..164f164844a 100644 --- a/tests/unit/states/test_module.py +++ b/tests/unit/states/test_module.py @@ -65,7 +65,13 @@ STATE_APPLY_RET = { } -def _mocked_func_named(name, names=("Fred", "Swen",)): +def _mocked_func_named( + name, + names=( + "Fred", + "Swen", + ), +): """ Mocked function with named defaults. @@ -327,7 +333,10 @@ class ModuleStateTest(TestCase, LoaderModuleMockMixin): 0, "a", "", - (1, 2,), + ( + 1, + 2, + ), (), [1, 2], [], diff --git a/tests/unit/states/test_network.py b/tests/unit/states/test_network.py index f0baf256b4b..65f2eb771c9 100644 --- a/tests/unit/states/test_network.py +++ b/tests/unit/states/test_network.py @@ -14,7 +14,7 @@ log = logging.getLogger(__name__) class MockNetwork: """ - Mock network class + Mock network class """ def __init__(self): @@ -23,7 +23,7 @@ class MockNetwork: @staticmethod def interfaces(): """ - Mock interface method + Mock interface method """ ifaces = { "salt": {"up": 1}, @@ -34,7 +34,7 @@ class MockNetwork: class MockGrains: """ - Mock Grains class + Mock Grains class """ def __init__(self): @@ -43,14 +43,14 @@ class MockGrains: @staticmethod def grains(lis, bol): """ - Mock grains method + Mock grains method """ return {"A": "B"} class NetworkTestCase(TestCase, LoaderModuleMockMixin): """ - Validate the network state + Validate the network state """ def setup_loader_modules(self): @@ -58,7 +58,7 @@ class NetworkTestCase(TestCase, LoaderModuleMockMixin): def test_managed(self): """ - Test to ensure that the named interface is configured properly + Test to ensure that the named interface is configured properly """ with patch("salt.states.network.salt.utils.network", MockNetwork()), patch( "salt.states.network.salt.loader", MockGrains() @@ -151,7 +151,7 @@ class NetworkTestCase(TestCase, LoaderModuleMockMixin): def test_routes(self): """ - Test to manage network interface static routes. + Test to manage network interface static routes. """ ret = {"name": "salt", "changes": {}, "result": False, "comment": ""} @@ -211,8 +211,8 @@ class NetworkTestCase(TestCase, LoaderModuleMockMixin): def test_system(self): """ - Test to ensure that global network settings - are configured properly + Test to ensure that global network settings + are configured properly """ ret = {"name": "salt", "changes": {}, "result": False, "comment": ""} diff --git a/tests/unit/states/test_saltmod.py b/tests/unit/states/test_saltmod.py index 4be2b3a1ab5..7ed6cead625 100644 --- a/tests/unit/states/test_saltmod.py +++ b/tests/unit/states/test_saltmod.py @@ -386,9 +386,9 @@ class StatemodTests(TestCase, LoaderModuleMockMixin): } def test_statemod_state(self): - """ Smoke test for for salt.states.statemod.state(). Ensures that we - don't take an exception if optional parameters are not specified in - __opts__ or __env__. + """Smoke test for for salt.states.statemod.state(). Ensures that we + don't take an exception if optional parameters are not specified in + __opts__ or __env__. """ args = ("webserver_setup", "webserver2") kwargs = { diff --git a/tests/unit/states/test_virt.py b/tests/unit/states/test_virt.py index 2ab73f8af48..f46096a77a0 100644 --- a/tests/unit/states/test_virt.py +++ b/tests/unit/states/test_virt.py @@ -413,7 +413,11 @@ class LibvirtTestCase(TestCase, LoaderModuleMockMixin): password=None, ) mocks["autostart"].assert_called_with( - "mypool", state="on", connection=None, username=None, password=None, + "mypool", + state="on", + connection=None, + username=None, + password=None, ) mocks["build"].assert_not_called() diff --git a/tests/unit/states/test_virtualenv_mod.py b/tests/unit/states/test_virtualenv_mod.py index fc9162747ff..30d1b62b4aa 100644 --- a/tests/unit/states/test_virtualenv_mod.py +++ b/tests/unit/states/test_virtualenv_mod.py @@ -13,7 +13,7 @@ from tests.support.unit import TestCase class VirtualenvModTestCase(TestCase, LoaderModuleMockMixin): """ - Validate the virtualenv_mod state + Validate the virtualenv_mod state """ def setup_loader_modules(self): @@ -21,7 +21,7 @@ class VirtualenvModTestCase(TestCase, LoaderModuleMockMixin): def test_managed(self): """ - Test to create a virtualenv and optionally manage it with pip + Test to create a virtualenv and optionally manage it with pip """ ret = {"name": "salt", "changes": {}, "result": False, "comment": ""} ret.update({"comment": "Virtualenv was not detected on this system"}) diff --git a/tests/unit/test_auth.py b/tests/unit/test_auth.py index f445b5a4ee8..cf7e76f5d94 100644 --- a/tests/unit/test_auth.py +++ b/tests/unit/test_auth.py @@ -52,7 +52,8 @@ class LoadAuthTestCase(TestCase): fake_get_token = MagicMock(side_effect=SaltDeserializationError("hi")) patch_opts = patch.dict(self.lauth.opts, {"eauth_tokens": "testfs"}) patch_get_token = patch.dict( - self.lauth.tokens, {"testfs.get_token": fake_get_token}, + self.lauth.tokens, + {"testfs.get_token": fake_get_token}, ) mock_rm_token = MagicMock() patch_rm_token = patch.object(self.lauth, "rm_token", mock_rm_token) @@ -65,7 +66,8 @@ class LoadAuthTestCase(TestCase): fake_get_token = MagicMock(return_value={"no_expire_here": "Nope"}) patch_opts = patch.dict(self.lauth.opts, {"eauth_tokens": "testfs"}) patch_get_token = patch.dict( - self.lauth.tokens, {"testfs.get_token": fake_get_token}, + self.lauth.tokens, + {"testfs.get_token": fake_get_token}, ) mock_rm_token = MagicMock() patch_rm_token = patch.object(self.lauth, "rm_token", mock_rm_token) @@ -78,7 +80,8 @@ class LoadAuthTestCase(TestCase): fake_get_token = MagicMock(return_value={"expire": time.time() - 1}) patch_opts = patch.dict(self.lauth.opts, {"eauth_tokens": "testfs"}) patch_get_token = patch.dict( - self.lauth.tokens, {"testfs.get_token": fake_get_token}, + self.lauth.tokens, + {"testfs.get_token": fake_get_token}, ) mock_rm_token = MagicMock() patch_rm_token = patch.object(self.lauth, "rm_token", mock_rm_token) @@ -92,7 +95,8 @@ class LoadAuthTestCase(TestCase): fake_get_token = MagicMock(return_value=expected_token) patch_opts = patch.dict(self.lauth.opts, {"eauth_tokens": "testfs"}) patch_get_token = patch.dict( - self.lauth.tokens, {"testfs.get_token": fake_get_token}, + self.lauth.tokens, + {"testfs.get_token": fake_get_token}, ) mock_rm_token = MagicMock() patch_rm_token = patch.object(self.lauth, "rm_token", mock_rm_token) diff --git a/tests/unit/test_loader.py b/tests/unit/test_loader.py index 3884c423e71..2319f815d31 100644 --- a/tests/unit/test_loader.py +++ b/tests/unit/test_loader.py @@ -5,7 +5,6 @@ Test Salt's loader """ - import collections import compileall import copy @@ -125,7 +124,7 @@ class LazyLoaderTest(TestCase): # results in a KeyError, the decorator is broken. self.assertTrue( isinstance( - self.loader[self.module_name + ".loaded"], salt.loader.lazy.LoadedFunc, + self.loader[self.module_name + ".loaded"], salt.loader.lazy.LoadedFunc ) ) # Make sure depends correctly kept a function from loading @@ -405,7 +404,7 @@ class LazyLoaderVirtualDisabledTest(TestCase): @pytest.mark.slow_test def test_virtual(self): self.assertTrue( - isinstance(self.loader["test_virtual.ping"], salt.loader.lazy.LoadedFunc,) + isinstance(self.loader["test_virtual.ping"], salt.loader.lazy.LoadedFunc) ) diff --git a/tests/unit/test_minion.py b/tests/unit/test_minion.py index 1265961a03d..0fb7575ff9a 100644 --- a/tests/unit/test_minion.py +++ b/tests/unit/test_minion.py @@ -406,7 +406,8 @@ class MinionTestCase(TestCase, AdaptedConfigurationTestCaseMixin): try: mock_opts = salt.config.DEFAULT_MINION_OPTS.copy() minion = salt.minion.Minion( - mock_opts, io_loop=salt.ext.tornado.ioloop.IOLoop(), + mock_opts, + io_loop=salt.ext.tornado.ioloop.IOLoop(), ) minion.schedule = salt.utils.schedule.Schedule( mock_opts, {}, returners={} diff --git a/tests/unit/test_pillar.py b/tests/unit/test_pillar.py index 59202fb7328..ee9ebc0db8e 100644 --- a/tests/unit/test_pillar.py +++ b/tests/unit/test_pillar.py @@ -354,7 +354,9 @@ class PillarTestCase(TestCase): tempdir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP) try: - sls_files = self._setup_test_topfile_sls_pillar_match(tempdir,) + sls_files = self._setup_test_topfile_sls_pillar_match( + tempdir, + ) fc_mock = MockFileclient( cache_file=sls_files["top"]["dest"], list_states=["top", "ssh", "ssh.minion", "generic", "generic.minion"], diff --git a/tests/unit/test_proxy_minion.py b/tests/unit/test_proxy_minion.py index c455830130e..e8272769652 100644 --- a/tests/unit/test_proxy_minion.py +++ b/tests/unit/test_proxy_minion.py @@ -156,7 +156,9 @@ class ProxyMinionTestCase(TestCase): ) ) opts = salt.config.proxy_config( - str(conf_file), minion_id=proxyid, cache_minion_id=False, + str(conf_file), + minion_id=proxyid, + cache_minion_id=False, ) self.assertIn("schedule", opts) self.assertIn("test_job", opts["schedule"]) diff --git a/tests/unit/tokens/test_localfs.py b/tests/unit/tokens/test_localfs.py index a9d6b6b3b6e..e4a73c92023 100644 --- a/tests/unit/tokens/test_localfs.py +++ b/tests/unit/tokens/test_localfs.py @@ -53,9 +53,10 @@ class TestLocalFS(TestCase): @with_tempdir() def test_get_token_should_return_token_if_exists(self, tempdir): opts = {"token_dir": tempdir} - tok = salt.tokens.localfs.mk_token(opts=opts, tdata=self.expected_data,)[ - "token" - ] + tok = salt.tokens.localfs.mk_token( + opts=opts, + tdata=self.expected_data, + )["token"] actual_data = salt.tokens.localfs.get_token(opts=opts, tok=tok) self.assertDictEqual(self.expected_data, actual_data) @@ -64,9 +65,10 @@ class TestLocalFS(TestCase): self, tempdir ): opts = {"token_dir": tempdir} - tok = salt.tokens.localfs.mk_token(opts=opts, tdata=self.expected_data,)[ - "token" - ] + tok = salt.tokens.localfs.mk_token( + opts=opts, + tdata=self.expected_data, + )["token"] with salt.utils.files.fopen(os.path.join(tempdir, tok), "w") as f: f.truncate() with self.assertRaises(salt.exceptions.SaltDeserializationError) as e: @@ -77,9 +79,10 @@ class TestLocalFS(TestCase): self, tempdir ): opts = {"token_dir": tempdir} - tok = salt.tokens.localfs.mk_token(opts=opts, tdata=self.expected_data,)[ - "token" - ] + tok = salt.tokens.localfs.mk_token( + opts=opts, + tdata=self.expected_data, + )["token"] with salt.utils.files.fopen(os.path.join(tempdir, tok), "w") as f: f.truncate() f.write("this is not valid msgpack data") diff --git a/tests/unit/transport/test_ipc.py b/tests/unit/transport/test_ipc.py index 056b520b112..f663d941b59 100644 --- a/tests/unit/transport/test_ipc.py +++ b/tests/unit/transport/test_ipc.py @@ -46,14 +46,16 @@ class IPCMessagePubSubCase(salt.ext.tornado.testing.AsyncTestCase): def _get_pub_channel(self): pub_channel = salt.transport.ipc.IPCMessagePublisher( - self.opts, self.socket_path, + self.opts, + self.socket_path, ) pub_channel.start() return pub_channel def _get_sub_channel(self): sub_channel = salt.transport.ipc.IPCMessageSubscriber( - socket_path=self.socket_path, io_loop=self.io_loop, + socket_path=self.socket_path, + io_loop=self.io_loop, ) sub_channel.connect(callback=self.stop) self.wait() diff --git a/tests/unit/transport/test_tcp.py b/tests/unit/transport/test_tcp.py index 58e1ae841f6..e528e019cb7 100644 --- a/tests/unit/transport/test_tcp.py +++ b/tests/unit/transport/test_tcp.py @@ -86,7 +86,11 @@ class AsyncPubChannelTest(AsyncTestCase, AdaptedConfigurationTestCaseMixin): cls.stop = threading.Event() cls.req_server_channel.post_fork(cls._handle_payload, io_loop=cls.io_loop) cls.server_thread = threading.Thread( - target=run_loop_in_thread, args=(cls.io_loop, cls.stop,), + target=run_loop_in_thread, + args=( + cls.io_loop, + cls.stop, + ), ) cls.server_thread.start() diff --git a/tests/unit/utils/test_args.py b/tests/unit/utils/test_args.py index ecd5b401e33..f65be0137b5 100644 --- a/tests/unit/utils/test_args.py +++ b/tests/unit/utils/test_args.py @@ -54,7 +54,10 @@ class ArgsTestCase(TestCase): # Callable class instance expected_argspec = _ArgSpec( - args=["first"], varargs=None, keywords=None, defaults=None, + args=["first"], + varargs=None, + keywords=None, + defaults=None, ) ret = salt.utils.args.get_function_argspec(dummy_class) self.assertEqual(ret, expected_argspec) @@ -81,7 +84,10 @@ class ArgsTestCase(TestCase): # Function with both varargs and keywords expected_argspec = _ArgSpec( - args=[], varargs="args", keywords="kwargs", defaults=None, + args=[], + varargs="args", + keywords="kwargs", + defaults=None, ) ret = salt.utils.args.get_function_argspec(dummy_func_varargs_keywords) self.assertEqual(ret, expected_argspec) @@ -91,7 +97,10 @@ class ArgsTestCase(TestCase): # this case, but we're testing for the behavior we expect, which is # that the first argument is popped off of the args. expected_argspec = _ArgSpec( - args=["second", "third"], varargs=None, keywords=None, defaults=None, + args=["second", "third"], + varargs=None, + keywords=None, + defaults=None, ) ret = salt.utils.args.get_function_argspec( dummy_func_nodefault, is_class_method=True diff --git a/tests/unit/utils/test_configcomparer.py b/tests/unit/utils/test_configcomparer.py index f2b922c69f8..31887669a00 100644 --- a/tests/unit/utils/test_configcomparer.py +++ b/tests/unit/utils/test_configcomparer.py @@ -20,7 +20,9 @@ class UtilConfigcomparerTestCase(TestCase): to_update = copy.deepcopy(self.base_config) changes = {} configcomparer.compare_and_update_config( - {}, to_update, changes, + {}, + to_update, + changes, ) self.assertEqual({}, changes) self.assertEqual(self.base_config, to_update) @@ -29,10 +31,13 @@ class UtilConfigcomparerTestCase(TestCase): to_update = copy.deepcopy(self.base_config) changes = {} configcomparer.compare_and_update_config( - {"attrx": "value1"}, to_update, changes, + {"attrx": "value1"}, + to_update, + changes, ) self.assertEqual( - {"attrx": {"new": "value1", "old": None}}, changes, + {"attrx": {"new": "value1", "old": None}}, + changes, ) self.assertEqual("value1", to_update["attrx"]) self.assertEqual("value1", to_update["attr1"]) @@ -40,10 +45,13 @@ class UtilConfigcomparerTestCase(TestCase): to_update = copy.deepcopy(self.base_config) changes = {} configcomparer.compare_and_update_config( - {"attr1": "value2"}, to_update, changes, + {"attr1": "value2"}, + to_update, + changes, ) self.assertEqual( - {"attr1": {"new": "value2", "old": "value1"}}, changes, + {"attr1": {"new": "value2", "old": "value1"}}, + changes, ) self.assertEqual("value2", to_update["attr1"]) self.assertEqual( @@ -61,7 +69,9 @@ class UtilConfigcomparerTestCase(TestCase): to_update = copy.deepcopy(self.base_config) changes = {} configcomparer.compare_and_update_config( - {"attr3": []}, to_update, changes, + {"attr3": []}, + to_update, + changes, ) self.assertEqual({}, changes) self.assertEqual(self.base_config, to_update) @@ -70,10 +80,13 @@ class UtilConfigcomparerTestCase(TestCase): to_update = copy.deepcopy(self.base_config) changes = {} configcomparer.compare_and_update_config( - {"attr2": ["item1", "item2", "item3", "item4"]}, to_update, changes, + {"attr2": ["item1", "item2", "item3", "item4"]}, + to_update, + changes, ) self.assertEqual( - {"attr2[3]": {"new": "item4", "old": None}}, changes, + {"attr2[3]": {"new": "item4", "old": None}}, + changes, ) self.assertEqual( { @@ -90,7 +103,9 @@ class UtilConfigcomparerTestCase(TestCase): to_update = copy.deepcopy(self.base_config) changes = {} configcomparer.compare_and_update_config( - {"attr2": ["itemx", "item2"]}, to_update, changes, + {"attr2": ["itemx", "item2"]}, + to_update, + changes, ) self.assertEqual( { @@ -114,7 +129,9 @@ class UtilConfigcomparerTestCase(TestCase): to_update = copy.deepcopy(self.base_config) changes = {} configcomparer.compare_and_update_config( - {"attr4": {}}, to_update, changes, + {"attr4": {}}, + to_update, + changes, ) self.assertEqual({}, changes) self.assertEqual(self.base_config, to_update) @@ -123,10 +140,13 @@ class UtilConfigcomparerTestCase(TestCase): to_update = copy.deepcopy(self.base_config) changes = {} configcomparer.compare_and_update_config( - {"attr5": {"subattr3": "value1"}}, to_update, changes, + {"attr5": {"subattr3": "value1"}}, + to_update, + changes, ) self.assertEqual( - {"attr5.subattr3": {"new": "value1", "old": None}}, changes, + {"attr5.subattr3": {"new": "value1", "old": None}}, + changes, ) self.assertEqual( { diff --git a/tests/unit/utils/test_configparser.py b/tests/unit/utils/test_configparser.py index 99d28ebdb63..ab32ec992d9 100644 --- a/tests/unit/utils/test_configparser.py +++ b/tests/unit/utils/test_configparser.py @@ -214,7 +214,9 @@ class TestGitConfigParser(TestCase): # If the regex doesn't match, no items should be removed self.assertFalse( self.conf.remove_option_regexp( - self.remote, "fetch", salt.utils.stringutils.to_unicode(r"\d{7,10}"), + self.remote, + "fetch", + salt.utils.stringutils.to_unicode(r"\d{7,10}"), ) ) # Make sure that all three values are still there (since none should diff --git a/tests/unit/utils/test_context.py b/tests/unit/utils/test_context.py index 437a59ca0d0..2b8ff989767 100644 --- a/tests/unit/utils/test_context.py +++ b/tests/unit/utils/test_context.py @@ -27,8 +27,7 @@ class ContextDictTests(AsyncTestCase): @pytest.mark.slow_test def test_threads(self): - """Verify that ContextDict overrides properly within threads - """ + """Verify that ContextDict overrides properly within threads""" rets = [] def tgt(x, s): @@ -61,8 +60,7 @@ class ContextDictTests(AsyncTestCase): @gen_test @pytest.mark.slow_test def test_coroutines(self): - """Verify that ContextDict overrides properly within coroutines - """ + """Verify that ContextDict overrides properly within coroutines""" @salt.ext.tornado.gen.coroutine def secondary_coroutine(over): @@ -111,41 +109,49 @@ class ContextDictTests(AsyncTestCase): ) # verify that the override sticks across coroutines def test_basic(self): - """Test that the contextDict is a dict - """ + """Test that the contextDict is a dict""" # ensure we get the global value self.assertEqual( - dict(self.cd), {"foo": "global"}, + dict(self.cd), + {"foo": "global"}, ) def test_override(self): over = self.cd.clone() over["bar"] = "global" self.assertEqual( - dict(over), {"foo": "global", "bar": "global"}, + dict(over), + {"foo": "global", "bar": "global"}, ) self.assertEqual( - dict(self.cd), {"foo": "global"}, + dict(self.cd), + {"foo": "global"}, ) with over: self.assertEqual( - dict(over), {"foo": "global", "bar": "global"}, + dict(over), + {"foo": "global", "bar": "global"}, ) self.assertEqual( - dict(self.cd), {"foo": "global", "bar": "global"}, + dict(self.cd), + {"foo": "global", "bar": "global"}, ) over["bar"] = "baz" self.assertEqual( - dict(over), {"foo": "global", "bar": "baz"}, + dict(over), + {"foo": "global", "bar": "baz"}, ) self.assertEqual( - dict(self.cd), {"foo": "global", "bar": "baz"}, + dict(self.cd), + {"foo": "global", "bar": "baz"}, ) self.assertEqual( - dict(over), {"foo": "global", "bar": "baz"}, + dict(over), + {"foo": "global", "bar": "baz"}, ) self.assertEqual( - dict(self.cd), {"foo": "global"}, + dict(self.cd), + {"foo": "global"}, ) def test_multiple_contexts(self): @@ -156,7 +162,8 @@ class ContextDictTests(AsyncTestCase): self.assertNotIn("bar", self.cd) with cd: self.assertEqual( - dict(self.cd), {"bar": x, "foo": "global"}, + dict(self.cd), + {"bar": x, "foo": "global"}, ) self.assertNotIn("bar", self.cd) diff --git a/tests/unit/utils/test_data.py b/tests/unit/utils/test_data.py index ace76ce8a9b..ce2748a5b0b 100644 --- a/tests/unit/utils/test_data.py +++ b/tests/unit/utils/test_data.py @@ -222,7 +222,9 @@ class DataTestCase(TestCase): self.assertEqual( "it worked", salt.utils.data.traverse_dict_and_list( - {"foo": {1234: "it worked"}}, "foo:1234", "it didn't work", + {"foo": {1234: "it worked"}}, + "foo:1234", + "it didn't work", ), ) # Make sure that we properly return the default value when the initial @@ -231,7 +233,9 @@ class DataTestCase(TestCase): self.assertEqual( "default", salt.utils.data.traverse_dict_and_list( - {"foo": {"baz": "didn't work"}}, "foo:bar", "default", + {"foo": {"baz": "didn't work"}}, + "foo:bar", + "default", ), ) @@ -495,7 +499,11 @@ class DataTestCase(TestCase): # Test binary blob self.assertEqual(salt.utils.data.decode(BYTES, keep=True, to_str=True), BYTES) self.assertRaises( - UnicodeDecodeError, salt.utils.data.decode, BYTES, keep=False, to_str=True, + UnicodeDecodeError, + salt.utils.data.decode, + BYTES, + keep=False, + to_str=True, ) def test_decode_fallback(self): diff --git a/tests/unit/utils/test_dns.py b/tests/unit/utils/test_dns.py index 70d0ecb0cb0..629cf995801 100644 --- a/tests/unit/utils/test_dns.py +++ b/tests/unit/utils/test_dns.py @@ -99,9 +99,19 @@ class DNShelpersCase(TestCase): ] schemas = [ OrderedDict((("address", ipaddress.IPv4Address),)), - OrderedDict((("preference", int), ("name", str),)), OrderedDict( - (("prio", int), ("weight", int), ("port", _to_port), ("name", str),) + ( + ("preference", int), + ("name", str), + ) + ), + OrderedDict( + ( + ("prio", int), + ("weight", int), + ("port", _to_port), + ("name", str), + ) ), ] @@ -135,7 +145,12 @@ class DNShelpersCase(TestCase): "30 mbox6.example.com", ], ] - rschema = OrderedDict((("prio", int), ("srvr", str),)) + rschema = OrderedDict( + ( + ("prio", int), + ("srvr", str), + ) + ) results = [ OrderedDict([(10, ["mbox.example.com"])]), diff --git a/tests/unit/utils/test_dockermod.py b/tests/unit/utils/test_dockermod.py index 42e7b5e1917..f93f2a80b8b 100644 --- a/tests/unit/utils/test_dockermod.py +++ b/tests/unit/utils/test_dockermod.py @@ -966,7 +966,9 @@ class TranslateContainerInputTestCase(TranslateBase): for val in ("8.8.8.8,8.8.4.4", ["8.8.8.8", "8.8.4.4"]): self.assertEqual( salt.utils.dockermod.translate_input( - self.translator, dns=val, validate_ip_addrs=True, + self.translator, + dns=val, + validate_ip_addrs=True, ), {"dns": ["8.8.8.8", "8.8.4.4"]}, ) @@ -977,7 +979,9 @@ class TranslateContainerInputTestCase(TranslateBase): CommandExecutionError, r"'8.8.8.888' is not a valid IP address" ): salt.utils.dockermod.translate_input( - self.translator, dns=val, validate_ip_addrs=True, + self.translator, + dns=val, + validate_ip_addrs=True, ) # This is not valid input but it will test whether or not IP address @@ -985,7 +989,9 @@ class TranslateContainerInputTestCase(TranslateBase): for val in ("foo,bar", ["foo", "bar"]): self.assertEqual( salt.utils.dockermod.translate_input( - self.translator, dns=val, validate_ip_addrs=False, + self.translator, + dns=val, + validate_ip_addrs=False, ), {"dns": ["foo", "bar"]}, ) @@ -1018,7 +1024,9 @@ class TranslateContainerInputTestCase(TranslateBase): for val in ("web1:10.9.8.7,web2:10.9.8.8", ["web1:10.9.8.7", "web2:10.9.8.8"]): self.assertEqual( salt.utils.dockermod.translate_input( - self.translator, extra_hosts=val, validate_ip_addrs=True, + self.translator, + extra_hosts=val, + validate_ip_addrs=True, ), {"extra_hosts": {"web1": "10.9.8.7", "web2": "10.9.8.8"}}, ) @@ -1032,7 +1040,9 @@ class TranslateContainerInputTestCase(TranslateBase): CommandExecutionError, r"'10.9.8.299' is not a valid IP address" ): salt.utils.dockermod.translate_input( - self.translator, extra_hosts=val, validate_ip_addrs=True, + self.translator, + extra_hosts=val, + validate_ip_addrs=True, ) # This is not valid input but it will test whether or not IP address @@ -1040,7 +1050,9 @@ class TranslateContainerInputTestCase(TranslateBase): for val in ("foo:bar,baz:qux", ["foo:bar", "baz:qux"]): self.assertEqual( salt.utils.dockermod.translate_input( - self.translator, extra_hosts=val, validate_ip_addrs=False, + self.translator, + extra_hosts=val, + validate_ip_addrs=False, ), {"extra_hosts": {"foo": "bar", "baz": "qux"}}, ) @@ -1211,7 +1223,8 @@ class TranslateContainerInputTestCase(TranslateBase): self.assertEqual( self.normalize_ports( salt.utils.dockermod.translate_input( - self.translator, port_bindings=val, + self.translator, + port_bindings=val, ) ), { @@ -1249,7 +1262,8 @@ class TranslateContainerInputTestCase(TranslateBase): self.assertEqual( self.normalize_ports( salt.utils.dockermod.translate_input( - self.translator, port_bindings=val, + self.translator, + port_bindings=val, ) ), { @@ -1286,7 +1300,8 @@ class TranslateContainerInputTestCase(TranslateBase): self.assertEqual( self.normalize_ports( salt.utils.dockermod.translate_input( - self.translator, port_bindings=val, + self.translator, + port_bindings=val, ) ), { @@ -1320,7 +1335,8 @@ class TranslateContainerInputTestCase(TranslateBase): self.assertEqual( self.normalize_ports( salt.utils.dockermod.translate_input( - self.translator, port_bindings=val, + self.translator, + port_bindings=val, ) ), { @@ -1357,7 +1373,8 @@ class TranslateContainerInputTestCase(TranslateBase): self.assertEqual( self.normalize_ports( salt.utils.dockermod.translate_input( - self.translator, port_bindings=val, + self.translator, + port_bindings=val, ) ), { @@ -1421,7 +1438,8 @@ class TranslateContainerInputTestCase(TranslateBase): r"of port range \(5554\)", ): salt.utils.dockermod.translate_input( - self.translator, port_bindings=val, + self.translator, + port_bindings=val, ) # Error case: non-numeric port range @@ -1437,7 +1455,8 @@ class TranslateContainerInputTestCase(TranslateBase): CommandExecutionError, "'foo' is non-numeric or an invalid port range" ): salt.utils.dockermod.translate_input( - self.translator, port_bindings=val, + self.translator, + port_bindings=val, ) # Error case: misatched port range @@ -1456,7 +1475,8 @@ class TranslateContainerInputTestCase(TranslateBase): r"number of ports as the container port range \(1111-1113\)", ): salt.utils.dockermod.translate_input( - self.translator, port_bindings=val, + self.translator, + port_bindings=val, ) # Error case: empty host port or container port @@ -1490,7 +1510,10 @@ class TranslateContainerInputTestCase(TranslateBase): ): self.assertEqual( self.normalize_ports( - salt.utils.dockermod.translate_input(self.translator, ports=val,) + salt.utils.dockermod.translate_input( + self.translator, + ports=val, + ) ), {"ports": [1111, 2222, 4505, 4506, (3333, "udp")]}, ) @@ -1501,7 +1524,8 @@ class TranslateContainerInputTestCase(TranslateBase): CommandExecutionError, "'1.0' is not a valid port definition" ): salt.utils.dockermod.translate_input( - self.translator, ports=val, + self.translator, + ports=val, ) # Error case: port range start is greater than end @@ -1511,7 +1535,8 @@ class TranslateContainerInputTestCase(TranslateBase): r"port range \(5554\)", ): salt.utils.dockermod.translate_input( - self.translator, ports="5555-5554", + self.translator, + ports="5555-5554", ) @assert_bool(salt.utils.dockermod.translate.container) @@ -1644,7 +1669,10 @@ class TranslateContainerInputTestCase(TranslateBase): ulimits = "nofile=1024:2048,nproc=50" for val in (ulimits, ulimits.split(",")): self.assertEqual( - salt.utils.dockermod.translate_input(self.translator, ulimits=val,), + salt.utils.dockermod.translate_input( + self.translator, + ulimits=val, + ), { "ulimits": [ {"Name": "nofile", "Soft": 1024, "Hard": 2048}, @@ -1878,7 +1906,8 @@ class TranslateNetworkInputTestCase(TranslateBase): ] self.assertEqual( salt.utils.dockermod.translate_input( - self.translator, ipam_pools=[good_pool], + self.translator, + ipam_pools=[good_pool], ), {"ipam_pools": [good_pool]}, ) @@ -1907,7 +1936,9 @@ class TranslateNetworkInputTestCase(TranslateBase): for val in self.ip_addrs[True]: self.assertEqual( salt.utils.dockermod.translate_input( - self.translator, validate_ip_addrs=True, gateway=val, + self.translator, + validate_ip_addrs=True, + gateway=val, ), self.apply_defaults({"gateway": val}), ) @@ -1917,11 +1948,15 @@ class TranslateNetworkInputTestCase(TranslateBase): CommandExecutionError, "'{}' is not a valid IP address".format(val) ): salt.utils.dockermod.translate_input( - self.translator, validate_ip_addrs=True, gateway=val, + self.translator, + validate_ip_addrs=True, + gateway=val, ) self.assertEqual( salt.utils.dockermod.translate_input( - self.translator, validate_ip_addrs=False, gateway=val, + self.translator, + validate_ip_addrs=False, + gateway=val, ), self.apply_defaults( {"gateway": val if isinstance(val, str) else str(val)} diff --git a/tests/unit/utils/test_event.py b/tests/unit/utils/test_event.py index 216b38e90dd..9522d2ef0b7 100644 --- a/tests/unit/utils/test_event.py +++ b/tests/unit/utils/test_event.py @@ -160,7 +160,7 @@ class TestSaltEvent(TestCase): @pytest.mark.slow_test def test_event_no_timeout(self): - """Test no wait timeout, we should block forever, until we get one """ + """Test no wait timeout, we should block forever, until we get one""" with eventpublisher_process(self.sock_dir): with salt.utils.event.MasterEvent(self.sock_dir, listen=True) as me: with eventsender_process({"data": "foo2"}, "evt2", self.sock_dir, 5): @@ -330,7 +330,10 @@ class TestAsyncEventPublisher(AsyncTestCase): os.makedirs(self.sock_dir) self.addCleanup(shutil.rmtree, self.sock_dir, ignore_errors=True) self.opts = {"sock_dir": self.sock_dir} - self.publisher = salt.utils.event.AsyncEventPublisher(self.opts, self.io_loop,) + self.publisher = salt.utils.event.AsyncEventPublisher( + self.opts, + self.io_loop, + ) self.event = salt.utils.event.get_event( "minion", opts=self.opts, io_loop=self.io_loop ) diff --git a/tests/unit/utils/test_jinja.py b/tests/unit/utils/test_jinja.py index fb67e17fa23..5af44ad796f 100644 --- a/tests/unit/utils/test_jinja.py +++ b/tests/unit/utils/test_jinja.py @@ -975,14 +975,23 @@ class TestCustomExtensions(TestCase): rendered = env.from_string("{{ data }}").render(data=data) self.assertEqual( - rendered, "{'foo': {'bar': 'baz', 'qux': 42}}", + rendered, + "{'foo': {'bar': 'baz', 'qux': 42}}", ) rendered = env.from_string("{{ data }}").render( - data=[OrderedDict(foo="bar",), OrderedDict(baz=42,)] + data=[ + OrderedDict( + foo="bar", + ), + OrderedDict( + baz=42, + ), + ] ) self.assertEqual( - rendered, "[{'foo': 'bar'}, {'baz': 42}]", + rendered, + "[{'foo': 'bar'}, {'baz': 42}]", ) def test_set_dict_key_value(self): @@ -1024,7 +1033,8 @@ class TestCustomExtensions(TestCase): ), ) self.assertEqual( - rendered, "{'bar': {'baz': {'qux': 1, 'quux': 3}}}", + rendered, + "{'bar': {'baz': {'qux': 1, 'quux': 3}}}", ) # Test incorrect usage @@ -1066,7 +1076,8 @@ class TestCustomExtensions(TestCase): ), ) self.assertEqual( - rendered, "{'bar': {'baz': [1, 2, 42]}}", + rendered, + "{'bar': {'baz': [1, 2, 42]}}", ) def test_extend_dict_key_value(self): @@ -1089,7 +1100,8 @@ class TestCustomExtensions(TestCase): ), ) self.assertEqual( - rendered, "{'bar': {'baz': [1, 2, 42, 43]}}", + rendered, + "{'bar': {'baz': [1, 2, 42, 43]}}", ) # Edge cases rendered = render_jinja_tmpl( diff --git a/tests/unit/utils/test_mac_utils.py b/tests/unit/utils/test_mac_utils.py index 256cd7bd257..822ac7cb591 100644 --- a/tests/unit/utils/test_mac_utils.py +++ b/tests/unit/utils/test_mac_utils.py @@ -300,7 +300,10 @@ class MacUtilsTestCase(TestCase, LoaderModuleMockMixin): @patch("os.path.exists") @patch("salt.utils.mac_utils.__salt__") def test_available_services_binary_plist( - self, mock_run, mock_exists, mock_os_walk, + self, + mock_run, + mock_exists, + mock_os_walk, ): """ test available_services handles binary plist files. diff --git a/tests/unit/utils/test_msgpack.py b/tests/unit/utils/test_msgpack.py index db26f8ca884..3f5e3e903c3 100644 --- a/tests/unit/utils/test_msgpack.py +++ b/tests/unit/utils/test_msgpack.py @@ -65,7 +65,10 @@ class TestMsgpack(TestCase): False, (), ((),), - ((), None,), + ( + (), + None, + ), {None: 0}, (1 << 23), ] @@ -376,7 +379,8 @@ class TestMsgpack(TestCase): b"\xca" + struct.pack(">f", 1.0), pack_func(1.0, use_single_float=True) ) self.assertEqual( - b"\xcb" + struct.pack(">d", 1.0), pack_func(1.0, use_single_float=False), + b"\xcb" + struct.pack(">d", 1.0), + pack_func(1.0, use_single_float=False), ) def _test_odict(self, pack_func, unpack_func): diff --git a/tests/unit/utils/test_process.py b/tests/unit/utils/test_process.py index ecf297dcb5d..ed3cab17205 100644 --- a/tests/unit/utils/test_process.py +++ b/tests/unit/utils/test_process.py @@ -389,7 +389,8 @@ class TestSignalHandlingProcess(TestCase): # Create a second process that should not respond to SIGINT or SIGTERM proc2 = multiprocessing.Process( - target=self.run_forever_target, args=(self.run_forever_sub_target, evt), + target=self.run_forever_target, + args=(self.run_forever_sub_target, evt), ) proc2.start() diff --git a/tests/unit/utils/test_pycrypto.py b/tests/unit/utils/test_pycrypto.py index c34bd399df9..18d55d603c7 100644 --- a/tests/unit/utils/test_pycrypto.py +++ b/tests/unit/utils/test_pycrypto.py @@ -48,7 +48,9 @@ class PycryptoTestCase(TestCase): for algorithm in methods: expected = self.expecteds[algorithm] ret = salt.utils.pycrypto.gen_hash( - crypt_salt=expected["salt"], password=self.passwd, algorithm=algorithm, + crypt_salt=expected["salt"], + password=self.passwd, + algorithm=algorithm, ) self.assertEqual(ret, expected["hashed"]) @@ -71,7 +73,8 @@ class PycryptoTestCase(TestCase): default_algorithm = salt.utils.pycrypto.crypt.methods[0].name.lower() expected = self.expecteds[default_algorithm] ret = salt.utils.pycrypto.gen_hash( - crypt_salt=expected["salt"], password=self.passwd, + crypt_salt=expected["salt"], + password=self.passwd, ) self.assertEqual(ret, expected["hashed"]) @@ -87,7 +90,9 @@ class PycryptoTestCase(TestCase): for algorithm in methods: expected = self.expecteds[algorithm] ret = salt.utils.pycrypto.gen_hash( - crypt_salt=expected["salt"], password=self.passwd, algorithm=algorithm, + crypt_salt=expected["salt"], + password=self.passwd, + algorithm=algorithm, ) self.assertEqual(ret, expected["hashed"]) diff --git a/tests/unit/utils/test_reactor.py b/tests/unit/utils/test_reactor.py index b83308cedbf..4123bdfb9b2 100644 --- a/tests/unit/utils/test_reactor.py +++ b/tests/unit/utils/test_reactor.py @@ -449,7 +449,9 @@ class TestReactor(TestCase, AdaptedConfigurationTestCaseMixin): MagicMock(return_value=self.render_pipe), ): reactions = self.reactor.reactions( - tag, REACTOR_DATA[rtype], reactors, + tag, + REACTOR_DATA[rtype], + reactors, ) log.debug( "test_reactions: %s reactions: %s", diff --git a/tests/unit/utils/test_schema.py b/tests/unit/utils/test_schema.py index ef7acdb7a3e..d8600bdc55f 100644 --- a/tests/unit/utils/test_schema.py +++ b/tests/unit/utils/test_schema.py @@ -2170,7 +2170,7 @@ class TestComplexComplexDefinitionsSchema(schema.DefinitionsSchema): class ComplexSchemaTestCase(TestCase): - """ Test cases with definition schemas containing complex items""" + """Test cases with definition schemas containing complex items""" obj = ComplexSchemaItem() complex_obj = ComplexComplexSchemaItem() diff --git a/tests/unit/utils/test_templates.py b/tests/unit/utils/test_templates.py index 766318967e5..4ca27cf4ed4 100644 --- a/tests/unit/utils/test_templates.py +++ b/tests/unit/utils/test_templates.py @@ -247,12 +247,12 @@ class MockRender: class WrapRenderTestCase(TestCase): def assertDictContainsAll(self, actual, **expected): - """ Make sure dictionary contains at least all expected values""" + """Make sure dictionary contains at least all expected values""" actual = {key: actual[key] for key in expected if key in actual} self.assertEqual(expected, actual) def _test_generated_sls_context(self, tmplpath, sls, **expected): - """ Generic SLS Context Test""" + """Generic SLS Context Test""" # DeNormalize tmplpath tmplpath = str(PurePath(PurePosixPath(tmplpath))) if tmplpath.startswith("\\"): @@ -264,7 +264,7 @@ class WrapRenderTestCase(TestCase): @patch("salt.utils.templates.generate_sls_context") @with_tempdir() def test_sls_context_call(self, tempdir, generate_sls_context): - """ Check that generate_sls_context is called with proper parameters""" + """Check that generate_sls_context is called with proper parameters""" sls = "foo.bar" tmplpath = "/tmp/foo/bar.sls" @@ -280,7 +280,7 @@ class WrapRenderTestCase(TestCase): @patch("salt.utils.templates.generate_sls_context") @with_tempdir() def test_sls_context_no_call(self, tempdir, generate_sls_context): - """ Check that generate_sls_context is not called if sls is not set""" + """Check that generate_sls_context is not called if sls is not set""" sls = "foo.bar" tmplpath = "/tmp/foo/bar.sls" @@ -294,7 +294,7 @@ class WrapRenderTestCase(TestCase): generate_sls_context.assert_not_called() def test_generate_sls_context__top_level(self): - """ generate_sls_context - top_level Use case""" + """generate_sls_context - top_level Use case""" self._test_generated_sls_context( "/tmp/boo.sls", "boo", @@ -308,7 +308,7 @@ class WrapRenderTestCase(TestCase): ) def test_generate_sls_context__one_level_init_implicit(self): - """ generate_sls_context - Basic one level with implicit init.sls """ + """generate_sls_context - Basic one level with implicit init.sls""" self._test_generated_sls_context( "/tmp/foo/init.sls", "foo", @@ -322,7 +322,7 @@ class WrapRenderTestCase(TestCase): ) def test_generate_sls_context__one_level_init_explicit(self): - """ generate_sls_context - Basic one level with explicit init.sls """ + """generate_sls_context - Basic one level with explicit init.sls""" self._test_generated_sls_context( "/tmp/foo/init.sls", "foo.init", @@ -336,7 +336,7 @@ class WrapRenderTestCase(TestCase): ) def test_generate_sls_context__one_level(self): - """ generate_sls_context - Basic one level with name""" + """generate_sls_context - Basic one level with name""" self._test_generated_sls_context( "/tmp/foo/boo.sls", "foo.boo", @@ -350,7 +350,7 @@ class WrapRenderTestCase(TestCase): ) def test_generate_sls_context__one_level_repeating(self): - """ generate_sls_context - Basic one level with name same as dir + """generate_sls_context - Basic one level with name same as dir (Issue #56410) """ @@ -367,7 +367,7 @@ class WrapRenderTestCase(TestCase): ) def test_generate_sls_context__two_level_init_implicit(self): - """ generate_sls_context - Basic two level with implicit init.sls """ + """generate_sls_context - Basic two level with implicit init.sls""" self._test_generated_sls_context( "/tmp/foo/bar/init.sls", "foo.bar", @@ -381,7 +381,7 @@ class WrapRenderTestCase(TestCase): ) def test_generate_sls_context__two_level_init_explicit(self): - """ generate_sls_context - Basic two level with explicit init.sls """ + """generate_sls_context - Basic two level with explicit init.sls""" self._test_generated_sls_context( "/tmp/foo/bar/init.sls", "foo.bar.init", @@ -395,7 +395,7 @@ class WrapRenderTestCase(TestCase): ) def test_generate_sls_context__two_level(self): - """ generate_sls_context - Basic two level with name""" + """generate_sls_context - Basic two level with name""" self._test_generated_sls_context( "/tmp/foo/bar/boo.sls", "foo.bar.boo", @@ -409,7 +409,7 @@ class WrapRenderTestCase(TestCase): ) def test_generate_sls_context__two_level_repeating(self): - """ generate_sls_context - Basic two level with name same as dir + """generate_sls_context - Basic two level with name same as dir (Issue #56410) """ @@ -429,7 +429,7 @@ class WrapRenderTestCase(TestCase): @patch("salt.utils.templates._generate_sls_context", return_value="new") @patch("salt.utils.templates.features.get", return_value=True) def test_feature_flag_on(self, feature_get, new_impl, legacy_impl): - """ Test feature flag selection with FF on""" + """Test feature flag selection with FF on""" tplpath = "tplpath" sls = "sls" self.assertEqual("new", salt.utils.templates.generate_sls_context(tplpath, sls)) @@ -440,7 +440,7 @@ class WrapRenderTestCase(TestCase): @patch("salt.utils.templates._generate_sls_context", return_value="new") @patch("salt.utils.templates.features.get", return_value=False) def test_feature_flag_off(self, feature_get, new_impl, legacy_impl): - """ Test feature flag selection with FF on""" + """Test feature flag selection with FF on""" tplpath = "tplpath" sls = "sls" self.assertEqual( @@ -452,8 +452,7 @@ class WrapRenderTestCase(TestCase): @skipIf(sys.platform == "win32", "Backslash not possible under windows") def test_generate_sls_context__backslash_in_path(self): - """ generate_sls_context - Handle backslash in path on non-windows - """ + """generate_sls_context - Handle backslash in path on non-windows""" self._test_generated_sls_context( "/tmp/foo/foo\\foo.sls", "foo.foo\\foo", diff --git a/tests/unit/utils/test_thin.py b/tests/unit/utils/test_thin.py index 091a6bf0c4f..b16634f41ab 100644 --- a/tests/unit/utils/test_thin.py +++ b/tests/unit/utils/test_thin.py @@ -370,7 +370,10 @@ class SSHThinTestCase(TestCase): :return: """ cfg = {"ns": {"py-version": [2, 7]}} - assert thin._get_ext_namespaces(cfg).get("ns") == (2, 7,) + assert thin._get_ext_namespaces(cfg).get("ns") == ( + 2, + 7, + ) assert isinstance(thin._get_ext_namespaces(cfg).get("ns"), tuple) def test_get_ext_namespaces_failure(self): @@ -387,14 +390,16 @@ class SSHThinTestCase(TestCase): type("distro", (), {"__file__": "/site-packages/distro"}), ) @patch( - "salt.utils.thin.salt", type("salt", (), {"__file__": "/site-packages/salt"}), + "salt.utils.thin.salt", + type("salt", (), {"__file__": "/site-packages/salt"}), ) @patch( "salt.utils.thin.jinja2", type("jinja2", (), {"__file__": "/site-packages/jinja2"}), ) @patch( - "salt.utils.thin.yaml", type("yaml", (), {"__file__": "/site-packages/yaml"}), + "salt.utils.thin.yaml", + type("yaml", (), {"__file__": "/site-packages/yaml"}), ) @patch( "salt.utils.thin.tornado", @@ -480,14 +485,16 @@ class SSHThinTestCase(TestCase): type("distro", (), {"__file__": "/site-packages/distro"}), ) @patch( - "salt.utils.thin.salt", type("salt", (), {"__file__": "/site-packages/salt"}), + "salt.utils.thin.salt", + type("salt", (), {"__file__": "/site-packages/salt"}), ) @patch( "salt.utils.thin.jinja2", type("jinja2", (), {"__file__": "/site-packages/jinja2"}), ) @patch( - "salt.utils.thin.yaml", type("yaml", (), {"__file__": "/site-packages/yaml"}), + "salt.utils.thin.yaml", + type("yaml", (), {"__file__": "/site-packages/yaml"}), ) @patch( "salt.utils.thin.tornado", @@ -583,14 +590,16 @@ class SSHThinTestCase(TestCase): type("distro", (), {"__file__": "/site-packages/distro"}), ) @patch( - "salt.utils.thin.salt", type("salt", (), {"__file__": "/site-packages/salt"}), + "salt.utils.thin.salt", + type("salt", (), {"__file__": "/site-packages/salt"}), ) @patch( "salt.utils.thin.jinja2", type("jinja2", (), {"__file__": "/site-packages/jinja2"}), ) @patch( - "salt.utils.thin.yaml", type("yaml", (), {"__file__": "/site-packages/yaml"}), + "salt.utils.thin.yaml", + type("yaml", (), {"__file__": "/site-packages/yaml"}), ) @patch( "salt.utils.thin.tornado", @@ -1357,6 +1366,9 @@ class SSHThinTestCase(TestCase): tar.extractall(str(thin_dir)) tar.close() ret = venv.run( - venv.venv_python, str(thin_dir / "salt-call"), "--version", check=False, + venv.venv_python, + str(thin_dir / "salt-call"), + "--version", + check=False, ) assert ret.exitcode == 0, ret diff --git a/tests/unit/utils/test_vmware.py b/tests/unit/utils/test_vmware.py index f64d6747d83..cb22d46d1ee 100644 --- a/tests/unit/utils/test_vmware.py +++ b/tests/unit/utils/test_vmware.py @@ -1797,7 +1797,8 @@ class PrivateGetServiceInstanceTestCase(TestCase): self.assertEqual(mock_sc.call_count, 1) self.assertIn( - "Could not connect to host 'fake_host.fqdn'", excinfo.exception.message, + "Could not connect to host 'fake_host.fqdn'", + excinfo.exception.message, ) def test_attempt_unsuccessful_connection_vim_fault(self): diff --git a/tests/unit/utils/test_vt.py b/tests/unit/utils/test_vt.py index 9fa6308a711..74c9c12bb9f 100644 --- a/tests/unit/utils/test_vt.py +++ b/tests/unit/utils/test_vt.py @@ -28,7 +28,7 @@ from tests.support.unit import TestCase, skipIf def stdout_fileno_available(): """ - Tests if sys.stdout.fileno is available in this testing environment + Tests if sys.stdout.fileno is available in this testing environment """ try: sys.stdout.fileno() @@ -39,11 +39,11 @@ def stdout_fileno_available(): def fixStdOutErrFileNoIfNeeded(func): """ - Decorator that sets stdout and stderr to their original objects if - sys.stdout.fileno() doesn't work and restores them after running the - decorated function. This doesn't check if the original objects actually - work. If they don't then the test environment is too broken to test - the VT. + Decorator that sets stdout and stderr to their original objects if + sys.stdout.fileno() doesn't work and restores them after running the + decorated function. This doesn't check if the original objects actually + work. If they don't then the test environment is too broken to test + the VT. """ @functools.wraps(func) @@ -267,8 +267,8 @@ class VTTestCase(TestCase): @fixStdOutErrFileNoIfNeeded def test_split_multibyte_characters_unicode(self): """ - Tests that the vt correctly handles multibyte characters that are - split between blocks of transmitted data. + Tests that the vt correctly handles multibyte characters that are + split between blocks of transmitted data. """ block_size = 1024 encoding = "utf-8" @@ -334,9 +334,9 @@ class VTTestCase(TestCase): @fixStdOutErrFileNoIfNeeded def test_split_multibyte_characters_shiftjis(self): """ - Tests that the vt correctly handles multibyte characters that are - split between blocks of transmitted data. - Uses shift-jis encoding to make sure code doesn't assume unicode. + Tests that the vt correctly handles multibyte characters that are + split between blocks of transmitted data. + Uses shift-jis encoding to make sure code doesn't assume unicode. """ block_size = 1024 encoding = "shift-jis" diff --git a/tests/unit/utils/test_win_functions.py b/tests/unit/utils/test_win_functions.py index 90013fac386..c17f3ba9256 100644 --- a/tests/unit/utils/test_win_functions.py +++ b/tests/unit/utils/test_win_functions.py @@ -56,7 +56,7 @@ class WinFunctionsTestCase(TestCase): @skipIf(not salt.utils.platform.is_windows(), "WinDLL only available on Windows") def test_broadcast_setting_change(self): """ - Test to rehash the Environment variables + Test to rehash the Environment variables """ self.assertTrue(win_functions.broadcast_setting_change()) diff --git a/tests/unit/utils/test_win_reg.py b/tests/unit/utils/test_win_reg.py index ff50801e1d6..5081bbdeb78 100644 --- a/tests/unit/utils/test_win_reg.py +++ b/tests/unit/utils/test_win_reg.py @@ -390,7 +390,11 @@ class WinFunctionsTestCase(TestCase): "vtype": "REG_MULTI_SZ", } self.assertEqual( - win_reg.read_value(hive="HKLM", key=FAKE_KEY, vname="empty_list",), + win_reg.read_value( + hive="HKLM", + key=FAKE_KEY, + vname="empty_list", + ), expected, ) finally: diff --git a/tests/unit/utils/test_zfs.py b/tests/unit/utils/test_zfs.py index a9f24ab61cc..d4c208c4b26 100644 --- a/tests/unit/utils/test_zfs.py +++ b/tests/unit/utils/test_zfs.py @@ -969,7 +969,8 @@ class ZfsUtilsTestCase(TestCase): res["stderr"] = "" res["stdout"] = "" self.assertEqual( - zfs.parse_command_result(res), OrderedDict(), + zfs.parse_command_result(res), + OrderedDict(), ) def test_parse_command_result_fail(self): @@ -1014,7 +1015,8 @@ class ZfsUtilsTestCase(TestCase): res["stderr"] = "" res["stdout"] = "" self.assertEqual( - zfs.parse_command_result(res), OrderedDict(), + zfs.parse_command_result(res), + OrderedDict(), ) def test_parse_command_result_fail_message(self):