From f4549113b17ddbb9ce71ee5ba50ba7acbe38982f Mon Sep 17 00:00:00 2001 From: Pedro Algarvio Date: Tue, 27 Feb 2024 10:24:22 +0000 Subject: [PATCH] Update pre-commit hook versions --- .pre-commit-config.yaml | 27 +- doc/_ext/saltdomain.py | 12 +- doc/ref/executors/index.rst | 3 +- doc/ref/modules/index.rst | 1 + doc/topics/development/tests/index.rst | 3 +- doc/topics/proxyminion/index.rst | 2 - doc/topics/releases/2016.11.0.rst | 15 +- noxfile.py | 3 +- salt/__init__.py | 6 - salt/_compat.py | 1 + salt/_logging/__init__.py | 1 + salt/auth/django.py | 3 +- salt/auth/file.py | 1 - salt/auth/keystone.py | 1 - salt/auth/ldap.py | 13 +- salt/auth/mysql.py | 1 - salt/auth/rest.py | 1 - salt/auth/yubico.py | 1 - salt/beacons/adb.py | 1 + salt/beacons/aix_account.py | 1 + salt/beacons/bonjour_announce.py | 1 + salt/beacons/btmp.py | 2 +- salt/beacons/cert_info.py | 1 + salt/beacons/diskusage.py | 3 +- salt/beacons/glxinfo.py | 1 + salt/beacons/haproxy.py | 1 + salt/beacons/inotify.py | 4 +- salt/beacons/journald.py | 1 + salt/beacons/load.py | 1 + salt/beacons/log_beacon.py | 1 + salt/beacons/memusage.py | 1 + salt/beacons/napalm_beacon.py | 2 +- salt/beacons/network_info.py | 1 + salt/beacons/pkg.py | 1 + salt/beacons/proxy_example.py | 1 + salt/beacons/ps.py | 1 + salt/beacons/salt_monitor.py | 11 +- salt/beacons/salt_proxy.py | 5 +- salt/beacons/sensehat.py | 5 +- salt/beacons/service.py | 1 + salt/beacons/sh.py | 3 +- salt/beacons/smartos_imgadm.py | 1 + salt/beacons/smartos_vmadm.py | 1 + salt/beacons/status.py | 7 +- salt/beacons/swapusage.py | 1 + salt/beacons/telegram_bot_msg.py | 1 + salt/beacons/twilio_txt_msg.py | 1 + salt/beacons/wtmp.py | 2 +- salt/cache/__init__.py | 17 +- salt/cache/etcd_cache.py | 38 +-- salt/cache/localfs.py | 24 +- salt/cache/redis_cache.py | 3 +- salt/channel/client.py | 1 + salt/cli/api.py | 1 - salt/cli/batch.py | 2 +- salt/cli/caller.py | 18 +- salt/cli/cp.py | 22 +- salt/cli/daemons.py | 1 - salt/cli/spm.py | 1 - salt/client/__init__.py | 1 - salt/client/mixins.py | 8 +- salt/client/netapi.py | 2 +- salt/client/ssh/__init__.py | 12 +- salt/client/ssh/ssh_py_shim.py | 4 +- salt/client/ssh/wrapper/__init__.py | 1 - salt/client/ssh/wrapper/cmdmod.py | 1 + salt/client/ssh/wrapper/grains.py | 1 - salt/client/ssh/wrapper/mine.py | 1 - salt/cloud/__init__.py | 1 + salt/cloud/cli.py | 21 +- salt/cloud/clouds/aliyun.py | 20 +- salt/cloud/clouds/cloudstack.py | 13 +- salt/cloud/clouds/ec2.py | 70 +++-- salt/cloud/clouds/gce.py | 28 +- salt/cloud/clouds/gogrid.py | 6 +- salt/cloud/clouds/hetzner.py | 43 +-- salt/cloud/clouds/joyent.py | 29 +- salt/cloud/clouds/libvirt.py | 32 +-- salt/cloud/clouds/lxc.py | 22 +- salt/cloud/clouds/oneandone.py | 22 +- salt/cloud/clouds/opennebula.py | 47 ++-- salt/cloud/clouds/openstack.py | 6 +- salt/cloud/clouds/packet.py | 14 +- salt/cloud/clouds/parallels.py | 24 +- salt/cloud/clouds/profitbricks.py | 24 +- salt/cloud/clouds/qingcloud.py | 22 +- salt/cloud/clouds/saltify.py | 10 +- salt/cloud/clouds/scaleway.py | 12 +- salt/cloud/clouds/softlayer.py | 10 +- salt/cloud/clouds/softlayer_hw.py | 10 +- salt/cloud/clouds/tencentcloud.py | 30 +- salt/cloud/clouds/vagrant.py | 12 +- salt/cloud/clouds/virtualbox.py | 6 +- salt/cloud/clouds/vmware.py | 162 ++++++----- salt/cloud/clouds/xen.py | 20 +- salt/cloud/libcloudfuncs.py | 20 +- salt/config/__init__.py | 1 + salt/config/schemas/common.py | 3 +- salt/config/schemas/esxcluster.py | 1 - salt/config/schemas/esxdatacenter.py | 1 - salt/config/schemas/esxi.py | 1 - salt/config/schemas/esxvm.py | 1 - salt/config/schemas/minion.py | 1 - salt/config/schemas/ssh.py | 1 - salt/daemons/__init__.py | 2 +- salt/daemons/masterapi.py | 4 +- salt/defaults/__init__.py | 4 +- salt/engines/__init__.py | 7 +- salt/engines/docker_events.py | 1 + salt/engines/ircbot.py | 18 +- salt/engines/libvirt_events.py | 10 +- salt/engines/napalm_syslog.py | 2 +- salt/engines/script.py | 2 +- salt/engines/slack.py | 7 +- salt/engines/slack_bolt_engine.py | 7 +- salt/exceptions.py | 2 +- salt/executors/sudo.py | 2 +- salt/features.py | 1 + salt/fileclient.py | 1 + salt/fileserver/__init__.py | 1 - salt/fileserver/gitfs.py | 1 - salt/fileserver/hgfs.py | 2 +- salt/fileserver/minionfs.py | 4 +- salt/fileserver/roots.py | 5 +- salt/fileserver/s3fs.py | 1 - salt/fileserver/svnfs.py | 3 +- salt/grains/cimc.py | 1 - salt/grains/core.py | 28 +- salt/grains/disks.py | 6 +- salt/grains/esxi.py | 1 - salt/grains/junos.py | 1 - salt/grains/lvm.py | 10 +- salt/grains/minion_process.py | 1 - salt/grains/napalm.py | 1 - salt/grains/package.py | 1 + salt/grains/panos.py | 1 - salt/grains/pending_reboot.py | 1 + salt/loader/context.py | 1 + salt/loader/dunder.py | 1 + salt/loader/lazy.py | 2 +- salt/log_handlers/fluent_mod.py | 8 +- salt/log_handlers/logstash_mod.py | 5 +- salt/log_handlers/sentry_mod.py | 2 +- salt/master.py | 25 +- salt/matchers/compound_match.py | 2 +- salt/matchers/confirm_top.py | 1 + salt/matchers/ipcidr_match.py | 2 +- salt/matchers/list_match.py | 2 +- salt/metaproxy/deltaproxy.py | 16 +- salt/minion.py | 1 + salt/modules/aix_group.py | 12 +- salt/modules/aix_shadow.py | 6 +- salt/modules/aixpkg.py | 30 +- salt/modules/aliases.py | 10 +- salt/modules/alternatives.py | 2 +- salt/modules/ansiblegate.py | 51 ++-- salt/modules/apache.py | 43 ++- salt/modules/apf.py | 8 +- salt/modules/apkpkg.py | 2 +- salt/modules/aptly.py | 34 +-- salt/modules/archive.py | 52 ++-- salt/modules/arista_pyeapi.py | 4 +- salt/modules/augeas_cfg.py | 16 +- salt/modules/aws_sqs.py | 6 +- salt/modules/bamboohr.py | 8 +- salt/modules/baredoc.py | 4 +- salt/modules/bcache.py | 50 ++-- salt/modules/beacons.py | 87 +++--- salt/modules/bigip.py | 72 ++--- salt/modules/bluez_bluetooth.py | 19 +- salt/modules/boto3_elasticache.py | 72 +++-- salt/modules/boto3_elasticsearch.py | 1 + salt/modules/boto3_route53.py | 26 +- salt/modules/boto3_sns.py | 1 + salt/modules/boto_apigateway.py | 21 +- salt/modules/boto_asg.py | 17 +- salt/modules/boto_cfn.py | 11 +- salt/modules/boto_cloudfront.py | 3 +- salt/modules/boto_cloudtrail.py | 3 +- salt/modules/boto_cloudwatch.py | 1 + salt/modules/boto_cloudwatch_event.py | 9 +- salt/modules/boto_cognitoidentity.py | 10 +- salt/modules/boto_datapipeline.py | 3 +- salt/modules/boto_dynamodb.py | 1 + salt/modules/boto_ec2.py | 28 +- salt/modules/boto_efs.py | 1 - salt/modules/boto_elasticache.py | 37 +-- salt/modules/boto_elasticsearch_domain.py | 5 +- salt/modules/boto_elb.py | 5 +- salt/modules/boto_elbv2.py | 1 + salt/modules/boto_iam.py | 3 +- salt/modules/boto_iot.py | 5 +- salt/modules/boto_kinesis.py | 3 +- salt/modules/boto_kms.py | 1 + salt/modules/boto_lambda.py | 9 +- salt/modules/boto_rds.py | 45 ++- salt/modules/boto_route53.py | 9 +- salt/modules/boto_s3.py | 1 + salt/modules/boto_s3_bucket.py | 3 +- salt/modules/boto_secgroup.py | 7 +- salt/modules/boto_sns.py | 5 +- salt/modules/boto_sqs.py | 1 + salt/modules/boto_ssm.py | 1 + salt/modules/boto_vpc.py | 118 ++++---- salt/modules/bsd_shadow.py | 7 +- salt/modules/btrfs.py | 100 +++---- salt/modules/cabal.py | 6 +- salt/modules/capirca_acl.py | 14 +- salt/modules/cassandra_cql.py | 36 +-- salt/modules/chef.py | 11 +- salt/modules/chronos.py | 6 +- salt/modules/chroot.py | 4 +- salt/modules/cimc.py | 23 +- salt/modules/ciscoconfparse_mod.py | 2 +- salt/modules/cloud.py | 1 - salt/modules/cmdmod.py | 123 ++++----- salt/modules/composer.py | 4 +- salt/modules/config.py | 4 +- salt/modules/consul.py | 100 ++++--- salt/modules/container_resource.py | 1 + salt/modules/cpan.py | 4 +- salt/modules/cron.py | 8 +- salt/modules/cryptdev.py | 10 +- salt/modules/csf.py | 46 +-- salt/modules/cyg.py | 16 +- salt/modules/daemontools.py | 16 +- salt/modules/datadog_api.py | 2 +- salt/modules/ddns.py | 18 +- salt/modules/deb_postgres.py | 7 +- salt/modules/debconfmod.py | 6 +- salt/modules/debian_ip.py | 46 ++- salt/modules/debian_service.py | 6 +- salt/modules/debuild_pkgbuild.py | 61 ++-- salt/modules/defaults.py | 1 - salt/modules/devinfo.py | 4 +- salt/modules/devmap.py | 4 +- salt/modules/dig.py | 16 +- salt/modules/djangomod.py | 19 +- salt/modules/dnsmasq.py | 11 +- salt/modules/dnsutil.py | 14 +- salt/modules/dockercompose.py | 1 - salt/modules/dockermod.py | 6 +- salt/modules/dpkg_lowpkg.py | 14 +- salt/modules/drac.py | 23 +- salt/modules/dracr.py | 55 ++-- salt/modules/ebuildpkg.py | 32 +-- salt/modules/elasticsearch.py | 1 - salt/modules/eselect.py | 3 +- salt/modules/esxi.py | 1 - salt/modules/esxvm.py | 1 - salt/modules/ethtool.py | 6 +- salt/modules/event.py | 1 - salt/modules/extfs.py | 1 - salt/modules/file.py | 16 +- salt/modules/firewalld.py | 67 +++-- salt/modules/freebsd_sysctl.py | 17 +- salt/modules/freebsd_update.py | 3 +- salt/modules/freebsdjail.py | 9 +- salt/modules/freebsdkmod.py | 6 +- salt/modules/freebsdpkg.py | 6 +- salt/modules/freebsdports.py | 20 +- salt/modules/freebsdservice.py | 42 ++- salt/modules/freezer.py | 4 +- salt/modules/genesis.py | 86 +++--- salt/modules/gentoo_service.py | 1 - salt/modules/gentoolkitmod.py | 8 +- salt/modules/github.py | 9 +- salt/modules/glanceng.py | 1 - salt/modules/glassfish.py | 16 +- salt/modules/glusterfs.py | 64 ++--- salt/modules/gnomedesktop.py | 7 +- salt/modules/gpg.py | 38 +-- salt/modules/grains.py | 11 +- salt/modules/grub_legacy.py | 6 +- salt/modules/haproxyconn.py | 6 +- salt/modules/hashutil.py | 1 - salt/modules/heat.py | 46 +-- salt/modules/helm.py | 3 +- salt/modules/hg.py | 23 +- salt/modules/highstate_doc.py | 26 +- salt/modules/hosts.py | 3 +- salt/modules/http.py | 1 - salt/modules/icinga2.py | 21 +- salt/modules/ifttt.py | 3 +- salt/modules/ilo.py | 8 +- salt/modules/incron.py | 14 +- salt/modules/influxdb08mod.py | 1 - salt/modules/influxdbmod.py | 11 +- salt/modules/infoblox.py | 10 +- salt/modules/inspectlib/collector.py | 8 +- salt/modules/inspectlib/fsdb.py | 4 +- salt/modules/inspectlib/kiwiproc.py | 6 +- salt/modules/inspectlib/query.py | 14 +- salt/modules/inspector.py | 2 +- salt/modules/iosconfig.py | 2 +- salt/modules/ipmi.py | 9 +- salt/modules/ipset.py | 1 - salt/modules/iptables.py | 58 ++-- salt/modules/iwtools.py | 8 +- salt/modules/jboss7.py | 39 ++- salt/modules/jboss7_cli.py | 5 +- salt/modules/jenkinsmod.py | 43 +-- salt/modules/junos.py | 132 ++++----- salt/modules/kapacitor.py | 24 +- salt/modules/kerberos.py | 19 +- salt/modules/kernelpkg_linux_apt.py | 18 +- salt/modules/kernelpkg_linux_yum.py | 6 +- salt/modules/keyboard.py | 13 +- salt/modules/keystone.py | 58 ++-- salt/modules/keystoneng.py | 3 +- salt/modules/keystore.py | 5 +- salt/modules/kmod.py | 10 +- salt/modules/launchctl_service.py | 7 +- salt/modules/layman.py | 6 +- salt/modules/ldap3.py | 7 +- salt/modules/ldapmod.py | 9 +- salt/modules/libcloud_compute.py | 3 +- salt/modules/libcloud_dns.py | 1 + salt/modules/libcloud_loadbalancer.py | 1 + salt/modules/libcloud_storage.py | 1 + salt/modules/linux_acl.py | 12 +- salt/modules/linux_ip.py | 6 +- salt/modules/linux_lvm.py | 58 ++-- salt/modules/linux_service.py | 2 +- salt/modules/linux_shadow.py | 2 +- salt/modules/linux_sysctl.py | 16 +- salt/modules/localemod.py | 26 +- salt/modules/locate.py | 8 +- salt/modules/logadm.py | 12 +- salt/modules/logrotate.py | 10 +- salt/modules/lvs.py | 18 +- salt/modules/lxc.py | 7 +- salt/modules/lxd.py | 91 +++--- salt/modules/mac_desktop.py | 4 +- salt/modules/mac_group.py | 13 +- salt/modules/mac_pkgutil.py | 8 +- salt/modules/mac_portspkg.py | 4 +- salt/modules/mac_shadow.py | 1 + salt/modules/mac_softwareupdate.py | 4 +- salt/modules/mac_sysctl.py | 14 +- salt/modules/mac_timezone.py | 12 +- salt/modules/mac_user.py | 42 +-- salt/modules/mac_xattr.py | 28 +- salt/modules/macdefaults.py | 6 +- salt/modules/makeconf.py | 14 +- salt/modules/mandrill.py | 1 - salt/modules/marathon.py | 15 +- salt/modules/mattermost.py | 1 - salt/modules/mdadm_raid.py | 13 +- salt/modules/mdata.py | 1 - salt/modules/memcached.py | 10 +- salt/modules/mine.py | 5 +- salt/modules/minion.py | 4 +- salt/modules/modjk.py | 33 ++- salt/modules/mongodb.py | 8 +- salt/modules/monit.py | 10 +- salt/modules/mount.py | 1 - salt/modules/mssql.py | 83 +++--- salt/modules/munin.py | 4 +- salt/modules/mysql.py | 1 - salt/modules/nacl.py | 1 - salt/modules/nagios.py | 5 +- salt/modules/nagios_rpc.py | 3 +- salt/modules/namecheap_domains.py | 8 +- salt/modules/namecheap_domains_dns.py | 1 - salt/modules/napalm_bgp.py | 3 - salt/modules/napalm_formula.py | 2 +- salt/modules/napalm_network.py | 75 ++--- salt/modules/napalm_ntp.py | 7 - salt/modules/napalm_probes.py | 4 - salt/modules/napalm_route.py | 2 - salt/modules/napalm_snmp.py | 4 - salt/modules/napalm_users.py | 4 - salt/modules/netaddress.py | 1 - salt/modules/netbox.py | 4 +- salt/modules/netmiko_mod.py | 4 +- salt/modules/netscaler.py | 2 +- salt/modules/neutronng.py | 1 - salt/modules/nexus.py | 12 +- salt/modules/nfs3.py | 4 +- salt/modules/nftables.py | 80 +++--- salt/modules/nginx.py | 10 +- salt/modules/nilrt_ip.py | 98 +++---- salt/modules/nix.py | 1 - salt/modules/npm.py | 14 +- salt/modules/nspawn.py | 1 - salt/modules/nxos_api.py | 6 +- salt/modules/nxos_upgrade.py | 12 +- salt/modules/omapi.py | 5 +- salt/modules/openbsd_sysctl.py | 10 +- salt/modules/openbsdpkg.py | 12 +- salt/modules/openbsdrcctl_service.py | 36 ++- salt/modules/openbsdservice.py | 13 +- salt/modules/opkg.py | 24 +- salt/modules/osquery.py | 16 +- salt/modules/pacmanpkg.py | 2 +- salt/modules/pagerduty_util.py | 10 +- salt/modules/pam.py | 2 +- salt/modules/panos.py | 55 ++-- salt/modules/parallels.py | 12 +- salt/modules/parted_partition.py | 38 ++- salt/modules/pcs.py | 9 +- salt/modules/pecl.py | 6 +- salt/modules/peeringdb.py | 4 +- salt/modules/pf.py | 23 +- salt/modules/pip.py | 10 +- salt/modules/pkg_resource.py | 5 +- salt/modules/pkgng.py | 34 ++- salt/modules/pkgutil.py | 4 +- salt/modules/portage_config.py | 6 +- salt/modules/postfix.py | 54 ++-- salt/modules/postgres.py | 2 +- salt/modules/poudriere.py | 50 ++-- salt/modules/powerpath.py | 4 +- salt/modules/proxy.py | 13 +- salt/modules/ps.py | 1 - salt/modules/publish.py | 6 +- salt/modules/puppet.py | 25 +- salt/modules/purefb.py | 2 +- salt/modules/pushbullet.py | 1 - salt/modules/pushover_notify.py | 1 - salt/modules/pw_group.py | 14 +- salt/modules/pw_user.py | 18 +- salt/modules/pyenv.py | 26 +- salt/modules/qemu_img.py | 2 +- salt/modules/qemu_nbd.py | 13 +- salt/modules/quota.py | 8 +- salt/modules/rabbitmq.py | 24 +- salt/modules/rallydev.py | 3 +- salt/modules/random_org.py | 31 ++- salt/modules/rbenv.py | 9 +- salt/modules/rdp.py | 4 +- salt/modules/reg.py | 5 +- salt/modules/restartcheck.py | 21 +- salt/modules/restconf.py | 3 +- salt/modules/ret.py | 8 +- salt/modules/rh_ip.py | 33 +-- salt/modules/riak.py | 6 +- salt/modules/rpm_lowpkg.py | 12 +- salt/modules/rpmbuild_pkgbuild.py | 27 +- salt/modules/rsync.py | 18 +- salt/modules/rvm.py | 6 +- salt/modules/s6.py | 14 +- salt/modules/salt_proxy.py | 22 +- salt/modules/salt_version.py | 1 - salt/modules/saltcheck.py | 13 +- salt/modules/saltcloudmod.py | 2 +- salt/modules/saltutil.py | 10 +- salt/modules/schedule.py | 35 +-- salt/modules/scp_mod.py | 4 +- salt/modules/scsi.py | 8 +- salt/modules/sdb.py | 1 - salt/modules/seed.py | 9 +- salt/modules/sensehat.py | 1 - salt/modules/sensors.py | 2 +- salt/modules/serverdensity_device.py | 21 +- salt/modules/servicenow.py | 2 +- salt/modules/slack_notify.py | 3 +- salt/modules/slsutil.py | 1 - salt/modules/smartos_imgadm.py | 4 +- salt/modules/smartos_nictagadm.py | 24 +- salt/modules/smartos_virt.py | 10 +- salt/modules/smartos_vmadm.py | 10 +- salt/modules/smbios.py | 6 +- salt/modules/smf_service.py | 25 +- salt/modules/smtp.py | 3 +- salt/modules/snapper.py | 31 +-- salt/modules/solaris_group.py | 6 +- salt/modules/solaris_shadow.py | 12 +- salt/modules/solaris_user.py | 15 +- salt/modules/solarisipspkg.py | 8 +- salt/modules/solarispkg.py | 22 +- salt/modules/solr.py | 33 ++- salt/modules/solrcloud.py | 14 +- salt/modules/splunk_search.py | 4 +- salt/modules/ssh.py | 32 +-- salt/modules/state.py | 2 +- salt/modules/status.py | 22 +- salt/modules/statuspage.py | 1 - salt/modules/supervisord.py | 15 +- salt/modules/suse_ip.py | 30 +- salt/modules/sysbench.py | 10 +- salt/modules/sysfs.py | 2 +- salt/modules/syslog_ng.py | 25 +- salt/modules/system_profiler.py | 1 - salt/modules/telegram.py | 2 +- salt/modules/telemetry.py | 19 +- salt/modules/testinframod.py | 2 +- salt/modules/textfsm_mod.py | 48 ++-- salt/modules/timezone.py | 1 - salt/modules/tls.py | 176 ++++++------ salt/modules/tomcat.py | 18 +- salt/modules/travisci.py | 1 + salt/modules/udev.py | 2 +- salt/modules/upstart_service.py | 18 +- salt/modules/uptime.py | 17 +- salt/modules/uwsgi.py | 2 +- salt/modules/vault.py | 1 + salt/modules/vbox_guest.py | 18 +- salt/modules/vboxmanage.py | 77 +++--- salt/modules/victorops.py | 5 +- salt/modules/virt.py | 239 ++++++++-------- salt/modules/virtualenv_mod.py | 17 +- salt/modules/vmctl.py | 11 +- salt/modules/vsphere.py | 51 ++-- salt/modules/webutil.py | 5 +- salt/modules/win_appx.py | 1 + salt/modules/win_autoruns.py | 1 - salt/modules/win_certutil.py | 14 +- salt/modules/win_dacl.py | 31 +-- salt/modules/win_disk.py | 12 +- salt/modules/win_dns_client.py | 2 +- salt/modules/win_dsc.py | 54 ++-- salt/modules/win_event.py | 5 +- salt/modules/win_firewall.py | 24 +- salt/modules/win_iis.py | 197 +++++++------ salt/modules/win_ip.py | 34 +-- salt/modules/win_lgpo.py | 73 ++--- salt/modules/win_lgpo_reg.py | 1 + salt/modules/win_license.py | 3 +- salt/modules/win_network.py | 4 +- salt/modules/win_pkg.py | 1 - salt/modules/win_pki.py | 40 +-- salt/modules/win_powercfg.py | 4 +- salt/modules/win_psget.py | 22 +- salt/modules/win_servermanager.py | 1 - salt/modules/win_service.py | 43 ++- salt/modules/win_shortcut.py | 19 +- salt/modules/win_smtp_server.py | 8 +- salt/modules/win_snmp.py | 6 +- salt/modules/win_status.py | 1 + salt/modules/win_task.py | 52 ++-- salt/modules/win_timezone.py | 7 +- salt/modules/win_useradd.py | 18 +- salt/modules/win_wua.py | 5 +- salt/modules/win_wusa.py | 1 - salt/modules/winrepo.py | 11 +- salt/modules/wordpress.py | 14 +- salt/modules/x509_v2.py | 9 +- salt/modules/xapi_virt.py | 16 +- salt/modules/xbpspkg.py | 6 +- salt/modules/xfs.py | 36 +-- salt/modules/xmpp.py | 1 - salt/modules/yumpkg.py | 1 + salt/modules/zcbuildout.py | 7 +- salt/modules/zenoss.py | 2 +- salt/modules/zypperpkg.py | 17 +- salt/netapi/__init__.py | 3 +- salt/netapi/rest_cherrypy/app.py | 14 +- salt/netapi/rest_wsgi.py | 2 +- salt/output/__init__.py | 3 +- salt/output/highstate.py | 13 +- salt/output/key.py | 2 +- salt/output/overstatestage.py | 1 - salt/output/pony.py | 1 - salt/output/profile.py | 4 +- salt/output/progress.py | 1 - salt/output/raw.py | 1 - salt/output/table_out.py | 10 +- salt/output/txt.py | 6 +- salt/output/virt_query.py | 8 +- salt/pillar/cmd_yamlex.py | 1 - salt/pillar/cobbler.py | 3 +- salt/pillar/consul_pillar.py | 1 - salt/pillar/django_orm.py | 6 +- salt/pillar/ec2_pillar.py | 5 +- salt/pillar/extra_minion_data_in_pillar.py | 1 + salt/pillar/gpg.py | 1 - salt/pillar/hiera.py | 5 +- salt/pillar/http_json.py | 3 +- salt/pillar/http_yaml.py | 3 +- salt/pillar/libvirt.py | 11 +- salt/pillar/makostack.py | 9 +- salt/pillar/nacl.py | 1 - salt/pillar/neutron.py | 1 - salt/pillar/pepa.py | 2 +- salt/pillar/puppet.py | 4 +- salt/pillar/reclass_adapter.py | 3 +- salt/pillar/s3.py | 4 +- salt/pillar/saltclass.py | 1 - salt/pillar/stack.py | 13 +- salt/pillar/varstack_pillar.py | 1 - salt/pillar/vault.py | 1 - salt/platform/win.py | 18 +- salt/proxy/chronos.py | 2 +- salt/proxy/cisconso.py | 1 - salt/proxy/dummy.py | 4 +- salt/proxy/esxcluster.py | 1 + salt/proxy/esxdatacenter.py | 1 - salt/proxy/esxi.py | 1 - salt/proxy/esxvm.py | 1 - salt/proxy/marathon.py | 2 +- salt/proxy/napalm.py | 2 +- salt/proxy/philips_hue.py | 8 +- salt/proxy/rest_sample.py | 2 - salt/proxy/restconf.py | 1 - salt/queues/pgjsonb_queue.py | 25 +- salt/queues/sqlite_queue.py | 28 +- salt/renderers/cheetah.py | 1 - salt/renderers/dson.py | 1 - salt/renderers/genshi.py | 1 - salt/renderers/gpg.py | 1 - salt/renderers/hjson.py | 1 - salt/renderers/jinja.py | 7 +- salt/renderers/json.py | 1 - salt/renderers/json5.py | 1 - salt/renderers/mako.py | 1 - salt/renderers/nacl.py | 1 - salt/renderers/pass.py | 1 - salt/renderers/py.py | 4 +- salt/renderers/pydsl.py | 1 + salt/renderers/pyobjects.py | 9 +- salt/renderers/stateconf.py | 9 +- salt/renderers/yaml.py | 1 - salt/returners/__init__.py | 8 +- salt/returners/appoptics_return.py | 1 - salt/returners/carbon_return.py | 4 +- salt/returners/couchdb_return.py | 3 +- salt/returners/elasticsearch_return.py | 11 +- salt/returners/influxdb_return.py | 8 +- salt/returners/librato_return.py | 1 - salt/returners/local_cache.py | 4 +- salt/returners/mattermost_returner.py | 4 +- salt/returners/memcache_return.py | 12 +- salt/returners/multi_returner.py | 19 +- salt/returners/mysql.py | 2 +- salt/returners/odbc.py | 4 +- salt/returners/pgjsonb.py | 6 +- salt/returners/postgres.py | 4 +- salt/returners/postgres_local_cache.py | 1 - salt/returners/rawfile_json.py | 1 - salt/returners/sentry_return.py | 6 +- salt/returners/slack_webhook_return.py | 12 +- salt/returners/smtp_return.py | 5 +- salt/returners/zabbix_return.py | 1 - salt/roster/__init__.py | 8 +- salt/roster/cache.py | 16 +- salt/roster/cloud.py | 1 - salt/roster/clustershell.py | 1 - salt/roster/dir.py | 7 +- salt/roster/sshconfig.py | 4 +- salt/roster/sshknownhosts.py | 5 +- salt/runners/asam.py | 20 +- salt/runners/auth.py | 1 - salt/runners/bgp.py | 4 +- salt/runners/cache.py | 2 +- salt/runners/ddns.py | 30 +- salt/runners/digicertapi.py | 33 +-- salt/runners/drac.py | 3 +- salt/runners/f5.py | 26 +- salt/runners/jobs.py | 30 +- salt/runners/launchd.py | 2 +- salt/runners/lxc.py | 11 +- salt/runners/manage.py | 11 +- salt/runners/match.py | 1 + salt/runners/mattermost.py | 5 +- salt/runners/nacl.py | 1 - salt/runners/net.py | 26 +- salt/runners/network.py | 5 +- salt/runners/pkg.py | 3 +- salt/runners/queue.py | 27 +- salt/runners/salt.py | 6 +- salt/runners/spacewalk.py | 18 +- salt/runners/ssh.py | 1 - salt/runners/test.py | 4 +- salt/runners/thin.py | 1 - salt/runners/venafiapi.py | 8 +- salt/runners/virt.py | 59 ++-- salt/runners/vistara.py | 8 +- salt/runners/winrepo.py | 2 +- salt/scripts.py | 4 +- salt/sdb/cache.py | 1 - salt/sdb/couchdb.py | 1 - salt/sdb/etcd_db.py | 1 - salt/sdb/rest.py | 1 - salt/sdb/sqlite3.py | 8 +- salt/sdb/tism.py | 1 - salt/sdb/vault.py | 1 - salt/sdb/yaml.py | 1 - salt/serializers/__init__.py | 1 - salt/serializers/configparser.py | 2 +- salt/serializers/json.py | 1 - salt/serializers/msgpack.py | 1 - salt/serializers/plist.py | 1 + salt/serializers/yaml.py | 1 - salt/serializers/yamlex.py | 3 +- salt/spm/__init__.py | 92 +++--- salt/spm/pkgdb/sqlite3.py | 3 +- salt/spm/pkgfiles/local.py | 25 +- salt/state.py | 16 +- salt/states/alias.py | 16 +- salt/states/alternatives.py | 44 +-- salt/states/apache.py | 1 - salt/states/aptpkg.py | 9 +- salt/states/archive.py | 46 +-- salt/states/artifactory.py | 1 - salt/states/at.py | 8 +- salt/states/aws_sqs.py | 8 +- salt/states/beacon.py | 26 +- salt/states/bigip.py | 49 ++-- salt/states/blockdev.py | 24 +- salt/states/boto3_elasticache.py | 76 ++--- salt/states/boto3_elasticsearch.py | 25 +- salt/states/boto3_route53.py | 101 +++---- salt/states/boto3_sns.py | 29 +- salt/states/boto_apigateway.py | 141 +++++----- salt/states/boto_asg.py | 5 +- salt/states/boto_cfn.py | 18 +- salt/states/boto_cloudfront.py | 9 +- salt/states/boto_cloudtrail.py | 21 +- salt/states/boto_cloudwatch_alarm.py | 21 +- salt/states/boto_cloudwatch_event.py | 13 +- salt/states/boto_cognitoidentity.py | 55 ++-- salt/states/boto_datapipeline.py | 13 +- salt/states/boto_dynamodb.py | 44 ++- salt/states/boto_ec2.py | 112 ++++---- salt/states/boto_elasticache.py | 39 ++- salt/states/boto_elasticsearch_domain.py | 29 +- salt/states/boto_elb.py | 133 +++++---- salt/states/boto_elbv2.py | 43 ++- salt/states/boto_iam.py | 174 ++++++------ salt/states/boto_iam_role.py | 56 ++-- salt/states/boto_iot.py | 46 ++- salt/states/boto_kinesis.py | 24 +- salt/states/boto_kms.py | 8 +- salt/states/boto_lambda.py | 45 ++- salt/states/boto_rds.py | 61 ++-- salt/states/boto_route53.py | 43 ++- salt/states/boto_s3.py | 13 +- salt/states/boto_s3_bucket.py | 31 +-- salt/states/boto_secgroup.py | 50 ++-- salt/states/boto_sns.py | 14 +- salt/states/boto_sqs.py | 12 +- salt/states/boto_vpc.py | 84 +++--- salt/states/bower.py | 29 +- salt/states/btrfs.py | 38 ++- salt/states/cabal.py | 15 +- salt/states/chocolatey.py | 24 +- salt/states/chronos_job.py | 14 +- salt/states/cimc.py | 7 +- salt/states/cloud.py | 61 ++-- salt/states/cmd.py | 39 ++- salt/states/composer.py | 34 +-- salt/states/consul.py | 5 +- salt/states/cron.py | 60 ++-- salt/states/cryptdev.py | 14 +- salt/states/csf.py | 8 +- salt/states/cyg.py | 4 +- salt/states/ddns.py | 6 +- salt/states/debconfmod.py | 4 +- salt/states/dellchassis.py | 9 +- salt/states/disk.py | 20 +- salt/states/docker_container.py | 18 +- salt/states/docker_image.py | 8 +- salt/states/docker_network.py | 18 +- salt/states/drac.py | 16 +- salt/states/dvs.py | 31 +-- salt/states/elasticsearch.py | 159 ++++++----- salt/states/elasticsearch_index.py | 19 +- salt/states/elasticsearch_index_template.py | 21 +- salt/states/environ.py | 1 - salt/states/eselect.py | 5 +- salt/states/esxcluster.py | 23 +- salt/states/esxdatacenter.py | 1 - salt/states/esxi.py | 10 +- salt/states/esxvm.py | 1 - salt/states/etcd_mod.py | 3 +- salt/states/ethtool.py | 57 ++-- salt/states/event.py | 1 - salt/states/file.py | 69 +++-- salt/states/firewalld.py | 2 - salt/states/gem.py | 6 +- salt/states/git.py | 196 ++++++------- salt/states/github.py | 128 +++++---- salt/states/glance_image.py | 5 +- salt/states/glassfish.py | 24 +- salt/states/glusterfs.py | 67 +++-- salt/states/gnomedesktop.py | 12 +- salt/states/grafana.py | 22 +- salt/states/grafana4_dashboard.py | 15 +- salt/states/grafana4_datasource.py | 16 +- salt/states/grafana4_org.py | 18 +- salt/states/grafana4_user.py | 18 +- salt/states/grafana_dashboard.py | 19 +- salt/states/grafana_datasource.py | 10 +- salt/states/grains.py | 74 +++-- salt/states/group.py | 7 +- salt/states/heat.py | 16 +- salt/states/helm.py | 8 +- salt/states/hg.py | 23 +- salt/states/highstate_doc.py | 3 +- salt/states/host.py | 37 ++- salt/states/http.py | 23 +- salt/states/icinga2.py | 55 ++-- salt/states/idem.py | 6 +- salt/states/ifttt.py | 4 +- salt/states/incron.py | 20 +- salt/states/influxdb08_database.py | 12 +- salt/states/influxdb08_user.py | 16 +- salt/states/influxdb_continuous_query.py | 20 +- salt/states/influxdb_database.py | 14 +- salt/states/influxdb_retention_policy.py | 26 +- salt/states/influxdb_user.py | 28 +- salt/states/infoblox_a.py | 14 +- salt/states/infoblox_cname.py | 14 +- salt/states/infoblox_host_record.py | 16 +- salt/states/infoblox_range.py | 4 +- salt/states/ini_manage.py | 37 ++- salt/states/ipmi.py | 6 +- salt/states/ipset.py | 22 +- salt/states/iptables.py | 67 ++--- salt/states/jboss7.py | 15 +- salt/states/jenkins.py | 11 +- salt/states/kapacitor.py | 3 +- salt/states/kernelpkg.py | 6 +- salt/states/keyboard.py | 12 +- salt/states/keystone.py | 122 ++++---- salt/states/keystone_domain.py | 7 +- salt/states/keystone_endpoint.py | 1 - salt/states/keystone_group.py | 1 - salt/states/keystone_project.py | 1 - salt/states/keystone_role.py | 1 - salt/states/keystone_role_grant.py | 1 - salt/states/keystone_service.py | 1 - salt/states/keystone_user.py | 1 - salt/states/keystore.py | 5 +- salt/states/kmod.py | 16 +- salt/states/layman.py | 18 +- salt/states/libcloud_dns.py | 2 +- salt/states/libcloud_loadbalancer.py | 1 - salt/states/libcloud_storage.py | 1 - salt/states/linux_acl.py | 1 - salt/states/locale.py | 19 +- salt/states/logrotate.py | 7 +- salt/states/loop.py | 19 +- salt/states/lvm.py | 28 +- salt/states/lvs_server.py | 64 ++--- salt/states/lvs_service.py | 28 +- salt/states/lxc.py | 55 ++-- salt/states/lxd.py | 13 +- salt/states/lxd_container.py | 73 +++-- salt/states/lxd_image.py | 21 +- salt/states/lxd_profile.py | 23 +- salt/states/mac_assistive.py | 4 +- salt/states/mac_keychain.py | 14 +- salt/states/macdefaults.py | 12 +- salt/states/macpackage.py | 14 +- salt/states/makeconf.py | 6 +- salt/states/marathon_app.py | 20 +- salt/states/mdadm_raid.py | 49 ++-- salt/states/memcached.py | 21 +- salt/states/modjk.py | 6 +- salt/states/modjk_worker.py | 18 +- salt/states/module.py | 21 +- salt/states/mongodb_database.py | 4 +- salt/states/mongodb_user.py | 18 +- salt/states/monit.py | 16 +- salt/states/mount.py | 32 +-- salt/states/mssql_database.py | 24 +- salt/states/mssql_login.py | 26 +- salt/states/mssql_role.py | 22 +- salt/states/mssql_user.py | 26 +- salt/states/msteams.py | 7 +- salt/states/mysql_database.py | 22 +- salt/states/mysql_grants.py | 36 +-- salt/states/mysql_query.py | 17 +- salt/states/mysql_user.py | 28 +- salt/states/netconfig.py | 16 +- salt/states/netntp.py | 28 +- salt/states/netsnmp.py | 16 +- salt/states/netusers.py | 11 +- salt/states/network.py | 64 ++--- salt/states/neutron_network.py | 3 +- salt/states/neutron_secgroup.py | 1 - salt/states/neutron_secgroup_rule.py | 3 +- salt/states/neutron_subnet.py | 1 - salt/states/nexus.py | 1 - salt/states/nfs_export.py | 12 +- salt/states/nftables.py | 102 +++---- salt/states/npm.py | 25 +- salt/states/nxos.py | 4 +- salt/states/nxos_upgrade.py | 4 +- salt/states/openstack_config.py | 3 +- salt/states/openvswitch_port.py | 80 +++--- salt/states/opsgenie.py | 16 +- salt/states/pagerduty.py | 4 +- salt/states/pagerduty_escalation_policy.py | 6 +- salt/states/pagerduty_schedule.py | 2 +- salt/states/pagerduty_service.py | 2 +- salt/states/panos.py | 60 ++-- salt/states/pbm.py | 15 +- salt/states/pecl.py | 18 +- salt/states/pip_state.py | 5 +- salt/states/pkg.py | 67 ++--- salt/states/pkgbuild.py | 2 +- salt/states/pkgrepo.py | 19 +- salt/states/ports.py | 36 +-- salt/states/postgres_cluster.py | 6 +- salt/states/postgres_database.py | 22 +- salt/states/postgres_extension.py | 16 +- salt/states/postgres_group.py | 20 +- salt/states/postgres_initdb.py | 8 +- salt/states/postgres_language.py | 16 +- salt/states/postgres_privileges.py | 8 +- salt/states/postgres_schema.py | 12 +- salt/states/postgres_tablespace.py | 35 ++- salt/states/postgres_user.py | 22 +- salt/states/powerpath.py | 8 +- salt/states/probes.py | 10 - salt/states/process.py | 2 +- salt/states/proxy.py | 6 +- salt/states/pyenv.py | 8 +- salt/states/pyrax_queues.py | 12 +- salt/states/quota.py | 10 +- salt/states/rabbitmq_cluster.py | 6 +- salt/states/rabbitmq_plugin.py | 21 +- salt/states/rabbitmq_policy.py | 12 +- salt/states/rabbitmq_upstream.py | 21 +- salt/states/rabbitmq_user.py | 37 ++- salt/states/rabbitmq_vhost.py | 9 +- salt/states/rbac_solaris.py | 4 +- salt/states/rbenv.py | 12 +- salt/states/redismod.py | 12 +- salt/states/restconf.py | 1 - salt/states/rsync.py | 2 +- salt/states/rvm.py | 6 +- salt/states/salt_proxy.py | 2 +- salt/states/saltmod.py | 8 +- salt/states/serverdensity_device.py | 13 +- salt/states/service.py | 151 +++++----- salt/states/slack.py | 5 +- salt/states/smartos.py | 20 +- salt/states/smtp.py | 4 +- salt/states/snapper.py | 5 +- salt/states/solrcloud.py | 15 +- salt/states/splunk.py | 22 +- salt/states/splunk_search.py | 14 +- salt/states/sqlite3.py | 1 - salt/states/ssh_auth.py | 15 +- salt/states/ssh_known_hosts.py | 14 +- salt/states/status.py | 8 +- salt/states/statuspage.py | 18 +- salt/states/supervisord.py | 56 ++-- salt/states/svn.py | 14 +- salt/states/sysctl.py | 8 +- salt/states/sysfs.py | 12 +- salt/states/sysrc.py | 15 +- salt/states/telemetry_alert.py | 18 +- salt/states/test.py | 6 +- salt/states/testinframod.py | 2 +- salt/states/timezone.py | 22 +- salt/states/tls.py | 5 +- salt/states/tomcat.py | 8 +- salt/states/trafficserver.py | 6 +- salt/states/uptime.py | 4 +- salt/states/user.py | 38 +-- salt/states/vagrant.py | 10 +- salt/states/vbox_guest.py | 6 +- salt/states/victorops.py | 2 +- salt/states/virt.py | 77 +++--- salt/states/virtualenv_mod.py | 23 +- salt/states/webutil.py | 7 +- salt/states/win_appx.py | 1 + salt/states/win_certutil.py | 28 +- salt/states/win_dns_client.py | 22 +- salt/states/win_firewall.py | 12 +- salt/states/win_iis.py | 73 +++-- salt/states/win_lgpo.py | 5 +- salt/states/win_lgpo_reg.py | 5 +- salt/states/win_network.py | 46 +-- salt/states/win_path.py | 20 +- salt/states/win_pki.py | 21 +- salt/states/win_powercfg.py | 13 +- salt/states/win_shortcut.py | 13 +- salt/states/win_smtp_server.py | 15 +- salt/states/win_snmp.py | 6 +- salt/states/win_system.py | 60 ++-- salt/states/win_task.py | 6 +- salt/states/win_wusa.py | 17 +- salt/states/winrepo.py | 4 +- salt/states/wordpress.py | 28 +- salt/states/x509_v2.py | 31 ++- salt/states/xml.py | 8 +- salt/states/xmpp.py | 8 +- salt/states/zabbix_action.py | 8 +- salt/states/zabbix_hostgroup.py | 1 + salt/states/zabbix_template.py | 8 +- salt/states/zabbix_user.py | 6 +- salt/states/zabbix_valuemap.py | 8 +- salt/states/zenoss.py | 23 +- salt/states/zk_concurrency.py | 7 +- salt/states/zone.py | 144 +++++----- salt/states/zookeeper.py | 37 ++- salt/syspaths.py | 1 - salt/template.py | 5 +- salt/thorium/__init__.py | 7 +- salt/thorium/calc.py | 3 +- salt/thorium/check.py | 26 +- salt/thorium/file.py | 1 - salt/thorium/reg.py | 1 - salt/thorium/timer.py | 1 - salt/tokens/localfs.py | 3 +- salt/tops/cobbler.py | 3 +- salt/tops/ext_nodes.py | 1 + salt/tops/reclass_adapter.py | 8 +- salt/tops/saltclass.py | 1 - salt/tops/varstack_top.py | 1 - salt/transport/__init__.py | 1 + salt/transport/client.py | 1 + salt/transport/frame.py | 1 - salt/transport/ipc.py | 1 - salt/transport/server.py | 1 + salt/transport/tcp.py | 1 + salt/transport/zeromq.py | 2 +- salt/utils/aggregation.py | 2 - salt/utils/ansible.py | 6 +- salt/utils/args.py | 15 +- salt/utils/asynchronous.py | 1 - salt/utils/atomicfile.py | 3 +- salt/utils/aws.py | 1 + salt/utils/boto3mod.py | 11 +- salt/utils/botomod.py | 9 +- salt/utils/cloud.py | 7 +- salt/utils/color.py | 3 +- salt/utils/configcomparer.py | 10 +- salt/utils/configparser.py | 6 +- salt/utils/crypt.py | 1 + salt/utils/data.py | 3 +- salt/utils/dateutils.py | 7 +- salt/utils/debug.py | 8 +- salt/utils/decorators/__init__.py | 23 +- .../utils/decorators/extension_deprecation.py | 1 + salt/utils/decorators/path.py | 4 +- salt/utils/decorators/state.py | 5 +- salt/utils/dns.py | 54 ++-- salt/utils/doc.py | 1 + salt/utils/dockermod/__init__.py | 1 - salt/utils/dockermod/translate/container.py | 26 +- salt/utils/dockermod/translate/helpers.py | 22 +- salt/utils/extend.py | 13 +- salt/utils/files.py | 31 +-- salt/utils/find.py | 29 +- salt/utils/fsutils.py | 3 +- salt/utils/functools.py | 1 + salt/utils/gitfs.py | 12 +- salt/utils/github.py | 3 +- salt/utils/gzip_util.py | 1 - salt/utils/hashutils.py | 4 +- salt/utils/http.py | 16 +- salt/utils/idem.py | 1 + salt/utils/immutabletypes.py | 6 +- salt/utils/itertools.py | 1 - salt/utils/jid.py | 4 +- salt/utils/job.py | 1 - salt/utils/json.py | 1 - salt/utils/kickstart.py | 2 +- salt/utils/lazy.py | 3 +- salt/utils/locales.py | 1 + salt/utils/mac_utils.py | 6 +- salt/utils/master.py | 15 +- salt/utils/mattermost.py | 2 +- salt/utils/memcached.py | 3 +- salt/utils/mine.py | 1 - salt/utils/minion.py | 3 +- salt/utils/minions.py | 1 - salt/utils/mount.py | 1 - salt/utils/msgpack.py | 1 + salt/utils/namecheap.py | 1 - salt/utils/napalm.py | 3 +- salt/utils/nb_popen.py | 8 +- salt/utils/network.py | 4 +- salt/utils/nxos.py | 16 +- salt/utils/openstack/neutron.py | 2 - salt/utils/openstack/nova.py | 37 ++- salt/utils/oset.py | 12 +- salt/utils/pagerduty.py | 2 +- salt/utils/parsers.py | 1 + salt/utils/path.py | 1 - salt/utils/pbm.py | 21 +- salt/utils/pkg/rpm.py | 5 +- salt/utils/pkg/win.py | 19 +- salt/utils/platform.py | 1 + salt/utils/powershell.py | 6 +- salt/utils/process.py | 13 +- salt/utils/profile.py | 9 +- salt/utils/proxy.py | 1 - salt/utils/psutil_compat.py | 1 - salt/utils/pushover.py | 4 +- salt/utils/pycrypto.py | 5 +- salt/utils/pydsl.py | 12 +- salt/utils/pyobjects.py | 6 +- salt/utils/reactor.py | 1 + salt/utils/roster_matcher.py | 2 +- salt/utils/s3.py | 22 +- salt/utils/saltclass.py | 8 +- salt/utils/schedule.py | 39 ++- salt/utils/schema.py | 18 +- salt/utils/slack.py | 2 +- salt/utils/smb.py | 9 +- salt/utils/smtp.py | 8 +- salt/utils/ssdp.py | 8 +- salt/utils/ssh.py | 2 +- salt/utils/state.py | 1 - salt/utils/stringio.py | 1 - salt/utils/stringutils.py | 15 +- salt/utils/templates.py | 1 + salt/utils/textformat.py | 3 +- salt/utils/thin.py | 18 +- salt/utils/timed_subprocess.py | 2 +- salt/utils/url.py | 11 +- salt/utils/user.py | 1 - salt/utils/validate/net.py | 2 +- salt/utils/vault/cache.py | 8 +- salt/utils/vault/helpers.py | 2 +- salt/utils/versions.py | 1 + salt/utils/virt.py | 2 +- salt/utils/virtualbox.py | 4 +- salt/utils/vmware.py | 148 +++++----- salt/utils/vsan.py | 23 +- salt/utils/vt.py | 16 +- salt/utils/vt_helper.py | 2 +- salt/utils/win_chcp.py | 8 +- salt/utils/win_dotnet.py | 4 +- salt/utils/win_functions.py | 6 +- salt/utils/win_lgpo_auditpol.py | 18 +- salt/utils/win_lgpo_netsh.py | 56 ++-- salt/utils/win_lgpo_reg.py | 1 + salt/utils/win_network.py | 1 + salt/utils/win_osinfo.py | 1 + salt/utils/win_pdh.py | 2 +- salt/utils/win_service.py | 8 +- salt/utils/win_system.py | 1 + salt/utils/win_update.py | 15 +- salt/utils/x509.py | 86 +++--- salt/utils/xmlutil.py | 8 +- salt/utils/yaml.py | 1 + salt/utils/yamldumper.py | 1 + salt/utils/yamlencoding.py | 1 - salt/utils/yamlloader.py | 7 +- salt/utils/yamlloader_old.py | 7 +- salt/utils/zfs.py | 1 - salt/version.py | 2 +- salt/wheel/config.py | 2 +- salt/wheel/file_roots.py | 1 - salt/wheel/key.py | 1 - salt/wheel/minions.py | 1 - salt/wheel/pillar_roots.py | 4 +- scripts/suse/yum/plugins/yumnotify.py | 4 +- tests/buildpackage.py | 28 +- tests/committer_parser.py | 10 +- tests/conftest.py | 4 +- tests/eventlisten.py | 3 +- .../cloud/clouds/test_digitalocean.py | 1 + .../cloud/clouds/test_dimensiondata.py | 9 +- tests/integration/cloud/clouds/test_ec2.py | 7 +- tests/integration/cloud/clouds/test_gce.py | 7 +- tests/integration/cloud/clouds/test_gogrid.py | 2 +- .../cloud/clouds/test_oneandone.py | 5 +- .../cloud/clouds/test_openstack.py | 2 +- .../cloud/clouds/test_profitbricks.py | 17 +- .../cloud/clouds/test_tencentcloud.py | 12 +- .../cloud/clouds/test_virtualbox.py | 10 +- tests/integration/cloud/clouds/test_vmware.py | 10 +- .../integration/cloud/clouds/test_vultrpy.py | 8 +- .../cloud/helpers/cloud_test_base.py | 5 +- tests/integration/cloud/helpers/virtualbox.py | 10 +- tests/integration/cloud/test_cloud.py | 3 +- tests/integration/conftest.py | 1 + .../pillar/ext_pillar_opts.py | 1 - .../file/base/_modules/runtests_decorators.py | 4 +- .../file/base/_modules/runtests_helpers.py | 1 - .../file/base/buildout/var/tb/2/bootstrap.py | 1 + .../files/returners/noop_returner.py | 1 - tests/integration/grains/test_core.py | 1 + tests/integration/grains/test_custom.py | 1 - tests/integration/loader/test_ext_grains.py | 1 - tests/integration/minion/test_timeout.py | 7 +- tests/integration/modules/test_boto_iam.py | 1 + tests/integration/modules/test_boto_sns.py | 3 +- tests/integration/modules/test_cmdmod.py | 12 +- tests/integration/modules/test_git.py | 32 +-- tests/integration/modules/test_groupadd.py | 2 +- .../integration/modules/test_linux_shadow.py | 2 +- tests/integration/modules/test_lxc.py | 4 +- tests/integration/modules/test_macdefaults.py | 1 + tests/integration/modules/test_mine.py | 16 +- tests/integration/modules/test_mysql.py | 14 +- tests/integration/modules/test_test.py | 5 +- tests/integration/modules/test_timezone.py | 1 + tests/integration/pillar/test_git_pillar.py | 6 +- .../runners/test_runner_returns.py | 2 +- tests/integration/shell/test_master_tops.py | 1 - tests/integration/shell/test_spm.py | 10 +- tests/integration/spm/test_install.py | 1 + tests/integration/states/test_boto_sns.py | 17 +- tests/integration/states/test_compiler.py | 1 - tests/integration/states/test_git.py | 34 ++- .../integration/states/test_handle_iorder.py | 1 - tests/integration/states/test_host.py | 2 +- tests/integration/states/test_lxd_image.py | 1 + tests/integration/states/test_lxd_profile.py | 1 + tests/integration/states/test_reg.py | 28 +- .../states/test_ssh_known_hosts.py | 10 +- tests/integration/states/test_x509.py | 20 +- tests/integration/utils/test_idem.py | 1 + tests/integration/utils/test_smb.py | 1 + tests/integration/utils/test_win_runas.py | 26 +- tests/minionswarm.py | 10 +- tests/modparser.py | 2 +- tests/packdump.py | 1 + tests/pytests/conftest.py | 2 + tests/pytests/functional/cache/helpers.py | 2 +- tests/pytests/functional/cli/test_batch.py | 1 + .../pytests/functional/cli/test_salt_cloud.py | 1 + .../functional/formulas/test_docker.py | 1 + .../pytests/functional/formulas/test_nginx.py | 1 + .../functional/formulas/test_sudoers.py | 1 + tests/pytests/functional/formulas/test_vim.py | 1 + .../loader/test_loaded_base_name.py | 2 +- .../log_handlers/test_logstash_mod.py | 4 +- .../functional/modules/cmd/test_powershell.py | 4 +- .../functional/modules/cmd/test_runas.py | 4 +- .../functional/modules/file/test_replace.py | 5 +- .../functional/modules/file/test_rmdir.py | 14 +- .../functional/modules/file/test_symlink.py | 2 +- .../modules/state/test_jinja_filters.py | 1 + .../functional/modules/test_archive.py | 9 +- .../functional/modules/test_dockermod.py | 1 + .../functional/modules/test_etcd_mod.py | 27 +- .../functional/modules/test_mac_pkgutil.py | 1 + .../pytests/functional/modules/test_mysql.py | 1 + .../functional/modules/test_network.py | 5 +- tests/pytests/functional/modules/test_opkg.py | 2 +- .../pytests/functional/modules/test_system.py | 4 +- .../functional/modules/test_win_dsc.py | 4 +- .../functional/modules/test_win_shortcut.py | 9 +- .../modules/win_file/test_check_perms.py | 1 + .../modules/win_file/test_remove.py | 1 + .../functional/modules/win_file/test_stat.py | 1 + .../win_lgpo/test_audit_settings_module.py | 2 +- .../netapi/rest_cherrypy/test_auth.py | 2 +- .../test_external_auth_syntax.py | 20 +- .../netapi/rest_tornado/test_auth_handler.py | 6 +- .../rest_tornado/test_auth_handler_pam.py | 6 +- .../rest_tornado/test_base_api_handler.py | 4 +- .../rest_tornado/test_external_auth_syntax.py | 20 +- tests/pytests/functional/pillar/test_gpg.py | 6 +- tests/pytests/functional/sdb/test_etcd_db.py | 9 +- .../functional/states/cmd/test_runas.py | 4 +- .../functional/states/file/test_append.py | 2 +- .../states/file/test_blockreplace.py | 4 +- .../functional/states/file/test_cached.py | 8 +- .../functional/states/file/test_comment.py | 1 + .../functional/states/file/test_managed.py | 1 - .../functional/states/file/test_patch.py | 4 +- .../functional/states/file/test_pruned.py | 16 +- .../functional/states/file/test_recurse.py | 8 +- .../functional/states/file/test_rename.py | 1 + .../functional/states/file/test_replace.py | 18 +- .../functional/states/file/test_symlink.py | 2 +- .../functional/states/rabbitmq/conftest.py | 6 +- .../states/test_chocolatey_1_2_1.py | 1 + .../states/test_chocolatey_latest.py | 1 + .../functional/states/test_docker_network.py | 17 +- .../functional/states/test_etcd_mod.py | 40 ++- tests/pytests/functional/states/test_mysql.py | 1 + tests/pytests/functional/states/test_svn.py | 3 +- .../functional/states/test_win_certutil.py | 1 + .../pytests/functional/states/test_x509_v2.py | 6 +- .../functional/states/test_zookeeper.py | 4 +- .../win_lgpo/test_audit_settings_state.py | 2 +- .../functional/transport/ipc/test_client.py | 2 +- .../transport/server/test_request_server.py | 6 +- .../transport/tcp/test_pub_server.py | 1 - .../functools/test_namespaced_function.py | 2 +- .../functional/utils/test_etcd_util.py | 261 ++++++++---------- tests/pytests/functional/utils/test_jinja.py | 4 +- .../pytests/functional/utils/test_process.py | 1 + .../utils/win_dacl/test_get_name.py | 1 + .../functional/utils/win_dacl/test_get_sid.py | 1 + .../utils/win_dacl/test_get_sid_string.py | 1 + .../test_multiple_processes_logging.py | 2 +- tests/pytests/integration/cli/test_batch.py | 6 +- tests/pytests/integration/cli/test_salt.py | 1 + tests/pytests/integration/cli/test_salt_cp.py | 1 - .../integration/cli/test_salt_deltaproxy.py | 23 +- .../integration/cluster/test_basic_cluster.py | 1 + .../pytests/integration/grains/test_grains.py | 1 + .../integration/master/test_payload.py | 1 + .../integration/minion/test_return_retries.py | 4 +- .../integration/modules/grains/test_module.py | 1 - .../modules/saltutil/test_modules.py | 1 - .../modules/saltutil/test_pillar.py | 1 - .../modules/saltutil/test_wheel.py | 1 - .../modules/state/test_state_test.py | 4 +- .../integration/modules/test_beacons.py | 1 + .../pytests/integration/modules/test_event.py | 1 + .../pytests/integration/modules/test_file.py | 3 +- .../pytests/integration/modules/test_idem.py | 1 + .../modules/test_rpmbuild_pkgbuild.py | 8 +- .../pytests/integration/modules/test_state.py | 8 +- .../integration/modules/test_useradd.py | 1 + .../pytests/integration/modules/test_virt.py | 1 + .../netapi/rest_cherrypy/test_arg_kwarg.py | 4 +- .../netapi/rest_cherrypy/test_auth.py | 2 +- .../rest_tornado/test_jobs_api_handler.py | 2 +- .../pillar/cache/test_pillar_cache.py | 1 + .../integration/pillar/test_pillar_include.py | 13 +- tests/pytests/integration/proxy/conftest.py | 16 +- .../integration/proxy/test_deltaproxy.py | 1 + tests/pytests/integration/proxy/test_shell.py | 1 + .../pytests/integration/proxy/test_simple.py | 1 + .../runners/state/orchestrate/test_events.py | 1 + .../pytests/integration/runners/test_match.py | 1 + tests/pytests/integration/sdb/test_vault.py | 1 + .../ssh/state/test_with_import_dir.py | 1 + .../integration/ssh/test_jinja_mods.py | 2 +- tests/pytests/integration/ssh/test_log.py | 1 + .../integration/ssh/test_py_versions.py | 1 + .../pytests/integration/ssh/test_ssh_setup.py | 1 + .../pytests/integration/states/test_beacon.py | 1 + tests/pytests/integration/states/test_file.py | 9 +- tests/pytests/integration/states/test_idem.py | 3 +- .../integration/states/test_include.py | 1 + .../integration/utils/test_templates.py | 5 +- .../integration/wheel/test_pillar_roots.py | 4 +- tests/pytests/pkg/conftest.py | 12 +- .../pytests/pkg/download/test_pkg_download.py | 1 + tests/pytests/scenarios/blackout/conftest.py | 2 +- .../blackout/test_minion_blackout.py | 1 - .../pytests/scenarios/cluster/test_cluster.py | 13 +- tests/pytests/scenarios/compat/conftest.py | 3 +- .../scenarios/compat/test_with_versions.py | 1 + .../failover/multimaster/conftest.py | 10 +- .../multimaster/test_failover_master.py | 18 +- .../pytests/scenarios/multimaster/conftest.py | 10 +- .../scenarios/multimaster/test_multimaster.py | 4 +- .../pytests/scenarios/performance/conftest.py | 1 + tests/pytests/scenarios/setup/test_install.py | 1 + tests/pytests/scenarios/setup/test_man.py | 2 +- tests/pytests/unit/auth/test_ldap.py | 1 + tests/pytests/unit/beacons/test_adb.py | 1 + .../unit/beacons/test_avahi_announce.py | 1 + .../unit/beacons/test_bonjour_announce.py | 1 + tests/pytests/unit/beacons/test_btmp.py | 2 +- tests/pytests/unit/beacons/test_diskusage.py | 1 + tests/pytests/unit/beacons/test_glxinfo.py | 1 + tests/pytests/unit/beacons/test_haproxy.py | 1 + tests/pytests/unit/beacons/test_load.py | 1 + tests/pytests/unit/beacons/test_log_beacon.py | 1 + tests/pytests/unit/beacons/test_memusage.py | 1 + .../pytests/unit/beacons/test_network_info.py | 1 + tests/pytests/unit/beacons/test_ps.py | 1 + tests/pytests/unit/beacons/test_swapusage.py | 1 + tests/pytests/unit/beacons/test_wtmp.py | 2 +- tests/pytests/unit/cache/test_localfs.py | 1 + tests/pytests/unit/cache/test_memcache.py | 1 + tests/pytests/unit/cache/test_mysql_cache.py | 1 - .../unit/client/ssh/wrapper/test_config.py | 1 - .../unit/client/ssh/wrapper/test_cp.py | 1 + .../unit/cloud/clouds/test_digitalocean.py | 1 - .../pytests/unit/cloud/clouds/test_hetzner.py | 12 +- .../pytests/unit/cloud/clouds/test_proxmox.py | 10 +- .../pytests/unit/cloud/clouds/test_saltify.py | 1 + .../pytests/unit/cloud/clouds/test_vultrpy.py | 12 +- tests/pytests/unit/config/schemas/test_ssh.py | 14 +- .../unit/config/test__validate_opts.py | 1 + tests/pytests/unit/crypt/test_crypt.py | 1 + tests/pytests/unit/engines/test_engines.py | 2 +- .../unit/engines/test_libvirt_events.py | 1 + tests/pytests/unit/engines/test_slack.py | 1 + .../unit/engines/test_slack_bolt_engine.py | 23 +- tests/pytests/unit/engines/test_sqs_events.py | 1 + .../unit/fileclient/test_fileclient.py | 1 + .../fileserver/gitfs/test_gitfs_config.py | 2 +- tests/pytests/unit/grains/test_core.py | 18 +- tests/pytests/unit/grains/test_esxi.py | 1 - tests/pytests/unit/loader/test_context.py | 1 + tests/pytests/unit/loader/test_lazy.py | 1 + tests/pytests/unit/loader/test_loader.py | 1 + .../unit/log_handlers/test_sentry_mod.py | 1 + .../unit/modules/dockermod/test_module.py | 30 +- .../unit/modules/file/test_file_chattr.py | 2 +- .../unit/modules/file/test_file_check.py | 4 +- .../unit/modules/file/test_file_grep.py | 4 +- .../unit/modules/file/test_file_line.py | 10 +- .../unit/modules/file/test_file_module.py | 7 +- tests/pytests/unit/modules/napalm/test_bgp.py | 1 - tests/pytests/unit/modules/napalm/test_mod.py | 1 + .../unit/modules/napalm/test_network.py | 1 - .../pytests/unit/modules/napalm/test_route.py | 2 +- .../pytests/unit/modules/napalm/test_snmp.py | 1 - .../pytests/unit/modules/napalm/test_users.py | 1 - tests/pytests/unit/modules/test_acme.py | 1 - tests/pytests/unit/modules/test_aixpkg.py | 36 ++- tests/pytests/unit/modules/test_at.py | 1 - tests/pytests/unit/modules/test_augeas_cfg.py | 1 + tests/pytests/unit/modules/test_bigip.py | 1 + .../unit/modules/test_bluez_bluetooth.py | 1 - .../unit/modules/test_boto_dynamodb.py | 1 - tests/pytests/unit/modules/test_bower.py | 1 - tests/pytests/unit/modules/test_bridge.py | 1 - .../unit/modules/test_cassandra_cql.py | 3 +- tests/pytests/unit/modules/test_chocolatey.py | 1 + tests/pytests/unit/modules/test_chroot.py | 6 +- tests/pytests/unit/modules/test_composer.py | 1 - tests/pytests/unit/modules/test_config.py | 1 - tests/pytests/unit/modules/test_consul.py | 17 +- tests/pytests/unit/modules/test_cp.py | 1 - .../pytests/unit/modules/test_daemontools.py | 1 - tests/pytests/unit/modules/test_data.py | 1 + tests/pytests/unit/modules/test_deb_apache.py | 1 - tests/pytests/unit/modules/test_devinfo.py | 11 +- tests/pytests/unit/modules/test_devmap.py | 1 - tests/pytests/unit/modules/test_dig.py | 1 - tests/pytests/unit/modules/test_disk.py | 5 +- tests/pytests/unit/modules/test_djangomod.py | 1 + .../pytests/unit/modules/test_dpkg_lowpkg.py | 1 - tests/pytests/unit/modules/test_drac.py | 1 - tests/pytests/unit/modules/test_drbd.py | 1 - tests/pytests/unit/modules/test_etcd_mod.py | 1 - tests/pytests/unit/modules/test_extfs.py | 1 - tests/pytests/unit/modules/test_genesis.py | 1 + .../unit/modules/test_gentoo_service.py | 1 - tests/pytests/unit/modules/test_git.py | 9 +- tests/pytests/unit/modules/test_glassfish.py | 1 + tests/pytests/unit/modules/test_glusterfs.py | 1 - .../pytests/unit/modules/test_grub_legacy.py | 1 - tests/pytests/unit/modules/test_hadoop.py | 1 - .../pytests/unit/modules/test_haproxyconn.py | 1 - tests/pytests/unit/modules/test_hashutil.py | 1 - tests/pytests/unit/modules/test_helm.py | 1 - tests/pytests/unit/modules/test_hg.py | 17 +- tests/pytests/unit/modules/test_http.py | 1 - tests/pytests/unit/modules/test_ilo.py | 1 - tests/pytests/unit/modules/test_incron.py | 1 - tests/pytests/unit/modules/test_ini_manage.py | 11 +- tests/pytests/unit/modules/test_introspect.py | 9 +- tests/pytests/unit/modules/test_ipset.py | 1 + tests/pytests/unit/modules/test_iptables.py | 4 +- tests/pytests/unit/modules/test_junos.py | 1 + tests/pytests/unit/modules/test_key.py | 1 - tests/pytests/unit/modules/test_keyboard.py | 1 - tests/pytests/unit/modules/test_kmod.py | 4 +- tests/pytests/unit/modules/test_kubeadm.py | 1 - .../unit/modules/test_launchctl_service.py | 1 - tests/pytests/unit/modules/test_ldapmod.py | 1 - tests/pytests/unit/modules/test_linux_lvm.py | 3 +- .../pytests/unit/modules/test_linux_shadow.py | 1 + tests/pytests/unit/modules/test_locate.py | 1 - tests/pytests/unit/modules/test_logadm.py | 1 - tests/pytests/unit/modules/test_logrotate.py | 1 - tests/pytests/unit/modules/test_lvs.py | 1 - .../unit/modules/test_mac_assistive.py | 2 +- .../pytests/unit/modules/test_mac_brew_pkg.py | 1 + .../pytests/unit/modules/test_mac_service.py | 1 - tests/pytests/unit/modules/test_mac_shadow.py | 1 + tests/pytests/unit/modules/test_mandrill.py | 1 - tests/pytests/unit/modules/test_match.py | 3 +- tests/pytests/unit/modules/test_mdadm_raid.py | 1 + tests/pytests/unit/modules/test_mine.py | 3 +- tests/pytests/unit/modules/test_mongodb.py | 56 +++- tests/pytests/unit/modules/test_monit.py | 1 - tests/pytests/unit/modules/test_mysql.py | 3 +- tests/pytests/unit/modules/test_nacl.py | 1 + tests/pytests/unit/modules/test_nfs3.py | 1 - tests/pytests/unit/modules/test_nftables.py | 1 + tests/pytests/unit/modules/test_npm.py | 1 - tests/pytests/unit/modules/test_openbsdpkg.py | 1 - .../unit/modules/test_openbsdrcctl_service.py | 24 +- tests/pytests/unit/modules/test_oracle.py | 1 - tests/pytests/unit/modules/test_osquery.py | 1 - tests/pytests/unit/modules/test_pacmanpkg.py | 5 +- tests/pytests/unit/modules/test_pagerduty.py | 1 - tests/pytests/unit/modules/test_pam.py | 1 + tests/pytests/unit/modules/test_parallels.py | 5 +- tests/pytests/unit/modules/test_pecl.py | 1 - tests/pytests/unit/modules/test_pkgutil.py | 1 - .../unit/modules/test_portage_config.py | 3 +- tests/pytests/unit/modules/test_postfix.py | 1 - tests/pytests/unit/modules/test_poudriere.py | 6 +- tests/pytests/unit/modules/test_ps.py | 8 +- tests/pytests/unit/modules/test_publish.py | 1 - tests/pytests/unit/modules/test_pw_user.py | 1 - tests/pytests/unit/modules/test_qemu_img.py | 1 - tests/pytests/unit/modules/test_rabbitmq.py | 1 - tests/pytests/unit/modules/test_rbenv.py | 1 - tests/pytests/unit/modules/test_rdp.py | 1 - tests/pytests/unit/modules/test_reg.py | 6 +- .../pytests/unit/modules/test_restartcheck.py | 24 +- tests/pytests/unit/modules/test_ret.py | 1 - tests/pytests/unit/modules/test_rh_service.py | 1 - tests/pytests/unit/modules/test_rvm.py | 1 - tests/pytests/unit/modules/test_s6.py | 1 - .../pytests/unit/modules/test_saltcloudmod.py | 1 - tests/pytests/unit/modules/test_schedule.py | 118 ++++++-- tests/pytests/unit/modules/test_sdb.py | 1 + .../unit/modules/test_serverdensity_device.py | 1 - tests/pytests/unit/modules/test_servicenow.py | 1 - .../unit/modules/test_slackware_service.py | 1 + .../unit/modules/test_smartos_imgadm.py | 1 - tests/pytests/unit/modules/test_smtp.py | 1 - tests/pytests/unit/modules/test_status.py | 3 +- tests/pytests/unit/modules/test_suse_ip.py | 12 +- tests/pytests/unit/modules/test_swift.py | 1 - tests/pytests/unit/modules/test_syslog_ng.py | 1 - tests/pytests/unit/modules/test_system.py | 1 + tests/pytests/unit/modules/test_telegram.py | 1 - tests/pytests/unit/modules/test_tls.py | 16 +- tests/pytests/unit/modules/test_tomcat.py | 1 - .../unit/modules/test_transactional_update.py | 8 +- tests/pytests/unit/modules/test_tuned.py | 1 - tests/pytests/unit/modules/test_udev.py | 1 - tests/pytests/unit/modules/test_uptime.py | 1 - tests/pytests/unit/modules/test_uwsgi.py | 1 - tests/pytests/unit/modules/test_vagrant.py | 1 - tests/pytests/unit/modules/test_vmctl.py | 1 - tests/pytests/unit/modules/test_webutil.py | 1 - .../pytests/unit/modules/test_win_autoruns.py | 1 - .../unit/modules/test_win_dns_client.py | 1 - tests/pytests/unit/modules/test_win_iis.py | 3 +- .../pytests/unit/modules/test_win_licence.py | 1 - tests/pytests/unit/modules/test_win_path.py | 1 - tests/pytests/unit/modules/test_win_pkg.py | 1 + tests/pytests/unit/modules/test_win_pki.py | 1 - .../pytests/unit/modules/test_win_powercfg.py | 1 - tests/pytests/unit/modules/test_win_psget.py | 1 - tests/pytests/unit/modules/test_win_shadow.py | 1 - tests/pytests/unit/modules/test_win_snmp.py | 1 - tests/pytests/unit/modules/test_win_system.py | 1 + tests/pytests/unit/modules/test_win_task.py | 1 + .../pytests/unit/modules/test_win_timezone.py | 1 + tests/pytests/unit/modules/test_win_wua.py | 1 + tests/pytests/unit/modules/test_xapi_virt.py | 1 - tests/pytests/unit/modules/test_xfs.py | 1 - tests/pytests/unit/modules/test_xml.py | 1 - tests/pytests/unit/modules/test_yumpkg.py | 6 +- tests/pytests/unit/modules/test_zenoss.py | 1 - tests/pytests/unit/modules/test_zfs.py | 6 +- tests/pytests/unit/modules/test_znc.py | 1 - tests/pytests/unit/modules/test_zpool.py | 6 +- tests/pytests/unit/modules/test_zypperpkg.py | 1 - tests/pytests/unit/modules/virt/conftest.py | 8 +- .../pytests/unit/modules/virt/test_domain.py | 23 +- .../modules/win_lgpo/test_admx_policies.py | 1 + .../modules/win_lgpo/test_defined_policies.py | 1 + .../unit/modules/win_lgpo/test_mechanisms.py | 1 + .../win_lgpo/test_point_print_enabled.py | 1 + .../modules/win_lgpo/test_point_print_nc.py | 1 + .../unit/modules/win_lgpo/test_policy_info.py | 1 + .../win_lgpo/test_policy_info_functions.py | 1 + .../modules/win_lgpo/test_policy_resources.py | 1 + .../unit/modules/win_lgpo/test_reg_pol.py | 1 + .../modules/win_lgpo/test_secedit_policy.py | 2 +- tests/pytests/unit/output/test_json_out.py | 1 + tests/pytests/unit/output/test_nested.py | 1 + tests/pytests/unit/output/test_yaml_out.py | 1 + tests/pytests/unit/pillar/test_csvpillar.py | 1 - .../unit/pillar/test_http_json_pillar.py | 8 +- .../unit/pillar/test_http_yaml_pillar.py | 4 +- tests/pytests/unit/pillar/test_mysql.py | 12 +- tests/pytests/unit/pillar/test_s3.py | 6 +- tests/pytests/unit/pillar/test_saltclass.py | 2 +- .../unit/proxy/nxos/test_nxos_nxapi.py | 18 -- .../pytests/unit/proxy/nxos/test_nxos_ssh.py | 14 - .../pytests/unit/proxy/test_esxdatacenter.py | 1 + tests/pytests/unit/proxy/test_napalm.py | 1 + tests/pytests/unit/renderers/test_aws_kms.py | 1 + .../returners/test_elasticsearch_return.py | 1 + tests/pytests/unit/returners/test_pgjsonb.py | 1 - .../returners/test_slack_webhook_return.py | 13 +- .../unit/returners/test_smtp_return.py | 1 + .../unit/returners/test_syslog_return.py | 3 +- .../unit/returners/test_telegram_return.py | 1 + tests/pytests/unit/roster/test_dir.py | 5 +- tests/pytests/unit/roster/test_terraform.py | 1 + tests/pytests/unit/runners/test_bgp.py | 1 + tests/pytests/unit/runners/test_fileserver.py | 3 +- tests/pytests/unit/runners/test_git_pillar.py | 1 - tests/pytests/unit/runners/test_jobs.py | 1 + tests/pytests/unit/runners/test_network.py | 1 + tests/pytests/unit/runners/test_reactor.py | 1 - tests/pytests/unit/runners/test_saltutil.py | 4 +- tests/pytests/unit/runners/test_spacewalk.py | 1 + tests/pytests/unit/runners/test_winrepo.py | 1 - .../vault/test_token_auth_deprecated.py | 1 - tests/pytests/unit/sdb/test_yaml.py | 1 - .../unit/serializers/test_serializers.py | 2 +- tests/pytests/unit/state/test_state_basic.py | 1 + tests/pytests/unit/states/apache/test_conf.py | 12 +- .../pytests/unit/states/apache/test_module.py | 12 +- tests/pytests/unit/states/apache/test_site.py | 12 +- .../unit/states/file/test__clean_dir.py | 1 + tests/pytests/unit/states/file/test_absent.py | 16 +- .../pytests/unit/states/file/test_comment.py | 12 +- tests/pytests/unit/states/file/test_copy.py | 10 +- .../unit/states/file/test_directory.py | 14 +- .../unit/states/file/test_filestate.py | 36 +-- .../pytests/unit/states/file/test_hardlink.py | 34 +-- .../pytests/unit/states/file/test_managed.py | 14 +- .../pytests/unit/states/file/test_prepend.py | 6 +- .../states/file/test_private_functions.py | 6 +- tests/pytests/unit/states/file/test_pruned.py | 6 +- .../states/file/test_retention_schedule.py | 14 +- .../pytests/unit/states/file/test_selinux.py | 2 +- .../pytests/unit/states/file/test_symlink.py | 28 +- tests/pytests/unit/states/file/test_tidied.py | 30 +- .../unit/states/mysql/test_database.py | 15 +- tests/pytests/unit/states/mysql/test_query.py | 2 +- .../unit/states/postgresql/test_cluster.py | 20 +- .../unit/states/postgresql/test_database.py | 8 +- .../unit/states/postgresql/test_initdb.py | 8 +- .../unit/states/postgresql/test_language.py | 16 +- .../unit/states/rabbitmq/test_vhost.py | 2 +- tests/pytests/unit/states/test_alias.py | 16 +- .../pytests/unit/states/test_alternatives.py | 26 +- tests/pytests/unit/states/test_aptpkg.py | 3 +- tests/pytests/unit/states/test_archive.py | 5 +- tests/pytests/unit/states/test_at.py | 4 +- tests/pytests/unit/states/test_aws_sqs.py | 9 +- tests/pytests/unit/states/test_blockdev.py | 10 +- .../unit/states/test_boto_cloudfront.py | 7 +- .../unit/states/test_boto_cloudwatch_alarm.py | 2 +- .../pytests/unit/states/test_boto_dynamodb.py | 8 +- tests/pytests/unit/states/test_boto_ec2.py | 10 +- .../unit/states/test_boto_elasticache.py | 12 +- tests/pytests/unit/states/test_boto_elb.py | 6 +- .../pytests/unit/states/test_boto_iam_role.py | 2 +- .../pytests/unit/states/test_boto_kinesis.py | 12 +- tests/pytests/unit/states/test_boto_lc.py | 1 + .../pytests/unit/states/test_boto_route53.py | 11 +- tests/pytests/unit/states/test_boto_sns.py | 13 +- tests/pytests/unit/states/test_boto_sqs.py | 7 +- tests/pytests/unit/states/test_bower.py | 1 + tests/pytests/unit/states/test_chocolatey.py | 1 + tests/pytests/unit/states/test_cloud.py | 46 +-- tests/pytests/unit/states/test_consul.py | 1 - tests/pytests/unit/states/test_ddns.py | 6 +- tests/pytests/unit/states/test_debconfmod.py | 1 + tests/pytests/unit/states/test_drac.py | 9 +- .../pytests/unit/states/test_elasticsearch.py | 1 + tests/pytests/unit/states/test_eselect.py | 3 +- tests/pytests/unit/states/test_etcd_mod.py | 1 - tests/pytests/unit/states/test_ethtool.py | 6 +- tests/pytests/unit/states/test_firewalld.py | 1 + tests/pytests/unit/states/test_gem.py | 1 - tests/pytests/unit/states/test_git.py | 1 - .../pytests/unit/states/test_gnomedesktop.py | 1 - tests/pytests/unit/states/test_grafana.py | 2 +- tests/pytests/unit/states/test_grains.py | 1 + tests/pytests/unit/states/test_group.py | 10 +- tests/pytests/unit/states/test_helm.py | 1 - tests/pytests/unit/states/test_host.py | 57 ++-- tests/pytests/unit/states/test_incron.py | 18 +- .../unit/states/test_influxdb08_database.py | 16 +- .../unit/states/test_influxdb08_user.py | 16 +- tests/pytests/unit/states/test_ini_manage.py | 1 - tests/pytests/unit/states/test_iptables.py | 1 - tests/pytests/unit/states/test_kapacitor.py | 1 - tests/pytests/unit/states/test_kernelpkg.py | 1 - tests/pytests/unit/states/test_keyboard.py | 12 +- tests/pytests/unit/states/test_keystone.py | 52 ++-- tests/pytests/unit/states/test_kmod.py | 13 +- tests/pytests/unit/states/test_layman.py | 9 +- tests/pytests/unit/states/test_ldap.py | 65 +++-- .../pytests/unit/states/test_libcloud_dns.py | 1 - tests/pytests/unit/states/test_linux_acl.py | 12 +- tests/pytests/unit/states/test_lvm.py | 44 +-- tests/pytests/unit/states/test_lxc.py | 18 +- tests/pytests/unit/states/test_makeconf.py | 4 +- .../unit/states/test_mongodb_database.py | 6 +- .../pytests/unit/states/test_mongodb_user.py | 10 +- tests/pytests/unit/states/test_mount.py | 6 +- tests/pytests/unit/states/test_npm.py | 12 +- tests/pytests/unit/states/test_pagerduty.py | 4 +- tests/pytests/unit/states/test_pdbedit.py | 2 +- tests/pytests/unit/states/test_pecl.py | 4 +- tests/pytests/unit/states/test_pip.py | 1 + tests/pytests/unit/states/test_ports.py | 3 +- tests/pytests/unit/states/test_powerpath.py | 4 +- .../pytests/unit/states/test_pyrax_queues.py | 2 +- tests/pytests/unit/states/test_rbenv.py | 18 +- tests/pytests/unit/states/test_slack.py | 4 +- tests/pytests/unit/states/test_smartos.py | 7 +- .../pytests/unit/states/test_splunk_search.py | 8 +- tests/pytests/unit/states/test_ssh_auth.py | 2 +- .../unit/states/test_ssh_known_hosts.py | 2 +- tests/pytests/unit/states/test_supervisord.py | 2 +- tests/pytests/unit/states/test_sysctl.py | 14 +- tests/pytests/unit/states/test_sysfs.py | 13 +- .../unit/states/test_virtualenv_mod.py | 1 - tests/pytests/unit/states/test_webutil.py | 1 - tests/pytests/unit/states/test_win_lgpo.py | 1 + tests/pytests/unit/states/test_win_path.py | 28 +- tests/pytests/unit/states/test_win_wua.py | 21 +- tests/pytests/unit/states/test_win_wusa.py | 32 +-- tests/pytests/unit/states/test_xml.py | 8 +- tests/pytests/unit/states/test_xmpp.py | 1 - tests/pytests/unit/states/virt/test_domain.py | 22 +- .../pytests/unit/states/zabbix/test_action.py | 30 +- .../unit/states/zabbix/test_template.py | 22 +- .../unit/states/zabbix/test_valuemap.py | 30 +- tests/pytests/unit/test_acl.py | 1 - tests/pytests/unit/test_config.py | 1 + tests/pytests/unit/test_fileclient.py | 1 + tests/pytests/unit/test_log.py | 9 +- tests/pytests/unit/test_pillar.py | 1 - tests/pytests/unit/test_request_channel.py | 1 + tests/pytests/unit/test_syspaths.py | 1 + tests/pytests/unit/test_version.py | 1 + tests/pytests/unit/tokens/test_localfs.py | 2 +- tests/pytests/unit/transport/test_base.py | 1 + tests/pytests/unit/utils/jinja/conftest.py | 1 + tests/pytests/unit/utils/jinja/test_jinja.py | 1 + .../pytests/unit/utils/scheduler/conftest.py | 1 - .../unit/utils/templates/test_jinja.py | 1 + .../utils/templates/test_wrap_tmpl_func.py | 1 + tests/pytests/unit/utils/test_aws.py | 1 + tests/pytests/unit/utils/test_cache.py | 6 +- tests/pytests/unit/utils/test_cloud.py | 1 - tests/pytests/unit/utils/test_compat.py | 1 + tests/pytests/unit/utils/test_crypt.py | 1 + tests/pytests/unit/utils/test_data.py | 1 + tests/pytests/unit/utils/test_files.py | 3 +- tests/pytests/unit/utils/test_nacl.py | 1 + tests/pytests/unit/utils/test_pycrypto.py | 8 +- tests/pytests/unit/utils/test_rsax931.py | 1 + tests/pytests/unit/utils/test_versions.py | 8 +- tests/pytests/unit/utils/test_win_reg.py | 12 +- tests/pytests/unit/utils/test_x509.py | 8 +- tests/pytests/unit/utils/vault/conftest.py | 11 +- .../pytests/unit/utils/vault/test_factory.py | 10 +- .../unit/utils/verify/test_clean_path_link.py | 1 + .../pytests/unit/utils/verify/test_verify.py | 16 +- .../unit/utils/win_lgpo/test_auditpol.py | 2 +- tests/support/case.py | 22 +- tests/support/cli_scripts.py | 1 - tests/support/helpers.py | 1 + tests/support/kernelpkg.py | 1 + tests/support/mixins.py | 28 +- tests/support/mock.py | 1 + tests/support/napalm.py | 1 - tests/support/netapi.py | 6 +- tests/support/pytest/etcd.py | 2 +- tests/support/pytest/helpers.py | 1 + tests/support/pytest/loader.py | 9 +- tests/support/runtests.py | 16 +- tests/support/sminion.py | 2 +- tests/support/unit.py | 3 +- tests/support/win_installer.py | 6 +- tests/support/xmlunit.py | 1 + tests/support/zfs.py | 1 - tests/unit/ext/test_ipaddress.py | 10 +- tests/unit/modules/nxos/nxos_n36k.py | 1 - tests/unit/modules/nxos/nxos_n3k.py | 1 - tests/unit/modules/nxos/nxos_n5k.py | 1 - tests/unit/modules/nxos/nxos_n7k.py | 1 - tests/unit/modules/nxos/nxos_n93k.py | 1 - tests/unit/modules/nxos/nxos_n93klxc.py | 1 - tests/unit/modules/nxos/nxos_n95k.py | 1 - tests/unit/modules/nxos/nxos_platform.py | 4 - .../unit/modules/test_boto3_elasticsearch.py | 1 + tests/unit/modules/test_boto3_route53.py | 1 + tests/unit/modules/test_boto_route53.py | 2 +- tests/unit/modules/test_boto_secgroup.py | 2 +- tests/unit/modules/test_boto_vpc.py | 14 +- tests/unit/modules/test_bsd_shadow.py | 1 + tests/unit/modules/test_cron.py | 10 +- tests/unit/modules/test_freezer.py | 1 - tests/unit/modules/test_influxdb08mod.py | 1 - tests/unit/modules/test_k8s.py | 56 ++-- .../unit/modules/test_kernelpkg_linux_apt.py | 6 +- .../unit/modules/test_kernelpkg_linux_yum.py | 3 +- tests/unit/modules/test_kubernetesmod.py | 1 + tests/unit/modules/test_libcloud_compute.py | 1 + tests/unit/modules/test_libcloud_dns.py | 1 + .../modules/test_libcloud_loadbalancer.py | 1 + tests/unit/modules/test_libcloud_storage.py | 1 + tests/unit/modules/test_linux_acl.py | 2 +- tests/unit/modules/test_localemod.py | 5 +- tests/unit/modules/test_memcached.py | 1 - tests/unit/modules/test_napalm_probes.py | 3 +- tests/unit/modules/test_napalm_yang_mod.py | 1 - tests/unit/modules/test_netbox.py | 1 + tests/unit/modules/test_netscaler.py | 1 - tests/unit/modules/test_neutron.py | 1 - tests/unit/modules/test_nova.py | 1 - tests/unit/modules/test_nxos.py | 60 ---- tests/unit/modules/test_nxos_upgrade.py | 23 -- tests/unit/modules/test_openstack_config.py | 1 - tests/unit/modules/test_opkg.py | 6 +- tests/unit/modules/test_parted_partition.py | 1 - tests/unit/modules/test_rh_ip.py | 16 +- tests/unit/modules/test_snapper.py | 1 + tests/unit/modules/test_sqlite3.py | 1 - tests/unit/modules/test_ssh.py | 16 +- tests/unit/modules/test_supervisord.py | 1 - tests/unit/modules/test_sysmod.py | 7 +- tests/unit/modules/test_twilio_notify.py | 1 + tests/unit/modules/test_useradd.py | 1 + tests/unit/modules/test_virt.py | 40 +-- tests/unit/modules/test_virtualenv_mod.py | 2 +- tests/unit/modules/test_vsphere.py | 7 +- tests/unit/modules/test_win_system.py | 1 + tests/unit/modules/test_zypperpkg.py | 1 - tests/unit/states/test_boto_vpc.py | 16 +- tests/unit/states/test_group.py | 1 - tests/unit/states/test_ipset.py | 14 +- tests/unit/states/test_module.py | 1 - tests/unit/states/test_syslog_ng.py | 1 - tests/unit/test_config.py | 67 ++--- tests/unit/test_mock.py | 6 +- tests/unit/test_zypp_plugins.py | 3 +- tests/unit/transport/test_ipc.py | 1 + tests/unit/transport/test_tcp.py | 8 +- tests/unit/utils/test_color.py | 1 - tests/unit/utils/test_context.py | 1 - tests/unit/utils/test_decorators.py | 1 - tests/unit/utils/test_dns.py | 8 +- tests/unit/utils/test_doc.py | 1 - tests/unit/utils/test_dockermod.py | 16 +- tests/unit/utils/test_environment.py | 1 + tests/unit/utils/test_extend.py | 1 + tests/unit/utils/test_filebuffer.py | 1 - tests/unit/utils/test_immutabletypes.py | 1 - tests/unit/utils/test_jid.py | 5 +- tests/unit/utils/test_job.py | 1 - tests/unit/utils/test_json.py | 2 +- tests/unit/utils/test_mac_utils.py | 1 + tests/unit/utils/test_msgpack.py | 1 + tests/unit/utils/test_pbm.py | 2 +- tests/unit/utils/test_proxy.py | 1 - tests/unit/utils/test_roster_matcher.py | 1 + tests/unit/utils/test_schema.py | 90 +++--- tests/unit/utils/test_sdb.py | 1 - tests/unit/utils/test_ssdp.py | 25 +- tests/unit/utils/test_state.py | 13 +- tests/unit/utils/test_systemd.py | 8 +- tests/unit/utils/test_thin.py | 24 +- tests/unit/utils/test_vmware.py | 30 +- tests/unit/utils/test_vsan.py | 1 + tests/unit/utils/test_vt.py | 6 +- tests/unit/utils/test_win_chcp.py | 1 + tests/unit/utils/test_win_service.py | 4 +- tests/unit/utils/test_win_system.py | 4 +- tests/unit/utils/test_xmlutil.py | 1 + tests/unit/utils/test_yamlencoding.py | 1 - tests/unit/utils/test_zeromq.py | 1 + tests/unit/utils/test_zfs.py | 1 - tools/changelog.py | 1 + tools/ci.py | 1 + tools/docs.py | 1 + tools/pkg/__init__.py | 3 +- tools/pkg/build.py | 5 +- tools/pkg/repo/__init__.py | 1 + tools/pkg/repo/create.py | 1 + tools/pkg/repo/publish.py | 1 + tools/precommit/__init__.py | 1 + tools/precommit/changelog.py | 1 + tools/precommit/docs.py | 1 + tools/precommit/docstrings.py | 1 + tools/precommit/filemap.py | 1 + tools/precommit/workflows.py | 1 + tools/release.py | 1 + tools/testsuite/__init__.py | 1 + tools/testsuite/download.py | 1 + tools/vm.py | 1 + 1867 files changed, 10506 insertions(+), 11419 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4f05fb991c6..4eb7e3af7d8 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -6,7 +6,7 @@ exclude: ^(doc/_static/.*|doc/_themes/.*)$ repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 + rev: v4.5.0 hooks: - id: check-merge-conflict # Check for files that contain merge conflict strings. - id: trailing-whitespace # Trims trailing whitespace. @@ -1397,7 +1397,7 @@ repos: # ----- Code Formatting -------------------------------------------------------------------------------------------> - repo: https://github.com/asottile/pyupgrade - rev: v2.37.2 + rev: v3.15.1 hooks: - id: pyupgrade name: Upgrade code for Py3.8+ @@ -1437,7 +1437,7 @@ repos: args: [--silent, -E, fix_asserts, -E, fix_docstrings, -E, fix_tornado_imports] - repo: https://github.com/timothycrosley/isort - rev: 5.12.0 + rev: 5.13.2 hooks: - id: isort additional_dependencies: ['toml'] @@ -1450,31 +1450,32 @@ repos: )$ - repo: https://github.com/psf/black - rev: 22.6.0 + rev: 24.2.0 hooks: - id: black # This tells pre-commit not to pass files to black. # This should be kept in sync with pyproject.toml exclude: > (?x)^( + salt/client/ssh/ssh_py_shim\.py| templates/.*| salt/ext/.*| )$ - repo: https://github.com/asottile/blacken-docs - rev: v1.12.1 + rev: 1.16.0 hooks: - id: blacken-docs args: [--skip-errors] files: ^doc/.*\.rst additional_dependencies: - - black==22.6.0 + - black==24.2.0 # <---- Code Formatting -------------------------------------------------------------------------------------------- # ----- Security --------------------------------------------------------------------------------------------------> - repo: https://github.com/PyCQA/bandit - rev: "1.7.4" + rev: "1.7.7" hooks: - id: bandit alias: bandit-salt @@ -1488,7 +1489,7 @@ repos: )$ additional_dependencies: ['importlib_metadata<5'] - repo: https://github.com/PyCQA/bandit - rev: "1.7.4" + rev: "1.7.7" hooks: - id: bandit alias: bandit-tests @@ -1501,7 +1502,7 @@ repos: # ----- Pre-Commit ------------------------------------------------------------------------------------------------> - repo: https://github.com/pre-commit/mirrors-mypy - rev: v1.3.0 + rev: v1.8.0 hooks: - id: mypy alias: mypy-tools @@ -1518,15 +1519,15 @@ repos: - types-attrs - types-pyyaml - types-requests - - python-tools-scripts>=0.18.6 + - python-tools-scripts==0.18.6 - repo: https://github.com/saltstack/mirrors-nox - rev: v2021.6.12 + rev: v2022.11.21 hooks: - id: nox alias: lint-salt name: Lint Salt - files: ^((setup|noxfile)|(salt|tasks|tools)/.*)\.py$ + files: ^((setup|noxfile)|(salt|tools)/.*)\.py$ exclude: > (?x)^( templates/.*| @@ -1541,7 +1542,7 @@ repos: - pip>=20.2.4,<21.2 - repo: https://github.com/saltstack/mirrors-nox - rev: v2021.6.12 + rev: v2022.11.21 hooks: - id: nox alias: lint-tests diff --git a/doc/_ext/saltdomain.py b/doc/_ext/saltdomain.py index 9810ae4c31a..03ad25cb93c 100644 --- a/doc/_ext/saltdomain.py +++ b/doc/_ext/saltdomain.py @@ -53,7 +53,7 @@ class LiterateCoding(Directive): comment; False designates code. """ comment_char = "#" # TODO: move this into a directive option - comment = re.compile(r"^\s*{}[ \n]".format(comment_char)) + comment = re.compile(rf"^\s*{comment_char}[ \n]") section_test = lambda val: bool(comment.match(val)) sections = [] @@ -136,7 +136,7 @@ class LiterateFormula(LiterateCoding): formulas_dirs = config.formulas_dirs fpath = sls_path.replace(".", "/") - name_options = ("{}.sls".format(fpath), os.path.join(fpath, "init.sls")) + name_options = (f"{fpath}.sls", os.path.join(fpath, "init.sls")) paths = [ os.path.join(fdir, fname) @@ -151,7 +151,7 @@ class LiterateFormula(LiterateCoding): except OSError: pass - raise OSError("Could not find sls file '{}'".format(sls_path)) + raise OSError(f"Could not find sls file '{sls_path}'") class CurrentFormula(Directive): @@ -196,7 +196,7 @@ class Formula(Directive): targetnode = nodes.target("", "", ids=["module-" + formname], ismod=True) self.state.document.note_explicit_target(targetnode) - indextext = "{}-formula)".format(formname) + indextext = f"{formname}-formula)" inode = addnodes.index( entries=[("single", indextext, "module-" + formname, "")] ) @@ -221,9 +221,9 @@ class State(Directive): formula = env.temp_data.get("salt:formula") - indextext = "{1} ({0}-formula)".format(formula, statename) + indextext = f"{statename} ({formula}-formula)" inode = addnodes.index( - entries=[("single", indextext, "module-{}".format(statename), "")] + entries=[("single", indextext, f"module-{statename}", "")] ) return [targetnode, inode] diff --git a/doc/ref/executors/index.rst b/doc/ref/executors/index.rst index 97379fdba3a..44df3a12918 100644 --- a/doc/ref/executors/index.rst +++ b/doc/ref/executors/index.rst @@ -59,8 +59,7 @@ the ``execute`` function with the following signature: .. code-block:: python - def execute(opts, data, func, args, kwargs): - ... + def execute(opts, data, func, args, kwargs): ... Where the args are: diff --git a/doc/ref/modules/index.rst b/doc/ref/modules/index.rst index ca9171383c5..3231368c036 100644 --- a/doc/ref/modules/index.rst +++ b/doc/ref/modules/index.rst @@ -329,6 +329,7 @@ the case when the dependency is unavailable. """ Cheese execution (or returner/beacon/etc.) module """ + try: import enzymes diff --git a/doc/topics/development/tests/index.rst b/doc/topics/development/tests/index.rst index 55e8bb18f2a..a789bab089d 100644 --- a/doc/topics/development/tests/index.rst +++ b/doc/topics/development/tests/index.rst @@ -364,8 +364,7 @@ the actual testing, such as functions containing assertions, must start with .. code-block:: python - def test_user_present(self): - ... + def test_user_present(self): ... When functions in test files are not prepended with ``test_``, the function acts as a normal, helper function and is not run as a test by the test suite. diff --git a/doc/topics/proxyminion/index.rst b/doc/topics/proxyminion/index.rst index cb4aec151a2..2d18e3607cf 100644 --- a/doc/topics/proxyminion/index.rst +++ b/doc/topics/proxyminion/index.rst @@ -581,7 +581,6 @@ and status; "package" installation, and a ping. def uptodate(name): - """ Call the REST endpoint to see if the packages on the "server" are up to date. """ @@ -592,7 +591,6 @@ and status; "package" installation, and a ping. def package_remove(name): - """ Remove a "package" on the REST server """ diff --git a/doc/topics/releases/2016.11.0.rst b/doc/topics/releases/2016.11.0.rst index 2aad664eca9..227eaa9ce93 100644 --- a/doc/topics/releases/2016.11.0.rst +++ b/doc/topics/releases/2016.11.0.rst @@ -551,15 +551,13 @@ General Deprecations .. code-block:: python - def fcn(msg="", env="base", refresh=True, saltenv="base", **kwargs): - ... + def fcn(msg="", env="base", refresh=True, saltenv="base", **kwargs): ... has been changed to .. code-block:: python - def fcn(msg="", refresh=True, saltenv="base", **kwargs): - ... + def fcn(msg="", refresh=True, saltenv="base", **kwargs): ... - If ``env`` (or ``__env__``) is supplied as a keyword argument to a function that also accepts arbitrary keyword arguments, then a new warning informs the @@ -568,8 +566,7 @@ General Deprecations .. code-block:: python - def fcn(msg="", refresh=True, saltenv="base", **kwargs): - ... + def fcn(msg="", refresh=True, saltenv="base", **kwargs): ... .. code-block:: python @@ -582,8 +579,7 @@ General Deprecations .. code-block:: python - def fcn(msg="", refresh=True, saltenv="base"): - ... + def fcn(msg="", refresh=True, saltenv="base"): ... .. code-block:: python @@ -597,8 +593,7 @@ General Deprecations .. code-block:: python - def fcn(msg="", refresh=True, saltenv="base"): - ... + def fcn(msg="", refresh=True, saltenv="base"): ... .. code-block:: python diff --git a/noxfile.py b/noxfile.py index 474dcd5bb75..4fa2b1a792d 100644 --- a/noxfile.py +++ b/noxfile.py @@ -4,6 +4,7 @@ noxfile Nox configuration script """ + # pylint: disable=resource-leakage,3rd-party-module-not-gated import contextlib @@ -1787,7 +1788,7 @@ class Recompress: d_targz = tempd.joinpath(targz.name) with tarfile.open(d_tar, "w|") as wfile: with tarfile.open(targz, "r:gz") as rfile: - rfile.extractall(d_src) + rfile.extractall(d_src) # nosec extracted_dir = next(pathlib.Path(d_src).iterdir()) for name in sorted(extracted_dir.rglob("*")): wfile.add( diff --git a/salt/__init__.py b/salt/__init__.py index a2b9365ab46..3d36a148f7f 100644 --- a/salt/__init__.py +++ b/salt/__init__.py @@ -12,12 +12,6 @@ import warnings if sys.platform.startswith("win"): asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy()) -if sys.version_info < (3,): # pragma: no cover - sys.stderr.write( - "\n\nAfter the Sodium release, 3001, Salt no longer supports Python 2. Exiting.\n\n" - ) - sys.stderr.flush() - class NaclImporter: """ diff --git a/salt/_compat.py b/salt/_compat.py index 7d20691f594..2cead97d0b2 100644 --- a/salt/_compat.py +++ b/salt/_compat.py @@ -1,6 +1,7 @@ """ Salt compatibility code """ + # pylint: disable=unused-import import sys diff --git a/salt/_logging/__init__.py b/salt/_logging/__init__.py index 43bcbac3aca..ea97b6ce9a8 100644 --- a/salt/_logging/__init__.py +++ b/salt/_logging/__init__.py @@ -9,6 +9,7 @@ The ``salt._logging`` package should be imported as soon as possible since salt tweaks the python's logging system. """ + from salt._logging.impl import ( DFLT_LOG_DATEFMT, DFLT_LOG_DATEFMT_LOGFILE, diff --git a/salt/auth/django.py b/salt/auth/django.py index a5a52063eb7..d11fa438f30 100644 --- a/salt/auth/django.py +++ b/salt/auth/django.py @@ -46,7 +46,6 @@ indicated above, though the model DOES NOT have to be named 'SaltExternalAuthModel'. """ - import logging import os import sys @@ -112,7 +111,7 @@ def __django_auth_setup(): django_module_name, globals(), locals(), "SaltExternalAuthModel" ) # pylint: enable=possibly-unused-variable - DJANGO_AUTH_CLASS_str = "django_auth_module.{}".format(django_model_name) + DJANGO_AUTH_CLASS_str = f"django_auth_module.{django_model_name}" DJANGO_AUTH_CLASS = eval(DJANGO_AUTH_CLASS_str) # pylint: disable=W0123 diff --git a/salt/auth/file.py b/salt/auth/file.py index 807c9c93bba..61f73480978 100644 --- a/salt/auth/file.py +++ b/salt/auth/file.py @@ -94,7 +94,6 @@ When using ``htdigest`` the ``^realm`` must be set: """ - import logging import os diff --git a/salt/auth/keystone.py b/salt/auth/keystone.py index 5ed9f7c499f..def2e8170e5 100644 --- a/salt/auth/keystone.py +++ b/salt/auth/keystone.py @@ -4,7 +4,6 @@ Provide authentication using OpenStack Keystone :depends: - keystoneclient Python module """ - try: from keystoneclient.exceptions import AuthorizationFailure, Unauthorized from keystoneclient.v2_0 import client diff --git a/salt/auth/ldap.py b/salt/auth/ldap.py index 629bd93a3e0..a3c952ce678 100644 --- a/salt/auth/ldap.py +++ b/salt/auth/ldap.py @@ -3,6 +3,7 @@ Provide authentication using simple LDAP binds :depends: - ldap Python module """ + import itertools import logging @@ -53,15 +54,15 @@ def _config(key, mandatory=True, opts=None): """ try: if opts: - value = opts["auth.ldap.{}".format(key)] + value = opts[f"auth.ldap.{key}"] else: - value = __opts__["auth.ldap.{}".format(key)] + value = __opts__[f"auth.ldap.{key}"] except KeyError: try: - value = __defopts__["auth.ldap.{}".format(key)] + value = __defopts__[f"auth.ldap.{key}"] except KeyError: if mandatory: - msg = "missing auth.ldap.{} in master config".format(key) + msg = f"missing auth.ldap.{key} in master config" raise SaltInvocationError(msg) return False return value @@ -119,13 +120,13 @@ class _LDAPConnection: schema = "ldaps" if tls else "ldap" if self.uri == "": - self.uri = "{}://{}:{}".format(schema, self.server, self.port) + self.uri = f"{schema}://{self.server}:{self.port}" try: if no_verify: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) - self.ldap = ldap.initialize("{}".format(self.uri)) + self.ldap = ldap.initialize(f"{self.uri}") self.ldap.protocol_version = 3 # ldap.VERSION3 self.ldap.set_option(ldap.OPT_REFERRALS, 0) # Needed for AD diff --git a/salt/auth/mysql.py b/salt/auth/mysql.py index d08accb6cf4..215e7a42d2b 100644 --- a/salt/auth/mysql.py +++ b/salt/auth/mysql.py @@ -47,7 +47,6 @@ Enable MySQL authentication. :depends: - MySQL-python Python module """ - import logging log = logging.getLogger(__name__) diff --git a/salt/auth/rest.py b/salt/auth/rest.py index 42fc73da59a..d48b24797aa 100644 --- a/salt/auth/rest.py +++ b/salt/auth/rest.py @@ -22,7 +22,6 @@ structure of a user as above. """ - import logging import salt.utils.http diff --git a/salt/auth/yubico.py b/salt/auth/yubico.py index f0b37eb6c0d..7682d444194 100644 --- a/salt/auth/yubico.py +++ b/salt/auth/yubico.py @@ -36,7 +36,6 @@ the API key will be updated on all the YubiCloud servers. """ - import logging log = logging.getLogger(__name__) diff --git a/salt/beacons/adb.py b/salt/beacons/adb.py index cea98eafdae..e5ebba1771c 100644 --- a/salt/beacons/adb.py +++ b/salt/beacons/adb.py @@ -3,6 +3,7 @@ Beacon to emit adb device state changes for Android devices .. versionadded:: 2016.3.0 """ + import logging import salt.utils.beacons diff --git a/salt/beacons/aix_account.py b/salt/beacons/aix_account.py index 8a9e0469bd0..07aad263846 100644 --- a/salt/beacons/aix_account.py +++ b/salt/beacons/aix_account.py @@ -5,6 +5,7 @@ Beacon to fire event when we notice a AIX user is locked due to many failed logi :depends: none """ + import logging log = logging.getLogger(__name__) diff --git a/salt/beacons/bonjour_announce.py b/salt/beacons/bonjour_announce.py index edbd135e751..c129128f849 100644 --- a/salt/beacons/bonjour_announce.py +++ b/salt/beacons/bonjour_announce.py @@ -1,6 +1,7 @@ """ Beacon to announce via Bonjour (zeroconf) """ + import atexit import logging import select diff --git a/salt/beacons/btmp.py b/salt/beacons/btmp.py index f980a3ff4e1..a5d10f997fc 100644 --- a/salt/beacons/btmp.py +++ b/salt/beacons/btmp.py @@ -130,7 +130,7 @@ except ImportError: def __virtual__(): if os.path.isfile(BTMP): return __virtualname__ - err_msg = "{} does not exist.".format(BTMP) + err_msg = f"{BTMP} does not exist." log.error("Unable to load %s beacon: %s", __virtualname__, err_msg) return False, err_msg diff --git a/salt/beacons/cert_info.py b/salt/beacons/cert_info.py index b9b59902063..298d56317bd 100644 --- a/salt/beacons/cert_info.py +++ b/salt/beacons/cert_info.py @@ -7,6 +7,7 @@ Beacon to monitor certificate expiration dates from files on the filesystem. :maturity: new :depends: OpenSSL """ + import logging from datetime import datetime diff --git a/salt/beacons/diskusage.py b/salt/beacons/diskusage.py index 5be33ff975e..da904cfa520 100644 --- a/salt/beacons/diskusage.py +++ b/salt/beacons/diskusage.py @@ -5,6 +5,7 @@ Beacon to monitor disk usage. :depends: python-psutil """ + import logging import re @@ -94,7 +95,7 @@ def beacon(config): # if our mount doesn't end with a $, insert one. mount_re = mount if not mount.endswith("$"): - mount_re = "{}$".format(mount) + mount_re = f"{mount}$" if salt.utils.platform.is_windows(): # mount_re comes in formatted with a $ at the end diff --git a/salt/beacons/glxinfo.py b/salt/beacons/glxinfo.py index 20c4d4b9b01..a4aa4013804 100644 --- a/salt/beacons/glxinfo.py +++ b/salt/beacons/glxinfo.py @@ -3,6 +3,7 @@ Beacon to emit when a display is available to a linux machine .. versionadded:: 2016.3.0 """ + import logging import salt.utils.beacons diff --git a/salt/beacons/haproxy.py b/salt/beacons/haproxy.py index e19ec34abd2..a3aa13de597 100644 --- a/salt/beacons/haproxy.py +++ b/salt/beacons/haproxy.py @@ -4,6 +4,7 @@ Fire an event when over a specified threshold. .. versionadded:: 2016.11.0 """ + import logging import salt.utils.beacons diff --git a/salt/beacons/inotify.py b/salt/beacons/inotify.py index 283b84fdc73..3b11322319b 100644 --- a/salt/beacons/inotify.py +++ b/salt/beacons/inotify.py @@ -68,7 +68,7 @@ def _get_notifier(config): Check the context for the notifier and construct it if not present """ beacon_name = config.get("_beacon_name", "inotify") - notifier = "{}.notifier".format(beacon_name) + notifier = f"{beacon_name}.notifier" if notifier not in __context__: __context__["inotify.queue"] = collections.deque() wm = pyinotify.WatchManager() @@ -353,7 +353,7 @@ def beacon(config): def close(config): config = salt.utils.beacons.list_to_dict(config) beacon_name = config.get("_beacon_name", "inotify") - notifier = "{}.notifier".format(beacon_name) + notifier = f"{beacon_name}.notifier" if notifier in __context__: __context__[notifier].stop() del __context__[notifier] diff --git a/salt/beacons/journald.py b/salt/beacons/journald.py index f2c46c02e7d..19618a59938 100644 --- a/salt/beacons/journald.py +++ b/salt/beacons/journald.py @@ -1,6 +1,7 @@ """ A simple beacon to watch journald for specific entries """ + import logging import salt.utils.beacons diff --git a/salt/beacons/load.py b/salt/beacons/load.py index 56bc5b0cfa0..90b76201f8e 100644 --- a/salt/beacons/load.py +++ b/salt/beacons/load.py @@ -1,6 +1,7 @@ """ Beacon to emit system load averages """ + import logging import os diff --git a/salt/beacons/log_beacon.py b/salt/beacons/log_beacon.py index 6e5621f53a7..52227cd09cb 100644 --- a/salt/beacons/log_beacon.py +++ b/salt/beacons/log_beacon.py @@ -4,6 +4,7 @@ Beacon to fire events at specific log messages. .. versionadded:: 2017.7.0 """ + import logging import salt.utils.beacons diff --git a/salt/beacons/memusage.py b/salt/beacons/memusage.py index a80423a398e..029fb8efbeb 100644 --- a/salt/beacons/memusage.py +++ b/salt/beacons/memusage.py @@ -5,6 +5,7 @@ Beacon to monitor memory usage. :depends: python-psutil """ + import logging import re diff --git a/salt/beacons/napalm_beacon.py b/salt/beacons/napalm_beacon.py index 122d56edb75..e1c97415bf8 100644 --- a/salt/beacons/napalm_beacon.py +++ b/salt/beacons/napalm_beacon.py @@ -298,7 +298,7 @@ def validate(config): " dictionary".format(fun), ) if fun not in __salt__: - return False, "Execution function {} is not availabe!".format(fun) + return False, f"Execution function {fun} is not availabe!" return True, "Valid configuration for the napal beacon!" diff --git a/salt/beacons/network_info.py b/salt/beacons/network_info.py index de85c39d94e..4d5743d20fb 100644 --- a/salt/beacons/network_info.py +++ b/salt/beacons/network_info.py @@ -3,6 +3,7 @@ Beacon to monitor statistics from ethernet adapters .. versionadded:: 2015.5.0 """ + import logging import salt.utils.beacons diff --git a/salt/beacons/pkg.py b/salt/beacons/pkg.py index 2613f41a61f..2a7c5e19eec 100644 --- a/salt/beacons/pkg.py +++ b/salt/beacons/pkg.py @@ -3,6 +3,7 @@ Watch for pkgs that have upgrades, then fire an event. .. versionadded:: 2016.3.0 """ + import logging __virtualname__ = "pkg" diff --git a/salt/beacons/proxy_example.py b/salt/beacons/proxy_example.py index 1c804d05284..960e23fa709 100644 --- a/salt/beacons/proxy_example.py +++ b/salt/beacons/proxy_example.py @@ -7,6 +7,7 @@ Example beacon to use with salt-proxy proxy_example: endpoint: beacon """ + import logging import salt.utils.beacons diff --git a/salt/beacons/ps.py b/salt/beacons/ps.py index 2b56cafd87b..a5d9aa3d91c 100644 --- a/salt/beacons/ps.py +++ b/salt/beacons/ps.py @@ -1,6 +1,7 @@ """ Send events covering process status """ + import logging import salt.utils.beacons diff --git a/salt/beacons/salt_monitor.py b/salt/beacons/salt_monitor.py index 1776d0ce896..d8d580edbb3 100644 --- a/salt/beacons/salt_monitor.py +++ b/salt/beacons/salt_monitor.py @@ -24,6 +24,7 @@ See example config below. - test.ping - interval: 3600 # seconds """ + import salt.utils.beacons @@ -44,7 +45,7 @@ def validate(config): # a simple str is taking as the single function with no args / kwargs fun = config["salt_fun"] if fun not in __salt__: - return False, "{} not in __salt__".format(fun) + return False, f"{fun} not in __salt__" else: for entry in config["salt_fun"]: if isinstance(entry, dict): @@ -55,7 +56,7 @@ def validate(config): if not isinstance(args_kwargs_dict[key], list): return ( False, - "args key for fun {} must be list".format(fun), + f"args key for fun {fun} must be list", ) elif key == "kwargs": if not isinstance(args_kwargs_dict[key], list): @@ -69,19 +70,19 @@ def validate(config): if not isinstance(key_value, dict): return ( False, - "{} is not a key / value pair".format(key_value), + f"{key_value} is not a key / value pair", ) else: return ( False, - "key {} not allowed under fun {}".format(key, fun), + f"key {key} not allowed under fun {fun}", ) else: # entry must be function itself fun = entry if fun not in __salt__: - return False, "{} not in __salt__".format(fun) + return False, f"{fun} not in __salt__" return True, "valid config" diff --git a/salt/beacons/salt_proxy.py b/salt/beacons/salt_proxy.py index dea7ce42057..2ec7c47d2a5 100644 --- a/salt/beacons/salt_proxy.py +++ b/salt/beacons/salt_proxy.py @@ -4,6 +4,7 @@ .. versionadded:: 2015.8.3 """ + import logging import salt.utils.beacons @@ -22,9 +23,9 @@ def _run_proxy_processes(proxies): result = {} if not __salt__["salt_proxy.is_running"](proxy)["result"]: __salt__["salt_proxy.configure_proxy"](proxy, start=True) - result[proxy] = "Proxy {} was started".format(proxy) + result[proxy] = f"Proxy {proxy} was started" else: - msg = "Proxy {} is already running".format(proxy) + msg = f"Proxy {proxy} is already running" result[proxy] = msg log.debug(msg) ret.append(result) diff --git a/salt/beacons/sensehat.py b/salt/beacons/sensehat.py index 8f1d1393350..a6b4c912a18 100644 --- a/salt/beacons/sensehat.py +++ b/salt/beacons/sensehat.py @@ -8,6 +8,7 @@ Monitor temperature, humidity and pressure using the SenseHat of a Raspberry Pi :maturity: new :depends: sense_hat Python module """ + import logging import re @@ -72,7 +73,7 @@ def beacon(config): config = salt.utils.beacons.list_to_dict(config) for sensor in config.get("sensors", {}): - sensor_function = "sensehat.get_{}".format(sensor) + sensor_function = f"sensehat.get_{sensor}" if sensor_function not in __salt__: log.error("No sensor for meassuring %s. Skipping.", sensor) continue @@ -94,6 +95,6 @@ def beacon(config): current_value = __salt__[sensor_function]() if not sensor_min <= current_value <= sensor_max: - ret.append({"tag": "sensehat/{}".format(sensor), sensor: current_value}) + ret.append({"tag": f"sensehat/{sensor}", sensor: current_value}) return ret diff --git a/salt/beacons/service.py b/salt/beacons/service.py index b27f75273af..6f7519e8f95 100644 --- a/salt/beacons/service.py +++ b/salt/beacons/service.py @@ -1,6 +1,7 @@ """ Send events covering service status """ + import logging import os import time diff --git a/salt/beacons/sh.py b/salt/beacons/sh.py index 29c2a2a206a..57ef43bca9c 100644 --- a/salt/beacons/sh.py +++ b/salt/beacons/sh.py @@ -1,6 +1,7 @@ """ Watch the shell commands being executed actively. This beacon requires strace. """ + import logging import time @@ -72,7 +73,7 @@ def beacon(config): __context__[pkey] = {} for pid in track_pids: if pid not in __context__[pkey]: - cmd = ["strace", "-f", "-e", "execve", "-p", "{}".format(pid)] + cmd = ["strace", "-f", "-e", "execve", "-p", f"{pid}"] __context__[pkey][pid] = {} __context__[pkey][pid]["vt"] = salt.utils.vt.Terminal( cmd, diff --git a/salt/beacons/smartos_imgadm.py b/salt/beacons/smartos_imgadm.py index dcf47c7d086..665168c0e3f 100644 --- a/salt/beacons/smartos_imgadm.py +++ b/salt/beacons/smartos_imgadm.py @@ -17,6 +17,7 @@ Beacon that fires events on image import/delete. - interval: 60 - startup_import_event: True """ + import logging import salt.utils.beacons diff --git a/salt/beacons/smartos_vmadm.py b/salt/beacons/smartos_vmadm.py index 2501de96da8..7cdb8806a18 100644 --- a/salt/beacons/smartos_vmadm.py +++ b/salt/beacons/smartos_vmadm.py @@ -17,6 +17,7 @@ Beacon that fires events on vm state changes - interval: 60 - startup_create_event: True """ + import logging import salt.utils.beacons diff --git a/salt/beacons/status.py b/salt/beacons/status.py index aa5aa13b478..8c1210e7dbc 100644 --- a/salt/beacons/status.py +++ b/salt/beacons/status.py @@ -87,6 +87,7 @@ markers for specific list items: to check the minion log for errors after configuring this beacon. """ + import datetime import logging @@ -142,7 +143,7 @@ def beacon(config): for func in entry: ret[func] = {} try: - data = __salt__["status.{}".format(func)]() + data = __salt__[f"status.{func}"]() except salt.exceptions.CommandExecutionError as exc: log.debug( "Status beacon attempted to process function %s " @@ -165,8 +166,6 @@ def beacon(config): except TypeError: ret[func][item] = data[int(item)] except KeyError as exc: - ret[ - func - ] = "Status beacon is incorrectly configured: {}".format(exc) + ret[func] = f"Status beacon is incorrectly configured: {exc}" return [{"tag": ctime, "data": ret}] diff --git a/salt/beacons/swapusage.py b/salt/beacons/swapusage.py index 0cbdec07ea4..1bb9a572a3d 100644 --- a/salt/beacons/swapusage.py +++ b/salt/beacons/swapusage.py @@ -5,6 +5,7 @@ Beacon to monitor swap usage. :depends: python-psutil """ + import logging import re diff --git a/salt/beacons/telegram_bot_msg.py b/salt/beacons/telegram_bot_msg.py index e11c869947f..76e0e2a6c34 100644 --- a/salt/beacons/telegram_bot_msg.py +++ b/salt/beacons/telegram_bot_msg.py @@ -4,6 +4,7 @@ Beacon to emit Telegram messages Requires the python-telegram-bot library """ + import logging import salt.utils.beacons diff --git a/salt/beacons/twilio_txt_msg.py b/salt/beacons/twilio_txt_msg.py index 6aed64531dd..1f2bc64f398 100644 --- a/salt/beacons/twilio_txt_msg.py +++ b/salt/beacons/twilio_txt_msg.py @@ -1,6 +1,7 @@ """ Beacon to emit Twilio text messages """ + import logging import salt.utils.beacons diff --git a/salt/beacons/wtmp.py b/salt/beacons/wtmp.py index c8ac6cfc379..a9f1b09281a 100644 --- a/salt/beacons/wtmp.py +++ b/salt/beacons/wtmp.py @@ -159,7 +159,7 @@ except ImportError: def __virtual__(): if os.path.isfile(WTMP): return __virtualname__ - err_msg = "{} does not exist.".format(WTMP) + err_msg = f"{WTMP} does not exist." log.error("Unable to load %s beacon: %s", __virtualname__, err_msg) return False, err_msg diff --git a/salt/cache/__init__.py b/salt/cache/__init__.py index 2b13a364235..fb2ecdc62f1 100644 --- a/salt/cache/__init__.py +++ b/salt/cache/__init__.py @@ -4,7 +4,6 @@ Loader mechanism for caching data, with data expiration, etc. .. versionadded:: 2016.11.0 """ - import logging import time @@ -70,7 +69,7 @@ class Cache: def __lazy_init(self): self._modules = salt.loader.cache(self.opts) - fun = "{}.init_kwargs".format(self.driver) + fun = f"{self.driver}.init_kwargs" if fun in self.modules: self._kwargs = self.modules[fun](self._kwargs) else: @@ -141,7 +140,7 @@ class Cache: Raises an exception if cache driver detected an error accessing data in the cache backend (auth, permissions, etc). """ - fun = "{}.store".format(self.driver) + fun = f"{self.driver}.store" return self.modules[fun](bank, key, data, **self._kwargs) def fetch(self, bank, key): @@ -165,7 +164,7 @@ class Cache: Raises an exception if cache driver detected an error accessing data in the cache backend (auth, permissions, etc). """ - fun = "{}.fetch".format(self.driver) + fun = f"{self.driver}.fetch" return self.modules[fun](bank, key, **self._kwargs) def updated(self, bank, key): @@ -189,7 +188,7 @@ class Cache: Raises an exception if cache driver detected an error accessing data in the cache backend (auth, permissions, etc). """ - fun = "{}.updated".format(self.driver) + fun = f"{self.driver}.updated" return self.modules[fun](bank, key, **self._kwargs) def flush(self, bank, key=None): @@ -210,7 +209,7 @@ class Cache: Raises an exception if cache driver detected an error accessing data in the cache backend (auth, permissions, etc). """ - fun = "{}.flush".format(self.driver) + fun = f"{self.driver}.flush" return self.modules[fun](bank, key=key, **self._kwargs) def list(self, bank): @@ -229,7 +228,7 @@ class Cache: Raises an exception if cache driver detected an error accessing data in the cache backend (auth, permissions, etc). """ - fun = "{}.list".format(self.driver) + fun = f"{self.driver}.list" return self.modules[fun](bank, **self._kwargs) def contains(self, bank, key=None): @@ -254,7 +253,7 @@ class Cache: Raises an exception if cache driver detected an error accessing data in the cache backend (auth, permissions, etc). """ - fun = "{}.contains".format(self.driver) + fun = f"{self.driver}.contains" return self.modules[fun](bank, key, **self._kwargs) @@ -289,7 +288,7 @@ class MemCache(Cache): break def _get_storage_id(self): - fun = "{}.storage_id".format(self.driver) + fun = f"{self.driver}.storage_id" if fun in self.modules: return self.modules[fun](self.kwargs) else: diff --git a/salt/cache/etcd_cache.py b/salt/cache/etcd_cache.py index c1a111bd4f9..36c23f8131c 100644 --- a/salt/cache/etcd_cache.py +++ b/salt/cache/etcd_cache.py @@ -141,16 +141,14 @@ def store(bank, key, data): Store a key value. """ _init_client() - etcd_key = "{}/{}/{}".format(path_prefix, bank, key) - etcd_tstamp_key = "{}/{}/{}".format(path_prefix, bank, key + _tstamp_suffix) + etcd_key = f"{path_prefix}/{bank}/{key}" + etcd_tstamp_key = f"{path_prefix}/{bank}/{key + _tstamp_suffix}" try: value = salt.payload.dumps(data) client.write(etcd_key, base64.b64encode(value)) client.write(etcd_tstamp_key, int(time.time())) except Exception as exc: # pylint: disable=broad-except - raise SaltCacheError( - "There was an error writing the key, {}: {}".format(etcd_key, exc) - ) + raise SaltCacheError(f"There was an error writing the key, {etcd_key}: {exc}") def fetch(bank, key): @@ -158,16 +156,14 @@ def fetch(bank, key): Fetch a key value. """ _init_client() - etcd_key = "{}/{}/{}".format(path_prefix, bank, key) + etcd_key = f"{path_prefix}/{bank}/{key}" try: value = client.read(etcd_key).value return salt.payload.loads(base64.b64decode(value)) except etcd.EtcdKeyNotFound: return {} except Exception as exc: # pylint: disable=broad-except - raise SaltCacheError( - "There was an error reading the key, {}: {}".format(etcd_key, exc) - ) + raise SaltCacheError(f"There was an error reading the key, {etcd_key}: {exc}") def flush(bank, key=None): @@ -176,11 +172,11 @@ def flush(bank, key=None): """ _init_client() if key is None: - etcd_key = "{}/{}".format(path_prefix, bank) + etcd_key = f"{path_prefix}/{bank}" tstamp_key = None else: - etcd_key = "{}/{}/{}".format(path_prefix, bank, key) - tstamp_key = "{}/{}/{}".format(path_prefix, bank, key + _tstamp_suffix) + etcd_key = f"{path_prefix}/{bank}/{key}" + tstamp_key = f"{path_prefix}/{bank}/{key + _tstamp_suffix}" try: client.read(etcd_key) except etcd.EtcdKeyNotFound: @@ -190,9 +186,7 @@ def flush(bank, key=None): client.delete(tstamp_key) client.delete(etcd_key, recursive=True) except Exception as exc: # pylint: disable=broad-except - raise SaltCacheError( - "There was an error removing the key, {}: {}".format(etcd_key, exc) - ) + raise SaltCacheError(f"There was an error removing the key, {etcd_key}: {exc}") def _walk(r): @@ -218,14 +212,14 @@ def ls(bank): bank. """ _init_client() - path = "{}/{}".format(path_prefix, bank) + path = f"{path_prefix}/{bank}" try: return _walk(client.read(path)) except etcd.EtcdKeyNotFound: return [] except Exception as exc: # pylint: disable=broad-except raise SaltCacheError( - 'There was an error getting the key "{}": {}'.format(bank, exc) + f'There was an error getting the key "{bank}": {exc}' ) from exc @@ -242,9 +236,7 @@ def contains(bank, key): except etcd.EtcdKeyNotFound: return False except Exception as exc: # pylint: disable=broad-except - raise SaltCacheError( - "There was an error getting the key, {}: {}".format(etcd_key, exc) - ) + raise SaltCacheError(f"There was an error getting the key, {etcd_key}: {exc}") def updated(bank, key): @@ -252,13 +244,11 @@ def updated(bank, key): Return Unix Epoch based timestamp of when the bank/key was updated. """ _init_client() - tstamp_key = "{}/{}/{}".format(path_prefix, bank, key + _tstamp_suffix) + tstamp_key = f"{path_prefix}/{bank}/{key + _tstamp_suffix}" try: value = client.read(tstamp_key).value return int(value) except etcd.EtcdKeyNotFound: return None except Exception as exc: # pylint: disable=broad-except - raise SaltCacheError( - "There was an error reading the key, {}: {}".format(tstamp_key, exc) - ) + raise SaltCacheError(f"There was an error reading the key, {tstamp_key}: {exc}") diff --git a/salt/cache/localfs.py b/salt/cache/localfs.py index df2f3ac4727..4ac5ecec062 100644 --- a/salt/cache/localfs.py +++ b/salt/cache/localfs.py @@ -51,10 +51,10 @@ def store(bank, key, data, cachedir): except OSError as exc: if exc.errno != errno.EEXIST: raise SaltCacheError( - "The cache directory, {}, could not be created: {}".format(base, exc) + f"The cache directory, {base}, could not be created: {exc}" ) - outfile = os.path.join(base, "{}.p".format(key)) + outfile = os.path.join(base, f"{key}.p") tmpfh, tmpfname = tempfile.mkstemp(dir=base) os.close(tmpfh) try: @@ -64,7 +64,7 @@ def store(bank, key, data, cachedir): salt.utils.atomicfile.atomic_rename(tmpfname, outfile) except OSError as exc: raise SaltCacheError( - "There was an error writing the cache file, {}: {}".format(base, exc) + f"There was an error writing the cache file, {base}: {exc}" ) @@ -73,7 +73,7 @@ def fetch(bank, key, cachedir): Fetch information from a file. """ inkey = False - key_file = os.path.join(cachedir, os.path.normpath(bank), "{}.p".format(key)) + key_file = os.path.join(cachedir, os.path.normpath(bank), f"{key}.p") if not os.path.isfile(key_file): # The bank includes the full filename, and the key is inside the file key_file = os.path.join(cachedir, os.path.normpath(bank) + ".p") @@ -90,7 +90,7 @@ def fetch(bank, key, cachedir): return salt.payload.load(fh_) except OSError as exc: raise SaltCacheError( - 'There was an error reading the cache file "{}": {}'.format(key_file, exc) + f'There was an error reading the cache file "{key_file}": {exc}' ) @@ -98,7 +98,7 @@ def updated(bank, key, cachedir): """ Return the epoch of the mtime for this cache file """ - key_file = os.path.join(cachedir, os.path.normpath(bank), "{}.p".format(key)) + key_file = os.path.join(cachedir, os.path.normpath(bank), f"{key}.p") if not os.path.isfile(key_file): log.warning('Cache file "%s" does not exist', key_file) return None @@ -106,7 +106,7 @@ def updated(bank, key, cachedir): return int(os.path.getmtime(key_file)) except OSError as exc: raise SaltCacheError( - 'There was an error reading the mtime for "{}": {}'.format(key_file, exc) + f'There was an error reading the mtime for "{key_file}": {exc}' ) @@ -124,12 +124,12 @@ def flush(bank, key=None, cachedir=None): return False shutil.rmtree(target) else: - target = os.path.join(cachedir, os.path.normpath(bank), "{}.p".format(key)) + target = os.path.join(cachedir, os.path.normpath(bank), f"{key}.p") if not os.path.isfile(target): return False os.remove(target) except OSError as exc: - raise SaltCacheError('There was an error removing "{}": {}'.format(target, exc)) + raise SaltCacheError(f'There was an error removing "{target}": {exc}') return True @@ -143,9 +143,7 @@ def list_(bank, cachedir): try: items = os.listdir(base) except OSError as exc: - raise SaltCacheError( - 'There was an error accessing directory "{}": {}'.format(base, exc) - ) + raise SaltCacheError(f'There was an error accessing directory "{base}": {exc}') ret = [] for item in items: if item.endswith(".p"): @@ -163,5 +161,5 @@ def contains(bank, key, cachedir): base = os.path.join(cachedir, os.path.normpath(bank)) return os.path.isdir(base) else: - keyfile = os.path.join(cachedir, os.path.normpath(bank), "{}.p".format(key)) + keyfile = os.path.join(cachedir, os.path.normpath(bank), f"{key}.p") return os.path.isfile(keyfile) diff --git a/salt/cache/redis_cache.py b/salt/cache/redis_cache.py index 6579303fef8..5584d118ba7 100644 --- a/salt/cache/redis_cache.py +++ b/salt/cache/redis_cache.py @@ -151,7 +151,6 @@ Cluster Configuration Example: cache.redis.separator: '@' """ - import itertools import logging import time @@ -352,7 +351,7 @@ def _get_banks_to_remove(redis_server, bank, path=""): A simple tree traversal algorithm that builds the list of banks to remove, starting from an arbitrary node in the tree. """ - current_path = bank if not path else "{path}/{bank}".format(path=path, bank=bank) + current_path = bank if not path else f"{path}/{bank}" bank_paths_to_remove = [current_path] # as you got here, you'll be removed diff --git a/salt/channel/client.py b/salt/channel/client.py index ea42cefaef0..f49ec473f85 100644 --- a/salt/channel/client.py +++ b/salt/channel/client.py @@ -3,6 +3,7 @@ Encapsulate the different transports available to Salt. This includes client side transport, for the ReqServer and the Publisher """ + import logging import os import time diff --git a/salt/cli/api.py b/salt/cli/api.py index a54595578c4..3e46676e1ef 100644 --- a/salt/cli/api.py +++ b/salt/cli/api.py @@ -6,7 +6,6 @@ """ - import logging import salt.client.netapi diff --git a/salt/cli/batch.py b/salt/cli/batch.py index 8e1547c61d4..85250c02efd 100644 --- a/salt/cli/batch.py +++ b/salt/cli/batch.py @@ -188,7 +188,7 @@ class Batch: if next_: if not self.quiet: salt.utils.stringutils.print_cli( - "\nExecuting run on {}\n".format(sorted(next_)) + f"\nExecuting run on {sorted(next_)}\n" ) # create a new iterator for this batch of minions return_value = self.opts.get("return", self.opts.get("ret", "")) diff --git a/salt/cli/caller.py b/salt/cli/caller.py index fd12b4e0ae3..ffc39356ba9 100644 --- a/salt/cli/caller.py +++ b/salt/cli/caller.py @@ -75,7 +75,7 @@ class BaseCaller: docs[name] = func.__doc__ for name in sorted(docs): if name.startswith(self.opts.get("fun", "")): - salt.utils.stringutils.print_cli("{}:\n{}\n".format(name, docs[name])) + salt.utils.stringutils.print_cli(f"{name}:\n{docs[name]}\n") def print_grains(self): """ @@ -130,7 +130,7 @@ class BaseCaller: salt.minion.get_proc_dir(self.opts["cachedir"]), ret["jid"] ) if fun not in self.minion.functions: - docs = self.minion.functions["sys.doc"]("{}*".format(fun)) + docs = self.minion.functions["sys.doc"](f"{fun}*") if docs: docs[fun] = self.minion.functions.missing_fun_string(fun) ret["out"] = "nested" @@ -194,20 +194,16 @@ class BaseCaller: executors = [executors] try: for name in executors: - fname = "{}.execute".format(name) + fname = f"{name}.execute" if fname not in self.minion.executors: - raise SaltInvocationError( - "Executor '{}' is not available".format(name) - ) + raise SaltInvocationError(f"Executor '{name}' is not available") ret["return"] = self.minion.executors[fname]( self.opts, data, func, args, kwargs ) if ret["return"] is not None: break except TypeError as exc: - sys.stderr.write( - "\nPassed invalid arguments: {}.\n\nUsage:\n".format(exc) - ) + sys.stderr.write(f"\nPassed invalid arguments: {exc}.\n\nUsage:\n") salt.utils.stringutils.print_cli(func.__doc__) active_level = LOG_LEVELS.get( self.opts["log_level"].lower(), logging.ERROR @@ -235,7 +231,7 @@ class BaseCaller: retcode = salt.defaults.exitcodes.EX_GENERIC ret["retcode"] = retcode - except (CommandExecutionError) as exc: + except CommandExecutionError as exc: msg = "Error running '{0}': {1}\n" active_level = LOG_LEVELS.get(self.opts["log_level"].lower(), logging.ERROR) if active_level <= logging.DEBUG: @@ -272,7 +268,7 @@ class BaseCaller: continue try: ret["success"] = True - self.minion.returners["{}.returner".format(returner)](ret) + self.minion.returners[f"{returner}.returner"](ret) except Exception: # pylint: disable=broad-except pass diff --git a/salt/cli/cp.py b/salt/cli/cp.py index 457be4b044e..39ba429134d 100644 --- a/salt/cli/cp.py +++ b/salt/cli/cp.py @@ -68,7 +68,7 @@ class SaltCP: except OSError as exc: if exc.errno == errno.ENOENT: # Path does not exist - sys.stderr.write("{} does not exist\n".format(path)) + sys.stderr.write(f"{path} does not exist\n") sys.exit(42) elif exc.errno in (errno.EINVAL, errno.ENOTDIR): # Path is a file (EINVAL on Windows, ENOTDIR otherwise) @@ -97,7 +97,7 @@ class SaltCP: Take a path and return the contents of the file as a string """ if not os.path.isfile(fn_): - err = "The referenced file, {} is not available.".format(fn_) + err = f"The referenced file, {fn_} is not available." sys.stderr.write(err + "\n") sys.exit(42) with salt.utils.files.fopen(fn_, "r") as fp_: @@ -211,12 +211,10 @@ class SaltCP: log.debug( "Copying %s to %starget '%s' as %s%s", fn_, - "{} ".format(selected_target_option) - if selected_target_option - else "", + f"{selected_target_option} " if selected_target_option else "", tgt, remote_path, - " (chunk #{})".format(index) if append else "", + f" (chunk #{index})" if append else "", ) args = [ tgt, @@ -261,11 +259,13 @@ class SaltCP: log.debug( "Creating empty dir %s on %starget '%s'", dirname, - "{} ".format( - selected_target_option - ) # pylint: disable=str-format-in-logging - if selected_target_option - else "", + ( + "{} ".format( + selected_target_option + ) # pylint: disable=str-format-in-logging + if selected_target_option + else "" + ), tgt, ) args = [tgt, "cp.recv_chunked", [remote_path, None], timeout] diff --git a/salt/cli/daemons.py b/salt/cli/daemons.py index 22d89e0541d..efd89219551 100644 --- a/salt/cli/daemons.py +++ b/salt/cli/daemons.py @@ -2,7 +2,6 @@ Make me some salt! """ - import logging import os import warnings diff --git a/salt/cli/spm.py b/salt/cli/spm.py index 9098e0d78e6..a4c97da5570 100644 --- a/salt/cli/spm.py +++ b/salt/cli/spm.py @@ -7,7 +7,6 @@ .. versionadded:: 2015.8.0 """ - import salt.spm import salt.utils.parsers as parsers from salt.utils.verify import verify_env diff --git a/salt/client/__init__.py b/salt/client/__init__.py index 9a1af36c872..3be1150b111 100644 --- a/salt/client/__init__.py +++ b/salt/client/__init__.py @@ -8,7 +8,6 @@ The data structure needs to be: 'key': ''} """ - import logging # The components here are simple, and they need to be and stay simple, we diff --git a/salt/client/mixins.py b/salt/client/mixins.py index 9bfa7c651d4..e8e22728a28 100644 --- a/salt/client/mixins.py +++ b/salt/client/mixins.py @@ -382,10 +382,10 @@ class SyncClientMixin(ClientStateMixin): try: data["return"] = func(*args, **kwargs) except TypeError as exc: - data[ - "return" - ] = "\nPassed invalid arguments: {}\n\nUsage:\n{}".format( - exc, func.__doc__ + data["return"] = ( + "\nPassed invalid arguments: {}\n\nUsage:\n{}".format( + exc, func.__doc__ + ) ) try: data["success"] = self.context.get("retcode", 0) == 0 diff --git a/salt/client/netapi.py b/salt/client/netapi.py index 6d0dc73b854..27029af85a3 100644 --- a/salt/client/netapi.py +++ b/salt/client/netapi.py @@ -48,7 +48,7 @@ class NetapiClient: for fun in self.netapi: if fun.endswith(".start"): - name = "RunNetapi({})".format(self.netapi[fun].__module__) + name = f"RunNetapi({self.netapi[fun].__module__})" log.info("Starting %s", name) self.process_manager.add_process( RunNetapi, args=(self.opts, fun), name=name diff --git a/salt/client/ssh/__init__.py b/salt/client/ssh/__init__.py index 4eec0eadcf6..ae51bdb4d8c 100644 --- a/salt/client/ssh/__init__.py +++ b/salt/client/ssh/__init__.py @@ -783,9 +783,9 @@ class SSH(MultiprocessingStateMixin): data["return"] = data.get("stdout") else: data["return"] = data.get("stderr", data.get("stdout")) - data[ - "jid" - ] = jid # make the jid in the payload the same as the jid in the tag + data["jid"] = ( + jid # make the jid in the payload the same as the jid in the tag + ) self.event.fire_event( data, salt.utils.event.tagify([jid, "ret", host], "job") ) @@ -923,9 +923,9 @@ class SSH(MultiprocessingStateMixin): data["return"] = data.get("stdout") else: data["return"] = data.get("stderr", data.get("stdout")) - data[ - "jid" - ] = jid # make the jid in the payload the same as the jid in the tag + data["jid"] = ( + jid # make the jid in the payload the same as the jid in the tag + ) self.event.fire_event( data, salt.utils.event.tagify([jid, "ret", host], "job") ) diff --git a/salt/client/ssh/ssh_py_shim.py b/salt/client/ssh/ssh_py_shim.py index 9b8f9e0f658..24e4c0cc9cb 100644 --- a/salt/client/ssh/ssh_py_shim.py +++ b/salt/client/ssh/ssh_py_shim.py @@ -170,7 +170,7 @@ def unpack_thin(thin_path): """ tfile = tarfile.TarFile.gzopen(thin_path) old_umask = os.umask(0o077) # pylint: disable=blacklisted-function - tfile.extractall(path=OPTIONS.saltdir) + tfile.extractall(path=OPTIONS.saltdir) # nosec tfile.close() os.umask(old_umask) # pylint: disable=blacklisted-function try: @@ -197,7 +197,7 @@ def unpack_ext(ext_path): ) tfile = tarfile.TarFile.gzopen(ext_path) old_umask = os.umask(0o077) # pylint: disable=blacklisted-function - tfile.extractall(path=modcache) + tfile.extractall(path=modcache) # nosec tfile.close() os.umask(old_umask) # pylint: disable=blacklisted-function os.unlink(ext_path) diff --git a/salt/client/ssh/wrapper/__init__.py b/salt/client/ssh/wrapper/__init__.py index bb60f58cd1a..4d29c168491 100644 --- a/salt/client/ssh/wrapper/__init__.py +++ b/salt/client/ssh/wrapper/__init__.py @@ -5,7 +5,6 @@ to be easily rewritten to execute in a way that makes them do the same tasks as ZeroMQ salt, but via ssh. """ - import copy import logging diff --git a/salt/client/ssh/wrapper/cmdmod.py b/salt/client/ssh/wrapper/cmdmod.py index 788c86b3144..e74079bfcbc 100644 --- a/salt/client/ssh/wrapper/cmdmod.py +++ b/salt/client/ssh/wrapper/cmdmod.py @@ -8,6 +8,7 @@ SSH wrapper module for the ``cmdmod`` execution module. value of the minion setting. This is the same for the ``state`` and `cp`` wrappers. """ + import logging import os.path import shlex diff --git a/salt/client/ssh/wrapper/grains.py b/salt/client/ssh/wrapper/grains.py index ff3789ff84c..2483726ae21 100644 --- a/salt/client/ssh/wrapper/grains.py +++ b/salt/client/ssh/wrapper/grains.py @@ -2,7 +2,6 @@ Return/control aspects of the grains data """ - import math import salt.utils.data diff --git a/salt/client/ssh/wrapper/mine.py b/salt/client/ssh/wrapper/mine.py index 32a0e01e90b..80e114ac738 100644 --- a/salt/client/ssh/wrapper/mine.py +++ b/salt/client/ssh/wrapper/mine.py @@ -8,7 +8,6 @@ Wrapper function for mine operations for salt-ssh accessing the regular mine as well. """ - import copy import logging diff --git a/salt/cloud/__init__.py b/salt/cloud/__init__.py index 5402bd848e9..61daa8db521 100644 --- a/salt/cloud/__init__.py +++ b/salt/cloud/__init__.py @@ -2,6 +2,7 @@ The top level interface used to translate configuration data back to the correct cloud modules """ + import copy import glob import logging diff --git a/salt/cloud/cli.py b/salt/cloud/cli.py index f458e975c63..4a441a0798c 100644 --- a/salt/cloud/cli.py +++ b/salt/cloud/cli.py @@ -1,6 +1,7 @@ """ Primary interfaces for the salt-cloud system """ + # Need to get data from 4 sources! # CLI options # salt cloud config - CONFIG_DIR + '/cloud' @@ -174,11 +175,11 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser): msg = "The following virtual machines are set to be destroyed:\n" names = set() for alias, drivers in matching.items(): - msg += " {}:\n".format(alias) + msg += f" {alias}:\n" for driver, vms in drivers.items(): - msg += " {}:\n".format(driver) + msg += f" {driver}:\n" for name in vms: - msg += " {}\n".format(name) + msg += f" {name}\n" names.add(name) try: if self.print_confirm(msg): @@ -212,7 +213,7 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser): key, value = name.split("=", 1) kwargs[key] = value else: - msg += " {}\n".format(name) + msg += f" {name}\n" machines.append(name) names = machines @@ -255,7 +256,7 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser): elif self.options.set_password: username = self.credential_username - provider_name = "salt.cloud.provider.{}".format(self.credential_provider) + provider_name = f"salt.cloud.provider.{self.credential_provider}" # TODO: check if provider is configured # set the password salt.utils.cloud.store_password_in_keyring(provider_name, username) @@ -275,7 +276,7 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser): # display profile errors msg += "Found the following errors:\n" for profile_name, error in dmap["errors"].items(): - msg += " {}: {}\n".format(profile_name, error) + msg += f" {profile_name}: {error}\n" sys.stderr.write(msg) sys.stderr.flush() @@ -283,17 +284,17 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser): if "existing" in dmap: msg += "The following virtual machines already exist:\n" for name in dmap["existing"]: - msg += " {}\n".format(name) + msg += f" {name}\n" if dmap["create"]: msg += "The following virtual machines are set to be created:\n" for name in dmap["create"]: - msg += " {}\n".format(name) + msg += f" {name}\n" if "destroy" in dmap: msg += "The following virtual machines are set to be destroyed:\n" for name in dmap["destroy"]: - msg += " {}\n".format(name) + msg += f" {name}\n" if not dmap["create"] and not dmap.get("destroy", None): if not dmap.get("existing", None): @@ -382,7 +383,7 @@ class SaltCloud(salt.utils.parsers.SaltCloudParser): # This is a salt cloud system exit if exc.exit_code > 0: # the exit code is bigger than 0, it's an error - msg = "Error: {}".format(msg) + msg = f"Error: {msg}" self.exit(exc.exit_code, msg.format(exc).rstrip() + "\n") # It's not a system exit but it's an error we can # handle diff --git a/salt/cloud/clouds/aliyun.py b/salt/cloud/clouds/aliyun.py index 9b1b318885b..9879e4df223 100644 --- a/salt/cloud/clouds/aliyun.py +++ b/salt/cloud/clouds/aliyun.py @@ -412,9 +412,7 @@ def get_image(vm_): if vm_image and str(vm_image) in images: return images[vm_image]["ImageId"] - raise SaltCloudNotFound( - "The specified image, '{}', could not be found.".format(vm_image) - ) + raise SaltCloudNotFound(f"The specified image, '{vm_image}', could not be found.") def get_securitygroup(vm_): @@ -432,7 +430,7 @@ def get_securitygroup(vm_): if securitygroup and str(securitygroup) in sgs: return sgs[securitygroup]["SecurityGroupId"] raise SaltCloudNotFound( - "The specified security group, '{}', could not be found.".format(securitygroup) + f"The specified security group, '{securitygroup}', could not be found." ) @@ -451,9 +449,7 @@ def get_size(vm_): if vm_size and str(vm_size) in sizes: return sizes[vm_size]["InstanceTypeId"] - raise SaltCloudNotFound( - "The specified size, '{}', could not be found.".format(vm_size) - ) + raise SaltCloudNotFound(f"The specified size, '{vm_size}', could not be found.") def __get_location(vm_): @@ -471,7 +467,7 @@ def __get_location(vm_): if vm_location and str(vm_location) in locations: return locations[vm_location]["RegionId"] raise SaltCloudNotFound( - "The specified location, '{}', could not be found.".format(vm_location) + f"The specified location, '{vm_location}', could not be found." ) @@ -575,7 +571,7 @@ def create_node(kwargs): "HostName", "Password", "SystemDisk.Category", - "VSwitchId" + "VSwitchId", # 'DataDisk.n.Size', 'DataDisk.n.Category', 'DataDisk.n.SnapshotId' ] @@ -920,7 +916,7 @@ def _get_node(name): ) # Just a little delay between attempts... time.sleep(0.5) - raise SaltCloudNotFound("The specified instance {} not found".format(name)) + raise SaltCloudNotFound(f"The specified instance {name} not found") def show_image(kwargs, call=None): @@ -982,7 +978,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -1001,7 +997,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], diff --git a/salt/cloud/clouds/cloudstack.py b/salt/cloud/clouds/cloudstack.py index ef50aaf3bf0..ff526aa82e0 100644 --- a/salt/cloud/clouds/cloudstack.py +++ b/salt/cloud/clouds/cloudstack.py @@ -20,6 +20,7 @@ Use of this module requires the ``apikey``, ``secretkey``, ``host`` and driver: cloudstack """ + # pylint: disable=function-redefined import logging @@ -473,7 +474,7 @@ def destroy(name, conn=None, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", sock_dir=__opts__["sock_dir"], args={"name": name}, ) @@ -498,7 +499,7 @@ def destroy(name, conn=None, call=None): __utils__["cloud.fire_event"]( "event", "detaching volume", - "salt/cloud/{}/detaching".format(volume.name), + f"salt/cloud/{volume.name}/detaching", sock_dir=__opts__["sock_dir"], args={"name": volume.name}, ) @@ -509,7 +510,7 @@ def destroy(name, conn=None, call=None): __utils__["cloud.fire_event"]( "event", "detached volume", - "salt/cloud/{}/detached".format(volume.name), + f"salt/cloud/{volume.name}/detached", sock_dir=__opts__["sock_dir"], args={"name": volume.name}, ) @@ -518,7 +519,7 @@ def destroy(name, conn=None, call=None): __utils__["cloud.fire_event"]( "event", "destroying volume", - "salt/cloud/{}/destroying".format(volume.name), + f"salt/cloud/{volume.name}/destroying", sock_dir=__opts__["sock_dir"], args={"name": volume.name}, ) @@ -529,7 +530,7 @@ def destroy(name, conn=None, call=None): __utils__["cloud.fire_event"]( "event", "destroyed volume", - "salt/cloud/{}/destroyed".format(volume.name), + f"salt/cloud/{volume.name}/destroyed", sock_dir=__opts__["sock_dir"], args={"name": volume.name}, ) @@ -544,7 +545,7 @@ def destroy(name, conn=None, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", sock_dir=__opts__["sock_dir"], args={"name": name}, ) diff --git a/salt/cloud/clouds/ec2.py b/salt/cloud/clouds/ec2.py index 3c8ea286bce..11f6dd6a926 100644 --- a/salt/cloud/clouds/ec2.py +++ b/salt/cloud/clouds/ec2.py @@ -296,11 +296,9 @@ def query( location = get_location() if not requesturl: - endpoint = provider.get( - "endpoint", "ec2.{}.{}".format(location, service_url) - ) + endpoint = provider.get("endpoint", f"ec2.{location}.{service_url}") - requesturl = "https://{}/".format(endpoint) + requesturl = f"https://{endpoint}/" endpoint = urllib.parse.urlparse(requesturl).netloc endpoint_path = urllib.parse.urlparse(requesturl).path else: @@ -1479,7 +1477,7 @@ def _create_eni_if_necessary(interface, vm_): eni_desc = result[1] if not eni_desc or not eni_desc.get("networkInterfaceId"): - raise SaltCloudException("Failed to create interface: {}".format(result)) + raise SaltCloudException(f"Failed to create interface: {result}") eni_id = eni_desc.get("networkInterfaceId") log.debug("Created network interface %s inst %s", eni_id, interface["DeviceIndex"]) @@ -1750,11 +1748,11 @@ def _param_from_config(key, data): if isinstance(data, dict): for k, v in data.items(): - param.update(_param_from_config("{}.{}".format(key, k), v)) + param.update(_param_from_config(f"{key}.{k}", v)) elif isinstance(data, list) or isinstance(data, tuple): for idx, conf_item in enumerate(data): - prefix = "{}.{}".format(key, idx) + prefix = f"{key}.{idx}" param.update(_param_from_config(prefix, conf_item)) else: @@ -1869,7 +1867,7 @@ def request_instance(vm_=None, call=None): params[spot_prefix + "SecurityGroup.1"] = ex_securitygroup else: for counter, sg_ in enumerate(ex_securitygroup): - params[spot_prefix + "SecurityGroup.{}".format(counter)] = sg_ + params[spot_prefix + f"SecurityGroup.{counter}"] = sg_ ex_iam_profile = iam_profile(vm_) if ex_iam_profile: @@ -1904,7 +1902,7 @@ def request_instance(vm_=None, call=None): params[spot_prefix + "SecurityGroupId.1"] = ex_securitygroupid else: for counter, sg_ in enumerate(ex_securitygroupid): - params[spot_prefix + "SecurityGroupId.{}".format(counter)] = sg_ + params[spot_prefix + f"SecurityGroupId.{counter}"] = sg_ placementgroup_ = get_placementgroup(vm_) if placementgroup_ is not None: @@ -2043,9 +2041,9 @@ def request_instance(vm_=None, call=None): else: dev_index = len(dev_list) # Add the device name in since it wasn't already there - params[ - "{}BlockDeviceMapping.{}.DeviceName".format(spot_prefix, dev_index) - ] = rd_name + params[f"{spot_prefix}BlockDeviceMapping.{dev_index}.DeviceName"] = ( + rd_name + ) # Set the termination value termination_key = "{}BlockDeviceMapping.{}.Ebs.DeleteOnTermination".format( @@ -2508,7 +2506,7 @@ def wait_for_instance( for line in comps[0].splitlines(): if not line: continue - keys += "\n{} {}".format(ip_address, line) + keys += f"\n{ip_address} {line}" with salt.utils.files.fopen(known_hosts_file, "a") as fp_: fp_.write(salt.utils.stringutils.to_str(keys)) @@ -2562,7 +2560,7 @@ def _validate_key_path_and_mode(key_filename): if not os.path.exists(key_filename): raise SaltCloudSystemExit( - "The EC2 key file '{}' does not exist.\n".format(key_filename) + f"The EC2 key file '{key_filename}' does not exist.\n" ) key_mode = stat.S_IMODE(os.stat(key_filename).st_mode) @@ -2751,7 +2749,7 @@ def create(vm_=None, call=None): __utils__["cloud.fire_event"]( "event", "setting tags", - "salt/cloud/spot_request_{}/tagging".format(sir_id), + f"salt/cloud/spot_request_{sir_id}/tagging", args={"tags": spot_request_tags}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -2923,7 +2921,7 @@ def create(vm_=None, call=None): __utils__["cloud.fire_event"]( "event", "setting tags", - "salt/cloud/block_volume_{}/tagging".format(str(volid)), + f"salt/cloud/block_volume_{str(volid)}/tagging", args={"tags": tags}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -3053,7 +3051,7 @@ def stop(name, call=None): __utils__["cloud.fire_event"]( "event", "stopping instance", - "salt/cloud/{}/stopping".format(name), + f"salt/cloud/{name}/stopping", args={"name": name, "instance_id": instance_id}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -3087,7 +3085,7 @@ def start(name, call=None): __utils__["cloud.fire_event"]( "event", "starting instance", - "salt/cloud/{}/starting".format(name), + f"salt/cloud/{name}/starting", args={"name": name, "instance_id": instance_id}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -3162,8 +3160,8 @@ def set_tags( tags = kwargs for idx, (tag_k, tag_v) in enumerate(tags.items()): - params["Tag.{}.Key".format(idx)] = tag_k - params["Tag.{}.Value".format(idx)] = tag_v + params[f"Tag.{idx}.Key"] = tag_k + params[f"Tag.{idx}.Value"] = tag_v attempts = 0 while attempts < aws.AWS_MAX_RETRIES: @@ -3209,7 +3207,7 @@ def set_tags( return settags - raise SaltCloudSystemExit("Failed to set tags on {}!".format(name)) + raise SaltCloudSystemExit(f"Failed to set tags on {name}!") def get_tags( @@ -3291,7 +3289,7 @@ def del_tags( params = {"Action": "DeleteTags", "ResourceId.1": instance_id} for idx, tag in enumerate(kwargs["tags"].split(",")): - params["Tag.{}.Key".format(idx)] = tag + params[f"Tag.{idx}.Key"] = tag aws.query( params, @@ -3355,7 +3353,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name, "instance_id": instance_id}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -3376,7 +3374,7 @@ def destroy(name, call=None): "rename_on_destroy", get_configured_provider(), __opts__, search_global=False ) if rename_on_destroy is not False: - newname = "{}-DEL{}".format(name, uuid.uuid4().hex) + newname = f"{name}-DEL{uuid.uuid4().hex}" rename(name, kwargs={"newname": newname}, call="action") log.info( "Machine will be identified as %s until it has been cleaned up.", newname @@ -3409,7 +3407,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name, "instance_id": instance_id}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -4055,8 +4053,8 @@ def _toggle_delvol( if volume_id is not None and volume_id != item["ebs"]["volumeId"]: continue - params["BlockDeviceMapping.{}.DeviceName".format(idx)] = device_name - params["BlockDeviceMapping.{}.Ebs.DeleteOnTermination".format(idx)] = value + params[f"BlockDeviceMapping.{idx}.DeviceName"] = device_name + params[f"BlockDeviceMapping.{idx}.Ebs.DeleteOnTermination"] = value aws.query( params, @@ -4476,7 +4474,7 @@ def describe_volumes(kwargs=None, call=None): if "volume_id" in kwargs: volume_id = kwargs["volume_id"].split(",") for volume_index, volume_id in enumerate(volume_id): - params["VolumeId.{}".format(volume_index)] = volume_id + params[f"VolumeId.{volume_index}"] = volume_id log.debug(params) @@ -4795,17 +4793,17 @@ def describe_snapshots(kwargs=None, call=None): if "snapshot_id" in kwargs: snapshot_ids = kwargs["snapshot_id"].split(",") for snapshot_index, snapshot_id in enumerate(snapshot_ids): - params["SnapshotId.{}".format(snapshot_index)] = snapshot_id + params[f"SnapshotId.{snapshot_index}"] = snapshot_id if "owner" in kwargs: owners = kwargs["owner"].split(",") for owner_index, owner in enumerate(owners): - params["Owner.{}".format(owner_index)] = owner + params[f"Owner.{owner_index}"] = owner if "restorable_by" in kwargs: restorable_bys = kwargs["restorable_by"].split(",") for restorable_by_index, restorable_by in enumerate(restorable_bys): - params["RestorableBy.{}".format(restorable_by_index)] = restorable_by + params[f"RestorableBy.{restorable_by_index}"] = restorable_by log.debug(params) @@ -5012,11 +5010,11 @@ def _parse_pricing(url, name): "storageGiB", "USD", ): - price_js = price_js.replace(keyword, '"{}"'.format(keyword)) + price_js = price_js.replace(keyword, f'"{keyword}"') for keyword in ("region", "price", "size"): - price_js = price_js.replace(keyword, '"{}"'.format(keyword)) - price_js = price_js.replace('"{}"s'.format(keyword), '"{}s"'.format(keyword)) + price_js = price_js.replace(keyword, f'"{keyword}"') + price_js = price_js.replace(f'"{keyword}"s', f'"{keyword}s"') price_js = price_js.replace('""', '"') @@ -5030,7 +5028,7 @@ def _parse_pricing(url, name): sizes[size["size"]] = size regions[region["region"]] = sizes - outfile = os.path.join(__opts__["cachedir"], "ec2-pricing-{}.p".format(name)) + outfile = os.path.join(__opts__["cachedir"], f"ec2-pricing-{name}.p") with salt.utils.files.fopen(outfile, "w") as fho: salt.utils.msgpack.dump(regions, fho) @@ -5092,7 +5090,7 @@ def show_pricing(kwargs=None, call=None): else: name = "linux" - pricefile = os.path.join(__opts__["cachedir"], "ec2-pricing-{}.p".format(name)) + pricefile = os.path.join(__opts__["cachedir"], f"ec2-pricing-{name}.p") if not os.path.isfile(pricefile): update_pricing({"type": name}, "function") diff --git a/salt/cloud/clouds/gce.py b/salt/cloud/clouds/gce.py index 4c14f4e74d8..f5b16897fa0 100644 --- a/salt/cloud/clouds/gce.py +++ b/salt/cloud/clouds/gce.py @@ -43,6 +43,7 @@ Example Provider Configuration :maintainer: Russell Tolle :depends: libcloud >= 1.0.0 """ + # pylint: disable=function-redefined import logging @@ -185,7 +186,7 @@ def get_conn(): "service_account_private_key", provider, __opts__ ) gce = driver(email, private_key, project=project) - gce.connection.user_agent_append("{}/{}".format(_UA_PRODUCT, _UA_VERSION)) + gce.connection.user_agent_append(f"{_UA_PRODUCT}/{_UA_VERSION}") return gce @@ -543,7 +544,7 @@ def _parse_allow(allow): pairs = p.split(":") if pairs[0].lower() not in ["tcp", "udp", "icmp"]: raise SaltCloudSystemExit( - "Unsupported protocol {}. Must be tcp, udp, or icmp.".format(pairs[0]) + f"Unsupported protocol {pairs[0]}. Must be tcp, udp, or icmp." ) if len(pairs) == 1 or pairs[0].lower() == "icmp": seen_protos[pairs[0]] = [] @@ -1698,7 +1699,6 @@ def delete_disk(kwargs=None, call=None): def create_disk(kwargs=None, call=None): - """ Create a new persistent disk. Must specify `disk_name` and `location`, and optionally can specify 'disk_type' as pd-standard or pd-ssd, which @@ -2014,7 +2014,7 @@ def reboot(vm_name, call=None): __utils__["cloud.fire_event"]( "event", "reboot instance", - "salt/cloud/{}/rebooting".format(vm_name), + f"salt/cloud/{vm_name}/rebooting", args={"name": vm_name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -2025,7 +2025,7 @@ def reboot(vm_name, call=None): __utils__["cloud.fire_event"]( "event", "reboot instance", - "salt/cloud/{}/rebooted".format(vm_name), + f"salt/cloud/{vm_name}/rebooted", args={"name": vm_name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -2056,7 +2056,7 @@ def start(vm_name, call=None): __utils__["cloud.fire_event"]( "event", "start instance", - "salt/cloud/{}/starting".format(vm_name), + f"salt/cloud/{vm_name}/starting", args={"name": vm_name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -2067,7 +2067,7 @@ def start(vm_name, call=None): __utils__["cloud.fire_event"]( "event", "start instance", - "salt/cloud/{}/started".format(vm_name), + f"salt/cloud/{vm_name}/started", args={"name": vm_name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -2096,7 +2096,7 @@ def stop(vm_name, call=None): __utils__["cloud.fire_event"]( "event", "stop instance", - "salt/cloud/{}/stopping".format(vm_name), + f"salt/cloud/{vm_name}/stopping", args={"name": vm_name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -2107,7 +2107,7 @@ def stop(vm_name, call=None): __utils__["cloud.fire_event"]( "event", "stop instance", - "salt/cloud/{}/stopped".format(vm_name), + f"salt/cloud/{vm_name}/stopped", args={"name": vm_name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -2145,12 +2145,12 @@ def destroy(vm_name, call=None): exc, exc_info_on_loglevel=logging.DEBUG, ) - raise SaltCloudSystemExit("Could not find instance {}.".format(vm_name)) + raise SaltCloudSystemExit(f"Could not find instance {vm_name}.") __utils__["cloud.fire_event"]( "event", "delete instance", - "salt/cloud/{}/deleting".format(vm_name), + f"salt/cloud/{vm_name}/deleting", args={"name": vm_name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -2186,11 +2186,11 @@ def destroy(vm_name, call=None): exc, exc_info_on_loglevel=logging.DEBUG, ) - raise SaltCloudSystemExit("Could not destroy instance {}.".format(vm_name)) + raise SaltCloudSystemExit(f"Could not destroy instance {vm_name}.") __utils__["cloud.fire_event"]( "event", "delete instance", - "salt/cloud/{}/deleted".format(vm_name), + f"salt/cloud/{vm_name}/deleted", args={"name": vm_name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -2279,7 +2279,7 @@ def create_attach_volumes(name, kwargs, call=None): letter = ord("a") - 1 for idx, volume in enumerate(volumes): - volume_name = "{}-sd{}".format(name, chr(letter + 2 + idx)) + volume_name = f"{name}-sd{chr(letter + 2 + idx)}" volume_dict = { "disk_name": volume_name, diff --git a/salt/cloud/clouds/gogrid.py b/salt/cloud/clouds/gogrid.py index a2457b48ca4..1a28f837459 100644 --- a/salt/cloud/clouds/gogrid.py +++ b/salt/cloud/clouds/gogrid.py @@ -417,7 +417,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -428,7 +428,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -536,7 +536,7 @@ def _query( path += action if command: - path += "/{}".format(command) + path += f"/{command}" log.debug("GoGrid URL: %s", path) diff --git a/salt/cloud/clouds/hetzner.py b/salt/cloud/clouds/hetzner.py index e666769ee6a..f8f34ad6d85 100644 --- a/salt/cloud/clouds/hetzner.py +++ b/salt/cloud/clouds/hetzner.py @@ -16,6 +16,7 @@ Use of this module requires the ``key`` parameter to be set. driver: hetzner """ + # pylint: disable=invalid-name,function-redefined @@ -469,22 +470,22 @@ def start(name, call=None, wait=True): client = _connect_client() server = client.servers.get_by_name(name) if server is None: - return "Instance {} doesn't exist.".format(name) + return f"Instance {name} doesn't exist." server.power_on() if wait and not wait_until(name, "running"): - return "Instance {} doesn't start.".format(name) + return f"Instance {name} doesn't start." __utils__["cloud.fire_event"]( "event", "started instance", - "salt/cloud/{}/started".format(name), + f"salt/cloud/{name}/started", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], ) - return {"Started": "{} was started.".format(name)} + return {"Started": f"{name} was started."} def stop(name, call=None, wait=True): @@ -503,22 +504,22 @@ def stop(name, call=None, wait=True): client = _connect_client() server = client.servers.get_by_name(name) if server is None: - return "Instance {} doesn't exist.".format(name) + return f"Instance {name} doesn't exist." server.power_off() if wait and not wait_until(name, "off"): - return "Instance {} doesn't stop.".format(name) + return f"Instance {name} doesn't stop." __utils__["cloud.fire_event"]( "event", "stopped instance", - "salt/cloud/{}/stopped".format(name), + f"salt/cloud/{name}/stopped", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], ) - return {"Stopped": "{} was stopped.".format(name)} + return {"Stopped": f"{name} was stopped."} def reboot(name, call=None, wait=True): @@ -539,14 +540,14 @@ def reboot(name, call=None, wait=True): client = _connect_client() server = client.servers.get_by_name(name) if server is None: - return "Instance {} doesn't exist.".format(name) + return f"Instance {name} doesn't exist." server.reboot() if wait and not wait_until(name, "running"): - return "Instance {} doesn't start.".format(name) + return f"Instance {name} doesn't start." - return {"Rebooted": "{} was rebooted.".format(name)} + return {"Rebooted": f"{name} was rebooted."} def destroy(name, call=None): @@ -567,12 +568,12 @@ def destroy(name, call=None): client = _connect_client() server = client.servers.get_by_name(name) if server is None: - return "Instance {} doesn't exist.".format(name) + return f"Instance {name} doesn't exist." __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -582,14 +583,14 @@ def destroy(name, call=None): if node["state"] == "running": stop(name, call="action", wait=False) if not wait_until(name, "off"): - return {"Error": "Unable to destroy {}, command timed out".format(name)} + return {"Error": f"Unable to destroy {name}, command timed out"} server.delete() __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -602,7 +603,7 @@ def destroy(name, call=None): __opts__, ) - return {"Destroyed": "{} was destroyed.".format(name)} + return {"Destroyed": f"{name} was destroyed."} def resize(name, kwargs, call=None): @@ -623,7 +624,7 @@ def resize(name, kwargs, call=None): client = _connect_client() server = client.servers.get_by_name(name) if server is None: - return "Instance {} doesn't exist.".format(name) + return f"Instance {name} doesn't exist." # Check the configuration size = kwargs.get("size", None) @@ -637,7 +638,7 @@ def resize(name, kwargs, call=None): __utils__["cloud.fire_event"]( "event", "resizing instance", - "salt/cloud/{}/resizing".format(name), + f"salt/cloud/{name}/resizing", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -647,17 +648,17 @@ def resize(name, kwargs, call=None): if node["state"] == "running": stop(name, call="action", wait=False) if not wait_until(name, "off"): - return {"Error": "Unable to resize {}, command timed out".format(name)} + return {"Error": f"Unable to resize {name}, command timed out"} server.change_type(server_type, kwargs.get("upgrade_disk", False)) __utils__["cloud.fire_event"]( "event", "resizing instance", - "salt/cloud/{}/resized".format(name), + f"salt/cloud/{name}/resized", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], ) - return {"Resized": "{} was resized.".format(name)} + return {"Resized": f"{name} was resized."} diff --git a/salt/cloud/clouds/joyent.py b/salt/cloud/clouds/joyent.py index 58b853b3f00..6326d202b58 100644 --- a/salt/cloud/clouds/joyent.py +++ b/salt/cloud/clouds/joyent.py @@ -161,9 +161,7 @@ def get_image(vm_): images[vm_image]["name"] = images[vm_image]["id"] return images[vm_image] - raise SaltCloudNotFound( - "The specified image, '{}', could not be found.".format(vm_image) - ) + raise SaltCloudNotFound(f"The specified image, '{vm_image}', could not be found.") def get_size(vm_): @@ -178,9 +176,7 @@ def get_size(vm_): if vm_size and str(vm_size) in sizes: return sizes[vm_size] - raise SaltCloudNotFound( - "The specified size, '{}', could not be found.".format(vm_size) - ) + raise SaltCloudNotFound(f"The specified size, '{vm_size}', could not be found.") def query_instance(vm_=None, call=None): @@ -375,11 +371,11 @@ def create_node(**kwargs): if metadata is not None: for key, value in metadata.items(): - create_data["metadata.{}".format(key)] = value + create_data[f"metadata.{key}"] = value if tag is not None: for key, value in tag.items(): - create_data["tag.{}".format(key)] = value + create_data[f"tag.{key}"] = value if firewall_enabled is not None: create_data["firewall_enabled"] = firewall_enabled @@ -419,7 +415,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -435,7 +431,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -532,7 +528,6 @@ def take_action( method="GET", location=DEFAULT_LOCATION, ): - """ take action call used by start,stop, reboot :param name: name given to the machine @@ -921,11 +916,11 @@ def avail_images(call=None): get_configured_provider(), __opts__, search_global=False, - default="{}{}/{}/images".format(DEFAULT_LOCATION, JOYENT_API_HOST_SUFFIX, user), + default=f"{DEFAULT_LOCATION}{JOYENT_API_HOST_SUFFIX}/{user}/images", ) if not img_url.startswith("http://") and not img_url.startswith("https://"): - img_url = "{}://{}".format(_get_proto(), img_url) + img_url = f"{_get_proto()}://{img_url}" rcode, data = query(command="my/images", method="GET") log.debug(data) @@ -1078,7 +1073,7 @@ def get_location_path( :param location: joyent data center location :return: url """ - return "{}://{}{}".format(_get_proto(), location, api_host_suffix) + return f"{_get_proto()}://{location}{api_host_suffix}" def query(action=None, command=None, args=None, method="GET", location=None, data=None): @@ -1152,7 +1147,7 @@ def query(action=None, command=None, args=None, method="GET", location=None, dat path += action if command: - path += "/{}".format(command) + path += f"/{command}" log.debug("User: '%s' on PATH: %s", user, path) @@ -1175,9 +1170,9 @@ def query(action=None, command=None, args=None, method="GET", location=None, dat signed = base64.b64encode(signed) user_arr = user.split("/") if len(user_arr) == 1: - keyid = "/{}/keys/{}".format(user_arr[0], ssh_keyname) + keyid = f"/{user_arr[0]}/keys/{ssh_keyname}" elif len(user_arr) == 2: - keyid = "/{}/users/{}/keys/{}".format(user_arr[0], user_arr[1], ssh_keyname) + keyid = f"/{user_arr[0]}/users/{user_arr[1]}/keys/{ssh_keyname}" else: log.error("Malformed user string") diff --git a/salt/cloud/clouds/libvirt.py b/salt/cloud/clouds/libvirt.py index 76f6f6daa26..366e1871e1f 100644 --- a/salt/cloud/clouds/libvirt.py +++ b/salt/cloud/clouds/libvirt.py @@ -258,7 +258,7 @@ def get_domain_ips(domain, ip_source): log.info("Exception polling address %s", error) return ips - for (name, val) in addresses.items(): + for name, val in addresses.items(): if val["addrs"]: for addr in val["addrs"]: tp = to_ip_addr_type(addr["type"]) @@ -332,7 +332,7 @@ def create(vm_): __utils__["cloud.fire_event"]( "event", "starting create", - "salt/cloud/{}/creating".format(name), + f"salt/cloud/{name}/creating", args=__utils__["cloud.filter_event"]( "creating", vm_, ["name", "profile", "provider", "driver"] ), @@ -345,7 +345,7 @@ def create(vm_): ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( - "The defined key_filename '{}' does not exist".format(key_filename) + f"The defined key_filename '{key_filename}' does not exist" ) vm_["key_filename"] = key_filename # wait_for_instance requires private_key @@ -374,7 +374,7 @@ def create(vm_): __utils__["cloud.fire_event"]( "event", "requesting instance", - "salt/cloud/{}/requesting".format(name), + f"salt/cloud/{name}/requesting", args={ "kwargs": __utils__["cloud.filter_event"]( "requesting", kwargs, list(kwargs) @@ -392,7 +392,7 @@ def create(vm_): description_elem = ElementTree.Element("description") domain_xml.insert(0, description_elem) description = domain_xml.find("./description") - description.text = "Cloned from {}".format(base) + description.text = f"Cloned from {base}" domain_xml.remove(domain_xml.find("./uuid")) for iface_xml in domain_xml.findall("./devices/interface"): @@ -426,9 +426,7 @@ def create(vm_): # see if there is a path element that needs rewriting if source_element and "path" in source_element.attrib: path = source_element.attrib["path"] - new_path = path.replace( - "/domain-{}/".format(base), "/domain-{}/".format(name) - ) + new_path = path.replace(f"/domain-{base}/", f"/domain-{name}/") log.debug("Rewriting agent socket path to %s", new_path) source_element.attrib["path"] = new_path @@ -471,7 +469,7 @@ def create(vm_): disk.find("./source").attrib["file"] = new_volume.path() else: raise SaltCloudExecutionFailure( - "Disk type '{}' not supported".format(disk_type) + f"Disk type '{disk_type}' not supported" ) clone_xml = salt.utils.stringutils.to_str(ElementTree.tostring(domain_xml)) @@ -515,7 +513,7 @@ def create(vm_): __utils__["cloud.fire_event"]( "event", "created instance", - "salt/cloud/{}/created".format(name), + f"salt/cloud/{name}/created", args=__utils__["cloud.filter_event"]( "created", vm_, ["name", "profile", "provider", "driver"] ), @@ -617,15 +615,15 @@ def destroy(name, call=None): pass if not found: - return "{} doesn't exist and can't be deleted".format(name) + return f"{name} doesn't exist and can't be deleted" if len(found) > 1: - return "{} doesn't identify a unique machine leaving things".format(name) + return f"{name} doesn't identify a unique machine leaving things" __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -636,7 +634,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -718,15 +716,15 @@ def find_pool_and_volume(conn, path): for v in sp.listAllVolumes(): if v.path() == path: return sp, v - raise SaltCloudNotFound("Could not find volume for path {}".format(path)) + raise SaltCloudNotFound(f"Could not find volume for path {path}") def generate_new_name(orig_name): if "." not in orig_name: - return "{}-{}".format(orig_name, uuid.uuid1()) + return f"{orig_name}-{uuid.uuid1()}" name, ext = orig_name.rsplit(".", 1) - return "{}-{}.{}".format(name, uuid.uuid1(), ext) + return f"{name}-{uuid.uuid1()}.{ext}" def get_domain_volumes(conn, domain): diff --git a/salt/cloud/clouds/lxc.py b/salt/cloud/clouds/lxc.py index da293dca66a..ced89e587bb 100644 --- a/salt/cloud/clouds/lxc.py +++ b/salt/cloud/clouds/lxc.py @@ -179,7 +179,7 @@ def _salt(fun, *args, **kw): ping_retries += 1 log.error("%s unreachable, retrying", target) if not ping: - raise SaltCloudSystemExit("Target {} unreachable".format(target)) + raise SaltCloudSystemExit(f"Target {target} unreachable") jid = conn.cmd_async(tgt=target, fun=fun, arg=args, kwarg=kw, **rkwargs) cret = conn.cmd( tgt=target, fun="saltutil.find_job", arg=[jid], timeout=10, **kwargs @@ -224,9 +224,7 @@ def _salt(fun, *args, **kw): time.sleep(0.5) try: if "is not available." in ret: - raise SaltCloudSystemExit( - "module/function {} is not available".format(fun) - ) + raise SaltCloudSystemExit(f"module/function {fun} is not available") except SaltCloudSystemExit: # pylint: disable=try-except-raise raise except TypeError: @@ -367,12 +365,12 @@ def destroy(vm_, call=None): ) if not get_configured_provider(): return - ret = {"comment": "{} was not found".format(vm_), "result": False} + ret = {"comment": f"{vm_} was not found", "result": False} if _salt("lxc.info", vm_, path=path): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(vm_), + f"salt/cloud/{vm_}/destroying", args={"name": vm_, "instance_id": vm_}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -380,11 +378,11 @@ def destroy(vm_, call=None): cret = _salt("lxc.destroy", vm_, stop=True, path=path) ret["result"] = cret["result"] if ret["result"]: - ret["comment"] = "{} was destroyed".format(vm_) + ret["comment"] = f"{vm_} was destroyed" __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(vm_), + f"salt/cloud/{vm_}/destroyed", args={"name": vm_, "instance_id": vm_}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -506,14 +504,14 @@ def get_configured_provider(vm_=None): matched = False # --list-images level if img_provider: - tgt = "provider: {}".format(img_provider) + tgt = f"provider: {img_provider}" if dalias == img_provider: data = get_provider(img_provider) matched = True # providers are set in configuration if not data and "profile" not in __opts__ and arg_providers: for name in arg_providers: - tgt = "provider: {}".format(name) + tgt = f"provider: {name}" if dalias == name: data = get_provider(name) if data: @@ -523,13 +521,13 @@ def get_configured_provider(vm_=None): elif "profile" in __opts__: curprof = __opts__["profile"] profs = __opts__["profiles"] - tgt = "profile: {}".format(curprof) + tgt = f"profile: {curprof}" if ( curprof in profs and profs[curprof]["provider"] == _get_active_provider_name() ): prov, cdriver = profs[curprof]["provider"].split(":") - tgt += " provider: {}".format(prov) + tgt += f" provider: {prov}" data = get_provider(prov) matched = True # fallback if we have only __active_provider_name__ diff --git a/salt/cloud/clouds/oneandone.py b/salt/cloud/clouds/oneandone.py index 7ddb50d3aba..6028e4f53e0 100644 --- a/salt/cloud/clouds/oneandone.py +++ b/salt/cloud/clouds/oneandone.py @@ -193,9 +193,7 @@ def get_size(vm_): if size: return size - raise SaltCloudNotFound( - "The specified size, '{}', could not be found.".format(vm_size) - ) + raise SaltCloudNotFound(f"The specified size, '{vm_size}', could not be found.") def get_image(vm_): @@ -211,9 +209,7 @@ def get_image(vm_): if vm_image and vm_image in (images[key]["id"], images[key]["name"]): return images[key] - raise SaltCloudNotFound( - "The specified image, '{}', could not be found.".format(vm_image) - ) + raise SaltCloudNotFound(f"The specified image, '{vm_image}', could not be found.") def avail_locations(conn=None, call=None): @@ -735,7 +731,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -749,7 +745,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -846,7 +842,7 @@ def get_key_filename(vm_): key_filename = os.path.expanduser(key_filename) if not os.path.isfile(key_filename): raise SaltCloudConfigError( - "The defined ssh_private_key '{}' does not exist".format(key_filename) + f"The defined ssh_private_key '{key_filename}' does not exist" ) return key_filename @@ -897,11 +893,9 @@ def _wait_for_completion(conn, wait_timeout, server_id): if server_state == "powered_on": return elif server_state == "failed": - raise Exception("Server creation failed for {}".format(server_id)) + raise Exception(f"Server creation failed for {server_id}") elif server_state in ("active", "enabled", "deploying", "configuring"): continue else: - raise Exception("Unknown server state {}".format(server_state)) - raise Exception( - "Timed out waiting for server create completion for {}".format(server_id) - ) + raise Exception(f"Unknown server state {server_state}") + raise Exception(f"Timed out waiting for server create completion for {server_id}") diff --git a/salt/cloud/clouds/opennebula.py b/salt/cloud/clouds/opennebula.py index 02602ca1e17..f3274a26b5a 100644 --- a/salt/cloud/clouds/opennebula.py +++ b/salt/cloud/clouds/opennebula.py @@ -76,7 +76,7 @@ from salt.exceptions import ( ) try: - import xmlrpc.client + import xmlrpc.client # nosec from lxml import etree @@ -85,7 +85,6 @@ except ImportError: HAS_XML_LIBS = False -# Get Logging Started log = logging.getLogger(__name__) __virtualname__ = "opennebula" @@ -558,7 +557,7 @@ def get_cluster_id(kwargs=None, call=None): try: ret = list_clusters()[name]["id"] except KeyError: - raise SaltCloudSystemExit("The cluster '{}' could not be found".format(name)) + raise SaltCloudSystemExit(f"The cluster '{name}' could not be found") return ret @@ -590,7 +589,7 @@ def get_datastore_id(kwargs=None, call=None): try: ret = list_datastores()[name]["id"] except KeyError: - raise SaltCloudSystemExit("The datastore '{}' could not be found.".format(name)) + raise SaltCloudSystemExit(f"The datastore '{name}' could not be found.") return ret @@ -622,7 +621,7 @@ def get_host_id(kwargs=None, call=None): try: ret = avail_locations()[name]["id"] except KeyError: - raise SaltCloudSystemExit("The host '{}' could not be found".format(name)) + raise SaltCloudSystemExit(f"The host '{name}' could not be found") return ret @@ -641,9 +640,7 @@ def get_image(vm_): for image in images: if vm_image in (images[image]["name"], images[image]["id"]): return images[image]["id"] - raise SaltCloudNotFound( - "The specified image, '{}', could not be found.".format(vm_image) - ) + raise SaltCloudNotFound(f"The specified image, '{vm_image}', could not be found.") def get_image_id(kwargs=None, call=None): @@ -673,7 +670,7 @@ def get_image_id(kwargs=None, call=None): try: ret = avail_images()[name]["id"] except KeyError: - raise SaltCloudSystemExit("The image '{}' could not be found".format(name)) + raise SaltCloudSystemExit(f"The image '{name}' could not be found") return ret @@ -697,7 +694,7 @@ def get_location(vm_): if vm_location in (locations[location]["name"], locations[location]["id"]): return locations[location]["id"] raise SaltCloudNotFound( - "The specified location, '{}', could not be found.".format(vm_location) + f"The specified location, '{vm_location}', could not be found." ) @@ -728,9 +725,7 @@ def get_secgroup_id(kwargs=None, call=None): try: ret = list_security_groups()[name]["id"] except KeyError: - raise SaltCloudSystemExit( - "The security group '{}' could not be found.".format(name) - ) + raise SaltCloudSystemExit(f"The security group '{name}' could not be found.") return ret @@ -761,7 +756,7 @@ def get_template_image(kwargs=None, call=None): ret = list_templates()[name]["template"]["disk"]["image"] except KeyError: raise SaltCloudSystemExit( - "The image for template '{}' could not be found.".format(name) + f"The image for template '{name}' could not be found." ) return ret @@ -794,7 +789,7 @@ def get_template_id(kwargs=None, call=None): try: ret = list_templates()[name]["id"] except KeyError: - raise SaltCloudSystemExit("The template '{}' could not be found.".format(name)) + raise SaltCloudSystemExit(f"The template '{name}' could not be found.") return ret @@ -816,7 +811,7 @@ def get_template(vm_): return list_templates()[vm_template]["id"] except KeyError: raise SaltCloudNotFound( - "The specified template, '{}', could not be found.".format(vm_template) + f"The specified template, '{vm_template}', could not be found." ) @@ -847,7 +842,7 @@ def get_vm_id(kwargs=None, call=None): try: ret = list_nodes()[name]["id"] except KeyError: - raise SaltCloudSystemExit("The VM '{}' could not be found.".format(name)) + raise SaltCloudSystemExit(f"The VM '{name}' could not be found.") return ret @@ -879,7 +874,7 @@ def get_vn_id(kwargs=None, call=None): try: ret = list_vns()[name]["id"] except KeyError: - raise SaltCloudSystemExit("The VN '{}' could not be found.".format(name)) + raise SaltCloudSystemExit(f"The VN '{name}' could not be found.") return ret @@ -895,9 +890,7 @@ def _get_device_template(disk, disk_info, template=None): def _require_disk_opts(*args): for arg in args: if arg not in disk_info: - raise SaltCloudSystemExit( - "The disk {} requires a {} argument".format(disk, arg) - ) + raise SaltCloudSystemExit(f"The disk {disk} requires a {arg} argument") _require_disk_opts("disk_type", "size") @@ -919,12 +912,12 @@ def _get_device_template(disk, disk_info, template=None): if disk_type == "volatile": _require_disk_opts("type") v_type = disk_info["type"] - temp = "DISK=[TYPE={}, SIZE={}]".format(v_type, size) + temp = f"DISK=[TYPE={v_type}, SIZE={size}]" if v_type == "fs": _require_disk_opts("format") format = disk_info["format"] - temp = "DISK=[TYPE={}, SIZE={}, FORMAT={}]".format(v_type, size, format) + temp = f"DISK=[TYPE={v_type}, SIZE={size}, FORMAT={format}]" return temp # TODO add persistant disk_type @@ -1101,7 +1094,7 @@ def create(vm_): ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( - "The defined key_filename '{}' does not exist".format(key_filename) + f"The defined key_filename '{key_filename}' does not exist" ) if fqdn: @@ -1178,7 +1171,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], ) @@ -1192,7 +1185,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], ) @@ -4474,7 +4467,7 @@ def _get_xml(xml_str): except etree.XMLSyntaxError as err: # opennebula returned invalid XML, which could be an error message, so # log it - raise SaltCloudSystemExit("opennebula returned: {}".format(xml_str)) + raise SaltCloudSystemExit(f"opennebula returned: {xml_str}") return xml_data diff --git a/salt/cloud/clouds/openstack.py b/salt/cloud/clouds/openstack.py index 0a8b8d7e1b2..8dfbf1c341c 100644 --- a/salt/cloud/clouds/openstack.py +++ b/salt/cloud/clouds/openstack.py @@ -737,7 +737,7 @@ def create(vm_): ) if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( - "The defined ssh_key_file '{}' does not exist".format(key_filename) + f"The defined ssh_key_file '{key_filename}' does not exist" ) vm_["key_filename"] = key_filename @@ -846,7 +846,7 @@ def destroy(name, conn=None, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -863,7 +863,7 @@ def destroy(name, conn=None, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], diff --git a/salt/cloud/clouds/packet.py b/salt/cloud/clouds/packet.py index 1c6217bf4f7..0e1b65bed0c 100644 --- a/salt/cloud/clouds/packet.py +++ b/salt/cloud/clouds/packet.py @@ -242,9 +242,7 @@ def _wait_for_status(status_type, object_id, status=None, timeout=500, quiet=Tru manager = packet.Manager(auth_token=vm_["token"]) for i in range(0, iterations): - get_object = getattr( - manager, "get_{status_type}".format(status_type=status_type) - ) + get_object = getattr(manager, f"get_{status_type}") obj = get_object(object_id) if obj.state == status: @@ -340,7 +338,7 @@ def create(vm_): __utils__["cloud.fire_event"]( "event", "starting create", - "salt/cloud/{}/creating".format(name), + f"salt/cloud/{name}/creating", args=__utils__["cloud.filter_event"]( "creating", vm_, ["name", "profile", "provider", "driver"] ), @@ -413,7 +411,7 @@ def create(vm_): volume = manager.create_volume( vm_["project_id"], - "{}_storage".format(name), + f"{name}_storage", vm_.get("storage_tier"), vm_.get("storage_size"), vm_.get("location"), @@ -441,7 +439,7 @@ def create(vm_): __utils__["cloud.fire_event"]( "event", "created instance", - "salt/cloud/{}/created".format(name), + f"salt/cloud/{name}/created", args=__utils__["cloud.filter_event"]( "created", vm_, ["name", "profile", "provider", "driver"] ), @@ -580,7 +578,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -606,7 +604,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], diff --git a/salt/cloud/clouds/parallels.py b/salt/cloud/clouds/parallels.py index 4b65ddd9c8a..a5e6ca0fff7 100644 --- a/salt/cloud/clouds/parallels.py +++ b/salt/cloud/clouds/parallels.py @@ -310,11 +310,11 @@ def create(vm_): name = vm_["name"] if not wait_until(name, "CREATED"): - return {"Error": "Unable to start {}, command timed out".format(name)} + return {"Error": f"Unable to start {name}, command timed out"} start(vm_["name"], call="action") if not wait_until(name, "STARTED"): - return {"Error": "Unable to start {}, command timed out".format(name)} + return {"Error": f"Unable to start {name}, command timed out"} def __query_node_data(vm_name): data = show_instance(vm_name, call="action") @@ -391,7 +391,7 @@ def query(action=None, command=None, args=None, method="GET", data=None): path += action if command: - path += "/{}".format(command) + path += f"/{command}" if not type(args, dict): args = {} @@ -404,7 +404,7 @@ def query(action=None, command=None, args=None, method="GET", data=None): if args: params = urllib.parse.urlencode(args) - req = urllib.request.Request(url="{}?{}".format(path, params), **kwargs) + req = urllib.request.Request(url=f"{path}?{params}", **kwargs) else: req = urllib.request.Request(url=path, **kwargs) @@ -526,7 +526,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -536,7 +536,7 @@ def destroy(name, call=None): if node["state"] == "STARTED": stop(name, call="action") if not wait_until(name, "STOPPED"): - return {"Error": "Unable to destroy {}, command timed out".format(name)} + return {"Error": f"Unable to destroy {name}, command timed out"} data = query(action="ve", command=name, method="DELETE") @@ -546,7 +546,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -557,7 +557,7 @@ def destroy(name, call=None): name, _get_active_provider_name().split(":")[0], __opts__ ) - return {"Destroyed": "{} was destroyed.".format(name)} + return {"Destroyed": f"{name} was destroyed."} def start(name, call=None): @@ -575,12 +575,12 @@ def start(name, call=None): "The show_instance action must be called with -a or --action." ) - data = query(action="ve", command="{}/start".format(name), method="PUT") + data = query(action="ve", command=f"{name}/start", method="PUT") if "error" in data: return data["error"] - return {"Started": "{} was started.".format(name)} + return {"Started": f"{name} was started."} def stop(name, call=None): @@ -598,9 +598,9 @@ def stop(name, call=None): "The show_instance action must be called with -a or --action." ) - data = query(action="ve", command="{}/stop".format(name), method="PUT") + data = query(action="ve", command=f"{name}/stop", method="PUT") if "error" in data: return data["error"] - return {"Stopped": "{} was stopped.".format(name)} + return {"Stopped": f"{name} was stopped."} diff --git a/salt/cloud/clouds/profitbricks.py b/salt/cloud/clouds/profitbricks.py index 72f1b362551..a8a9351a717 100644 --- a/salt/cloud/clouds/profitbricks.py +++ b/salt/cloud/clouds/profitbricks.py @@ -328,9 +328,7 @@ def get_size(vm_): combinations = (str(sizes[size]["id"]), str(size)) if vm_size and str(vm_size) in combinations: return sizes[size] - raise SaltCloudNotFound( - "The specified size, '{}', could not be found.".format(vm_size) - ) + raise SaltCloudNotFound(f"The specified size, '{vm_size}', could not be found.") def get_datacenter_id(): @@ -415,7 +413,7 @@ def get_datacenter(conn): return item raise SaltCloudNotFound( - "The specified datacenter '{}' could not be found.".format(datacenter_id) + f"The specified datacenter '{datacenter_id}' could not be found." ) @@ -488,9 +486,7 @@ def get_image(vm_): if vm_image and vm_image in (images[key]["id"], images[key]["name"]): return images[key] - raise SaltCloudNotFound( - "The specified image, '{}', could not be found.".format(vm_image) - ) + raise SaltCloudNotFound(f"The specified image, '{vm_image}', could not be found.") def list_datacenters(conn=None, call=None): @@ -725,7 +721,7 @@ def get_public_keys(vm_): key_filename = os.path.expanduser(key_filename) if not os.path.isfile(key_filename): raise SaltCloudConfigError( - "The defined ssh_public_key '{}' does not exist".format(key_filename) + f"The defined ssh_public_key '{key_filename}' does not exist" ) ssh_keys = [] with salt.utils.files.fopen(key_filename) as rfh: @@ -746,7 +742,7 @@ def get_key_filename(vm_): key_filename = os.path.expanduser(key_filename) if not os.path.isfile(key_filename): raise SaltCloudConfigError( - "The defined ssh_private_key '{}' does not exist".format(key_filename) + f"The defined ssh_private_key '{key_filename}' does not exist" ) return key_filename @@ -941,7 +937,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -972,7 +968,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -1142,9 +1138,7 @@ def _get_data_volumes(vm_): # Verify the required 'disk_size' property is present in the cloud # profile config if "disk_size" not in volumes[key].keys(): - raise SaltCloudConfigError( - "The volume '{}' is missing 'disk_size'".format(key) - ) + raise SaltCloudConfigError(f"The volume '{key}' is missing 'disk_size'") # Use 'HDD' if no 'disk_type' property is present in cloud profile if "disk_type" not in volumes[key].keys(): volumes[key]["disk_type"] = "HDD" @@ -1187,7 +1181,7 @@ def _get_firewall_rules(firewall_rules): # profile config if "protocol" not in firewall_rules[key].keys(): raise SaltCloudConfigError( - "The firewall rule '{}' is missing 'protocol'".format(key) + f"The firewall rule '{key}' is missing 'protocol'" ) ret.append( FirewallRule( diff --git a/salt/cloud/clouds/qingcloud.py b/salt/cloud/clouds/qingcloud.py index b684f6bc9d8..5cfa8a19930 100644 --- a/salt/cloud/clouds/qingcloud.py +++ b/salt/cloud/clouds/qingcloud.py @@ -108,7 +108,7 @@ def _compute_signature(parameters, access_key_secret, method, path): """ parameters["signature_method"] = "HmacSHA256" - string_to_sign = "{}\n{}\n".format(method.upper(), path) + string_to_sign = f"{method.upper()}\n{path}\n" keys = sorted(parameters.keys()) pairs = [] @@ -166,9 +166,9 @@ def query(params=None): for sk, sv in value[i - 1].items(): if isinstance(sv, dict) or isinstance(sv, list): sv = salt.utils.json.dumps(sv, separators=(",", ":")) - real_parameters["{}.{}.{}".format(key, i, sk)] = sv + real_parameters[f"{key}.{i}.{sk}"] = sv else: - real_parameters["{}.{}".format(key, i)] = value[i - 1] + real_parameters[f"{key}.{i}"] = value[i - 1] else: real_parameters[key] = value @@ -252,7 +252,7 @@ def _get_location(vm_=None): return vm_location raise SaltCloudNotFound( - "The specified location, '{}', could not be found.".format(vm_location) + f"The specified location, '{vm_location}', could not be found." ) @@ -320,9 +320,7 @@ def _get_image(vm_): if vm_image in images: return vm_image - raise SaltCloudNotFound( - "The specified image, '{}', could not be found.".format(vm_image) - ) + raise SaltCloudNotFound(f"The specified image, '{vm_image}', could not be found.") def show_image(kwargs, call=None): @@ -442,9 +440,7 @@ def _get_size(vm_): if vm_size in sizes.keys(): return vm_size - raise SaltCloudNotFound( - "The specified size, '{}', could not be found.".format(vm_size) - ) + raise SaltCloudNotFound(f"The specified size, '{vm_size}', could not be found.") def _show_normalized_node(full_node): @@ -626,7 +622,7 @@ def show_instance(instance_id, call=None, kwargs=None): if items["total_count"] == 0: raise SaltCloudNotFound( - "The specified instance, '{}', could not be found.".format(instance_id) + f"The specified instance, '{instance_id}', could not be found." ) full_node = items["instance_set"][0] @@ -878,7 +874,7 @@ def destroy(instance_id, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -894,7 +890,7 @@ def destroy(instance_id, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], diff --git a/salt/cloud/clouds/saltify.py b/salt/cloud/clouds/saltify.py index 89082ddbef5..d3430935fc0 100644 --- a/salt/cloud/clouds/saltify.py +++ b/salt/cloud/clouds/saltify.py @@ -289,7 +289,7 @@ def create(vm_): if ssh_host: log.info("trying to ping %s", ssh_host) count = "n" if salt.utils.platform.is_windows() else "c" - cmd = "ping -{} 1 {}".format(count, ssh_host) + cmd = f"ping -{count} 1 {ssh_host}" good_ping = local.cmd(wol_host, "cmd.retcode", [cmd]) == 0 if good_ping: log.info("successful ping.") @@ -358,7 +358,7 @@ def _verify(vm_): log.debug("Testing SMB protocol for %s", vm_["name"]) if __utils__["smb.get_conn"](**kwargs) is False: return False - except (smbSessionError) as exc: + except smbSessionError as exc: log.error("Exception: %s", exc) return False @@ -464,7 +464,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=opts["sock_dir"], transport=opts["transport"], @@ -510,13 +510,13 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=opts["sock_dir"], transport=opts["transport"], ) - return {"Destroyed": "{} was destroyed.".format(name)} + return {"Destroyed": f"{name} was destroyed."} def reboot(name, call=None): diff --git a/salt/cloud/clouds/scaleway.py b/salt/cloud/clouds/scaleway.py index 9b412181c01..d261e50360f 100644 --- a/salt/cloud/clouds/scaleway.py +++ b/salt/cloud/clouds/scaleway.py @@ -160,7 +160,7 @@ def get_image(server_): if server_image in (images[image]["name"], images[image]["id"]): return images[image]["id"] raise SaltCloudNotFound( - "The specified image, '{}', could not be found.".format(server_image) + f"The specified image, '{server_image}', could not be found." ) @@ -225,7 +225,7 @@ def create(server_): if key_filename is not None and not os.path.isfile(key_filename): raise SaltCloudConfigError( - "The defined key_filename '{}' does not exist".format(key_filename) + f"The defined key_filename '{key_filename}' does not exist" ) ssh_password = config.get_cloud_config_value("ssh_password", server_, __opts__) @@ -346,10 +346,10 @@ def query( ) ) - path = "{}/{}/".format(base_path, method) + path = f"{base_path}/{method}/" if server_id: - path += "{}/".format(server_id) + path += f"{server_id}/" if command: path += command @@ -439,7 +439,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -457,7 +457,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], diff --git a/salt/cloud/clouds/softlayer.py b/salt/cloud/clouds/softlayer.py index 5c6892227ef..c0f282f84ed 100644 --- a/salt/cloud/clouds/softlayer.py +++ b/salt/cloud/clouds/softlayer.py @@ -269,7 +269,7 @@ def create(vm_): __utils__["cloud.fire_event"]( "event", "starting create", - "salt/cloud/{}/creating".format(name), + f"salt/cloud/{name}/creating", args=__utils__["cloud.filter_event"]( "creating", vm_, ["name", "profile", "provider", "driver"] ), @@ -395,7 +395,7 @@ def create(vm_): __utils__["cloud.fire_event"]( "event", "requesting instance", - "salt/cloud/{}/requesting".format(name), + f"salt/cloud/{name}/requesting", args={ "kwargs": __utils__["cloud.filter_event"]( "requesting", kwargs, list(kwargs) @@ -513,7 +513,7 @@ def create(vm_): __utils__["cloud.fire_event"]( "event", "created instance", - "salt/cloud/{}/created".format(name), + f"salt/cloud/{name}/created", args=__utils__["cloud.filter_event"]( "created", vm_, ["name", "profile", "provider", "driver"] ), @@ -620,7 +620,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -633,7 +633,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], diff --git a/salt/cloud/clouds/softlayer_hw.py b/salt/cloud/clouds/softlayer_hw.py index 2cfd2fbf38c..f8a92f8a8a8 100644 --- a/salt/cloud/clouds/softlayer_hw.py +++ b/salt/cloud/clouds/softlayer_hw.py @@ -241,7 +241,7 @@ def create(vm_): __utils__["cloud.fire_event"]( "event", "starting create", - "salt/cloud/{}/creating".format(name), + f"salt/cloud/{name}/creating", args=__utils__["cloud.filter_event"]( "creating", vm_, ["name", "profile", "provider", "driver"] ), @@ -311,7 +311,7 @@ def create(vm_): __utils__["cloud.fire_event"]( "event", "requesting instance", - "salt/cloud/{}/requesting".format(name), + f"salt/cloud/{name}/requesting", args={ "kwargs": __utils__["cloud.filter_event"]( "requesting", kwargs, list(kwargs) @@ -406,7 +406,7 @@ def create(vm_): __utils__["cloud.fire_event"]( "event", "created instance", - "salt/cloud/{}/created".format(name), + f"salt/cloud/{name}/created", args=__utils__["cloud.filter_event"]( "created", vm_, ["name", "profile", "provider", "driver"] ), @@ -514,7 +514,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -535,7 +535,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], diff --git a/salt/cloud/clouds/tencentcloud.py b/salt/cloud/clouds/tencentcloud.py index b2903b9380a..374f4a3247b 100644 --- a/salt/cloud/clouds/tencentcloud.py +++ b/salt/cloud/clouds/tencentcloud.py @@ -123,7 +123,7 @@ def get_provider_client(name=None): elif name == "vpc_client": client = vpc_client.VpcClient(crd, region, cpf) else: - raise SaltCloudSystemExit("Client name {} is not supported".format(name)) + raise SaltCloudSystemExit(f"Client name {name} is not supported") return client @@ -206,11 +206,11 @@ def avail_sizes(call=None): ret[typeConfig.InstanceType] = { "Zone": typeConfig.Zone, "InstanceFamily": typeConfig.InstanceFamily, - "Memory": "{}GB".format(typeConfig.Memory), - "CPU": "{}-Core".format(typeConfig.CPU), + "Memory": f"{typeConfig.Memory}GB", + "CPU": f"{typeConfig.CPU}-Core", } if typeConfig.GPU: - ret[typeConfig.InstanceType]["GPU"] = "{}-Core".format(typeConfig.GPU) + ret[typeConfig.InstanceType]["GPU"] = f"{typeConfig.GPU}-Core" return ret @@ -714,7 +714,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -730,7 +730,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -782,9 +782,7 @@ def show_image(kwargs, call=None): resp = client.DescribeImages(req) if not resp.ImageSet: - raise SaltCloudNotFound( - "The specified image '{}' could not be found.".format(image) - ) + raise SaltCloudNotFound(f"The specified image '{image}' could not be found.") ret = {} for image in resp.ImageSet: @@ -794,7 +792,7 @@ def show_image(kwargs, call=None): "ImageSource": image.ImageSource, "Platform": image.Platform, "Architecture": image.Architecture, - "ImageSize": "{}GB".format(image.ImageSize), + "ImageSize": f"{image.ImageSize}GB", "ImageState": image.ImageState, } @@ -893,7 +891,7 @@ def _get_node(name): ) time.sleep(0.5) - raise SaltCloudNotFound("Failed to get instance info {}".format(name)) + raise SaltCloudNotFound(f"Failed to get instance info {name}") def _get_nodes(): @@ -940,7 +938,7 @@ def _get_images(image_type): "ImageSource": image.ImageSource, "Platform": image.Platform, "Architecture": image.Architecture, - "ImageSize": "{}GB".format(image.ImageSize), + "ImageSize": f"{image.ImageSize}GB", } return ret @@ -958,9 +956,7 @@ def __get_image(vm_): if vm_image in images: return vm_image - raise SaltCloudNotFound( - "The specified image '{}' could not be found.".format(vm_image) - ) + raise SaltCloudNotFound(f"The specified image '{vm_image}' could not be found.") def __get_size(vm_): @@ -975,9 +971,7 @@ def __get_size(vm_): if vm_size in sizes: return vm_size - raise SaltCloudNotFound( - "The specified size '{}' could not be found.".format(vm_size) - ) + raise SaltCloudNotFound(f"The specified size '{vm_size}' could not be found.") def __get_securitygroups(vm_): diff --git a/salt/cloud/clouds/vagrant.py b/salt/cloud/clouds/vagrant.py index 836ea44badd..ac9119b70d9 100644 --- a/salt/cloud/clouds/vagrant.py +++ b/salt/cloud/clouds/vagrant.py @@ -256,7 +256,7 @@ def create(vm_): vm_.setdefault("ssh_port", ret["ssh_port"]) except (KeyError, TypeError): raise SaltInvocationError( - "Insufficient SSH addressing information for {}".format(name) + f"Insufficient SSH addressing information for {name}" ) log.info( @@ -300,7 +300,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=opts["sock_dir"], transport=opts["transport"], @@ -317,7 +317,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=opts["sock_dir"], transport=opts["transport"], @@ -328,11 +328,11 @@ def destroy(name, call=None): name, _get_active_provider_name().split(":")[0], opts ) - return {"Destroyed": "{} was destroyed.".format(name)} + return {"Destroyed": f"{name} was destroyed."} else: - return {"Error": "Error destroying {}".format(name)} + return {"Error": f"Error destroying {name}"} else: - return {"Error": "No response from {}. Cannot destroy.".format(name)} + return {"Error": f"No response from {name}. Cannot destroy."} # noinspection PyTypeChecker diff --git a/salt/cloud/clouds/virtualbox.py b/salt/cloud/clouds/virtualbox.py index 58b8ecd0242..0f7c169cef6 100644 --- a/salt/cloud/clouds/virtualbox.py +++ b/salt/cloud/clouds/virtualbox.py @@ -368,12 +368,12 @@ def destroy(name, call=None): """ log.info("Attempting to delete instance %s", name) if not vb_machine_exists(name): - return "{} doesn't exist and can't be deleted".format(name) + return f"{name} doesn't exist and can't be deleted" __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -384,7 +384,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], diff --git a/salt/cloud/clouds/vmware.py b/salt/cloud/clouds/vmware.py index 68fa1c821ab..2a9c0563b87 100644 --- a/salt/cloud/clouds/vmware.py +++ b/salt/cloud/clouds/vmware.py @@ -306,7 +306,7 @@ def _add_new_hard_disk_helper( disk_spec.device.key = random_key disk_spec.device.deviceInfo = vim.Description() disk_spec.device.deviceInfo.label = disk_label - disk_spec.device.deviceInfo.summary = "{} GB".format(size_gb) + disk_spec.device.deviceInfo.summary = f"{size_gb} GB" disk_spec.device.backing = vim.vm.device.VirtualDisk.FlatVer2BackingInfo() disk_spec.device.backing.thinProvisioned = thin_provision @@ -662,7 +662,7 @@ def _set_cd_or_dvd_backing_type(drive, device_type, mode, iso_path): if datastore_ref: drive.backing.datastore = datastore_ref - drive.deviceInfo.summary = "ISO {}".format(iso_path) + drive.deviceInfo.summary = f"ISO {iso_path}" elif device_type == "client_device": if mode == "passthrough": @@ -917,7 +917,7 @@ def _manage_devices(devices, vm=None, container_ref=None, new_vm_name=None): else None ) if bus_sharing and bus_sharing in ["virtual", "physical", "no"]: - bus_sharing = "{}Sharing".format(bus_sharing) + bus_sharing = f"{bus_sharing}Sharing" if bus_sharing != device.sharedBus: # Only edit the SCSI controller if bus_sharing is different scsi_spec = _edit_existing_scsi_controller( @@ -1327,7 +1327,7 @@ def _format_instance_info_select(vm, selection): if "size" in selection: cpu = defaultto(vm, "config.hardware.numCPU") ram = "{} MB".format(defaultto(vm, "config.hardware.memoryMB")) - vm_select_info["size"] = "cpu: {}\nram: {}".format(cpu, ram) + vm_select_info["size"] = f"cpu: {cpu}\nram: {ram}" vm_select_info["size_dict"] = { "cpu": cpu, "memory": ram, @@ -1454,15 +1454,21 @@ def _format_instance_info_select(vm, selection): if "storage" in selection: storage_full_info = { - "committed": int(vm["summary.storage.committed"]) - if "summary.storage.committed" in vm - else "N/A", - "uncommitted": int(vm["summary.storage.uncommitted"]) - if "summary.storage.uncommitted" in vm - else "N/A", - "unshared": int(vm["summary.storage.unshared"]) - if "summary.storage.unshared" in vm - else "N/A", + "committed": ( + int(vm["summary.storage.committed"]) + if "summary.storage.committed" in vm + else "N/A" + ), + "uncommitted": ( + int(vm["summary.storage.uncommitted"]) + if "summary.storage.uncommitted" in vm + else "N/A" + ), + "unshared": ( + int(vm["summary.storage.unshared"]) + if "summary.storage.unshared" in vm + else "N/A" + ), } vm_select_info["storage"] = storage_full_info @@ -1553,15 +1559,21 @@ def _format_instance_info(vm): ] = device.backing.fileName storage_full_info = { - "committed": int(vm["summary.storage.committed"]) - if "summary.storage.committed" in vm - else "N/A", - "uncommitted": int(vm["summary.storage.uncommitted"]) - if "summary.storage.uncommitted" in vm - else "N/A", - "unshared": int(vm["summary.storage.unshared"]) - if "summary.storage.unshared" in vm - else "N/A", + "committed": ( + int(vm["summary.storage.committed"]) + if "summary.storage.committed" in vm + else "N/A" + ), + "uncommitted": ( + int(vm["summary.storage.uncommitted"]) + if "summary.storage.uncommitted" in vm + else "N/A" + ), + "unshared": ( + int(vm["summary.storage.unshared"]) + if "summary.storage.unshared" in vm + else "N/A" + ), } file_full_info = {} @@ -1593,14 +1605,18 @@ def _format_instance_info(vm): ) vm_full_info = { "id": str(vm["name"]), - "image": "{} (Detected)".format(vm["config.guestFullName"]) - if "config.guestFullName" in vm - else "N/A", - "size": "cpu: {}\nram: {}".format(cpu, ram), + "image": ( + "{} (Detected)".format(vm["config.guestFullName"]) + if "config.guestFullName" in vm + else "N/A" + ), + "size": f"cpu: {cpu}\nram: {ram}", "size_dict": {"cpu": cpu, "memory": ram}, - "state": str(vm["summary.runtime.powerState"]) - if "summary.runtime.powerState" in vm - else "N/A", + "state": ( + str(vm["summary.runtime.powerState"]) + if "summary.runtime.powerState" in vm + else "N/A" + ), "private_ips": ip_addresses, "public_ips": [], "devices": device_full_info, @@ -1610,12 +1626,14 @@ def _format_instance_info(vm): "hostname": str(vm["object"].guest.hostName), "mac_addresses": device_mac_addresses, "networks": network_full_info, - "path": str(vm["config.files.vmPathName"]) - if "config.files.vmPathName" in vm - else "N/A", - "tools_status": str(vm["guest.toolsStatus"]) - if "guest.toolsStatus" in vm - else "N/A", + "path": ( + str(vm["config.files.vmPathName"]) + if "config.files.vmPathName" in vm + else "N/A" + ), + "tools_status": ( + str(vm["guest.toolsStatus"]) if "guest.toolsStatus" in vm else "N/A" + ), } return vm_full_info @@ -1624,7 +1642,7 @@ def _format_instance_info(vm): def _get_snapshots(snapshot_list, current_snapshot=None, parent_snapshot_path=""): snapshots = {} for snapshot in snapshot_list: - snapshot_path = "{}/{}".format(parent_snapshot_path, snapshot.name) + snapshot_path = f"{parent_snapshot_path}/{snapshot.name}" snapshots[snapshot_path] = { "name": snapshot.name, "description": snapshot.description, @@ -1759,7 +1777,7 @@ def test_vcenter_connection(kwargs=None, call=None): # Get the service instance object _get_si() except Exception as exc: # pylint: disable=broad-except - return "failed to connect: {}".format(exc) + return f"failed to connect: {exc}" return "connection successful" @@ -2004,14 +2022,18 @@ def list_nodes(kwargs=None, call=None): ) vm_info = { "id": vm["name"], - "image": "{} (Detected)".format(vm["config.guestFullName"]) - if "config.guestFullName" in vm - else "N/A", - "size": "cpu: {}\nram: {}".format(cpu, ram), + "image": ( + "{} (Detected)".format(vm["config.guestFullName"]) + if "config.guestFullName" in vm + else "N/A" + ), + "size": f"cpu: {cpu}\nram: {ram}", "size_dict": {"cpu": cpu, "memory": ram}, - "state": str(vm["summary.runtime.powerState"]) - if "summary.runtime.powerState" in vm - else "N/A", + "state": ( + str(vm["summary.runtime.powerState"]) + if "summary.runtime.powerState" in vm + else "N/A" + ), "private_ips": [vm["guest.ipAddress"]] if "guest.ipAddress" in vm else [], "public_ips": [], } @@ -2242,15 +2264,21 @@ def avail_images(call=None): if "config.template" in vm and vm["config.template"]: templates[vm["name"]] = { "name": vm["name"], - "guest_fullname": vm["config.guestFullName"] - if "config.guestFullName" in vm - else "N/A", - "cpus": vm["config.hardware.numCPU"] - if "config.hardware.numCPU" in vm - else "N/A", - "ram": vm["config.hardware.memoryMB"] - if "config.hardware.memoryMB" in vm - else "N/A", + "guest_fullname": ( + vm["config.guestFullName"] + if "config.guestFullName" in vm + else "N/A" + ), + "cpus": ( + vm["config.hardware.numCPU"] + if "config.hardware.numCPU" in vm + else "N/A" + ), + "ram": ( + vm["config.hardware.memoryMB"] + if "config.hardware.memoryMB" in vm + else "N/A" + ), } return templates @@ -2656,7 +2684,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -2702,7 +2730,7 @@ def destroy(name, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -3107,7 +3135,7 @@ def create(vm_): ) if not datastore_ref: raise SaltCloudSystemExit( - "Specified datastore: '{}' does not exist".format(datastore) + f"Specified datastore: '{datastore}' does not exist" ) if host: @@ -3123,7 +3151,7 @@ def create(vm_): # If the hardware version is specified and if it is different from the current # hardware version, then schedule a hardware version upgrade if hardware_version and object_ref is not None: - hardware_version = "vmx-{:02}".format(hardware_version) + hardware_version = f"vmx-{hardware_version:02}" if hardware_version != object_ref.config.version: log.debug( "Scheduling hardware version upgrade from %s to %s", @@ -3153,7 +3181,7 @@ def create(vm_): elif memory_unit.lower() == "gb": memory_mb = int(float(memory_num) * 1024.0) else: - err_msg = "Invalid memory type specified: '{}'".format(memory_unit) + err_msg = f"Invalid memory type specified: '{memory_unit}'" log.error(err_msg) return {"Error": err_msg} except (TypeError, ValueError): @@ -3601,7 +3629,7 @@ def rescan_hba(kwargs=None, call=None): if hba: log.info("Rescanning HBA %s on host %s", hba, host_name) host_ref.configManager.storageSystem.RescanHba(hba) - ret = "rescanned HBA {}".format(hba) + ret = f"rescanned HBA {hba}" else: log.info("Rescanning all HBAs on host %s", host_name) host_ref.configManager.storageSystem.RescanAllHba() @@ -3879,7 +3907,7 @@ def list_hbas(kwargs=None, call=None): if hba_type and hba_type not in ["parallel", "block", "iscsi", "fibre"]: raise SaltCloudSystemExit( - "Specified hba type {} currently not supported.".format(hba_type) + f"Specified hba type {hba_type} currently not supported." ) host_list = salt.utils.vmware.get_mors_with_properties( @@ -4252,10 +4280,10 @@ def revert_to_snapshot(name, kwargs=None, call=None): task = vm_ref.RevertToCurrentSnapshot(suppressPowerOn=suppress_power_on) else: log.debug("Reverting VM %s to snapshot %s", name, snapshot_name) - msg = "reverted to snapshot {}".format(snapshot_name) + msg = f"reverted to snapshot {snapshot_name}" snapshot_ref = _get_snapshot_ref_by_name(vm_ref, snapshot_name) if snapshot_ref is None: - return "specified snapshot '{}' does not exist".format(snapshot_name) + return f"specified snapshot '{snapshot_name}' does not exist" task = snapshot_ref.snapshot.Revert(suppressPowerOn=suppress_power_on) salt.utils.vmware.wait_for_task(task, name, "revert to snapshot", 5, "info") @@ -4393,7 +4421,7 @@ def convert_to_template(name, kwargs=None, call=None): vm_ref = salt.utils.vmware.get_mor_by_property(_get_si(), vim.VirtualMachine, name) if vm_ref.config.template: - raise SaltCloudSystemExit("{} already a template".format(name)) + raise SaltCloudSystemExit(f"{name} already a template") try: vm_ref.MarkAsTemplate() @@ -4407,7 +4435,7 @@ def convert_to_template(name, kwargs=None, call=None): ) return "failed to convert to teamplate" - return "{} converted to template".format(name) + return f"{name} converted to template" def add_host(kwargs=None, call=None): @@ -4529,7 +4557,7 @@ def add_host(kwargs=None, call=None): ("echo", "-n"), stdout=subprocess.PIPE, stderr=subprocess.PIPE ) p2 = subprocess.Popen( - ("openssl", "s_client", "-connect", "{}:443".format(host_name)), + ("openssl", "s_client", "-connect", f"{host_name}:443"), stdin=p1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE, @@ -4559,12 +4587,12 @@ def add_host(kwargs=None, call=None): try: if cluster_name: task = cluster_ref.AddHost(spec=spec, asConnected=True) - ret = "added host system to cluster {}".format(cluster_name) + ret = f"added host system to cluster {cluster_name}" if datacenter_name: task = datacenter_ref.hostFolder.AddStandaloneHost( spec=spec, addConnected=True ) - ret = "added host system to datacenter {}".format(datacenter_name) + ret = f"added host system to datacenter {datacenter_name}" salt.utils.vmware.wait_for_task(task, host_name, "add host system", 5, "info") except Exception as exc: # pylint: disable=broad-except if isinstance(exc, vim.fault.SSLVerifyFault): diff --git a/salt/cloud/clouds/xen.py b/salt/cloud/clouds/xen.py index 878f74f2a7a..810ff460227 100644 --- a/salt/cloud/clouds/xen.py +++ b/salt/cloud/clouds/xen.py @@ -124,7 +124,7 @@ def _get_session(): Get a connection to the XenServer host """ api_version = "1.0" - originator = "salt_cloud_{}_driver".format(__virtualname__) + originator = f"salt_cloud_{__virtualname__}_driver" url = config.get_cloud_config_value( "url", get_configured_provider(), __opts__, search_global=False ) @@ -550,7 +550,7 @@ def create(vm_): __utils__["cloud.fire_event"]( "event", "starting create", - "salt/cloud/{}/creating".format(name), + f"salt/cloud/{name}/creating", args={"name": name, "profile": vm_["profile"], "provider": vm_["driver"]}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -580,7 +580,7 @@ def create(vm_): __utils__["cloud.fire_event"]( "event", "requesting instance", - "salt/cloud/{}/requesting".format(name), + f"salt/cloud/{name}/requesting", sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], ) @@ -623,7 +623,7 @@ def create(vm_): __utils__["cloud.fire_event"]( "event", "created instance", - "salt/cloud/{}/created".format(name), + f"salt/cloud/{name}/created", args={"name": name, "profile": vm_["profile"], "provider": vm_["driver"]}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -923,7 +923,7 @@ def reboot(name, call=None, session=None): _run_async_task(task, session) return show_instance(name) else: - return "{} is not running to be rebooted".format(name) + return f"{name} is not running to be rebooted" def _get_vm(name=None, session=None): @@ -984,7 +984,7 @@ def destroy(name=None, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -1009,7 +1009,7 @@ def destroy(name=None, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -1134,7 +1134,7 @@ def vif_list(name, call=None, kwargs=None): x = 0 for vif in vifs: vif_record = session.xenapi.VIF.get_record(vif) - data["vif-{}".format(x)] = vif_record + data[f"vif-{x}"] = vif_record x += 1 ret[name] = data return ret @@ -1168,7 +1168,7 @@ def vbd_list(name=None, call=None): x = 0 for vbd in vbds: vbd_record = session.xenapi.VBD.get_record(vbd) - data["vbd-{}".format(x)] = vbd_record + data[f"vbd-{x}"] = vbd_record x += 1 ret = data return ret @@ -1219,7 +1219,7 @@ def destroy_vm_vdis(name=None, session=None, call=None): vdi_record = session.xenapi.VDI.get_record(vbd_record["VDI"]) if "iso" not in vdi_record["name_label"]: session.xenapi.VDI.destroy(vbd_record["VDI"]) - ret["vdi-{}".format(x)] = vdi_record["name_label"] + ret[f"vdi-{x}"] = vdi_record["name_label"] x += 1 return ret diff --git a/salt/cloud/libcloudfuncs.py b/salt/cloud/libcloudfuncs.py index cee5ea724f9..2165e3ee442 100644 --- a/salt/cloud/libcloudfuncs.py +++ b/salt/cloud/libcloudfuncs.py @@ -61,7 +61,7 @@ def check_libcloud_version(reqver=LIBCLOUD_MINIMAL_VERSION, why=None): ) ) if why: - errormsg += " for {}".format(why) + errormsg += f" for {why}" errormsg += ". Please upgrade." raise ImportError(errormsg) @@ -186,7 +186,7 @@ def get_location(conn, vm_): return img raise SaltCloudNotFound( - "The specified location, '{}', could not be found.".format(vm_location) + f"The specified location, '{vm_location}', could not be found." ) @@ -204,9 +204,7 @@ def get_image(conn, vm_): if vm_image and vm_image in (img_id, img_name): return img - raise SaltCloudNotFound( - "The specified image, '{}', could not be found.".format(vm_image) - ) + raise SaltCloudNotFound(f"The specified image, '{vm_image}', could not be found.") def get_size(conn, vm_): @@ -224,9 +222,7 @@ def get_size(conn, vm_): str(size.name), ): return size - raise SaltCloudNotFound( - "The specified size, '{}', could not be found.".format(vm_size) - ) + raise SaltCloudNotFound(f"The specified size, '{vm_size}', could not be found.") def script(vm_): @@ -257,7 +253,7 @@ def destroy(name, conn=None, call=None): __utils__["cloud.fire_event"]( "event", "destroying instance", - "salt/cloud/{}/destroying".format(name), + f"salt/cloud/{name}/destroying", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -296,7 +292,7 @@ def destroy(name, conn=None, call=None): __utils__["cloud.fire_event"]( "event", "destroyed instance", - "salt/cloud/{}/destroyed".format(name), + f"salt/cloud/{name}/destroyed", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], @@ -338,8 +334,8 @@ def reboot(name, conn=None): # Fire reboot action __utils__["cloud.fire_event"]( "event", - "{} has been rebooted".format(name), - "salt/cloud/{}/rebooting".format(name), + f"{name} has been rebooted", + f"salt/cloud/{name}/rebooting", args={"name": name}, sock_dir=__opts__["sock_dir"], transport=__opts__["transport"], diff --git a/salt/config/__init__.py b/salt/config/__init__.py index f39494babda..edc4cc6b5b2 100644 --- a/salt/config/__init__.py +++ b/salt/config/__init__.py @@ -1,6 +1,7 @@ """ All salt configuration loading and defaults should be in this module """ + import codecs import glob import logging diff --git a/salt/config/schemas/common.py b/salt/config/schemas/common.py index f8d164abfed..5c32ecf789a 100644 --- a/salt/config/schemas/common.py +++ b/salt/config/schemas/common.py @@ -8,7 +8,6 @@ Common salt configuration schemas """ - from salt.utils.schema import ArrayItem, OneOfItem, Schema, StringItem @@ -26,7 +25,7 @@ class DefaultIncludeConfig(StringItem): description = __doc__ def __init__(self, default=None, pattern=None, **kwargs): - default = "{}/*.conf".format(self.__confd_directory__) + default = f"{self.__confd_directory__}/*.conf" pattern = r"(?:.*)/\*\.conf" super().__init__(default=default, pattern=pattern, **kwargs) diff --git a/salt/config/schemas/esxcluster.py b/salt/config/schemas/esxcluster.py index 2522a4bf4e1..cc3f30da6e5 100644 --- a/salt/config/schemas/esxcluster.py +++ b/salt/config/schemas/esxcluster.py @@ -8,7 +8,6 @@ ESX Cluster configuration schemas """ - from salt.utils.schema import ( AnyOfItem, ArrayItem, diff --git a/salt/config/schemas/esxdatacenter.py b/salt/config/schemas/esxdatacenter.py index 2bb4ec0b29f..edf8b404cd4 100644 --- a/salt/config/schemas/esxdatacenter.py +++ b/salt/config/schemas/esxdatacenter.py @@ -8,7 +8,6 @@ ESX Datacenter configuration schemas """ - from salt.utils.schema import ArrayItem, IntegerItem, Schema, StringItem diff --git a/salt/config/schemas/esxi.py b/salt/config/schemas/esxi.py index 1bb03b44c34..822f382b098 100644 --- a/salt/config/schemas/esxi.py +++ b/salt/config/schemas/esxi.py @@ -8,7 +8,6 @@ ESXi host configuration schemas """ - from salt.utils.schema import ( ArrayItem, BooleanItem, diff --git a/salt/config/schemas/esxvm.py b/salt/config/schemas/esxvm.py index 5842cb0be5c..2dfdbb26ac5 100644 --- a/salt/config/schemas/esxvm.py +++ b/salt/config/schemas/esxvm.py @@ -7,7 +7,6 @@ ESX Virtual Machine configuration schemas """ - from salt.utils.schema import ( AnyOfItem, ArrayItem, diff --git a/salt/config/schemas/minion.py b/salt/config/schemas/minion.py index 9aee9fe4c0f..22fe2fdeb7f 100644 --- a/salt/config/schemas/minion.py +++ b/salt/config/schemas/minion.py @@ -7,7 +7,6 @@ Minion configuration schema """ - from salt.config.schemas.common import IncludeConfig, MinionDefaultInclude from salt.utils.schema import IPv4Item, Schema diff --git a/salt/config/schemas/ssh.py b/salt/config/schemas/ssh.py index 2db9acda5de..2123768935c 100644 --- a/salt/config/schemas/ssh.py +++ b/salt/config/schemas/ssh.py @@ -8,7 +8,6 @@ Salt SSH related configuration schemas """ - from salt.config.schemas.minion import MinionConfiguration from salt.utils.schema import ( AnyOfItem, diff --git a/salt/daemons/__init__.py b/salt/daemons/__init__.py index f044f827b44..cb3b7c99c31 100644 --- a/salt/daemons/__init__.py +++ b/salt/daemons/__init__.py @@ -140,7 +140,7 @@ def extract_masters(opts, masters="master", port=None, raise_if_empty=True): entries = opts.get(masters, []) if not entries: - emsg = "Invalid or missing opts['{}'].".format(masters) + emsg = f"Invalid or missing opts['{masters}']." log.error(emsg) if raise_if_empty: raise ValueError(emsg) diff --git a/salt/daemons/masterapi.py b/salt/daemons/masterapi.py index 07ce6122ba4..df09f0b2380 100644 --- a/salt/daemons/masterapi.py +++ b/salt/daemons/masterapi.py @@ -132,7 +132,7 @@ def clean_pub_auth(opts): if not os.path.exists(auth_cache): return else: - for (dirpath, dirnames, filenames) in salt.utils.path.os_walk(auth_cache): + for dirpath, dirnames, filenames in salt.utils.path.os_walk(auth_cache): for auth_file in filenames: auth_file_path = os.path.join(dirpath, auth_file) if not os.path.isfile(auth_file_path): @@ -738,7 +738,7 @@ class RemoteFuncs: if not os.path.isdir(cdir): try: os.makedirs(cdir) - except os.error: + except OSError: pass if os.path.isfile(cpath) and load["loc"] != 0: mode = "ab" diff --git a/salt/defaults/__init__.py b/salt/defaults/__init__.py index 35bdf162a02..5ebdb694a58 100644 --- a/salt/defaults/__init__.py +++ b/salt/defaults/__init__.py @@ -45,8 +45,8 @@ class _Constant: def __repr__(self): if self.value: - return "".format(self.name, self.value) - return "".format(self.name) + return f"" + return f"" # Default delimiter for multi-level traversal in targeting diff --git a/salt/engines/__init__.py b/salt/engines/__init__.py index edd4a178225..11baafb2b86 100644 --- a/salt/engines/__init__.py +++ b/salt/engines/__init__.py @@ -2,6 +2,7 @@ Initialize the engines system. This plugin system allows for complex services to be encapsulated within the salt plugin environment """ + import logging import salt @@ -47,13 +48,13 @@ def start_engines(opts, proc_mgr, proxy=None): engine_name = engine del engine_opts["engine_module"] else: - fun = "{}.start".format(engine) + fun = f"{engine}.start" if fun in engines: start_func = engines[fun] if engine_name: - name = "Engine({}, name={})".format(start_func.__module__, engine_name) + name = f"Engine({start_func.__module__}, name={engine_name})" else: - name = "Engine({})".format(start_func.__module__) + name = f"Engine({start_func.__module__})" log.info("Starting %s", name) proc_mgr.add_process( Engine, diff --git a/salt/engines/docker_events.py b/salt/engines/docker_events.py index 024b75597cf..3bcabedc8ba 100644 --- a/salt/engines/docker_events.py +++ b/salt/engines/docker_events.py @@ -2,6 +2,7 @@ Send events from Docker events :Depends: Docker API >= 1.22 """ + import logging import traceback diff --git a/salt/engines/ircbot.py b/salt/engines/ircbot.py index 3e134c4e8b9..fc1241bc85b 100644 --- a/salt/engines/ircbot.py +++ b/salt/engines/ircbot.py @@ -173,16 +173,16 @@ class IRCClient: event.source, nick, user, host, event.code, channel, command, line ) if (self._allow_nick(nick) or self._allow_host(host)) and hasattr( - self, "_command_{}".format(command) + self, f"_command_{command}" ): - getattr(self, "_command_{}".format(command))(privevent) + getattr(self, f"_command_{command}")(privevent) def _command_echo(self, event): - message = "PRIVMSG {} :{}".format(event.channel, event.line) + message = f"PRIVMSG {event.channel} :{event.line}" self.send_message(message) def _command_ping(self, event): - message = "PRIVMSG {} :{}: pong".format(event.channel, event.nick) + message = f"PRIVMSG {event.channel} :{event.nick}: pong" self.send_message(message) def _command_event(self, event): @@ -210,7 +210,7 @@ class IRCClient: payload = {"data": []} fire("salt/engines/ircbot/" + tag, payload) - message = "PRIVMSG {} :{}: TaDa!".format(event.channel, event.nick) + message = f"PRIVMSG {event.channel} :{event.nick}: TaDa!" self.send_message(message) def _message(self, raw): @@ -219,7 +219,7 @@ class IRCClient: if event.code == "PING": tornado.ioloop.IOLoop.current().spawn_callback( - self.send_message, "PONG {}".format(event.line) + self.send_message, f"PONG {event.line}" ) elif event.code == "PRIVMSG": tornado.ioloop.IOLoop.current().spawn_callback(self._privmsg, event) @@ -228,13 +228,13 @@ class IRCClient: def join_channel(self, channel): if not channel.startswith("#"): channel = "#" + channel - self.send_message("JOIN {}".format(channel)) + self.send_message(f"JOIN {channel}") def on_connect(self): logging.info("on_connect") if self.sasl is True: self.send_message("CAP REQ :sasl") - self.send_message("NICK {}".format(self.nick)) + self.send_message(f"NICK {self.nick}") self.send_message("USER saltstack 0 * :saltstack") if self.password: if self.sasl is True: @@ -242,7 +242,7 @@ class IRCClient: "{0}\x00{0}\x00{1}".format(self.username, self.password).encode() ) self.send_message("AUTHENTICATE PLAIN") - self.send_message("AUTHENTICATE {}".format(authstring)) + self.send_message(f"AUTHENTICATE {authstring}") self.send_message("CAP END") else: self.send_message( diff --git a/salt/engines/libvirt_events.py b/salt/engines/libvirt_events.py index 3b77515f408..f09a298dc47 100644 --- a/salt/engines/libvirt_events.py +++ b/salt/engines/libvirt_events.py @@ -189,7 +189,7 @@ def _get_domain_event_detail(event, detail): if event_name == "unknown": return event_name, "unknown" - prefix = "VIR_DOMAIN_EVENT_{}_".format(event_name.upper()) + prefix = f"VIR_DOMAIN_EVENT_{event_name.upper()}_" detail_name = _get_libvirt_enum_string(prefix, detail) return event_name, detail_name @@ -333,9 +333,7 @@ def _domain_event_graphics_cb( transform address structure into event data piece """ return { - "family": _get_libvirt_enum_string( - "{}_ADDRESS_".format(prefix), addr["family"] - ), + "family": _get_libvirt_enum_string(f"{prefix}_ADDRESS_", addr["family"]), "node": addr["node"], "service": addr["service"], } @@ -680,14 +678,14 @@ def _register_callback(cnx, tag_prefix, obj, event, real_id): """ libvirt_name = real_id if real_id is None: - libvirt_name = "VIR_{}_EVENT_ID_{}".format(obj, event).upper() + libvirt_name = f"VIR_{obj}_EVENT_ID_{event}".upper() if not hasattr(libvirt, libvirt_name): log.warning('Skipping "%s/%s" events: libvirt too old', obj, event) return None libvirt_id = getattr(libvirt, libvirt_name) - callback_name = "_{}_event_{}_cb".format(obj, event) + callback_name = f"_{obj}_event_{event}_cb" callback = globals().get(callback_name, None) if callback is None: log.error("Missing function %s in engine", callback_name) diff --git a/salt/engines/napalm_syslog.py b/salt/engines/napalm_syslog.py index 3956a2836fd..e64f3c6b54b 100644 --- a/salt/engines/napalm_syslog.py +++ b/salt/engines/napalm_syslog.py @@ -209,7 +209,7 @@ def _zmq(address, port, **kwargs): socket = context.socket(zmq.SUB) if salt.utils.network.is_ipv6(address): socket.ipv6 = True - socket.connect("tcp://{addr}:{port}".format(addr=address, port=port)) + socket.connect(f"tcp://{address}:{port}") socket.setsockopt(zmq.SUBSCRIBE, b"") return socket.recv diff --git a/salt/engines/script.py b/salt/engines/script.py index 67277b14d5f..7b0e750d449 100644 --- a/salt/engines/script.py +++ b/salt/engines/script.py @@ -59,7 +59,7 @@ def _get_serializer(output): return getattr(serializers, output) except AttributeError: raise CommandExecutionError( - "Unknown serializer `{}` found for output option".format(output) + f"Unknown serializer `{output}` found for output option" ) diff --git a/salt/engines/slack.py b/salt/engines/slack.py index 65009619a17..cf8bef74d13 100644 --- a/salt/engines/slack.py +++ b/salt/engines/slack.py @@ -800,9 +800,9 @@ class SlackClient: channel = self.sc.server.channels.find(msg["channel"]) jid = self.run_command_async(msg) log.debug("Submitted a job and got jid: %s", jid) - outstanding[ - jid - ] = msg # record so we can return messages to the caller + outstanding[jid] = ( + msg # record so we can return messages to the caller + ) channel.send_message( "@{}'s job is submitted as salt jid {}".format( msg["user_name"], jid @@ -855,7 +855,6 @@ class SlackClient: del outstanding[jid] def run_command_async(self, msg): - """ :type message_generator: generator of dict :param message_generator: Generates messages from slack that should be run diff --git a/salt/engines/slack_bolt_engine.py b/salt/engines/slack_bolt_engine.py index 75eb0909e48..954ef79f556 100644 --- a/salt/engines/slack_bolt_engine.py +++ b/salt/engines/slack_bolt_engine.py @@ -913,9 +913,9 @@ class SlackClient: if control and (len(msg) > 1) and msg.get("cmdline"): jid = self.run_command_async(msg) log.debug("Submitted a job and got jid: %s", jid) - outstanding[ - jid - ] = msg # record so we can return messages to the caller + outstanding[jid] = ( + msg # record so we can return messages to the caller + ) text_msg = "@{}'s job is submitted as salt jid {}".format( msg["user_name"], jid ) @@ -969,7 +969,6 @@ class SlackClient: del outstanding[jid] def run_command_async(self, msg): - """ :type msg: dict :param msg: The message dictionary that contains the command and all information. diff --git a/salt/exceptions.py b/salt/exceptions.py index e351584bc03..57a6175de2d 100644 --- a/salt/exceptions.py +++ b/salt/exceptions.py @@ -284,7 +284,7 @@ class SaltRenderError(SaltException): self.buffer = buf self.context = "" if trace: - exc_str += "\n{}\n".format(trace) + exc_str += f"\n{trace}\n" if self.line_num and self.buffer: # Avoid circular import import salt.utils.templates diff --git a/salt/executors/sudo.py b/salt/executors/sudo.py index 4d5a2fd71aa..799e77f5486 100644 --- a/salt/executors/sudo.py +++ b/salt/executors/sudo.py @@ -64,7 +64,7 @@ def execute(opts, data, func, args, kwargs): for arg in args: cmd.append(shlex.quote(str(arg))) for key in kwargs: - cmd.append(shlex.quote("{}={}".format(key, kwargs[key]))) + cmd.append(shlex.quote(f"{key}={kwargs[key]}")) cmd_ret = __salt__["cmd.run_all"](cmd, use_vt=True, python_shell=False) diff --git a/salt/features.py b/salt/features.py index 4335c46ca5a..51761c24fcb 100644 --- a/salt/features.py +++ b/salt/features.py @@ -1,6 +1,7 @@ """ Feature flags """ + import logging log = logging.getLogger(__name__) diff --git a/salt/fileclient.py b/salt/fileclient.py index 317d0c6607f..fb27cedecab 100644 --- a/salt/fileclient.py +++ b/salt/fileclient.py @@ -1,6 +1,7 @@ """ Classes that manage file clients """ + import contextlib import errno import ftplib # nosec diff --git a/salt/fileserver/__init__.py b/salt/fileserver/__init__.py index 89f1fd70460..fe4b3b8e496 100644 --- a/salt/fileserver/__init__.py +++ b/salt/fileserver/__init__.py @@ -2,7 +2,6 @@ File server pluggable modules and generic backend functions """ - import errno import fnmatch import logging diff --git a/salt/fileserver/gitfs.py b/salt/fileserver/gitfs.py index 968e2c9ebfe..3f947d2384c 100644 --- a/salt/fileserver/gitfs.py +++ b/salt/fileserver/gitfs.py @@ -47,7 +47,6 @@ Walkthrough `. .. _GitPython: https://github.com/gitpython-developers/GitPython """ - import logging import salt.utils.gitfs diff --git a/salt/fileserver/hgfs.py b/salt/fileserver/hgfs.py index 947380b106a..48d17557886 100644 --- a/salt/fileserver/hgfs.py +++ b/salt/fileserver/hgfs.py @@ -858,7 +858,7 @@ def _file_lists(load, form): if not os.path.isdir(list_cachedir): try: os.makedirs(list_cachedir) - except os.error: + except OSError: log.critical("Unable to make cachedir %s", list_cachedir) return [] list_cache = os.path.join(list_cachedir, "{}.p".format(load["saltenv"])) diff --git a/salt/fileserver/minionfs.py b/salt/fileserver/minionfs.py index 02b1b59eeab..0cc77994fc2 100644 --- a/salt/fileserver/minionfs.py +++ b/salt/fileserver/minionfs.py @@ -150,7 +150,7 @@ def update(): salt.fileserver.reap_fileserver_cache_dir( os.path.join(__opts__["cachedir"], "minionfs/hash"), find_file ) - except os.error: + except OSError: # Hash file won't exist if no files have yet been served up pass @@ -204,7 +204,7 @@ def file_hash(load, fnd): ret["hsum"] = hsum return ret # Can't use Python select() because we need Windows support - except os.error: + except OSError: log.debug("Fileserver encountered lock when reading cache file. Retrying.") file_hash(load, fnd) return ret diff --git a/salt/fileserver/roots.py b/salt/fileserver/roots.py index e2ea92029c3..91536d737ce 100644 --- a/salt/fileserver/roots.py +++ b/salt/fileserver/roots.py @@ -289,10 +289,7 @@ def file_hash(load, fnd): # check if mtime changed ret["hsum"] = hsum return ret - except ( - os.error, - OSError, - ): # Can't use Python select() because we need Windows support + except OSError: # Can't use Python select() because we need Windows support log.debug("Fileserver encountered lock when reading cache file. Retrying.") # Delete the file since its incomplete (either corrupted or incomplete) try: diff --git a/salt/fileserver/s3fs.py b/salt/fileserver/s3fs.py index d013ea3b193..520c3d53635 100644 --- a/salt/fileserver/s3fs.py +++ b/salt/fileserver/s3fs.py @@ -87,7 +87,6 @@ structure:: s3.s3_sync_on_update: False """ - import datetime import logging import os diff --git a/salt/fileserver/svnfs.py b/salt/fileserver/svnfs.py index 82f1541fe8d..8e13ec99353 100644 --- a/salt/fileserver/svnfs.py +++ b/salt/fileserver/svnfs.py @@ -30,7 +30,6 @@ This backend assumes a standard svn layout with directories for ``branches``, :conf_master:`documentation ` for more information. """ - import copy import errno import fnmatch @@ -721,7 +720,7 @@ def _file_lists(load, form): if not os.path.isdir(list_cachedir): try: os.makedirs(list_cachedir) - except os.error: + except OSError: log.critical("Unable to make cachedir %s", list_cachedir) return [] list_cache = os.path.join(list_cachedir, "{}.p".format(load["saltenv"])) diff --git a/salt/grains/cimc.py b/salt/grains/cimc.py index 72b89d931bb..30032159294 100644 --- a/salt/grains/cimc.py +++ b/salt/grains/cimc.py @@ -3,7 +3,6 @@ Generate baseline proxy minion grains for cimc hosts. """ - import logging import salt.proxy.cimc diff --git a/salt/grains/core.py b/salt/grains/core.py index 1a701f2f53d..728a5b1494a 100644 --- a/salt/grains/core.py +++ b/salt/grains/core.py @@ -2380,10 +2380,10 @@ def _legacy_linux_distribution_data(grains, os_release, lsb_has_error): "Please report this, as it is likely a bug." ) else: - grains[ - "osrelease" - ] = "{majorversion}.{minorversion}-{buildnumber}".format( - **synoinfo + grains["osrelease"] = ( + "{majorversion}.{minorversion}-{buildnumber}".format( + **synoinfo + ) ) log.trace( @@ -2871,14 +2871,16 @@ def fqdns(): opt = {"fqdns": []} if __opts__.get( "enable_fqdns_grains", - False - if salt.utils.platform.is_windows() - or salt.utils.platform.is_proxy() - or salt.utils.platform.is_sunos() - or salt.utils.platform.is_aix() - or salt.utils.platform.is_junos() - or salt.utils.platform.is_darwin() - else True, + ( + False + if salt.utils.platform.is_windows() + or salt.utils.platform.is_proxy() + or salt.utils.platform.is_sunos() + or salt.utils.platform.is_aix() + or salt.utils.platform.is_junos() + or salt.utils.platform.is_darwin() + else True + ), ): opt = __salt__["network.fqdns"]() return opt @@ -3309,7 +3311,7 @@ def _hw_data(osdata): # of information. With that said, consolidate the output from various # commands and attempt various lookups. data = "" - for (cmd, args) in ( + for cmd, args in ( ("/usr/sbin/prtdiag", "-v"), ("/usr/sbin/prtconf", "-vp"), ("/usr/sbin/virtinfo", "-a"), diff --git a/salt/grains/disks.py b/salt/grains/disks.py index 1dfbeb737bb..f61ad6d6b34 100644 --- a/salt/grains/disks.py +++ b/salt/grains/disks.py @@ -91,14 +91,14 @@ def _freebsd_geom(): geom = salt.utils.path.which("geom") ret = {"disks": {}, "ssds": []} - devices = __salt__["cmd.run"]("{} disk list".format(geom)) + devices = __salt__["cmd.run"](f"{geom} disk list") devices = devices.split("\n\n") def parse_geom_attribs(device): tmp = {} for line in device.split("\n"): for attrib in _geom_attribs: - search = re.search(r"{}:\s(.*)".format(attrib), line) + search = re.search(rf"{attrib}:\s(.*)", line) if search: value = _datavalue( _geomconsts._datatypes.get(attrib), search.group(1) @@ -174,7 +174,7 @@ def _windows_disks(): info = line.split() if len(info) != 2 or not info[0].isdigit() or not info[1].isdigit(): continue - device = r"\\.\PhysicalDrive{}".format(info[0]) + device = rf"\\.\PhysicalDrive{info[0]}" mediatype = info[1] if mediatype == "3": log.trace("Device %s reports itself as an HDD", device) diff --git a/salt/grains/esxi.py b/salt/grains/esxi.py index 57041db8283..e9b40e73c22 100644 --- a/salt/grains/esxi.py +++ b/salt/grains/esxi.py @@ -13,7 +13,6 @@ Generate baseline proxy minion grains for ESXi hosts. """ - import logging import salt.utils.proxy diff --git a/salt/grains/junos.py b/salt/grains/junos.py index a24e39dade4..0dfd3344ff2 100644 --- a/salt/grains/junos.py +++ b/salt/grains/junos.py @@ -5,7 +5,6 @@ via salt-proxy-minion. Thus, some grains make sense to get them from the minion (PYTHONPATH), but others don't (ip_interfaces) """ - import logging import salt.utils.platform diff --git a/salt/grains/lvm.py b/salt/grains/lvm.py index 586b187ddb9..bb08de96e8b 100644 --- a/salt/grains/lvm.py +++ b/salt/grains/lvm.py @@ -33,14 +33,12 @@ def _linux_lvm(): ret = {} cmd = salt.utils.path.which("lvm") if cmd: - vgs = __salt__["cmd.run_all"]("{} vgs -o vg_name --noheadings".format(cmd)) + vgs = __salt__["cmd.run_all"](f"{cmd} vgs -o vg_name --noheadings") for vg in vgs["stdout"].splitlines(): vg = vg.strip() ret[vg] = [] - lvs = __salt__["cmd.run_all"]( - "{} lvs -o lv_name --noheadings {}".format(cmd, vg) - ) + lvs = __salt__["cmd.run_all"](f"{cmd} lvs -o lv_name --noheadings {vg}") for lv in lvs["stdout"].splitlines(): ret[vg].append(lv.strip()) @@ -52,11 +50,11 @@ def _linux_lvm(): def _aix_lvm(): ret = {} cmd = salt.utils.path.which("lsvg") - vgs = __salt__["cmd.run"]("{}".format(cmd)) + vgs = __salt__["cmd.run"](f"{cmd}") for vg in vgs.splitlines(): ret[vg] = [] - lvs = __salt__["cmd.run"]("{} -l {}".format(cmd, vg)) + lvs = __salt__["cmd.run"](f"{cmd} -l {vg}") for lvline in lvs.splitlines()[2:]: lv = lvline.split(" ", 1)[0] ret[vg].append(lv) diff --git a/salt/grains/minion_process.py b/salt/grains/minion_process.py index 54c0b61eb07..9a8dd420f0a 100644 --- a/salt/grains/minion_process.py +++ b/salt/grains/minion_process.py @@ -2,7 +2,6 @@ Set grains describing the minion process. """ - import os import salt.utils.platform diff --git a/salt/grains/napalm.py b/salt/grains/napalm.py index d36eb0273ab..5fca987e132 100644 --- a/salt/grains/napalm.py +++ b/salt/grains/napalm.py @@ -15,7 +15,6 @@ Dependencies .. versionadded:: 2016.11.0 """ - import logging import salt.utils.dns diff --git a/salt/grains/package.py b/salt/grains/package.py index c60a9fbb8d8..6d1963aea95 100644 --- a/salt/grains/package.py +++ b/salt/grains/package.py @@ -3,6 +3,7 @@ Grains for detecting what type of package Salt is using .. versionadded:: 3007.0 """ + import logging import salt.utils.package diff --git a/salt/grains/panos.py b/salt/grains/panos.py index 60d0e52b71e..f5ba8d731de 100644 --- a/salt/grains/panos.py +++ b/salt/grains/panos.py @@ -3,7 +3,6 @@ Generate baseline proxy minion grains for panos hosts. """ - import logging import salt.proxy.panos diff --git a/salt/grains/pending_reboot.py b/salt/grains/pending_reboot.py index dddba83fb6f..c83aecaf7ed 100644 --- a/salt/grains/pending_reboot.py +++ b/salt/grains/pending_reboot.py @@ -3,6 +3,7 @@ Grain that indicates the system is pending a reboot See functions in salt.utils.win_system to see what conditions would indicate a reboot is pending """ + import logging import salt.utils.platform diff --git a/salt/loader/context.py b/salt/loader/context.py index 560b05a8d2b..88a6472a8f3 100644 --- a/salt/loader/context.py +++ b/salt/loader/context.py @@ -1,6 +1,7 @@ """ Manage the context a module loaded by Salt's loader """ + import collections.abc import contextlib import copy diff --git a/salt/loader/dunder.py b/salt/loader/dunder.py index f0235d19a29..d3027098b5a 100644 --- a/salt/loader/dunder.py +++ b/salt/loader/dunder.py @@ -1,6 +1,7 @@ """ Salt dunders. """ + import salt.loader.context loader_context = salt.loader.context.LoaderContext() diff --git a/salt/loader/lazy.py b/salt/loader/lazy.py index 97fd3085573..3e6ad9ffa7c 100644 --- a/salt/loader/lazy.py +++ b/salt/loader/lazy.py @@ -315,7 +315,7 @@ class LazyLoader(salt.utils.lazy.LazyDict): # A list to determine precedence of extensions # Prefer packages (directories) over modules (single files)! self.suffix_order = [""] - for (suffix, mode, kind) in SUFFIXES: + for suffix, mode, kind in SUFFIXES: self.suffix_map[suffix] = (suffix, mode, kind) self.suffix_order.append(suffix) diff --git a/salt/log_handlers/fluent_mod.py b/salt/log_handlers/fluent_mod.py index 1086a926158..a23544ff871 100644 --- a/salt/log_handlers/fluent_mod.py +++ b/salt/log_handlers/fluent_mod.py @@ -181,7 +181,7 @@ class MessageFormatter(logging.Formatter): self.tags = tags self.msg_path = msg_path if msg_path else payload_type self.msg_type = msg_type if msg_type else payload_type - format_func = "format_{}_v{}".format(payload_type, version).replace(".", "_") + format_func = f"format_{payload_type}_v{version}".replace(".", "_") self.format = getattr(self, format_func) super().__init__(fmt=None, datefmt=None) @@ -236,7 +236,7 @@ class MessageFormatter(logging.Formatter): val = value else: val = repr(value) - message_dict.update({"{}".format(key): val}) + message_dict.update({f"{key}": val}) return message_dict def format_gelf_v1_1(self, record): @@ -286,7 +286,7 @@ class MessageFormatter(logging.Formatter): else: val = repr(value) # GELF spec require "non-standard" fields to be prefixed with '_' (underscore). - message_dict.update({"_{}".format(key): val}) + message_dict.update({f"_{key}": val}) return message_dict @@ -308,7 +308,7 @@ class MessageFormatter(logging.Formatter): "processName": record.processName, }, "@message": record.getMessage(), - "@source": "{}://{}/{}".format(self.msg_type, host, self.msg_path), + "@source": f"{self.msg_type}://{host}/{self.msg_path}", "@source_host": host, "@source_path": self.msg_path, "@tags": self.tags, diff --git a/salt/log_handlers/logstash_mod.py b/salt/log_handlers/logstash_mod.py index 1d69cfc8945..b3e30f83a99 100644 --- a/salt/log_handlers/logstash_mod.py +++ b/salt/log_handlers/logstash_mod.py @@ -154,7 +154,6 @@ """ - import datetime import logging import logging.handlers @@ -266,7 +265,7 @@ class LogstashFormatter(logging.Formatter): self.msg_path = msg_path self.msg_type = msg_type self.version = version - self.format = getattr(self, "format_v{}".format(version)) + self.format = getattr(self, f"format_v{version}") super().__init__(fmt=None, datefmt=None) def formatTime(self, record, datefmt=None): @@ -287,7 +286,7 @@ class LogstashFormatter(logging.Formatter): "processName": record.processName, }, "@message": record.getMessage(), - "@source": "{}://{}/{}".format(self.msg_type, host, self.msg_path), + "@source": f"{self.msg_type}://{host}/{self.msg_path}", "@source_host": host, "@source_path": self.msg_path, "@tags": ["salt"], diff --git a/salt/log_handlers/sentry_mod.py b/salt/log_handlers/sentry_mod.py index c3a6209b1f1..a12366f9fcb 100644 --- a/salt/log_handlers/sentry_mod.py +++ b/salt/log_handlers/sentry_mod.py @@ -140,7 +140,7 @@ def setup_handlers(): transport_registry = TransportRegistry(default_transports) url = urlparse(dsn) if not transport_registry.supported_scheme(url.scheme): - raise ValueError("Unsupported Sentry DSN scheme: {}".format(url.scheme)) + raise ValueError(f"Unsupported Sentry DSN scheme: {url.scheme}") except ValueError as exc: log.info("Raven failed to parse the configuration provided DSN: %s", exc) diff --git a/salt/master.py b/salt/master.py index 6bf7ca68fe0..516bdd5bf84 100644 --- a/salt/master.py +++ b/salt/master.py @@ -2,6 +2,7 @@ This module contains all of the routines needed to set up a master server, this involves preparing the three listeners and the workers needed by the master. """ + import asyncio import collections import copy @@ -181,16 +182,16 @@ class SMaster: if use_lock: with cls.secrets["cluster_aes"]["secret"].get_lock(): - cls.secrets["cluster_aes"][ - "secret" - ].value = salt.utils.stringutils.to_bytes( - cls.secrets["cluster_aes"]["reload"](remove=owner) + cls.secrets["cluster_aes"]["secret"].value = ( + salt.utils.stringutils.to_bytes( + cls.secrets["cluster_aes"]["reload"](remove=owner) + ) ) else: - cls.secrets["cluster_aes"][ - "secret" - ].value = salt.utils.stringutils.to_bytes( - cls.secrets["cluster_aes"]["reload"](remove=owner) + cls.secrets["cluster_aes"]["secret"].value = ( + salt.utils.stringutils.to_bytes( + cls.secrets["cluster_aes"]["reload"](remove=owner) + ) ) if event: @@ -363,7 +364,7 @@ class Maintenance(salt.utils.process.SignalHandlingProcess): log.error("Found dropfile with incorrect permissions, ignoring...") if to_rotate: os.remove(dfn) - except os.error: + except OSError: pass # There is no need to check key against publish_session if we're @@ -373,7 +374,7 @@ class Maintenance(salt.utils.process.SignalHandlingProcess): keyfile = os.path.join(self.opts["cluster_pki_dir"], ".aes") try: stats = os.stat(keyfile) - except os.error as exc: + except OSError as exc: log.error("Unexpected condition while reading keyfile %s", exc) return if now - stats.st_mtime >= self.opts["publish_session"]: @@ -1042,7 +1043,7 @@ class ReqServer(salt.utils.process.SignalHandlingProcess): # Cannot delete read-only files on Windows. os.chmod(dfn, stat.S_IRUSR | stat.S_IWUSR) os.remove(dfn) - except os.error: + except OSError: pass # Wait for kill should be less then parent's ProcessManager. @@ -1735,7 +1736,7 @@ class AESFuncs(TransportMethods): if not os.path.isdir(cdir): try: os.makedirs(cdir) - except os.error: + except OSError: pass if os.path.isfile(cpath) and load["loc"] != 0: mode = "ab" diff --git a/salt/matchers/compound_match.py b/salt/matchers/compound_match.py index 2bce58f117a..04da7281e3e 100644 --- a/salt/matchers/compound_match.py +++ b/salt/matchers/compound_match.py @@ -111,7 +111,7 @@ def match(tgt, opts=None, minion_id=None): results.append( str( - __context__["matchers"]["{}_match.match".format(engine)]( + __context__["matchers"][f"{engine}_match.match"]( *engine_args, **engine_kwargs ) ) diff --git a/salt/matchers/confirm_top.py b/salt/matchers/confirm_top.py index 7435f4ae94d..09a11ff428d 100644 --- a/salt/matchers/confirm_top.py +++ b/salt/matchers/confirm_top.py @@ -3,6 +3,7 @@ The matcher subsystem needs a function called "confirm_top", which takes the data passed to a top file environment and determines if that data matches this minion. """ + import logging import salt.loader diff --git a/salt/matchers/ipcidr_match.py b/salt/matchers/ipcidr_match.py index 175dade0024..8cfbf4d3332 100644 --- a/salt/matchers/ipcidr_match.py +++ b/salt/matchers/ipcidr_match.py @@ -27,7 +27,7 @@ def match(tgt, opts=None, minion_id=None): except: # pylint: disable=bare-except log.error("Invalid IP/CIDR target: %s", tgt) return [] - proto = "ipv{}".format(tgt.version) + proto = f"ipv{tgt.version}" grains = opts["grains"] diff --git a/salt/matchers/list_match.py b/salt/matchers/list_match.py index 5b790666ee3..91520cbb13d 100644 --- a/salt/matchers/list_match.py +++ b/salt/matchers/list_match.py @@ -19,7 +19,7 @@ def match(tgt, opts=None, minion_id=None): try: if ( - ",{},".format(minion_id) in tgt + f",{minion_id}," in tgt or tgt.startswith(minion_id + ",") or tgt.endswith("," + minion_id) ): diff --git a/salt/metaproxy/deltaproxy.py b/salt/metaproxy/deltaproxy.py index fdf80491ed2..50bdaa0b3c3 100644 --- a/salt/metaproxy/deltaproxy.py +++ b/salt/metaproxy/deltaproxy.py @@ -371,10 +371,10 @@ def post_master_init(self, master): self.deltaproxy_objs[minion_id] = sub_proxy_data["proxy_minion"] if self.deltaproxy_opts[minion_id] and self.deltaproxy_objs[minion_id]: - self.deltaproxy_objs[ - minion_id - ].req_channel = salt.channel.client.AsyncReqChannel.factory( - sub_proxy_data["proxy_opts"], io_loop=self.io_loop + self.deltaproxy_objs[minion_id].req_channel = ( + salt.channel.client.AsyncReqChannel.factory( + sub_proxy_data["proxy_opts"], io_loop=self.io_loop + ) ) else: log.debug("Initiating non-parallel startup for proxies") @@ -398,10 +398,10 @@ def post_master_init(self, master): self.deltaproxy_objs[minion_id] = sub_proxy_data["proxy_minion"] if self.deltaproxy_opts[minion_id] and self.deltaproxy_objs[minion_id]: - self.deltaproxy_objs[ - minion_id - ].req_channel = salt.channel.client.AsyncReqChannel.factory( - sub_proxy_data["proxy_opts"], io_loop=self.io_loop + self.deltaproxy_objs[minion_id].req_channel = ( + salt.channel.client.AsyncReqChannel.factory( + sub_proxy_data["proxy_opts"], io_loop=self.io_loop + ) ) if _failed: diff --git a/salt/minion.py b/salt/minion.py index 729053ed402..4246bdfdee8 100644 --- a/salt/minion.py +++ b/salt/minion.py @@ -1,6 +1,7 @@ """ Routines to set up a minion """ + import asyncio import binascii import contextlib diff --git a/salt/modules/aix_group.py b/salt/modules/aix_group.py index ddbb452fcbf..b1e5f092e79 100644 --- a/salt/modules/aix_group.py +++ b/salt/modules/aix_group.py @@ -48,7 +48,7 @@ def add(name, gid=None, system=False, root=None, **kwargs): cmd += "-a " if gid: - cmd += "id={} ".format(gid) + cmd += f"id={gid} " cmd += name @@ -67,7 +67,7 @@ def delete(name): salt '*' group.delete foo """ - ret = __salt__["cmd.run_all"]("rmgroup {}".format(name), python_shell=False) + ret = __salt__["cmd.run_all"](f"rmgroup {name}", python_shell=False) return not ret["retcode"] @@ -129,7 +129,7 @@ def chgid(name, gid): pre_gid = __salt__["file.group_to_gid"](name) if gid == pre_gid: return True - cmd = "chgroup id={} {}".format(gid, name) + cmd = f"chgroup id={gid} {name}" __salt__["cmd.run"](cmd, python_shell=False) post_gid = __salt__["file.group_to_gid"](name) if post_gid != pre_gid: @@ -150,7 +150,7 @@ def adduser(name, username, root=None): Verifies if a valid username 'bar' as a member of an existing group 'foo', if not then adds it. """ - cmd = "chgrpmem -m + {} {}".format(username, name) + cmd = f"chgrpmem -m + {username} {name}" retcode = __salt__["cmd.retcode"](cmd, python_shell=False) @@ -173,7 +173,7 @@ def deluser(name, username, root=None): grp_info = __salt__["group.info"](name) try: if username in grp_info["members"]: - cmd = "chgrpmem -m - {} {}".format(username, name) + cmd = f"chgrpmem -m - {username} {name}" ret = __salt__["cmd.run"](cmd, python_shell=False) return not ret["retcode"] else: @@ -195,7 +195,7 @@ def members(name, members_list, root=None): Replaces a membership list for a local group 'foo'. foo:x:1234:user1,user2,user3,... """ - cmd = "chgrpmem -m = {} {}".format(members_list, name) + cmd = f"chgrpmem -m = {members_list} {name}" retcode = __salt__["cmd.retcode"](cmd, python_shell=False) return not retcode diff --git a/salt/modules/aix_shadow.py b/salt/modules/aix_shadow.py index aa7471cb026..e58f93180fe 100644 --- a/salt/modules/aix_shadow.py +++ b/salt/modules/aix_shadow.py @@ -6,7 +6,6 @@ Manage account locks on AIX systems :depends: none """ - # Import python librarie import logging @@ -30,7 +29,6 @@ def __virtual__(): def login_failures(user): - """ Query for all accounts which have 3 or more login failures. @@ -41,7 +39,7 @@ def login_failures(user): salt shadow.login_failures ALL """ - cmd = "lsuser -a unsuccessful_login_count {}".format(user) + cmd = f"lsuser -a unsuccessful_login_count {user}" cmd += " | grep -E 'unsuccessful_login_count=([3-9]|[0-9][0-9]+)'" out = __salt__["cmd.run_all"](cmd, output_loglevel="trace", python_shell=True) @@ -65,7 +63,7 @@ def locked(user): salt shadow.locked ALL """ - cmd = "lsuser -a account_locked {}".format(user) + cmd = f"lsuser -a account_locked {user}" cmd += ' | grep "account_locked=true"' out = __salt__["cmd.run_all"](cmd, output_loglevel="trace", python_shell=True) diff --git a/salt/modules/aixpkg.py b/salt/modules/aixpkg.py index 25c0b2dbdfc..a77cff26788 100644 --- a/salt/modules/aixpkg.py +++ b/salt/modules/aixpkg.py @@ -184,7 +184,7 @@ def version(*names, **kwargs): for name in names: # AIX packaging includes info on filesets and rpms version_found = "" - cmd = "lslpp -Lq {}".format(name) + cmd = f"lslpp -Lq {name}" aix_info = __salt__["cmd.run_all"](cmd, python_shell=False) if 0 == aix_info["retcode"]: aix_info_list = aix_info["stdout"].split("\n") @@ -344,7 +344,7 @@ def install(name=None, refresh=False, pkgs=None, version=None, test=False, **kwa if refresh: cmdflags += "--refresh " - cmd = "{} {} {}".format(cmdexe, cmdflags, target) + cmd = f"{cmdexe} {cmdflags} {target}" out = __salt__["cmd.run_all"]( cmd, python_shell=False, @@ -360,7 +360,7 @@ def install(name=None, refresh=False, pkgs=None, version=None, test=False, **kwa else: cmdflags += "--assumeyes " - cmd = "{} {} {}".format(cmdexe, cmdflags, target) + cmd = f"{cmdexe} {cmdflags} {target}" out = __salt__["cmd.run_all"]( cmd, python_shell=False, @@ -378,7 +378,7 @@ def install(name=None, refresh=False, pkgs=None, version=None, test=False, **kwa if refresh: cmdflags += "--refresh " - cmd = "{} {} {}".format(cmdexe, cmdflags, target) + cmd = f"{cmdexe} {cmdflags} {target}" out = __salt__["cmd.run_all"]( cmd, python_shell=False, @@ -392,7 +392,7 @@ def install(name=None, refresh=False, pkgs=None, version=None, test=False, **kwa if test: cmdflags += "--test" - cmd = "{} {} {}".format(cmdexe, cmdflags, target) + cmd = f"{cmdexe} {cmdflags} {target}" out = __salt__["cmd.run_all"](cmd, python_shell=False) if "retcode" in out and not (0 == out["retcode"] or 100 == out["retcode"]): @@ -510,7 +510,7 @@ def remove(name=None, pkgs=None, **kwargs): libpathenv = {"LIBPATH": "/opt/freeware/lib:/usr/lib"} if pathlib.Path("/opt/freeware/bin/dnf").is_file(): cmdexe = "/opt/freeware/bin/dnf" - cmd = "{} {} {}".format(cmdexe, cmdflags, target) + cmd = f"{cmdexe} {cmdflags} {target}" out = __salt__["cmd.run_all"]( cmd, python_shell=False, @@ -519,7 +519,7 @@ def remove(name=None, pkgs=None, **kwargs): ) elif pathlib.Path("/opt/freeware/bin/yum").is_file(): cmdexe = "/opt/freeware/bin/yum" - cmd = "{} {} {}".format(cmdexe, cmdflags, target) + cmd = f"{cmdexe} {cmdflags} {target}" out = __salt__["cmd.run_all"]( cmd, python_shell=False, @@ -528,7 +528,7 @@ def remove(name=None, pkgs=None, **kwargs): ) elif pathlib.Path("/usr/bin/yum").is_file(): cmdexe = "/usr/bin/yum" - cmd = "{} {} {}".format(cmdexe, cmdflags, target) + cmd = f"{cmdexe} {cmdflags} {target}" out = __salt__["cmd.run_all"]( cmd, python_shell=False, @@ -538,7 +538,7 @@ def remove(name=None, pkgs=None, **kwargs): else: cmdexe = "/usr/bin/rpm" cmdflags = "-e" - cmd = "{} {} {}".format(cmdexe, cmdflags, target) + cmd = f"{cmdexe} {cmdflags} {target}" out = __salt__["cmd.run_all"](cmd, python_shell=False) else: cmd = ["/usr/sbin/installp", "-u", named] @@ -594,19 +594,19 @@ def latest_version(*names, **kwargs): libpathenv = {"LIBPATH": "/opt/freeware/lib:/usr/lib"} if pathlib.Path("/opt/freeware/bin/dnf").is_file(): cmdexe = "/opt/freeware/bin/dnf" - cmd = "{} check-update {}".format(cmdexe, name) + cmd = f"{cmdexe} check-update {name}" available_info = __salt__["cmd.run_all"]( cmd, python_shell=False, env=libpathenv, ignore_retcode=True ) elif pathlib.Path("/opt/freeware/bin/yum").is_file(): cmdexe = "/opt/freeware/bin/yum" - cmd = "{} check-update {}".format(cmdexe, name) + cmd = f"{cmdexe} check-update {name}" available_info = __salt__["cmd.run_all"]( cmd, python_shell=False, env=libpathenv, ignore_retcode=True ) elif pathlib.Path("/usr/bin/yum").is_file(): cmdexe = "/usr/bin/yum" - cmd = "{} check-update {}".format(cmdexe, name) + cmd = f"{cmdexe} check-update {name}" available_info = __salt__["cmd.run_all"]( cmd, python_shell=False, env=libpathenv, ignore_retcode=True ) @@ -683,19 +683,19 @@ def upgrade_available(name, **kwargs): libpathenv = {"LIBPATH": "/opt/freeware/lib:/usr/lib"} if pathlib.Path("/opt/freeware/bin/dnf").is_file(): cmdexe = "/opt/freeware/bin/dnf" - cmd = "{} check-update {}".format(cmdexe, name) + cmd = f"{cmdexe} check-update {name}" available_info = __salt__["cmd.run_all"]( cmd, python_shell=False, env=libpathenv, ignore_retcode=True ) elif pathlib.Path("/opt/freeware/bin/yum").is_file(): cmdexe = "/opt/freeware/bin/yum" - cmd = "{} check-update {}".format(cmdexe, name) + cmd = f"{cmdexe} check-update {name}" available_info = __salt__["cmd.run_all"]( cmd, python_shell=False, env=libpathenv, ignore_retcode=True ) elif pathlib.Path("/usr/bin/yum").is_file(): cmdexe = "/usr/bin/yum" - cmd = "{} check-update {}".format(cmdexe, name) + cmd = f"{cmdexe} check-update {name}" available_info = __salt__["cmd.run_all"]( cmd, python_shell=False, env=libpathenv, ignore_retcode=True ) diff --git a/salt/modules/aliases.py b/salt/modules/aliases.py index f04b457ac80..b006593767f 100644 --- a/salt/modules/aliases.py +++ b/salt/modules/aliases.py @@ -74,15 +74,15 @@ def __write_aliases_file(lines): os.chmod(out.name, 0o644) os.chown(out.name, 0, 0) - for (line_alias, line_target, line_comment) in lines: + for line_alias, line_target, line_comment in lines: if isinstance(line_target, list): line_target = ", ".join(line_target) if not line_comment: line_comment = "" if line_alias and line_target: - write_line = "{}: {}{}\n".format(line_alias, line_target, line_comment) + write_line = f"{line_alias}: {line_target}{line_comment}\n" else: - write_line = "{}\n".format(line_comment) + write_line = f"{line_comment}\n" write_line = write_line.encode(__salt_system_encoding__) out.write(write_line) @@ -173,7 +173,7 @@ def set_target(alias, target): lines = __parse_aliases() out = [] ovr = False - for (line_alias, line_target, line_comment) in lines: + for line_alias, line_target, line_comment in lines: if line_alias == alias: if not ovr: out.append((alias, target, line_comment)) @@ -202,7 +202,7 @@ def rm_alias(alias): lines = __parse_aliases() out = [] - for (line_alias, line_target, line_comment) in lines: + for line_alias, line_target, line_comment in lines: if line_alias != alias: out.append((line_alias, line_target, line_comment)) diff --git a/salt/modules/alternatives.py b/salt/modules/alternatives.py index 64df8d78367..a71814b6ef1 100644 --- a/salt/modules/alternatives.py +++ b/salt/modules/alternatives.py @@ -241,5 +241,5 @@ def _read_link(name): Throws an OSError if the link does not exist """ - alt_link_path = "/etc/alternatives/{}".format(name) + alt_link_path = f"/etc/alternatives/{name}" return salt.utils.path.readlink(alt_link_path) diff --git a/salt/modules/ansiblegate.py b/salt/modules/ansiblegate.py index 2f60a7444fb..ec87aa9969c 100644 --- a/salt/modules/ansiblegate.py +++ b/salt/modules/ansiblegate.py @@ -101,17 +101,16 @@ def __virtual__(): proc = subprocess.run( [ansible_doc_bin, "--list", "--json", "--type=module"], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, + capture_output=True, check=False, shell=False, - universal_newlines=True, + text=True, env=env, ) if proc.returncode != 0: return ( False, - "Failed to get the listing of ansible modules:\n{}".format(proc.stderr), + f"Failed to get the listing of ansible modules:\n{proc.stderr}", ) module_funcs = dir(sys.modules[__name__]) @@ -170,11 +169,10 @@ def help(module=None, *args): proc = subprocess.run( [ansible_doc_bin, "--json", "--type=module", module], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, + capture_output=True, check=True, shell=False, - universal_newlines=True, + text=True, env=env, ) data = salt.utils.json.loads(proc.stdout) @@ -240,7 +238,7 @@ def call(module, *args, **kwargs): _kwargs = {k: v for (k, v) in kwargs.items() if not k.startswith("__pub")} for key, value in _kwargs.items(): - module_args.append("{}={}".format(key, salt.utils.json.dumps(value))) + module_args.append(f"{key}={salt.utils.json.dumps(value)}") with NamedTemporaryFile(mode="w") as inventory: @@ -263,10 +261,9 @@ def call(module, *args, **kwargs): "-i", inventory.name, ], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, + capture_output=True, timeout=__opts__.get("ansible_timeout", DEFAULT_TIMEOUT), - universal_newlines=True, + text=True, check=True, shell=False, env=env, @@ -367,15 +364,15 @@ def playbooks( if diff: command.append("--diff") if isinstance(extra_vars, dict): - command.append("--extra-vars='{}'".format(json.dumps(extra_vars))) + command.append(f"--extra-vars='{json.dumps(extra_vars)}'") elif isinstance(extra_vars, str) and extra_vars.startswith("@"): - command.append("--extra-vars={}".format(extra_vars)) + command.append(f"--extra-vars={extra_vars}") if flush_cache: command.append("--flush-cache") if inventory: - command.append("--inventory={}".format(inventory)) + command.append(f"--inventory={inventory}") if limit: - command.append("--limit={}".format(limit)) + command.append(f"--limit={limit}") if list_hosts: command.append("--list-hosts") if list_tags: @@ -383,25 +380,25 @@ def playbooks( if list_tasks: command.append("--list-tasks") if module_path: - command.append("--module-path={}".format(module_path)) + command.append(f"--module-path={module_path}") if skip_tags: - command.append("--skip-tags={}".format(skip_tags)) + command.append(f"--skip-tags={skip_tags}") if start_at_task: - command.append("--start-at-task={}".format(start_at_task)) + command.append(f"--start-at-task={start_at_task}") if syntax_check: command.append("--syntax-check") if tags: - command.append("--tags={}".format(tags)) + command.append(f"--tags={tags}") if playbook_kwargs: for key, value in playbook_kwargs.items(): key = key.replace("_", "-") if value is True: - command.append("--{}".format(key)) + command.append(f"--{key}") elif isinstance(value, str): - command.append("--{}={}".format(key, value)) + command.append(f"--{key}={value}") elif isinstance(value, dict): - command.append("--{}={}".format(key, json.dumps(value))) - command.append("--forks={}".format(forks)) + command.append(f"--{key}={json.dumps(value)}") + command.append(f"--forks={forks}") cmd_kwargs = { "env": { "ANSIBLE_STDOUT_CALLBACK": "json", @@ -540,12 +537,10 @@ def discover_playbooks( if path: if not os.path.isabs(path): raise CommandExecutionError( - "The given path is not an absolute path: {}".format(path) + f"The given path is not an absolute path: {path}" ) if not os.path.isdir(path): - raise CommandExecutionError( - "The given path is not a directory: {}".format(path) - ) + raise CommandExecutionError(f"The given path is not a directory: {path}") return { path: _explore_path(path, playbook_extension, hosts_filename, syntax_check) } @@ -599,7 +594,7 @@ def _explore_path(path, playbook_extension, hosts_filename, syntax_check): ) except Exception as exc: raise CommandExecutionError( - "There was an exception while discovering playbooks: {}".format(exc) + f"There was an exception while discovering playbooks: {exc}" ) # Run syntax check validation diff --git a/salt/modules/apache.py b/salt/modules/apache.py index 4b867706d10..3d9fc41c618 100644 --- a/salt/modules/apache.py +++ b/salt/modules/apache.py @@ -8,7 +8,6 @@ Support for Apache Debian-based system is detected. """ - import io import logging import re @@ -61,7 +60,7 @@ def version(): salt '*' apache.version """ - cmd = "{} -v".format(_detect_os()) + cmd = f"{_detect_os()} -v" out = __salt__["cmd.run"](cmd).splitlines() ret = out[0].split(": ") return ret[1] @@ -77,7 +76,7 @@ def fullversion(): salt '*' apache.fullversion """ - cmd = "{} -V".format(_detect_os()) + cmd = f"{_detect_os()} -V" ret = {} ret["compiled_with"] = [] out = __salt__["cmd.run"](cmd).splitlines() @@ -106,7 +105,7 @@ def modules(): salt '*' apache.modules """ - cmd = "{} -M".format(_detect_os()) + cmd = f"{_detect_os()} -M" ret = {} ret["static"] = [] ret["shared"] = [] @@ -132,7 +131,7 @@ def servermods(): salt '*' apache.servermods """ - cmd = "{} -l".format(_detect_os()) + cmd = f"{_detect_os()} -l" ret = [] out = __salt__["cmd.run"](cmd).splitlines() for line in out: @@ -154,7 +153,7 @@ def directives(): salt '*' apache.directives """ - cmd = "{} -L".format(_detect_os()) + cmd = f"{_detect_os()} -L" ret = {} out = __salt__["cmd.run"](cmd) out = out.replace("\n\t", "\t") @@ -181,7 +180,7 @@ def vhosts(): salt -t 10 '*' apache.vhosts """ - cmd = "{} -S".format(_detect_os()) + cmd = f"{_detect_os()} -S" ret = {} namevhost = "" out = __salt__["cmd.run"](cmd) @@ -222,9 +221,9 @@ def signal(signal=None): return # Make sure you use the right arguments if signal in valid_signals: - arguments = " -k {}".format(signal) + arguments = f" -k {signal}" else: - arguments = " {}".format(signal) + arguments = f" {signal}" cmd = _detect_os() + arguments out = __salt__["cmd.run_all"](cmd) @@ -238,7 +237,7 @@ def signal(signal=None): ret = out["stdout"].strip() # No output for something like: apachectl graceful else: - ret = 'Command: "{}" completed successfully!'.format(cmd) + ret = f'Command: "{cmd}" completed successfully!' return ret @@ -327,14 +326,12 @@ def server_status(profile="default"): # Get configuration from pillar url = __salt__["config.get"]( - "apache.server-status:{}:url".format(profile), "http://localhost/server-status" - ) - user = __salt__["config.get"]("apache.server-status:{}:user".format(profile), "") - passwd = __salt__["config.get"]("apache.server-status:{}:pass".format(profile), "") - realm = __salt__["config.get"]("apache.server-status:{}:realm".format(profile), "") - timeout = __salt__["config.get"]( - "apache.server-status:{}:timeout".format(profile), 5 + f"apache.server-status:{profile}:url", "http://localhost/server-status" ) + user = __salt__["config.get"](f"apache.server-status:{profile}:user", "") + passwd = __salt__["config.get"](f"apache.server-status:{profile}:pass", "") + realm = __salt__["config.get"](f"apache.server-status:{profile}:realm", "") + timeout = __salt__["config.get"](f"apache.server-status:{profile}:timeout", 5) # create authentication handler if configuration exists if user and passwd: @@ -380,9 +377,9 @@ def _parse_config(conf, slot=None): ret = io.StringIO() if isinstance(conf, str): if slot: - print("{} {}".format(slot, conf), file=ret, end="") + print(f"{slot} {conf}", file=ret, end="") else: - print("{}".format(conf), file=ret, end="") + print(f"{conf}", file=ret, end="") elif isinstance(conf, list): is_section = False for item in conf: @@ -390,12 +387,12 @@ def _parse_config(conf, slot=None): is_section = True slot_this = str(item["this"]) if is_section: - print("<{} {}>".format(slot, slot_this), file=ret) + print(f"<{slot} {slot_this}>", file=ret) for item in conf: for key, val in item.items(): if key != "this": print(_parse_config(val, str(key)), file=ret) - print("".format(slot), file=ret) + print(f"", file=ret) else: for value in conf: print(_parse_config(value, str(slot)), file=ret) @@ -410,12 +407,12 @@ def _parse_config(conf, slot=None): for key, value in conf.items(): if key != "this": if isinstance(value, str): - print("{} {}".format(key, value), file=ret) + print(f"{key} {value}", file=ret) elif isinstance(value, list): print(_parse_config(value, key), file=ret) elif isinstance(value, dict): print(_parse_config(value, key), file=ret) - print("".format(slot), file=ret) + print(f"", file=ret) ret.seek(0) return ret.read() diff --git a/salt/modules/apf.py b/salt/modules/apf.py index 406f2c9d417..c7de7e47895 100644 --- a/salt/modules/apf.py +++ b/salt/modules/apf.py @@ -45,7 +45,7 @@ def __apf_cmd(cmd): msg = out["stdout"] else: msg = out["stderr"] - raise CommandExecutionError("apf failed: {}".format(msg)) + raise CommandExecutionError(f"apf failed: {msg}") return out["stdout"] @@ -140,7 +140,7 @@ def allow(ip, port=None): salt '*' apf.allow 127.0.0.1 """ if port is None: - return __apf_cmd("-a {}".format(ip)) + return __apf_cmd(f"-a {ip}") def deny(ip): @@ -153,7 +153,7 @@ def deny(ip): salt '*' apf.deny 1.2.3.4 """ - return __apf_cmd("-d {}".format(ip)) + return __apf_cmd(f"-d {ip}") def remove(ip): @@ -166,4 +166,4 @@ def remove(ip): salt '*' apf.remove 1.2.3.4 """ - return __apf_cmd("-u {}".format(ip)) + return __apf_cmd(f"-u {ip}") diff --git a/salt/modules/apkpkg.py b/salt/modules/apkpkg.py index 365c9e4c941..e1240d28d15 100644 --- a/salt/modules/apkpkg.py +++ b/salt/modules/apkpkg.py @@ -597,6 +597,6 @@ def owner(*paths, **kwargs): else: ret[path] = output.split("by ")[1].strip() else: - ret[path] = "Error running {}".format(cmd) + ret[path] = f"Error running {cmd}" return ret diff --git a/salt/modules/aptly.py b/salt/modules/aptly.py index a3409abfc3b..6a0a653b3ff 100644 --- a/salt/modules/aptly.py +++ b/salt/modules/aptly.py @@ -77,10 +77,10 @@ def _format_repo_args( for setting in settings: if settings[setting] is not None: - ret.append("-{}={}".format(setting, settings[setting])) + ret.append(f"-{setting}={settings[setting]}") if cached_uploaders_path: - ret.append("-uploaders-file={}".format(cached_uploaders_path)) + ret.append(f"-uploaders-file={cached_uploaders_path}") return ret @@ -97,7 +97,7 @@ def _validate_config(config_path): log.debug("Checking configuration file: %s", config_path) if not os.path.isfile(config_path): - message = "Unable to get configuration file: {}".format(config_path) + message = f"Unable to get configuration file: {config_path}" log.error(message) raise SaltInvocationError(message) @@ -119,7 +119,7 @@ def get_config(config_path=_DEFAULT_CONFIG_PATH): """ _validate_config(config_path) - cmd = ["config", "show", "-config={}".format(config_path)] + cmd = ["config", "show", f"-config={config_path}"] cmd_ret = _cmd_run(cmd) @@ -145,7 +145,7 @@ def list_repos(config_path=_DEFAULT_CONFIG_PATH, with_packages=False): _validate_config(config_path) ret = dict() - cmd = ["repo", "list", "-config={}".format(config_path), "-raw=true"] + cmd = ["repo", "list", f"-config={config_path}", "-raw=true"] cmd_ret = _cmd_run(cmd) repos = [line.strip() for line in cmd_ret.splitlines()] @@ -183,8 +183,8 @@ def get_repo(name, config_path=_DEFAULT_CONFIG_PATH, with_packages=False): cmd = [ "repo", "show", - "-config={}".format(config_path), - "-with-packages={}".format(with_packages), + f"-config={config_path}", + f"-with-packages={with_packages}", name, ] @@ -250,7 +250,7 @@ def new_repo( log.debug("Repository already exists: %s", name) return True - cmd = ["repo", "create", "-config={}".format(config_path)] + cmd = ["repo", "create", f"-config={config_path}"] repo_params = _format_repo_args( comment=comment, component=component, @@ -336,7 +336,7 @@ def set_repo( log.debug("Settings already have the desired values for repository: %s", name) return True - cmd = ["repo", "edit", "-config={}".format(config_path)] + cmd = ["repo", "edit", f"-config={config_path}"] repo_params = _format_repo_args( comment=comment, @@ -395,8 +395,8 @@ def delete_repo(name, config_path=_DEFAULT_CONFIG_PATH, force=False): cmd = [ "repo", "drop", - "-config={}".format(config_path), - "-force={}".format(force), + f"-config={config_path}", + f"-force={force}", name, ] @@ -427,7 +427,7 @@ def list_mirrors(config_path=_DEFAULT_CONFIG_PATH): """ _validate_config(config_path) - cmd = ["mirror", "list", "-config={}".format(config_path), "-raw=true"] + cmd = ["mirror", "list", f"-config={config_path}", "-raw=true"] cmd_ret = _cmd_run(cmd) ret = [line.strip() for line in cmd_ret.splitlines()] @@ -453,7 +453,7 @@ def list_published(config_path=_DEFAULT_CONFIG_PATH): """ _validate_config(config_path) - cmd = ["publish", "list", "-config={}".format(config_path), "-raw=true"] + cmd = ["publish", "list", f"-config={config_path}", "-raw=true"] cmd_ret = _cmd_run(cmd) ret = [line.strip() for line in cmd_ret.splitlines()] @@ -480,7 +480,7 @@ def list_snapshots(config_path=_DEFAULT_CONFIG_PATH, sort_by_time=False): """ _validate_config(config_path) - cmd = ["snapshot", "list", "-config={}".format(config_path), "-raw=true"] + cmd = ["snapshot", "list", f"-config={config_path}", "-raw=true"] if sort_by_time: cmd.append("-sort=time") @@ -518,8 +518,8 @@ def cleanup_db(config_path=_DEFAULT_CONFIG_PATH, dry_run=False): cmd = [ "db", "cleanup", - "-config={}".format(config_path), - "-dry-run={}".format(dry_run), + f"-config={config_path}", + f"-dry-run={dry_run}", "-verbose=true", ] @@ -533,7 +533,7 @@ def cleanup_db(config_path=_DEFAULT_CONFIG_PATH, dry_run=False): if current_block: match = re.search(list_pattern, line) if match: - package_type = "deleted_{}".format(current_block) + package_type = f"deleted_{current_block}" ret[package_type].append(match.group("package")) else: current_block = None diff --git a/salt/modules/archive.py b/salt/modules/archive.py index 3f91cd9cefe..f96d03bc404 100644 --- a/salt/modules/archive.py +++ b/salt/modules/archive.py @@ -207,7 +207,7 @@ def list_( stderr = cached.communicate()[1] if cached.returncode != 0: raise CommandExecutionError( - "Failed to decompress {}".format(name), + f"Failed to decompress {name}", info={"error": stderr}, ) else: @@ -290,7 +290,7 @@ def list_( files.remove(dirname) return list(dirs), files, links except zipfile.BadZipfile: - raise CommandExecutionError("{} is not a ZIP file".format(name)) + raise CommandExecutionError(f"{name} is not a ZIP file") def _list_rar(name, cached): """ @@ -335,7 +335,7 @@ def list_( name, saltenv, source_hash=source_hash, use_etag=use_etag ) if not cached: - raise CommandExecutionError("Failed to cache {}".format(name)) + raise CommandExecutionError(f"Failed to cache {name}") try: if strip_components: @@ -362,7 +362,7 @@ def list_( "'archive_format' argument." ) raise CommandExecutionError( - "Unsupported archive format '{}'".format(archive_format) + f"Unsupported archive format '{archive_format}'" ) if not archive_format: @@ -380,13 +380,13 @@ def list_( dirs, files, links = func(name, cached, *args) except OSError as exc: raise CommandExecutionError( - "Failed to list contents of {}: {}".format(name, exc.__str__()) + f"Failed to list contents of {name}: {exc.__str__()}" ) except CommandExecutionError as exc: raise except Exception as exc: # pylint: disable=broad-except raise CommandExecutionError( - "Uncaught exception '{}' when listing contents of {}".format(exc, name) + f"Uncaught exception '{exc}' when listing contents of {name}" ) if clean: @@ -551,10 +551,10 @@ def tar(options, tarfile, sources=None, dest=None, cwd=None, template=None, runa if options: cmd.extend(options.split()) - cmd.extend(["{}".format(tarfile)]) + cmd.extend([f"{tarfile}"]) cmd.extend(_expand_sources(sources)) if dest: - cmd.extend(["-C", "{}".format(dest)]) + cmd.extend(["-C", f"{dest}"]) return __salt__["cmd.run"]( cmd, cwd=cwd, template=template, runas=runas, python_shell=False @@ -593,7 +593,7 @@ def gzip(sourcefile, template=None, runas=None, options=None): cmd = ["gzip"] if options: cmd.append(options) - cmd.append("{}".format(sourcefile)) + cmd.append(f"{sourcefile}") return __salt__["cmd.run"]( cmd, template=template, runas=runas, python_shell=False @@ -632,7 +632,7 @@ def gunzip(gzipfile, template=None, runas=None, options=None): cmd = ["gunzip"] if options: cmd.append(options) - cmd.append("{}".format(gzipfile)) + cmd.append(f"{gzipfile}") return __salt__["cmd.run"]( cmd, template=template, runas=runas, python_shell=False @@ -698,7 +698,7 @@ def cmd_zip(zip_file, sources, template=None, cwd=None, runas=None): salt '*' archive.cmd_zip /tmp/zipfile.zip '/tmp/sourcefile*' """ cmd = ["zip", "-r"] - cmd.append("{}".format(zip_file)) + cmd.append(f"{zip_file}") cmd.extend(_expand_sources(sources)) return __salt__["cmd.run"]( cmd, cwd=cwd, template=template, runas=runas, python_shell=False @@ -773,7 +773,7 @@ def zip_(zip_file, sources, template=None, cwd=None, runas=None, zip64=False): egid = os.getegid() uinfo = __salt__["user.info"](runas) if not uinfo: - raise SaltInvocationError("User '{}' does not exist".format(runas)) + raise SaltInvocationError(f"User '{runas}' does not exist") zip_file, sources = _render_filenames(zip_file, sources, None, template) sources = _expand_sources(sources) @@ -848,7 +848,7 @@ def zip_(zip_file, sources, template=None, cwd=None, runas=None, zip64=False): ) else: raise CommandExecutionError( - "Exception encountered creating zipfile: {}".format(exc) + f"Exception encountered creating zipfile: {exc}" ) return archived_files @@ -942,7 +942,7 @@ def cmd_unzip( cmd.extend(["-P", password]) if options: cmd.extend(shlex.split(options)) - cmd.extend(["{}".format(zip_file), "-d", "{}".format(dest)]) + cmd.extend([f"{zip_file}", "-d", f"{dest}"]) if excludes is not None: cmd.append("-x") @@ -1060,7 +1060,7 @@ def unzip( egid = os.getegid() uinfo = __salt__["user.info"](runas) if not uinfo: - raise SaltInvocationError("User '{}' does not exist".format(runas)) + raise SaltInvocationError(f"User '{runas}' does not exist") zip_file, dest = _render_filenames(zip_file, dest, None, template) @@ -1121,9 +1121,7 @@ def unzip( os.setegid(egid) # Wait to raise the exception until euid/egid are restored to avoid # permission errors in writing to minion log. - raise CommandExecutionError( - "Exception encountered unpacking zipfile: {}".format(exc) - ) + raise CommandExecutionError(f"Exception encountered unpacking zipfile: {exc}") finally: # Restore the euid/egid if runas: @@ -1190,7 +1188,7 @@ def is_encrypted(name, clean=False, saltenv="base", source_hash=None, use_etag=F name, saltenv, source_hash=source_hash, use_etag=use_etag ) if not cached: - raise CommandExecutionError("Failed to cache {}".format(name)) + raise CommandExecutionError(f"Failed to cache {name}") archive_info = {"archive location": cached} try: @@ -1199,9 +1197,7 @@ def is_encrypted(name, clean=False, saltenv="base", source_hash=None, use_etag=F except RuntimeError: ret = True except zipfile.BadZipfile: - raise CommandExecutionError( - "{} is not a ZIP file".format(name), info=archive_info - ) + raise CommandExecutionError(f"{name} is not a ZIP file", info=archive_info) except Exception as exc: # pylint: disable=broad-except raise CommandExecutionError(exc.__str__(), info=archive_info) else: @@ -1261,7 +1257,7 @@ def rar(rarfile, sources, template=None, cwd=None, runas=None): # Globbing for sources (2017.7.0 and later) salt '*' archive.rar /tmp/rarfile.rar '/tmp/sourcefile*' """ - cmd = ["rar", "a", "-idp", "{}".format(rarfile)] + cmd = ["rar", "a", "-idp", f"{rarfile}"] cmd.extend(_expand_sources(sources)) return __salt__["cmd.run"]( cmd, cwd=cwd, template=template, runas=runas, python_shell=False @@ -1307,12 +1303,12 @@ def unrar(rarfile, dest, excludes=None, template=None, runas=None, trim_output=F salt.utils.path.which_bin(("unrar", "rar")), "x", "-idp", - "{}".format(rarfile), + f"{rarfile}", ] if excludes is not None: for exclude in excludes: - cmd.extend(["-x", "{}".format(exclude)]) - cmd.append("{}".format(dest)) + cmd.extend(["-x", f"{exclude}"]) + cmd.append(f"{dest}") files = __salt__["cmd.run"]( cmd, template=template, runas=runas, python_shell=False ).splitlines() @@ -1332,7 +1328,7 @@ def _render_filenames(filenames, zip_file, saltenv, template): # render the path as a template using path_template_engine as the engine if template not in salt.utils.templates.TEMPLATE_REGISTRY: raise CommandExecutionError( - "Attempted to render file paths with unavailable engine {}".format(template) + f"Attempted to render file paths with unavailable engine {template}" ) kwargs = {} @@ -1381,6 +1377,6 @@ def _trim_files(files, trim_output): and len(files) > count ): files = files[:count] - files.append("List trimmed after {} files.".format(count)) + files.append(f"List trimmed after {count} files.") return files diff --git a/salt/modules/arista_pyeapi.py b/salt/modules/arista_pyeapi.py index 1dbd27fd872..9e9abb1a973 100644 --- a/salt/modules/arista_pyeapi.py +++ b/salt/modules/arista_pyeapi.py @@ -398,7 +398,7 @@ def config( context=None, defaults=None, saltenv="base", - **kwargs + **kwargs, ): """ Configures the node with the specified commands. @@ -509,7 +509,7 @@ def config( if config_file: file_str = __salt__["cp.get_file_str"](config_file, saltenv=saltenv) if file_str is False: - raise CommandExecutionError("Source file {} not found".format(config_file)) + raise CommandExecutionError(f"Source file {config_file} not found") log.debug("Fetched from %s", config_file) log.debug(file_str) elif commands: diff --git a/salt/modules/augeas_cfg.py b/salt/modules/augeas_cfg.py index 70f05b3a465..adc4fa22b21 100644 --- a/salt/modules/augeas_cfg.py +++ b/salt/modules/augeas_cfg.py @@ -190,7 +190,7 @@ def execute(context=None, lens=None, commands=(), load_path=None): cmd, arg = command.split(" ", 1) if cmd not in METHOD_MAP: - ret["error"] = "Command {} is not supported (yet)".format(cmd) + ret["error"] = f"Command {cmd} is not supported (yet)" return ret method = METHOD_MAP[cmd] @@ -199,7 +199,7 @@ def execute(context=None, lens=None, commands=(), load_path=None): parts = salt.utils.args.shlex_split(arg) if len(parts) not in nargs: - err = "{} takes {} args: {}".format(method, nargs, parts) + err = f"{method} takes {nargs} args: {parts}" raise ValueError(err) if method == "set": path = make_path(parts[0]) @@ -217,9 +217,7 @@ def execute(context=None, lens=None, commands=(), load_path=None): elif method == "insert": label, where, path = parts if where not in ("before", "after"): - raise ValueError( - 'Expected "before" or "after", not {}'.format(where) - ) + raise ValueError(f'Expected "before" or "after", not {where}') path = make_path(path) args = {"path": path, "label": label, "before": where == "before"} elif method == "remove": @@ -230,9 +228,9 @@ 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"] = ( + f"Invalid formatted command, see debug log for details: {arg}" + ) return ret args = salt.utils.data.decode(args, to_str=True) @@ -374,7 +372,7 @@ def setvalue(*args): try: aug.set(target_path, str(value)) except ValueError as err: - ret["error"] = "Multiple values: {}".format(err) + ret["error"] = f"Multiple values: {err}" try: aug.save() diff --git a/salt/modules/aws_sqs.py b/salt/modules/aws_sqs.py index e85417faf1a..428f4062dad 100644 --- a/salt/modules/aws_sqs.py +++ b/salt/modules/aws_sqs.py @@ -23,7 +23,7 @@ def _region(region): """ Return the region argument. """ - return " --region {r}".format(r=region) + return f" --region {region}" def _run_aws(cmd, region, opts, user, **kwargs): @@ -49,7 +49,7 @@ def _run_aws(cmd, region, opts, user, **kwargs): if num: kwargs["max-number-of-messages"] = num - _formatted_args = ['--{} "{}"'.format(k, v) for k, v in kwargs.items()] + _formatted_args = [f'--{k} "{v}"' for k, v in kwargs.items()] cmd = "aws sqs {cmd} {args} {region} {out}".format( cmd=cmd, args=" ".join(_formatted_args), region=_region(region), out=_OUTPUT @@ -245,7 +245,7 @@ def delete_queue(name, region, opts=None, user=None): rtn = _run_aws("delete-queue", region=region, opts=opts, user=user, **delete) success = True err = "" - out = "{} deleted".format(name) + out = f"{name} deleted" else: out = "" diff --git a/salt/modules/bamboohr.py b/salt/modules/bamboohr.py index 5cdd05bee8e..e1582ff9a3f 100644 --- a/salt/modules/bamboohr.py +++ b/salt/modules/bamboohr.py @@ -175,8 +175,8 @@ def update_employee(emp_id, key=None, value=None, items=None): xml_items = "" for pair in items: - xml_items += '{}'.format(pair, items[pair]) - xml_items = "{}".format(xml_items) + xml_items += f'{items[pair]}' + xml_items = f"{xml_items}" status, result = _query( action="employees", @@ -259,13 +259,13 @@ def _query(action=None, command=None, args=None, method="GET", data=None): The password can be any random text, so we chose Salty text. """ subdomain = __opts__.get("bamboohr", {}).get("subdomain", None) - path = "https://api.bamboohr.com/api/gateway.php/{}/v1/".format(subdomain) + path = f"https://api.bamboohr.com/api/gateway.php/{subdomain}/v1/" if action: path += action if command: - path += "/{}".format(command) + path += f"/{command}" log.debug("BambooHR URL: %s", path) diff --git a/salt/modules/baredoc.py b/salt/modules/baredoc.py index aa867102bd4..7513b546919 100644 --- a/salt/modules/baredoc.py +++ b/salt/modules/baredoc.py @@ -122,9 +122,9 @@ def _parse_module_docs(module_path, mod_name=None): function_name = v if mod_name and "." in mod_name: if function_name == mod_name.split(".")[1]: - ret["{}.{}".format(module_name, function_name)] = doc_string + ret[f"{module_name}.{function_name}"] = doc_string else: - ret["{}.{}".format(module_name, function_name)] = doc_string + ret[f"{module_name}.{function_name}"] = doc_string return salt.utils.doc.strip_rst(ret) diff --git a/salt/modules/bcache.py b/salt/modules/bcache.py index 7e69b45ad57..acd4fdbcd56 100644 --- a/salt/modules/bcache.py +++ b/salt/modules/bcache.py @@ -117,14 +117,14 @@ def attach_(dev=None): "attach", cache, "error", - "Error attaching {} to bcache {}".format(dev, cache), + f"Error attaching {dev} to bcache {cache}", ): return False return _wait( lambda: uuid(dev) == cache, "error", - "{} received attach to bcache {}, but did not comply".format(dev, cache), + f"{dev} received attach to bcache {cache}, but did not comply", ) @@ -153,12 +153,12 @@ def detach(dev=None): return res if res else None log.debug("Detaching %s", dev) - if not _bcsys(dev, "detach", "goaway", "error", "Error detaching {}".format(dev)): + if not _bcsys(dev, "detach", "goaway", "error", f"Error detaching {dev}"): return False return _wait( lambda: uuid(dev) is False, "error", - "{} received detach, but did not comply".format(dev), + f"{dev} received detach, but did not comply", 300, ) @@ -203,12 +203,12 @@ def stop(dev=None): """ if dev is not None: log.warning("Stopping %s, device will only reappear after reregistering!", dev) - if not _bcsys(dev, "stop", "goaway", "error", "Error stopping {}".format(dev)): + if not _bcsys(dev, "stop", "goaway", "error", f"Error stopping {dev}"): return False return _wait( lambda: _sysfs_attr(_bcpath(dev)) is False, "error", - "Device {} did not stop".format(dev), + f"Device {dev} did not stop", 300, ) else: @@ -271,19 +271,19 @@ def back_make(dev, cache_mode="writeback", force=False, attach=True, bucket_size if force: cmd += " --wipe-bcache" - if not _run_all(cmd, "error", "Error creating backing device {}: %s".format(dev)): + if not _run_all(cmd, "error", f"Error creating backing device {dev}: %s"): return False elif not _sysfs_attr( "fs/bcache/register", _devpath(dev), "error", - "Error registering backing device {}".format(dev), + f"Error registering backing device {dev}", ): return False elif not _wait( lambda: _sysfs_attr(_bcpath(dev)) is not False, "error", - "Backing device {} did not register".format(dev), + f"Backing device {dev} did not register", ): return False elif attach: @@ -370,25 +370,23 @@ def cache_make( ) # if wipe was incomplete & part layout remains the same, # this is one condition set where udev would make it accidentally popup again - if not _run_all( - cmd, "error", "Error creating bcache partitions on {}: %s".format(dev) - ): + if not _run_all(cmd, "error", f"Error creating bcache partitions on {dev}: %s"): return False - dev = "{}2".format(dev) + dev = f"{dev}2" # ---------------- Finally, create a cache ---------------- - cmd = "make-bcache --cache /dev/{} --block {} --wipe-bcache".format(dev, block_size) + cmd = f"make-bcache --cache /dev/{dev} --block {block_size} --wipe-bcache" # Actually bucket_size should always have a value, but for testing 0 is possible as well if bucket_size: - cmd += " --bucket {}".format(bucket_size) + cmd += f" --bucket {bucket_size}" - if not _run_all(cmd, "error", "Error creating cache {}: %s".format(dev)): + if not _run_all(cmd, "error", f"Error creating cache {dev}: %s"): return False elif not _wait( lambda: uuid() is not False, "error", - "Cache {} seemingly created OK, but FS did not activate".format(dev), + f"Cache {dev} seemingly created OK, but FS did not activate", ): return False @@ -430,7 +428,7 @@ def config_(dev=None, **kwargs): [spath, key], val, "warn", - "Failed to update {} with {}".format(os.path.join(spath, key), val), + f"Failed to update {os.path.join(spath, key)} with {val}", ) return endres > 0 else: @@ -470,7 +468,7 @@ def status(stats=False, config=False, internals=False, superblock=False, alldevs continue for spath, sdirs, _ in salt.utils.path.os_walk( - "/sys/block/{}".format(block), followlinks=False + f"/sys/block/{block}", followlinks=False ): if "bcache" in sdirs: bdevs.append(os.path.basename(spath)) @@ -514,7 +512,7 @@ def device(dev, stats=False, config=False, internals=False, superblock=False): result = {} if not _sysfs_attr( - _bcpath(dev), None, "error", "{} is not a bcache fo any kind".format(dev) + _bcpath(dev), None, "error", f"{dev} is not a bcache fo any kind" ): return False elif _bcsys(dev, "set"): @@ -632,9 +630,9 @@ def super_(dev): ret = {} res = _run_all( - "bcache-super-show {}".format(dev), + f"bcache-super-show {dev}", "error", - "Error reading superblock on {}: %s".format(dev), + f"Error reading superblock on {dev}: %s", ) if not res: return False @@ -992,18 +990,18 @@ def _wipe(dev): else: wiper = "blkdiscard" - wipe_failmsg = "Error wiping {}: %s".format(dev) + wipe_failmsg = f"Error wiping {dev}: %s" if wiper == "dd": blocks = 4 - cmd = "dd if=/dev/zero of=/dev/{} bs=1M count={}".format(dev, blocks) + cmd = f"dd if=/dev/zero of=/dev/{dev} bs=1M count={blocks}" endres += _run_all(cmd, "warn", wipe_failmsg) # Some stuff (GPT) writes stuff at the end of a dev as well - cmd += " seek={}".format((size / 1024**2) - blocks) + cmd += f" seek={(size / 1024**2) - blocks}" endres += _run_all(cmd, "warn", wipe_failmsg) elif wiper == "blkdiscard": - cmd = "blkdiscard /dev/{}".format(dev) + cmd = f"blkdiscard /dev/{dev}" endres += _run_all(cmd, "warn", wipe_failmsg) # TODO: fix annoying bug failing blkdiscard by trying to discard 1 sector past blkdev endres = 1 diff --git a/salt/modules/beacons.py b/salt/modules/beacons.py index 3aef0abbec2..e482abcf235 100644 --- a/salt/modules/beacons.py +++ b/salt/modules/beacons.py @@ -5,7 +5,6 @@ Module for managing the Salt beacons on a minion """ - import difflib import logging import os @@ -139,10 +138,10 @@ def add(name, beacon_data, **kwargs): salt '*' beacons.add ps "[{'processes': {'salt-master': 'stopped', 'apache2': 'stopped'}}]" """ - ret = {"comment": "Failed to add beacon {}.".format(name), "result": False} + ret = {"comment": f"Failed to add beacon {name}.", "result": False} if name in list_(return_yaml=False, **kwargs): - ret["comment"] = "Beacon {} is already configured.".format(name) + ret["comment"] = f"Beacon {name} is already configured." ret["result"] = True return ret @@ -155,12 +154,12 @@ def add(name, beacon_data, **kwargs): beacon_name = name if beacon_name not in list_available(return_yaml=False, **kwargs): - ret["comment"] = 'Beacon "{}" is not available.'.format(beacon_name) + ret["comment"] = f'Beacon "{beacon_name}" is not available.' return ret if "test" in kwargs and kwargs["test"]: ret["result"] = True - ret["comment"] = "Beacon: {} would be added.".format(name) + ret["comment"] = f"Beacon: {name} would be added." else: try: # Attempt to load the beacon module so we have access to the validate function @@ -185,10 +184,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: @@ -216,7 +215,7 @@ def add(name, beacon_data, **kwargs): [item in beacons[name] for item in beacon_data] ): ret["result"] = True - ret["comment"] = "Added beacon: {}.".format(name) + ret["comment"] = f"Added beacon: {name}." elif event_ret: ret["result"] = False ret["comment"] = event_ret["comment"] @@ -255,12 +254,12 @@ def modify(name, beacon_data, **kwargs): current_beacons = list_(return_yaml=False, **kwargs) if name not in current_beacons: - ret["comment"] = "Beacon {} is not configured.".format(name) + ret["comment"] = f"Beacon {name} is not configured." return ret if "test" in kwargs and kwargs["test"]: ret["result"] = True - ret["comment"] = "Beacon: {} would be modified.".format(name) + ret["comment"] = f"Beacon: {name} would be modified." else: try: # Attempt to load the beacon module so we have access to the validate function @@ -285,10 +284,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,10 +299,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 @@ -311,19 +310,17 @@ def modify(name, beacon_data, **kwargs): _new = beacon_data if _new == _current: - ret["comment"] = "Job {} in correct state".format(name) + ret["comment"] = f"Job {name} in correct state" return ret _current_lines = [] for _item in _current: _current_lines.extend( - ["{}:{}\n".format(key, value) for (key, value) in _item.items()] + [f"{key}:{value}\n" for (key, value) in _item.items()] ) _new_lines = [] for _item in _new: - _new_lines.extend( - ["{}:{}\n".format(key, value) for (key, value) in _item.items()] - ) + _new_lines.extend([f"{key}:{value}\n" for (key, value) in _item.items()]) _diff = difflib.unified_diff(_current_lines, _new_lines) ret["changes"] = {} @@ -346,7 +343,7 @@ def modify(name, beacon_data, **kwargs): beacons = event_ret["beacons"] if name in beacons and beacons[name] == beacon_data: ret["result"] = True - ret["comment"] = "Modified beacon: {}.".format(name) + ret["comment"] = f"Modified beacon: {name}." elif event_ret: ret["result"] = False ret["comment"] = event_ret["comment"] @@ -383,11 +380,11 @@ def delete(name, **kwargs): """ - ret = {"comment": "Failed to delete beacon {}.".format(name), "result": False} + ret = {"comment": f"Failed to delete beacon {name}.", "result": False} if "test" in kwargs and kwargs["test"]: ret["result"] = True - ret["comment"] = "Beacon: {} would be deleted.".format(name) + ret["comment"] = f"Beacon: {name} would be deleted." else: try: with salt.utils.event.get_event( @@ -405,7 +402,7 @@ def delete(name, **kwargs): beacons = event_ret["beacons"] if name not in beacons: ret["result"] = True - ret["comment"] = "Deleted beacon: {}.".format(name) + ret["comment"] = f"Deleted beacon: {name}." return ret elif event_ret: ret["result"] = False @@ -457,11 +454,9 @@ def save(**kwargs): try: with salt.utils.files.fopen(sfn, "w+") as fp_: fp_.write(yaml_out) - ret["comment"] = "Beacons saved to {}.".format(sfn) + ret["comment"] = f"Beacons saved to {sfn}." except OSError: - ret[ - "comment" - ] = "Unable to write to beacons file at {}. Check permissions.".format(sfn) + ret["comment"] = f"Unable to write to beacons file at {sfn}. Check permissions." ret["result"] = False return ret @@ -604,11 +599,11 @@ def enable_beacon(name, **kwargs): return ret if "test" in kwargs and kwargs["test"]: - ret["comment"] = "Beacon {} would be enabled.".format(name) + ret["comment"] = f"Beacon {name} would be enabled." else: _beacons = list_(return_yaml=False, **kwargs) if name not in _beacons: - ret["comment"] = "Beacon {} is not currently configured.".format(name) + ret["comment"] = f"Beacon {name} is not currently configured." ret["result"] = False return ret @@ -633,12 +628,12 @@ def enable_beacon(name, **kwargs): and beacon_config_dict["enabled"] ): ret["result"] = True - ret["comment"] = "Enabled beacon {} on minion.".format(name) + ret["comment"] = f"Enabled beacon {name} on minion." else: ret["result"] = False - ret[ - "comment" - ] = "Failed to enable beacon {} on minion.".format(name) + ret["comment"] = ( + f"Failed to enable beacon {name} on minion." + ) elif event_ret: ret["result"] = False ret["comment"] = event_ret["comment"] @@ -654,9 +649,9 @@ def enable_beacon(name, **kwargs): except KeyError: # Effectively a no-op, since we can't really return without an event system ret["result"] = False - ret[ - "comment" - ] = "Event module not available. Beacon enable_beacon job failed." + ret["comment"] = ( + "Event module not available. Beacon enable_beacon job failed." + ) return ret @@ -686,7 +681,7 @@ def disable_beacon(name, **kwargs): else: _beacons = list_(return_yaml=False, **kwargs) if name not in _beacons: - ret["comment"] = "Beacon {} is not currently configured.".format(name) + ret["comment"] = f"Beacon {name} is not currently configured." ret["result"] = False return ret @@ -732,9 +727,9 @@ def disable_beacon(name, **kwargs): except KeyError: # Effectively a no-op, since we can't really return without an event system ret["result"] = False - ret[ - "comment" - ] = "Event module not available. Beacon disable_beacon job failed." + ret["comment"] = ( + "Event module not available. Beacon disable_beacon job failed." + ) return ret diff --git a/salt/modules/bigip.py b/salt/modules/bigip.py index 219afea9726..6624b85c6f8 100644 --- a/salt/modules/bigip.py +++ b/salt/modules/bigip.py @@ -48,9 +48,7 @@ def _build_session(username, password, trans_label=None): if trans_label: # pull the trans id from the grain - trans_id = __salt__["grains.get"]( - "bigip_f5_trans:{label}".format(label=trans_label) - ) + trans_id = __salt__["grains.get"](f"bigip_f5_trans:{trans_label}") if trans_id: bigip.headers.update({"X-F5-REST-Coordination-Id": trans_id}) @@ -311,7 +309,7 @@ def list_transaction(hostname, username, password, label): bigip_session = _build_session(username, password) # pull the trans id from the grain - trans_id = __salt__["grains.get"]("bigip_f5_trans:{label}".format(label=label)) + trans_id = __salt__["grains.get"](f"bigip_f5_trans:{label}") if trans_id: @@ -319,7 +317,7 @@ def list_transaction(hostname, username, password, label): try: response = bigip_session.get( BIG_IP_URL_BASE.format(host=hostname) - + "/transaction/{trans_id}/commands".format(trans_id=trans_id) + + f"/transaction/{trans_id}/commands" ) return _load_response(response) except requests.exceptions.ConnectionError as e: @@ -356,7 +354,7 @@ def commit_transaction(hostname, username, password, label): bigip_session = _build_session(username, password) # pull the trans id from the grain - trans_id = __salt__["grains.get"]("bigip_f5_trans:{label}".format(label=label)) + trans_id = __salt__["grains.get"](f"bigip_f5_trans:{label}") if trans_id: @@ -366,8 +364,7 @@ def commit_transaction(hostname, username, password, label): # patch to REST to get trans id try: response = bigip_session.patch( - BIG_IP_URL_BASE.format(host=hostname) - + "/transaction/{trans_id}".format(trans_id=trans_id), + BIG_IP_URL_BASE.format(host=hostname) + f"/transaction/{trans_id}", data=salt.utils.json.dumps(payload), ) return _load_response(response) @@ -405,15 +402,14 @@ def delete_transaction(hostname, username, password, label): bigip_session = _build_session(username, password) # pull the trans id from the grain - trans_id = __salt__["grains.get"]("bigip_f5_trans:{label}".format(label=label)) + trans_id = __salt__["grains.get"](f"bigip_f5_trans:{label}") if trans_id: # patch to REST to get trans id try: response = bigip_session.delete( - BIG_IP_URL_BASE.format(host=hostname) - + "/transaction/{trans_id}".format(trans_id=trans_id) + BIG_IP_URL_BASE.format(host=hostname) + f"/transaction/{trans_id}" ) return _load_response(response) except requests.exceptions.ConnectionError as e: @@ -457,8 +453,7 @@ def list_node(hostname, username, password, name=None, trans_label=None): try: if name: response = bigip_session.get( - BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/node/{name}".format(name=name) + BIG_IP_URL_BASE.format(host=hostname) + f"/ltm/node/{name}" ) else: response = bigip_session.get( @@ -593,8 +588,7 @@ def modify_node( # put to REST try: response = bigip_session.put( - BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/node/{name}".format(name=name), + BIG_IP_URL_BASE.format(host=hostname) + f"/ltm/node/{name}", data=salt.utils.json.dumps(payload), ) except requests.exceptions.ConnectionError as e: @@ -632,7 +626,7 @@ def delete_node(hostname, username, password, name, trans_label=None): # delete to REST try: response = bigip_session.delete( - BIG_IP_URL_BASE.format(host=hostname) + "/ltm/node/{name}".format(name=name) + BIG_IP_URL_BASE.format(host=hostname) + f"/ltm/node/{name}" ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) @@ -672,7 +666,7 @@ def list_pool(hostname, username, password, name=None): if name: response = bigip_session.get( BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/pool/{name}/?expandSubcollections=true".format(name=name) + + f"/ltm/pool/{name}/?expandSubcollections=true" ) else: response = bigip_session.get( @@ -991,8 +985,7 @@ def modify_pool( # post to REST try: response = bigip_session.put( - BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/pool/{name}".format(name=name), + BIG_IP_URL_BASE.format(host=hostname) + f"/ltm/pool/{name}", data=salt.utils.json.dumps(payload), ) except requests.exceptions.ConnectionError as e: @@ -1027,7 +1020,7 @@ def delete_pool(hostname, username, password, name): # delete to REST try: response = bigip_session.delete( - BIG_IP_URL_BASE.format(host=hostname) + "/ltm/pool/{name}".format(name=name) + BIG_IP_URL_BASE.format(host=hostname) + f"/ltm/pool/{name}" ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) @@ -1098,8 +1091,7 @@ def replace_pool_members(hostname, username, password, name, members): # put to REST try: response = bigip_session.put( - BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/pool/{name}".format(name=name), + BIG_IP_URL_BASE.format(host=hostname) + f"/ltm/pool/{name}", data=salt.utils.json.dumps(payload), ) except requests.exceptions.ConnectionError as e: @@ -1155,8 +1147,7 @@ def add_pool_member(hostname, username, password, name, member): # post to REST try: response = bigip_session.post( - BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/pool/{name}/members".format(name=name), + BIG_IP_URL_BASE.format(host=hostname) + f"/ltm/pool/{name}/members", data=salt.utils.json.dumps(payload), ) except requests.exceptions.ConnectionError as e: @@ -1254,7 +1245,7 @@ def modify_pool_member( try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/pool/{name}/members/{member}".format(name=name, member=member), + + f"/ltm/pool/{name}/members/{member}", data=salt.utils.json.dumps(payload), ) except requests.exceptions.ConnectionError as e: @@ -1291,8 +1282,7 @@ def delete_pool_member(hostname, username, password, name, member): # delete to REST try: response = bigip_session.delete( - BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/pool/{name}/members/{member}".format(name=name, member=member) + BIG_IP_URL_BASE.format(host=hostname) + f"/ltm/pool/{name}/members/{member}" ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) @@ -1332,7 +1322,7 @@ def list_virtual(hostname, username, password, name=None): if name: response = bigip_session.get( BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/virtual/{name}/?expandSubcollections=true".format(name=name) + + f"/ltm/virtual/{name}/?expandSubcollections=true" ) else: response = bigip_session.get( @@ -1925,8 +1915,7 @@ def modify_virtual( # put to REST try: response = bigip_session.put( - BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/virtual/{name}".format(name=name), + BIG_IP_URL_BASE.format(host=hostname) + f"/ltm/virtual/{name}", data=salt.utils.json.dumps(payload), ) except requests.exceptions.ConnectionError as e: @@ -1961,8 +1950,7 @@ def delete_virtual(hostname, username, password, name): # delete to REST try: response = bigip_session.delete( - BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/virtual/{name}".format(name=name) + BIG_IP_URL_BASE.format(host=hostname) + f"/ltm/virtual/{name}" ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) @@ -2017,8 +2005,7 @@ def list_monitor( ) else: response = bigip_session.get( - BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/monitor/{type}".format(type=monitor_type) + BIG_IP_URL_BASE.format(host=hostname) + f"/ltm/monitor/{monitor_type}" ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) @@ -2069,8 +2056,7 @@ def create_monitor(hostname, username, password, monitor_type, name, **kwargs): # post to REST try: response = bigip_session.post( - BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/monitor/{type}".format(type=monitor_type), + BIG_IP_URL_BASE.format(host=hostname) + f"/ltm/monitor/{monitor_type}", data=salt.utils.json.dumps(payload), ) except requests.exceptions.ConnectionError as e: @@ -2123,7 +2109,7 @@ def modify_monitor(hostname, username, password, monitor_type, name, **kwargs): try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/monitor/{type}/{name}".format(type=monitor_type, name=name), + + f"/ltm/monitor/{monitor_type}/{name}", data=salt.utils.json.dumps(payload), ) except requests.exceptions.ConnectionError as e: @@ -2162,7 +2148,7 @@ def delete_monitor(hostname, username, password, monitor_type, name): try: response = bigip_session.delete( BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/monitor/{type}/{name}".format(type=monitor_type, name=name) + + f"/ltm/monitor/{monitor_type}/{name}" ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) @@ -2217,8 +2203,7 @@ def list_profile( ) else: response = bigip_session.get( - BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/profile/{type}".format(type=profile_type) + BIG_IP_URL_BASE.format(host=hostname) + f"/ltm/profile/{profile_type}" ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) @@ -2302,8 +2287,7 @@ def create_profile(hostname, username, password, profile_type, name, **kwargs): # post to REST try: response = bigip_session.post( - BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/profile/{type}".format(type=profile_type), + BIG_IP_URL_BASE.format(host=hostname) + f"/ltm/profile/{profile_type}", data=salt.utils.json.dumps(payload), ) except requests.exceptions.ConnectionError as e: @@ -2396,7 +2380,7 @@ def modify_profile(hostname, username, password, profile_type, name, **kwargs): try: response = bigip_session.put( BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/profile/{type}/{name}".format(type=profile_type, name=name), + + f"/ltm/profile/{profile_type}/{name}", data=salt.utils.json.dumps(payload), ) except requests.exceptions.ConnectionError as e: @@ -2435,7 +2419,7 @@ def delete_profile(hostname, username, password, profile_type, name): try: response = bigip_session.delete( BIG_IP_URL_BASE.format(host=hostname) - + "/ltm/profile/{type}/{name}".format(type=profile_type, name=name) + + f"/ltm/profile/{profile_type}/{name}" ) except requests.exceptions.ConnectionError as e: return _load_connection_error(hostname, e) diff --git a/salt/modules/bluez_bluetooth.py b/salt/modules/bluez_bluetooth.py index ba2ec098e5d..1813e7014ef 100644 --- a/salt/modules/bluez_bluetooth.py +++ b/salt/modules/bluez_bluetooth.py @@ -8,6 +8,7 @@ The following packages are required packages for this module: bluez-utils >= 5.7 pybluez >= 0.18 """ + import shlex import salt.utils.validate.net @@ -80,7 +81,7 @@ def address_(): dev = comps[0] ret[dev] = { "device": dev, - "path": "/sys/class/bluetooth/{}".format(dev), + "path": f"/sys/class/bluetooth/{dev}", } if "BD Address" in line: comps = line.split() @@ -112,7 +113,7 @@ def power(dev, mode): else: state = "down" mode = "off" - cmd = "hciconfig {} {}".format(dev, state) + cmd = f"hciconfig {dev} {state}" __salt__["cmd.run"](cmd).splitlines() info = address_() if info[dev]["power"] == mode: @@ -133,9 +134,9 @@ def discoverable(dev): if dev not in address_(): raise CommandExecutionError("Invalid dev passed to bluetooth.discoverable") - cmd = "hciconfig {} iscan".format(dev) + cmd = f"hciconfig {dev} iscan" __salt__["cmd.run"](cmd).splitlines() - cmd = "hciconfig {}".format(dev) + cmd = f"hciconfig {dev}" out = __salt__["cmd.run"](cmd) if "UP RUNNING ISCAN" in out: return True @@ -155,9 +156,9 @@ def noscan(dev): if dev not in address_(): raise CommandExecutionError("Invalid dev passed to bluetooth.noscan") - cmd = "hciconfig {} noscan".format(dev) + cmd = f"hciconfig {dev} noscan" __salt__["cmd.run"](cmd).splitlines() - cmd = "hciconfig {}".format(dev) + cmd = f"hciconfig {dev}" out = __salt__["cmd.run"](cmd) if "SCAN" in out: return False @@ -194,7 +195,7 @@ def block(bdaddr): if not salt.utils.validate.net.mac(bdaddr): raise CommandExecutionError("Invalid BD address passed to bluetooth.block") - cmd = "hciconfig {} block".format(bdaddr) + cmd = f"hciconfig {bdaddr} block" __salt__["cmd.run"](cmd).splitlines() @@ -211,7 +212,7 @@ def unblock(bdaddr): if not salt.utils.validate.net.mac(bdaddr): raise CommandExecutionError("Invalid BD address passed to bluetooth.unblock") - cmd = "hciconfig {} unblock".format(bdaddr) + cmd = f"hciconfig {bdaddr} unblock" __salt__["cmd.run"](cmd).splitlines() @@ -267,7 +268,7 @@ def unpair(address): if not salt.utils.validate.net.mac(address): raise CommandExecutionError("Invalid BD address passed to bluetooth.unpair") - cmd = "bluez-test-device remove {}".format(address) + cmd = f"bluez-test-device remove {address}" out = __salt__["cmd.run"](cmd).splitlines() return out diff --git a/salt/modules/boto3_elasticache.py b/salt/modules/boto3_elasticache.py index 1e52ea25a2c..ec644d92ccb 100644 --- a/salt/modules/boto3_elasticache.py +++ b/salt/modules/boto3_elasticache.py @@ -107,7 +107,7 @@ def _describe_resource( key=None, keyid=None, profile=None, - **args + **args, ): if conn is None: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) @@ -115,9 +115,7 @@ def _describe_resource( func = "describe_" + res_type + "s" f = getattr(conn, func) except (AttributeError, KeyError) as e: - raise SaltInvocationError( - "No function '{}()' found: {}".format(func, e.message) - ) + raise SaltInvocationError(f"No function '{func}()' found: {e.message}") # Undocumented, but you can't pass 'Marker' if searching for a specific resource... args.update({name_param: name} if name else {"Marker": ""}) args = {k: v for k, v in args.items() if not k.startswith("_")} @@ -140,7 +138,7 @@ def _delete_resource( key=None, keyid=None, profile=None, - **args + **args, ): """ Delete a generic Elasticache resource. @@ -171,9 +169,7 @@ def _delete_resource( func = "describe_" + res_type + "s" s = globals()[func] except (AttributeError, KeyError) as e: - raise SaltInvocationError( - "No function '{}()' found: {}".format(func, e.message) - ) + raise SaltInvocationError(f"No function '{func}()' found: {e.message}") try: f(**args) @@ -211,7 +207,7 @@ def _create_resource( key=None, keyid=None, profile=None, - **args + **args, ): try: wait = int(wait) @@ -239,9 +235,7 @@ def _create_resource( func = "describe_" + res_type + "s" s = globals()[func] except (AttributeError, KeyError) as e: - raise SaltInvocationError( - "No function '{}()' found: {}".format(func, e.message) - ) + raise SaltInvocationError(f"No function '{func}()' found: {e.message}") try: f(**args) if not wait: @@ -270,7 +264,7 @@ def _create_resource( ) return False except botocore.exceptions.ClientError as e: - msg = "Failed to create {} {}: {}".format(desc, name, e) + msg = f"Failed to create {desc} {name}: {e}" log.error(msg) return False @@ -287,7 +281,7 @@ def _modify_resource( key=None, keyid=None, profile=None, - **args + **args, ): try: wait = int(wait) @@ -315,9 +309,7 @@ def _modify_resource( func = "describe_" + res_type + "s" s = globals()[func] except (AttributeError, KeyError) as e: - raise SaltInvocationError( - "No function '{}()' found: {}".format(func, e.message) - ) + raise SaltInvocationError(f"No function '{func}()' found: {e.message}") try: f(**args) if not wait: @@ -346,7 +338,7 @@ def _modify_resource( ) return False except botocore.exceptions.ClientError as e: - msg = "Failed to modify {} {}: {}".format(desc, name, e) + msg = f"Failed to modify {desc} {name}: {e}" log.error(msg) return False @@ -374,7 +366,7 @@ def describe_cache_clusters( key=key, keyid=keyid, profile=profile, - **args + **args, ) @@ -405,7 +397,7 @@ def create_cache_cluster( key=None, keyid=None, profile=None, - **args + **args, ): """ Create a cache cluster. @@ -442,7 +434,7 @@ def create_cache_cluster( key=key, keyid=keyid, profile=profile, - **args + **args, ) @@ -454,7 +446,7 @@ def modify_cache_cluster( key=None, keyid=None, profile=None, - **args + **args, ): """ Update a cache cluster in place. @@ -496,7 +488,7 @@ def modify_cache_cluster( key=key, keyid=keyid, profile=profile, - **args + **args, ) @@ -523,7 +515,7 @@ def delete_cache_cluster( key=key, keyid=keyid, profile=profile, - **args + **args, ) @@ -578,7 +570,7 @@ def create_replication_group( key=None, keyid=None, profile=None, - **args + **args, ): """ Create a replication group. @@ -615,7 +607,7 @@ def create_replication_group( key=key, keyid=keyid, profile=profile, - **args + **args, ) @@ -627,7 +619,7 @@ def modify_replication_group( key=None, keyid=None, profile=None, - **args + **args, ): """ Modify a replication group. @@ -661,7 +653,7 @@ def modify_replication_group( key=key, keyid=keyid, profile=profile, - **args + **args, ) @@ -688,7 +680,7 @@ def delete_replication_group( key=key, keyid=keyid, profile=profile, - **args + **args, ) @@ -783,13 +775,13 @@ def create_cache_subnet_group( ).get("subnets") if not sn: raise SaltInvocationError( - "Could not resolve Subnet Name {} to an ID.".format(subnet) + f"Could not resolve Subnet Name {subnet} to an ID." ) if len(sn) == 1: args["SubnetIds"] += [sn[0]["id"]] elif len(sn) > 1: raise CommandExecutionError( - "Subnet Name {} returned more than one ID.".format(subnet) + f"Subnet Name {subnet} returned more than one ID." ) args = {k: v for k, v in args.items() if not k.startswith("_")} return _create_resource( @@ -801,7 +793,7 @@ def create_cache_subnet_group( key=key, keyid=keyid, profile=profile, - **args + **args, ) @@ -836,14 +828,14 @@ def modify_cache_subnet_group( args["SubnetIds"] += [sn[0]["id"]] elif len(sn) > 1: raise CommandExecutionError( - "Subnet Name {} returned more than one ID.".format(subnet) + f"Subnet Name {subnet} returned more than one ID." ) elif subnet.startswith("subnet-"): # Moderately safe assumption... :) Will be caught later if incorrect. args["SubnetIds"] += [subnet] else: raise SaltInvocationError( - "Could not resolve Subnet Name {} to an ID.".format(subnet) + f"Could not resolve Subnet Name {subnet} to an ID." ) args = {k: v for k, v in args.items() if not k.startswith("_")} return _modify_resource( @@ -855,7 +847,7 @@ def modify_cache_subnet_group( key=key, keyid=keyid, profile=profile, - **args + **args, ) @@ -880,7 +872,7 @@ def delete_cache_subnet_group( key=key, keyid=keyid, profile=profile, - **args + **args, ) @@ -948,7 +940,7 @@ def create_cache_security_group( key=key, keyid=keyid, profile=profile, - **args + **args, ) @@ -973,7 +965,7 @@ def delete_cache_security_group( key=key, keyid=keyid, profile=profile, - **args + **args, ) @@ -1264,7 +1256,7 @@ def create_cache_parameter_group( key=key, keyid=keyid, profile=profile, - **args + **args, ) @@ -1289,5 +1281,5 @@ def delete_cache_parameter_group( key=key, keyid=keyid, profile=profile, - **args + **args, ) diff --git a/salt/modules/boto3_elasticsearch.py b/salt/modules/boto3_elasticsearch.py index 7462ea74d5d..60238776980 100644 --- a/salt/modules/boto3_elasticsearch.py +++ b/salt/modules/boto3_elasticsearch.py @@ -46,6 +46,7 @@ Connection module for Amazon Elasticsearch Service :codeauthor: Herbert Buurman :depends: boto3 """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 diff --git a/salt/modules/boto3_route53.py b/salt/modules/boto3_route53.py index 32c971356c2..5a0f730e018 100644 --- a/salt/modules/boto3_route53.py +++ b/salt/modules/boto3_route53.py @@ -913,10 +913,12 @@ def _aws_encode_changebatch(o): ) rr_idx += 1 if "AliasTarget" in o["Changes"][change_idx]["ResourceRecordSet"]: - o["Changes"][change_idx]["ResourceRecordSet"]["AliasTarget"][ - "DNSName" - ] = _aws_encode( - o["Changes"][change_idx]["ResourceRecordSet"]["AliasTarget"]["DNSName"] + o["Changes"][change_idx]["ResourceRecordSet"]["AliasTarget"]["DNSName"] = ( + _aws_encode( + o["Changes"][change_idx]["ResourceRecordSet"]["AliasTarget"][ + "DNSName" + ] + ) ) change_idx += 1 return o @@ -1026,13 +1028,17 @@ def get_resource_records( if done: return ret args = {"HostedZoneId": HostedZoneId} - args.update( - {"StartRecordName": _aws_encode(next_rr_name)} - ) if next_rr_name else None + ( + args.update({"StartRecordName": _aws_encode(next_rr_name)}) + if next_rr_name + else None + ) # Grrr, can't specify type unless name is set... We'll do this via filtering later instead - args.update( - {"StartRecordType": next_rr_type} - ) if next_rr_name and next_rr_type else None + ( + args.update({"StartRecordType": next_rr_type}) + if next_rr_name and next_rr_type + else None + ) args.update({"StartRecordIdentifier": next_rr_id}) if next_rr_id else None try: r = conn.list_resource_record_sets(**args) diff --git a/salt/modules/boto3_sns.py b/salt/modules/boto3_sns.py index 65ab6283f51..197cd795e24 100644 --- a/salt/modules/boto3_sns.py +++ b/salt/modules/boto3_sns.py @@ -38,6 +38,7 @@ Connection module for Amazon SNS :depends: boto3 """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 diff --git a/salt/modules/boto_apigateway.py b/salt/modules/boto_apigateway.py index dad8858edb5..ccaeb163ac5 100644 --- a/salt/modules/boto_apigateway.py +++ b/salt/modules/boto_apigateway.py @@ -74,6 +74,7 @@ Connection module for Amazon APIGateway message: error message """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -131,7 +132,7 @@ def _convert_datetime_str(response): if response: return dict( [ - (k, "{}".format(v)) if isinstance(v, datetime.date) else (k, v) + (k, f"{v}") if isinstance(v, datetime.date) else (k, v) for k, v in response.items() ] ) @@ -378,9 +379,9 @@ def create_api_resources( conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) for path_part in path_parts: if current_path == "/": - current_path = "{}{}".format(current_path, path_part) + current_path = f"{current_path}{path_part}" else: - current_path = "{}/{}".format(current_path, path_part) + current_path = f"{current_path}/{path_part}" r = describe_api_resource( restApiId, current_path, @@ -431,7 +432,7 @@ def delete_api_resources( conn.delete_resource(restApiId=restApiId, resourceId=resource["id"]) return {"deleted": True} else: - return {"deleted": False, "error": "no resource found by {}".format(path)} + return {"deleted": False, "error": f"no resource found by {path}"} except ClientError as e: return {"created": False, "error": __utils__["boto3.get_error"](e)} @@ -895,12 +896,12 @@ def overwrite_api_stage_variables( for old_var in old_vars: if old_var not in variables: patch_ops.append( - dict(op="remove", path="/variables/{}".format(old_var), value="") + dict(op="remove", path=f"/variables/{old_var}", value="") ) for var, val in variables.items(): if var not in old_vars or old_vars[var] != val: patch_ops.append( - dict(op="replace", path="/variables/{}".format(var), value=val) + dict(op="replace", path=f"/variables/{var}", value=val) ) if patch_ops: @@ -1622,7 +1623,7 @@ def _get_role_arn(name, region=None, key=None, keyid=None, profile=None): region=region, key=key, keyid=keyid, profile=profile ) - return "arn:aws:iam::{}:role/{}".format(account_id, name) + return f"arn:aws:iam::{account_id}:role/{name}" def create_api_integration( @@ -1799,7 +1800,7 @@ def _validate_throttle(throttle): if throttle is not None: if not isinstance(throttle, dict): raise TypeError( - "throttle must be a dictionary, provided value: {}".format(throttle) + f"throttle must be a dictionary, provided value: {throttle}" ) @@ -1809,9 +1810,7 @@ def _validate_quota(quota): """ if quota is not None: if not isinstance(quota, dict): - raise TypeError( - "quota must be a dictionary, provided value: {}".format(quota) - ) + raise TypeError(f"quota must be a dictionary, provided value: {quota}") periods = ["DAY", "WEEK", "MONTH"] if "period" not in quota or quota["period"] not in periods: raise ValueError( diff --git a/salt/modules/boto_asg.py b/salt/modules/boto_asg.py index c52c7946791..9d915c34ddb 100644 --- a/salt/modules/boto_asg.py +++ b/salt/modules/boto_asg.py @@ -41,6 +41,7 @@ Connection module for Amazon Autoscale Groups :depends: boto :depends: boto3 """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -119,7 +120,7 @@ def exists(name, region=None, key=None, keyid=None, profile=None): if _conn: return True else: - msg = "The autoscale group does not exist in region {}".format(region) + msg = f"The autoscale group does not exist in region {region}" log.debug(msg) return False except boto.exception.BotoServerError as e: @@ -429,12 +430,12 @@ def update( key = tag.get("key") except KeyError: log.error("Tag missing key.") - return False, "Tag {} missing key".format(tag) + return False, f"Tag {tag} missing key" try: value = tag.get("value") except KeyError: log.error("Tag missing value.") - return False, "Tag {} missing value".format(tag) + return False, f"Tag {tag} missing value" propagate_at_launch = tag.get("propagate_at_launch", False) _tag = { "key": key, @@ -508,7 +509,7 @@ def update( retries -= 1 continue log.error(e) - msg = "Failed to update ASG {}".format(name) + msg = f"Failed to update ASG {name}" log.error(msg) return False, str(e) @@ -569,7 +570,7 @@ def delete(name, force=False, region=None, key=None, keyid=None, profile=None): while True: try: conn.delete_auto_scaling_group(name, force) - msg = "Deleted autoscale group {}.".format(name) + msg = f"Deleted autoscale group {name}." log.info(msg) return True except boto.exception.BotoServerError as e: @@ -579,7 +580,7 @@ def delete(name, force=False, region=None, key=None, keyid=None, profile=None): retries -= 1 continue log.error(e) - msg = "Failed to delete autoscale group {}".format(name) + msg = f"Failed to delete autoscale group {name}" log.error(msg) return False @@ -821,7 +822,7 @@ def create_launch_configuration( retries -= 1 continue log.error(e) - msg = "Failed to create LC {}".format(name) + msg = f"Failed to create LC {name}" log.error(msg) return False @@ -850,7 +851,7 @@ def delete_launch_configuration(name, region=None, key=None, keyid=None, profile retries -= 1 continue log.error(e) - msg = "Failed to delete LC {}".format(name) + msg = f"Failed to delete LC {name}" log.error(msg) return False diff --git a/salt/modules/boto_cfn.py b/salt/modules/boto_cfn.py index 4c6b700482a..647bb185e42 100644 --- a/salt/modules/boto_cfn.py +++ b/salt/modules/boto_cfn.py @@ -28,6 +28,7 @@ Connection module for Amazon Cloud Formation :depends: boto """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -184,7 +185,7 @@ def create( stack_policy_url, ) except BotoServerError as e: - msg = "Failed to create stack {}.\n{}".format(name, e) + msg = f"Failed to create stack {name}.\n{e}" log.error(msg) log.debug(e) return False @@ -244,7 +245,7 @@ def update_stack( log.debug("Updated result is : %s.", update) return update except BotoServerError as e: - msg = "Failed to update stack {}.".format(name) + msg = f"Failed to update stack {name}." log.debug(e) log.error(msg) return str(e) @@ -265,7 +266,7 @@ def delete(name, region=None, key=None, keyid=None, profile=None): try: return conn.delete_stack(name) except BotoServerError as e: - msg = "Failed to create stack {}.".format(name) + msg = f"Failed to create stack {name}." log.error(msg) log.debug(e) return str(e) @@ -289,7 +290,7 @@ def get_template(name, region=None, key=None, keyid=None, profile=None): return template except BotoServerError as e: log.debug(e) - msg = "Template {} does not exist".format(name) + msg = f"Template {name} does not exist" log.error(msg) return str(e) @@ -320,6 +321,6 @@ def validate_template( return conn.validate_template(template_body, template_url) except BotoServerError as e: log.debug(e) - msg = "Error while trying to validate template {}.".format(template_body) + msg = f"Error while trying to validate template {template_body}." log.error(msg) return str(e) diff --git a/salt/modules/boto_cloudfront.py b/salt/modules/boto_cloudfront.py index 7e4db092d06..33ac1b76652 100644 --- a/salt/modules/boto_cloudfront.py +++ b/salt/modules/boto_cloudfront.py @@ -46,6 +46,7 @@ Connection module for Amazon CloudFront key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs region: us-east-1 """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -255,7 +256,7 @@ def export_distributions(region=None, key=None, keyid=None, profile=None): {"config": config}, {"tags": tags}, ] - results["Manage CloudFront distribution {}".format(name)] = { + results[f"Manage CloudFront distribution {name}"] = { "boto_cloudfront.present": distribution_sls_data, } except botocore.exceptions.ClientError as exc: diff --git a/salt/modules/boto_cloudtrail.py b/salt/modules/boto_cloudtrail.py index 25c165bd424..0a789a86150 100644 --- a/salt/modules/boto_cloudtrail.py +++ b/salt/modules/boto_cloudtrail.py @@ -45,6 +45,7 @@ The dependencies listed above can be installed via package or pip. region: us-east-1 """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -424,7 +425,7 @@ def _get_trail_arn(name, region=None, key=None, keyid=None, profile=None): region = profile["region"] if region is None: region = "us-east-1" - return "arn:aws:cloudtrail:{}:{}:trail/{}".format(region, account_id, name) + return f"arn:aws:cloudtrail:{region}:{account_id}:trail/{name}" def add_tags(Name, region=None, key=None, keyid=None, profile=None, **kwargs): diff --git a/salt/modules/boto_cloudwatch.py b/salt/modules/boto_cloudwatch.py index f7967d23876..c3a36561f71 100644 --- a/salt/modules/boto_cloudwatch.py +++ b/salt/modules/boto_cloudwatch.py @@ -40,6 +40,7 @@ Connection module for Amazon CloudWatch :depends: boto """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 diff --git a/salt/modules/boto_cloudwatch_event.py b/salt/modules/boto_cloudwatch_event.py index 1e8def652d1..7729cf715b8 100644 --- a/salt/modules/boto_cloudwatch_event.py +++ b/salt/modules/boto_cloudwatch_event.py @@ -40,6 +40,7 @@ Connection module for Amazon CloudWatch Events :depends: boto3 """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -214,7 +215,7 @@ def describe(Name, region=None, key=None, keyid=None, profile=None): except ClientError as e: err = __utils__["boto3.get_error"](e) if e.response.get("Error", {}).get("Code") == "RuleNotFoundException": - return {"error": "Rule {} not found".format(Rule)} + return {"error": f"Rule {Rule} not found"} return {"error": __utils__["boto3.get_error"](e)} @@ -270,7 +271,7 @@ def list_targets(Rule, region=None, key=None, keyid=None, profile=None): except ClientError as e: err = __utils__["boto3.get_error"](e) if e.response.get("Error", {}).get("Code") == "RuleNotFoundException": - return {"error": "Rule {} not found".format(Rule)} + return {"error": f"Rule {Rule} not found"} return {"error": __utils__["boto3.get_error"](e)} @@ -299,7 +300,7 @@ def put_targets(Rule, Targets, region=None, key=None, keyid=None, profile=None): except ClientError as e: err = __utils__["boto3.get_error"](e) if e.response.get("Error", {}).get("Code") == "RuleNotFoundException": - return {"error": "Rule {} not found".format(Rule)} + return {"error": f"Rule {Rule} not found"} return {"error": __utils__["boto3.get_error"](e)} @@ -328,5 +329,5 @@ def remove_targets(Rule, Ids, region=None, key=None, keyid=None, profile=None): except ClientError as e: err = __utils__["boto3.get_error"](e) if e.response.get("Error", {}).get("Code") == "RuleNotFoundException": - return {"error": "Rule {} not found".format(Rule)} + return {"error": f"Rule {Rule} not found"} return {"error": __utils__["boto3.get_error"](e)} diff --git a/salt/modules/boto_cognitoidentity.py b/salt/modules/boto_cognitoidentity.py index 5d8e7d8aa8f..37943d28c1f 100644 --- a/salt/modules/boto_cognitoidentity.py +++ b/salt/modules/boto_cognitoidentity.py @@ -72,6 +72,7 @@ Connection module for Amazon CognitoIdentity :depends: boto3 """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -147,7 +148,6 @@ def describe_identity_pools( keyid=None, profile=None, ): - """ Given an identity pool name, (optionally if an identity pool id is given, the given name will be ignored) @@ -365,7 +365,7 @@ def set_identity_pool_roles( if role_arn is None: return { "set": False, - "error": "invalid AuthenticatedRole {}".format(AuthenticatedRole), + "error": f"invalid AuthenticatedRole {AuthenticatedRole}", } AuthenticatedRole = role_arn @@ -447,9 +447,9 @@ def update_identity_pool( if AllowUnauthenticatedIdentities != request_params.get( "AllowUnauthenticatedIdentities" ): - request_params[ - "AllowUnauthenticatedIdentities" - ] = AllowUnauthenticatedIdentities + request_params["AllowUnauthenticatedIdentities"] = ( + AllowUnauthenticatedIdentities + ) current_val = request_params.pop("SupportedLoginProviders", None) if SupportedLoginProviders is not None and SupportedLoginProviders != current_val: diff --git a/salt/modules/boto_datapipeline.py b/salt/modules/boto_datapipeline.py index 52d5872d360..b2cc6ca773f 100644 --- a/salt/modules/boto_datapipeline.py +++ b/salt/modules/boto_datapipeline.py @@ -6,7 +6,6 @@ Connection module for Amazon Data Pipeline :depends: boto3 """ - import logging import salt.utils.versions @@ -182,7 +181,7 @@ def pipeline_id_from_name(name, region=None, key=None, keyid=None, profile=None) if pipeline["name"] == name: r["result"] = pipeline["id"] return r - r["error"] = "No pipeline found with name={}".format(name) + r["error"] = f"No pipeline found with name={name}" return r diff --git a/salt/modules/boto_dynamodb.py b/salt/modules/boto_dynamodb.py index 29e2757f63b..10201cb48e0 100644 --- a/salt/modules/boto_dynamodb.py +++ b/salt/modules/boto_dynamodb.py @@ -40,6 +40,7 @@ Connection module for Amazon DynamoDB :depends: boto """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 diff --git a/salt/modules/boto_ec2.py b/salt/modules/boto_ec2.py index be4edce11dc..f5f8a7fd3e6 100644 --- a/salt/modules/boto_ec2.py +++ b/salt/modules/boto_ec2.py @@ -39,6 +39,7 @@ as a passed in dict, or as a string to pull from pillars or minion config: :depends: boto """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -658,7 +659,6 @@ def find_instances( in_states=None, filters=None, ): - """ Given instance properties, find and return matching instance ids @@ -685,7 +685,7 @@ def find_instances( if tags: for tag_name, tag_value in tags.items(): - filter_parameters["filters"]["tag:{}".format(tag_name)] = tag_value + filter_parameters["filters"][f"tag:{tag_name}"] = tag_value if filters: filter_parameters["filters"].update(filters) @@ -785,7 +785,6 @@ def find_images( profile=None, return_objs=False, ): - """ Given image properties, find and return matching AMI ids @@ -811,7 +810,7 @@ def find_images( filter_parameters["filters"]["name"] = ami_name if tags: for tag_name, tag_value in tags.items(): - filter_parameters["filters"]["tag:{}".format(tag_name)] = tag_value + filter_parameters["filters"][f"tag:{tag_name}"] = tag_value images = conn.get_all_images(**filter_parameters) log.debug( "The filters criteria %s matched the following images:%s", @@ -885,7 +884,6 @@ def get_id( in_states=None, filters=None, ): - """ Given instance properties, return the instance id if it exists. @@ -1518,9 +1516,7 @@ def get_attribute( " command." ) if attribute not in attribute_list: - raise SaltInvocationError( - "Attribute must be one of: {}.".format(attribute_list) - ) + raise SaltInvocationError(f"Attribute must be one of: {attribute_list}.") try: if instance_name: instances = find_instances( @@ -1611,9 +1607,7 @@ def set_attribute( " command." ) if attribute not in attribute_list: - raise SaltInvocationError( - "Attribute must be one of: {}.".format(attribute_list) - ) + raise SaltInvocationError(f"Attribute must be one of: {attribute_list}.") try: if instance_name: instances = find_instances( @@ -1824,7 +1818,7 @@ def create_network_interface( ) vpc_id = vpc_id.get("vpc_id") if not vpc_id: - msg = "subnet_id {} does not map to a valid vpc id.".format(subnet_id) + msg = f"subnet_id {subnet_id} does not map to a valid vpc id." r["error"] = {"message": msg} return r _groups = __salt__["boto_secgroup.convert_to_group_ids"]( @@ -2233,7 +2227,7 @@ def set_volumes_tags( profile=profile, ) if not instance_id: - msg = "Couldn't resolve instance Name {} to an ID.".format(v) + msg = f"Couldn't resolve instance Name {v} to an ID." raise CommandExecutionError(msg) new_filters["attachment.instance_id"] = instance_id else: @@ -2295,10 +2289,10 @@ def set_volumes_tags( profile=profile, ): ret["success"] = False - ret[ - "comment" - ] = "Failed to remove tags on vol.id {}: {}".format( - vol.id, remove + ret["comment"] = ( + "Failed to remove tags on vol.id {}: {}".format( + vol.id, remove + ) ) return ret if changes["old"] or changes["new"]: diff --git a/salt/modules/boto_efs.py b/salt/modules/boto_efs.py index 70f226bf67c..800aa7977f6 100644 --- a/salt/modules/boto_efs.py +++ b/salt/modules/boto_efs.py @@ -47,7 +47,6 @@ Connection module for Amazon EFS :depends: boto3 """ - import logging import salt.utils.versions diff --git a/salt/modules/boto_elasticache.py b/salt/modules/boto_elasticache.py index 43f183b0f39..fdcec9d4962 100644 --- a/salt/modules/boto_elasticache.py +++ b/salt/modules/boto_elasticache.py @@ -40,6 +40,7 @@ Connection module for Amazon Elasticache :depends: boto """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -156,7 +157,7 @@ def create_replication_group( if config["status"] == "available": return True except boto.exception.BotoServerError as e: - msg = "Failed to create replication group {}.".format(name) + msg = f"Failed to create replication group {name}." log.error(msg) log.debug(e) return {} @@ -178,12 +179,12 @@ def delete_replication_group(name, region=None, key=None, keyid=None, profile=No return False try: conn.delete_replication_group(name) - msg = "Deleted ElastiCache replication group {}.".format(name) + msg = f"Deleted ElastiCache replication group {name}." log.info(msg) return True except boto.exception.BotoServerError as e: log.debug(e) - msg = "Failed to delete ElastiCache replication group {}".format(name) + msg = f"Failed to delete ElastiCache replication group {name}" log.error(msg) return False @@ -207,7 +208,7 @@ def describe_replication_group( try: cc = conn.describe_replication_groups(name) except boto.exception.BotoServerError as e: - msg = "Failed to get config for cache cluster {}.".format(name) + msg = f"Failed to get config for cache cluster {name}." log.error(msg) log.debug(e) return {} @@ -277,7 +278,7 @@ def get_config(name, region=None, key=None, keyid=None, profile=None): try: cc = conn.describe_cache_clusters(name, show_cache_node_info=True) except boto.exception.BotoServerError as e: - msg = "Failed to get config for cache cluster {}.".format(name) + msg = f"Failed to get config for cache cluster {name}." log.error(msg) log.debug(e) return {} @@ -356,7 +357,7 @@ def get_node_host(name, region=None, key=None, keyid=None, profile=None): try: cc = conn.describe_cache_clusters(name, show_cache_node_info=True) except boto.exception.BotoServerError as e: - msg = "Failed to get config for cache cluster {}.".format(name) + msg = f"Failed to get config for cache cluster {name}." log.error(msg) log.debug(e) return {} @@ -383,7 +384,7 @@ def get_group_host(name, region=None, key=None, keyid=None, profile=None): try: cc = conn.describe_replication_groups(name) except boto.exception.BotoServerError as e: - msg = "Failed to get config for cache cluster {}.".format(name) + msg = f"Failed to get config for cache cluster {name}." log.error(msg) log.debug(e) return {} @@ -464,7 +465,7 @@ def subnet_group_exists( try: ec = conn.describe_cache_subnet_groups(cache_subnet_group_name=name) if not ec: - msg = "ElastiCache subnet group does not exist in region {}".format(region) + msg = f"ElastiCache subnet group does not exist in region {region}" log.debug(msg) return False return True @@ -515,14 +516,14 @@ def create_subnet_group( try: ec = conn.create_cache_subnet_group(name, description, subnet_ids) if not ec: - msg = "Failed to create ElastiCache subnet group {}".format(name) + msg = f"Failed to create ElastiCache subnet group {name}" log.error(msg) return False log.info("Created ElastiCache subnet group %s", name) return True except boto.exception.BotoServerError as e: log.debug(e) - msg = "Failed to create ElastiCache subnet group {}".format(name) + msg = f"Failed to create ElastiCache subnet group {name}" log.error(msg) return False @@ -544,12 +545,12 @@ def get_cache_subnet_group(name, region=None, key=None, keyid=None, profile=None csg = csg["DescribeCacheSubnetGroupsResponse"] csg = csg["DescribeCacheSubnetGroupsResult"]["CacheSubnetGroups"][0] except boto.exception.BotoServerError as e: - msg = "Failed to get cache subnet group {}.".format(name) + msg = f"Failed to get cache subnet group {name}." log.error(msg) log.debug(e) return False except (IndexError, TypeError, KeyError): - msg = "Failed to get cache subnet group {} (2).".format(name) + msg = f"Failed to get cache subnet group {name} (2)." log.error(msg) return False ret = {} @@ -589,12 +590,12 @@ def delete_subnet_group(name, region=None, key=None, keyid=None, profile=None): return False try: conn.delete_cache_subnet_group(name) - msg = "Deleted ElastiCache subnet group {}.".format(name) + msg = f"Deleted ElastiCache subnet group {name}." log.info(msg) return True except boto.exception.BotoServerError as e: log.debug(e) - msg = "Failed to delete ElastiCache subnet group {}".format(name) + msg = f"Failed to delete ElastiCache subnet group {name}" log.error(msg) return False @@ -665,7 +666,7 @@ def create( return True log.info("Created cache cluster %s.", name) except boto.exception.BotoServerError as e: - msg = "Failed to create cache cluster {}.".format(name) + msg = f"Failed to create cache cluster {name}." log.error(msg) log.debug(e) return False @@ -698,7 +699,7 @@ def delete(name, wait=False, region=None, key=None, keyid=None, profile=None): log.info("Deleted cache cluster %s.", name) return True except boto.exception.BotoServerError as e: - msg = "Failed to delete cache cluster {}.".format(name) + msg = f"Failed to delete cache cluster {name}." log.error(msg) log.debug(e) return False @@ -723,7 +724,7 @@ def create_cache_security_group( log.info("Created cache security group %s.", name) return True else: - msg = "Failed to create cache security group {}.".format(name) + msg = f"Failed to create cache security group {name}." log.error(msg) return False @@ -745,7 +746,7 @@ def delete_cache_security_group(name, region=None, key=None, keyid=None, profile log.info("Deleted cache security group %s.", name) return True else: - msg = "Failed to delete cache security group {}.".format(name) + msg = f"Failed to delete cache security group {name}." log.error(msg) return False diff --git a/salt/modules/boto_elasticsearch_domain.py b/salt/modules/boto_elasticsearch_domain.py index 050ef2f011b..ff11574685c 100644 --- a/salt/modules/boto_elasticsearch_domain.py +++ b/salt/modules/boto_elasticsearch_domain.py @@ -70,6 +70,7 @@ Connection module for Amazon Elasticsearch Service :depends: boto3 """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -273,7 +274,7 @@ def create( except ValueError as e: return { "updated": False, - "error": "Error parsing {}: {}".format(k, e.message), + "error": f"Error parsing {k}: {e.message}", } kwargs[k] = val if "AccessPolicies" in kwargs: @@ -364,7 +365,7 @@ def update( except ValueError as e: return { "updated": False, - "error": "Error parsing {}: {}".format(k, e.message), + "error": f"Error parsing {k}: {e.message}", } call_args[k] = val if "AccessPolicies" in call_args: diff --git a/salt/modules/boto_elb.py b/salt/modules/boto_elb.py index 310b91134bf..5c5d3c016b4 100644 --- a/salt/modules/boto_elb.py +++ b/salt/modules/boto_elb.py @@ -40,6 +40,7 @@ Connection module for Amazon ELB :depends: boto >= 2.33.0 """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -1101,9 +1102,9 @@ def _build_tag_param_list(params, tags): i = 1 for key in keys: value = tags[key] - params["Tags.member.{}.Key".format(i)] = key + params[f"Tags.member.{i}.Key"] = key if value is not None: - params["Tags.member.{}.Value".format(i)] = value + params[f"Tags.member.{i}.Value"] = value i += 1 diff --git a/salt/modules/boto_elbv2.py b/salt/modules/boto_elbv2.py index d91927caa67..7754ef1ef86 100644 --- a/salt/modules/boto_elbv2.py +++ b/salt/modules/boto_elbv2.py @@ -36,6 +36,7 @@ Connection module for Amazon ALB :depends: boto3 """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 diff --git a/salt/modules/boto_iam.py b/salt/modules/boto_iam.py index 521b1ff7140..54322e12eb5 100644 --- a/salt/modules/boto_iam.py +++ b/salt/modules/boto_iam.py @@ -33,6 +33,7 @@ Connection module for Amazon IAM :depends: boto """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -1733,7 +1734,7 @@ def _get_policy_arn(name, region=None, key=None, keyid=None, profile=None): return name account_id = get_account_id(region=region, key=key, keyid=keyid, profile=profile) - return "arn:aws:iam::{}:policy/{}".format(account_id, name) + return f"arn:aws:iam::{account_id}:policy/{name}" def policy_exists(policy_name, region=None, key=None, keyid=None, profile=None): diff --git a/salt/modules/boto_iot.py b/salt/modules/boto_iot.py index 1243a1700f9..7df25b47acf 100644 --- a/salt/modules/boto_iot.py +++ b/salt/modules/boto_iot.py @@ -45,6 +45,7 @@ The dependencies listed above can be installed via package or pip. region: us-east-1 """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -148,7 +149,7 @@ def describe_thing_type(thingTypeName, region=None, key=None, keyid=None, profil for dtype in ("creationDate", "deprecationDate"): dval = thingTypeMetadata.get(dtype) if dval and isinstance(dval, datetime.date): - thingTypeMetadata[dtype] = "{}".format(dval) + thingTypeMetadata[dtype] = f"{dval}" return {"thing_type": res} else: return {"thing_type": None} @@ -915,7 +916,7 @@ def list_topic_rules( conn.list_topic_rules, marker_flag="nextToken", marker_arg="nextToken", - **kwargs + **kwargs, ): rules.extend(ret["rules"]) if not bool(rules): diff --git a/salt/modules/boto_kinesis.py b/salt/modules/boto_kinesis.py index 846defa5d6a..d2d999a733c 100644 --- a/salt/modules/boto_kinesis.py +++ b/salt/modules/boto_kinesis.py @@ -41,6 +41,7 @@ Connection module for Amazon Kinesis :depends: boto3 """ + # keep lint from choking on _get_conn # pylint: disable=E0602 @@ -491,7 +492,7 @@ def reshard( # merge next_shard_id = _get_next_open_shard(stream_details, shard_id) if not next_shard_id: - r["error"] = "failed to find next shard after {}".format(shard_id) + r["error"] = f"failed to find next shard after {shard_id}" return r if force: log.debug( diff --git a/salt/modules/boto_kms.py b/salt/modules/boto_kms.py index ac106655d5b..70a172d51c7 100644 --- a/salt/modules/boto_kms.py +++ b/salt/modules/boto_kms.py @@ -32,6 +32,7 @@ Connection module for Amazon KMS :depends: boto """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 diff --git a/salt/modules/boto_lambda.py b/salt/modules/boto_lambda.py index 5dcd82a3634..87ef561c3c5 100644 --- a/salt/modules/boto_lambda.py +++ b/salt/modules/boto_lambda.py @@ -74,6 +74,7 @@ as a passed in dict, or as a string to pull from pillars or minion config: message: error message """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -176,7 +177,7 @@ def _get_role_arn(name, region=None, key=None, keyid=None, profile=None): region = profile["region"] if region is None: region = "us-east-1" - return "arn:aws:iam::{}:role/{}".format(account_id, name) + return f"arn:aws:iam::{account_id}:role/{name}" def _filedata(infile): @@ -272,7 +273,7 @@ def create_function( dlZipFile = __salt__["cp.cache_file"](path=ZipFile) if dlZipFile is False: ret["result"] = False - ret["comment"] = "Failed to cache ZipFile `{}`.".format(ZipFile) + ret["comment"] = f"Failed to cache ZipFile `{ZipFile}`." return ret ZipFile = dlZipFile code = { @@ -313,7 +314,7 @@ def create_function( Timeout=Timeout, MemorySize=MemorySize, Publish=Publish, - **kwargs + **kwargs, ) except ClientError as e: if ( @@ -645,7 +646,7 @@ def add_permission( StatementId=StatementId, Action=Action, Principal=str(Principal), - **kwargs + **kwargs, ) return {"updated": True} except ClientError as e: diff --git a/salt/modules/boto_rds.py b/salt/modules/boto_rds.py index 129c80bc6fe..9c65ee737ea 100644 --- a/salt/modules/boto_rds.py +++ b/salt/modules/boto_rds.py @@ -40,6 +40,7 @@ Connection module for Amazon RDS :depends: boto3 """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 # pylint whinging perfectly valid code @@ -294,9 +295,7 @@ def create( if wait_status: wait_stati = ["available", "modifying", "backing-up"] if wait_status not in wait_stati: - raise SaltInvocationError( - "wait_status can be one of: {}".format(wait_stati) - ) + raise SaltInvocationError(f"wait_status can be one of: {wait_stati}") if vpc_security_groups: v_tmp = __salt__["boto_secgroup.convert_to_group_ids"]( groups=vpc_security_groups, @@ -336,7 +335,7 @@ def create( if not wait_status: return { "created": True, - "message": "RDS instance {} created.".format(name), + "message": f"RDS instance {name} created.", } while True: @@ -408,14 +407,14 @@ def create_read_replica( if not res.get("exists"): return { "exists": bool(res), - "message": "RDS instance source {} does not exists.".format(source_name), + "message": f"RDS instance source {source_name} does not exists.", } res = __salt__["boto_rds.exists"](name, tags, region, key, keyid, profile) if res.get("exists"): return { "exists": bool(res), - "message": "RDS replica instance {} already exists.".format(name), + "message": f"RDS replica instance {name} already exists.", } try: @@ -444,7 +443,7 @@ def create_read_replica( Tags=taglist, DBSubnetGroupName=db_subnet_group_name, StorageType=storage_type, - **kwargs + **kwargs, ) return {"exists": bool(rds_replica)} @@ -535,12 +534,12 @@ def create_parameter_group( if not rds: return { "created": False, - "message": "Failed to create RDS parameter group {}".format(name), + "message": f"Failed to create RDS parameter group {name}", } return { "exists": bool(rds), - "message": "Created RDS parameter group {}".format(name), + "message": f"Created RDS parameter group {name}", } except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} @@ -617,7 +616,7 @@ def update_parameter_group( if not res.get("exists"): return { "exists": bool(res), - "message": "RDS parameter group {} does not exist.".format(name), + "message": f"RDS parameter group {name} does not exist.", } param_list = [] @@ -662,7 +661,7 @@ def describe(name, tags=None, region=None, key=None, keyid=None, profile=None): if not res.get("exists"): return { "exists": bool(res), - "message": "RDS instance {} does not exist.".format(name), + "message": f"RDS instance {name} does not exist.", } try: @@ -867,7 +866,7 @@ def delete( if not wait_for_deletion: return { "deleted": bool(res), - "message": "Deleted RDS instance {}.".format(name), + "message": f"Deleted RDS instance {name}.", } start_time = time.time() @@ -883,7 +882,7 @@ def delete( if not res.get("exists"): return { "deleted": bool(res), - "message": "Deleted RDS instance {} completely.".format(name), + "message": f"Deleted RDS instance {name} completely.", } if time.time() - start_time > timeout: @@ -922,12 +921,12 @@ def delete_option_group(name, region=None, key=None, keyid=None, profile=None): if not res: return { "deleted": bool(res), - "message": "Failed to delete RDS option group {}.".format(name), + "message": f"Failed to delete RDS option group {name}.", } return { "deleted": bool(res), - "message": "Deleted RDS option group {}.".format(name), + "message": f"Deleted RDS option group {name}.", } except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} @@ -952,7 +951,7 @@ def delete_parameter_group(name, region=None, key=None, keyid=None, profile=None r = conn.delete_db_parameter_group(DBParameterGroupName=name) return { "deleted": bool(r), - "message": "Deleted RDS parameter group {}.".format(name), + "message": f"Deleted RDS parameter group {name}.", } except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} @@ -977,7 +976,7 @@ def delete_subnet_group(name, region=None, key=None, keyid=None, profile=None): r = conn.delete_db_subnet_group(DBSubnetGroupName=name) return { "deleted": bool(r), - "message": "Deleted RDS subnet group {}.".format(name), + "message": f"Deleted RDS subnet group {name}.", } except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} @@ -1024,12 +1023,12 @@ def describe_parameter_group( if not info: return { "results": bool(info), - "message": "Failed to get RDS description for group {}.".format(name), + "message": f"Failed to get RDS description for group {name}.", } return { "results": bool(info), - "message": "Got RDS descrition for group {}.".format(name), + "message": f"Got RDS descrition for group {name}.", } except ClientError as e: return {"error": __utils__["boto3.get_error"](e)} @@ -1058,7 +1057,7 @@ def describe_parameters( if not res.get("exists"): return { "result": False, - "message": "Parameter group {} does not exist".format(name), + "message": f"Parameter group {name} does not exist", } try: @@ -1166,7 +1165,7 @@ def modify_db_instance( if not res.get("exists"): return { "modified": False, - "message": "RDS db instance {} does not exist.".format(name), + "message": f"RDS db instance {name} does not exist.", } try: @@ -1189,12 +1188,12 @@ def modify_db_instance( if not info: return { "modified": bool(info), - "message": "Failed to modify RDS db instance {}.".format(name), + "message": f"Failed to modify RDS db instance {name}.", } return { "modified": bool(info), - "message": "Modified RDS db instance {}.".format(name), + "message": f"Modified RDS db instance {name}.", "results": dict(info), } except ClientError as e: diff --git a/salt/modules/boto_route53.py b/salt/modules/boto_route53.py index 500e6f2cb78..bee6cff4d3a 100644 --- a/salt/modules/boto_route53.py +++ b/salt/modules/boto_route53.py @@ -41,6 +41,7 @@ Connection module for Amazon Route53 :depends: boto """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -589,7 +590,7 @@ def get_record( else: _zone = conn.get_zone(zone) if not _zone: - msg = "Failed to retrieve zone {}".format(zone) + msg = f"Failed to retrieve zone {zone}" log.error(msg) return None _type = record_type.upper() @@ -698,7 +699,7 @@ def add_record( else: _zone = conn.get_zone(zone) if not _zone: - msg = "Failed to retrieve zone {}".format(zone) + msg = f"Failed to retrieve zone {zone}" log.error(msg) return False _type = record_type.upper() @@ -797,7 +798,7 @@ def update_record( else: _zone = conn.get_zone(zone) if not _zone: - msg = "Failed to retrieve zone {}".format(zone) + msg = f"Failed to retrieve zone {zone}" log.error(msg) return False _type = record_type.upper() @@ -886,7 +887,7 @@ def delete_record( else: _zone = conn.get_zone(zone) if not _zone: - msg = "Failed to retrieve zone {}".format(zone) + msg = f"Failed to retrieve zone {zone}" log.error(msg) return False _type = record_type.upper() diff --git a/salt/modules/boto_s3.py b/salt/modules/boto_s3.py index bef68657e9b..54939033667 100644 --- a/salt/modules/boto_s3.py +++ b/salt/modules/boto_s3.py @@ -46,6 +46,7 @@ Connection module for Amazon S3 using boto3 :depends: boto3 """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 diff --git a/salt/modules/boto_s3_bucket.py b/salt/modules/boto_s3_bucket.py index 9fc2417cbfc..d461c320a76 100644 --- a/salt/modules/boto_s3_bucket.py +++ b/salt/modules/boto_s3_bucket.py @@ -45,6 +45,7 @@ The dependencies listed above can be installed via package or pip. region: us-east-1 """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 # disable complaints about perfectly valid non-assignment code @@ -773,7 +774,7 @@ def _get_role_arn(name, region=None, key=None, keyid=None, profile=None): region = profile["region"] if region is None: region = "us-east-1" - return "arn:aws:iam::{}:role/{}".format(account_id, name) + return f"arn:aws:iam::{account_id}:role/{name}" def put_replication( diff --git a/salt/modules/boto_secgroup.py b/salt/modules/boto_secgroup.py index 97941147933..9ecdb782900 100644 --- a/salt/modules/boto_secgroup.py +++ b/salt/modules/boto_secgroup.py @@ -40,6 +40,7 @@ Connection module for Amazon Security Groups :depends: boto """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -509,7 +510,7 @@ def create( log.info("Created security group %s.", name) return True else: - msg = "Failed to create security group {}.".format(name) + msg = f"Failed to create security group {name}." log.error(msg) return False @@ -552,7 +553,7 @@ def delete( log.info("Deleted security group %s with id %s.", group.name, group.id) return True else: - msg = "Failed to delete security group {}.".format(name) + msg = f"Failed to delete security group {name}." log.error(msg) return False else: @@ -776,7 +777,7 @@ def _find_vpcs( if tags: for tag_name, tag_value in tags.items(): - filter_parameters["filters"]["tag:{}".format(tag_name)] = tag_value + filter_parameters["filters"][f"tag:{tag_name}"] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug( diff --git a/salt/modules/boto_sns.py b/salt/modules/boto_sns.py index 7df58b95e5a..2814f56ea41 100644 --- a/salt/modules/boto_sns.py +++ b/salt/modules/boto_sns.py @@ -38,6 +38,7 @@ Connection module for Amazon SNS :depends: boto """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -235,7 +236,7 @@ def get_arn(name, region=None, key=None, keyid=None, profile=None): account_id = __salt__["boto_iam.get_account_id"]( region=region, key=key, keyid=keyid, profile=profile ) - return "arn:aws:sns:{}:{}:{}".format(_get_region(region, profile), account_id, name) + return f"arn:aws:sns:{_get_region(region, profile)}:{account_id}:{name}" def _get_region(region=None, profile=None): @@ -252,7 +253,7 @@ def _get_region(region=None, profile=None): def _subscriptions_cache_key(name): - return "{}_{}_subscriptions".format(_cache_get_key(), name) + return f"{_cache_get_key()}_{name}_subscriptions" def _invalidate_cache(): diff --git a/salt/modules/boto_sqs.py b/salt/modules/boto_sqs.py index c2a572ab248..cb9033d4ce4 100644 --- a/salt/modules/boto_sqs.py +++ b/salt/modules/boto_sqs.py @@ -40,6 +40,7 @@ Connection module for Amazon SQS :depends: boto3 """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 diff --git a/salt/modules/boto_ssm.py b/salt/modules/boto_ssm.py index f2908a46edc..475279a9153 100644 --- a/salt/modules/boto_ssm.py +++ b/salt/modules/boto_ssm.py @@ -12,6 +12,7 @@ Connection module for Amazon SSM :depends: boto3 """ + import logging import salt.utils.json as json diff --git a/salt/modules/boto_vpc.py b/salt/modules/boto_vpc.py index ee7a757e2b2..289a7a2fb78 100644 --- a/salt/modules/boto_vpc.py +++ b/salt/modules/boto_vpc.py @@ -120,6 +120,7 @@ Deleting VPC peering connection via this module salt myminion boto_vpc.delete_vpc_peering_connection conn_id=pcx-8a8939e3 """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -242,7 +243,7 @@ def _create_resource( key=None, keyid=None, profile=None, - **kwargs + **kwargs, ): """ Create a VPC resource. Returns the resource id if created, or False @@ -265,9 +266,7 @@ def _create_resource( ): return { "created": False, - "error": { - "message": "A {} named {} already exists.".format(resource, name) - }, + "error": {"message": f"A {resource} named {name} already exists."}, } r = create_resource(**kwargs) @@ -293,9 +292,9 @@ def _create_resource( return {"created": True, "id": r.id} else: if name: - e = "{} {} was not created.".format(resource, name) + e = f"{resource} {name} was not created." else: - e = "{} was not created.".format(resource) + e = f"{resource} was not created." log.warning(e) return {"created": False, "error": {"message": e}} except BotoServerError as e: @@ -310,7 +309,7 @@ def _delete_resource( key=None, keyid=None, profile=None, - **kwargs + **kwargs, ): """ Delete a VPC resource. Returns True if successful, otherwise False. @@ -337,9 +336,7 @@ def _delete_resource( if not resource_id: return { "deleted": False, - "error": { - "message": "{} {} does not exist.".format(resource, name) - }, + "error": {"message": f"{resource} {name} does not exist."}, } if delete_resource(resource_id, **kwargs): @@ -356,9 +353,9 @@ def _delete_resource( return {"deleted": True} else: if name: - e = "{} {} was not deleted.".format(resource, name) + e = f"{resource} {name} was not deleted." else: - e = "{} was not deleted.".format(resource) + e = f"{resource} was not deleted." return {"deleted": False, "error": {"message": e}} except BotoServerError as e: return {"deleted": False, "error": __utils__["boto.get_error"](e)} @@ -383,7 +380,7 @@ def _get_resource( conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) - f = "get_all_{}".format(resource) + f = f"get_all_{resource}" if not f.endswith("s"): f = f + "s" get_resources = getattr(conn, f) @@ -392,7 +389,7 @@ def _get_resource( if name: filter_parameters["filters"] = {"tag:Name": name} if resource_id: - filter_parameters["{}_ids".format(resource)] = resource_id + filter_parameters[f"{resource}_ids"] = resource_id try: r = get_resources(**filter_parameters) @@ -416,7 +413,7 @@ def _get_resource( return r[0] else: raise CommandExecutionError( - 'Found more than one {} named "{}"'.format(resource, name) + f'Found more than one {resource} named "{name}"' ) else: return None @@ -446,7 +443,7 @@ def _find_resources( conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) - f = "get_all_{}".format(resource) + f = f"get_all_{resource}" if not f.endswith("s"): f = f + "s" get_resources = getattr(conn, f) @@ -455,10 +452,10 @@ def _find_resources( if name: filter_parameters["filters"] = {"tag:Name": name} if resource_id: - filter_parameters["{}_ids".format(resource)] = resource_id + filter_parameters[f"{resource}_ids"] = resource_id if tags: for tag_name, tag_value in tags.items(): - filter_parameters["filters"]["tag:{}".format(tag_name)] = tag_value + filter_parameters["filters"][f"tag:{tag_name}"] = tag_value try: r = get_resources(**filter_parameters) @@ -579,7 +576,6 @@ def _find_vpcs( keyid=None, profile=None, ): - """ Given VPC properties, find and return matching VPC ids. """ @@ -601,7 +597,7 @@ def _find_vpcs( if tags: for tag_name, tag_value in tags.items(): - filter_parameters["filters"]["tag:{}".format(tag_name)] = tag_value + filter_parameters["filters"][f"tag:{tag_name}"] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) log.debug( @@ -868,7 +864,7 @@ def delete( if not vpc_id: return { "deleted": False, - "error": {"message": "VPC {} not found".format(vpc_name)}, + "error": {"message": f"VPC {vpc_name} not found"}, } if conn.delete_vpc(vpc_id): @@ -1013,7 +1009,7 @@ def describe_vpcs( if tags: for tag_name, tag_value in tags.items(): - filter_parameters["filters"]["tag:{}".format(tag_name)] = tag_value + filter_parameters["filters"][f"tag:{tag_name}"] = tag_value vpcs = conn.get_all_vpcs(**filter_parameters) @@ -1055,7 +1051,7 @@ def _find_subnets(subnet_name=None, vpc_id=None, cidr=None, tags=None, conn=None if tags: for tag_name, tag_value in tags.items(): - filter_parameters["filters"]["tag:{}".format(tag_name)] = tag_value + filter_parameters["filters"][f"tag:{tag_name}"] = tag_value subnets = conn.get_all_subnets(**filter_parameters) log.debug( @@ -1108,9 +1104,7 @@ def create_subnet( if not vpc_id: return { "created": False, - "error": { - "message": "VPC {} does not exist.".format(vpc_name or vpc_id) - }, + "error": {"message": f"VPC {vpc_name or vpc_id} does not exist."}, } except BotoServerError as e: return {"created": False, "error": __utils__["boto.get_error"](e)} @@ -1222,7 +1216,7 @@ def subnet_exists( filter_parameters["filters"]["cidr"] = cidr if tags: for tag_name, tag_value in tags.items(): - filter_parameters["filters"]["tag:{}".format(tag_name)] = tag_value + filter_parameters["filters"][f"tag:{tag_name}"] = tag_value if zones: filter_parameters["filters"]["availability_zone"] = zones @@ -1419,9 +1413,9 @@ def describe_subnets( subnet["id"], subnet["vpc_id"], conn=conn ) if explicit_route_table_assoc: - subnet[ - "explicit_route_table_association_id" - ] = explicit_route_table_assoc + subnet["explicit_route_table_association_id"] = ( + explicit_route_table_assoc + ) subnets_list.append(subnet) return {"subnets": subnets_list} @@ -1462,9 +1456,7 @@ def create_internet_gateway( if not vpc_id: return { "created": False, - "error": { - "message": "VPC {} does not exist.".format(vpc_name or vpc_id) - }, + "error": {"message": f"VPC {vpc_name or vpc_id} does not exist."}, } r = _create_resource( @@ -1622,7 +1614,7 @@ def _find_nat_gateways( conn3.describe_nat_gateways, marker_flag="NextToken", marker_arg="NextToken", - **filter_parameters + **filter_parameters, ): for gw in ret.get("NatGateways", []): if gw.get("State") in states: @@ -1769,9 +1761,7 @@ def create_nat_gateway( if not subnet_id: return { "created": False, - "error": { - "message": "Subnet {} does not exist.".format(subnet_name) - }, + "error": {"message": f"Subnet {subnet_name} does not exist."}, } else: if not _get_resource( @@ -1784,7 +1774,7 @@ def create_nat_gateway( ): return { "created": False, - "error": {"message": "Subnet {} does not exist.".format(subnet_id)}, + "error": {"message": f"Subnet {subnet_id} does not exist."}, } conn3 = _get_conn3(region=region, key=key, keyid=keyid, profile=profile) @@ -2035,9 +2025,7 @@ def create_dhcp_options( if not vpc_id: return { "created": False, - "error": { - "message": "VPC {} does not exist.".format(vpc_name or vpc_id) - }, + "error": {"message": f"VPC {vpc_name or vpc_id} does not exist."}, } r = _create_resource( @@ -2177,9 +2165,7 @@ def associate_dhcp_options_to_vpc( if not vpc_id: return { "associated": False, - "error": { - "message": "VPC {} does not exist.".format(vpc_name or vpc_id) - }, + "error": {"message": f"VPC {vpc_name or vpc_id} does not exist."}, } conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) @@ -2284,7 +2270,7 @@ def create_network_acl( if not vpc_id: return { "created": False, - "error": {"message": "VPC {} does not exist.".format(_id)}, + "error": {"message": f"VPC {_id} does not exist."}, } if all((subnet_id, subnet_name)): @@ -2298,7 +2284,7 @@ def create_network_acl( if not subnet_id: return { "created": False, - "error": {"message": "Subnet {} does not exist.".format(subnet_name)}, + "error": {"message": f"Subnet {subnet_name} does not exist."}, } elif subnet_id: if not _get_resource( @@ -2311,7 +2297,7 @@ def create_network_acl( ): return { "created": False, - "error": {"message": "Subnet {} does not exist.".format(subnet_id)}, + "error": {"message": f"Subnet {subnet_id} does not exist."}, } r = _create_resource( @@ -2468,9 +2454,7 @@ def associate_network_acl_to_subnet( if not network_acl_id: return { "associated": False, - "error": { - "message": "Network ACL {} does not exist.".format(network_acl_name) - }, + "error": {"message": f"Network ACL {network_acl_name} does not exist."}, } if subnet_name: subnet_id = _get_resource_id( @@ -2479,7 +2463,7 @@ def associate_network_acl_to_subnet( if not subnet_id: return { "associated": False, - "error": {"message": "Subnet {} does not exist.".format(subnet_name)}, + "error": {"message": f"Subnet {subnet_name} does not exist."}, } try: conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) @@ -2547,9 +2531,7 @@ def disassociate_network_acl( if not subnet_id: return { "disassociated": False, - "error": { - "message": "Subnet {} does not exist.".format(subnet_name) - }, + "error": {"message": f"Subnet {subnet_name} does not exist."}, } if vpc_name or vpc_id: @@ -2592,7 +2574,7 @@ def _create_network_acl_entry( for v in ("rule_number", "protocol", "rule_action", "cidr_block"): if locals()[v] is None: - raise SaltInvocationError("{} is required.".format(v)) + raise SaltInvocationError(f"{v} is required.") if network_acl_name: network_acl_id = _get_resource_id( @@ -2742,7 +2724,7 @@ def delete_network_acl_entry( for v in ("rule_number", "egress"): if locals()[v] is None: - raise SaltInvocationError("{} is required.".format(v)) + raise SaltInvocationError(f"{v} is required.") if network_acl_name: network_acl_id = _get_resource_id( @@ -2805,7 +2787,7 @@ def create_route_table( if not vpc_id: return { "created": False, - "error": {"message": "VPC {} does not exist.".format(vpc_name or vpc_id)}, + "error": {"message": f"VPC {vpc_name or vpc_id} does not exist."}, } return _create_resource( @@ -2941,7 +2923,7 @@ def route_exists( if tags: for tag_name, tag_value in tags.items(): - filter_parameters["filters"]["tag:{}".format(tag_name)] = tag_value + filter_parameters["filters"][f"tag:{tag_name}"] = tag_value route_tables = conn.get_all_route_tables(**filter_parameters) @@ -3013,7 +2995,7 @@ def associate_route_table( if not subnet_id: return { "associated": False, - "error": {"message": "Subnet {} does not exist.".format(subnet_name)}, + "error": {"message": f"Subnet {subnet_name} does not exist."}, } if all((route_table_id, route_table_name)): @@ -3032,9 +3014,7 @@ def associate_route_table( if not route_table_id: return { "associated": False, - "error": { - "message": "Route table {} does not exist.".format(route_table_name) - }, + "error": {"message": f"Route table {route_table_name} does not exist."}, } try: @@ -3484,7 +3464,7 @@ def describe_route_tables( if tags: for tag_name, tag_value in tags.items(): filter_parameters["Filters"].append( - {"Name": "tag:{}".format(tag_name), "Values": [tag_value]} + {"Name": f"tag:{tag_name}", "Values": [tag_value]} ) route_tables = conn3.describe_route_tables(**filter_parameters).get( @@ -3598,7 +3578,7 @@ def _maybe_name_route_table(conn, vpcid, vpc_name): log.warning("no default route table found") return - name = "{}-default-table".format(vpc_name) + name = f"{vpc_name}-default-table" _maybe_set_name_tag(name, default_table) log.debug("Default route table name was set to: %s on vpc %s", name, vpcid) @@ -3755,9 +3735,7 @@ def request_vpc_peering_connection( vpc_name=peer_vpc_name, region=region, key=key, keyid=keyid, profile=profile ) if not peer_vpc_id: - return { - "error": "Could not resolve VPC name {} to an ID".format(peer_vpc_name) - } + return {"error": f"Could not resolve VPC name {peer_vpc_name} to an ID"} peering_params = { "VpcId": requester_vpc_id, @@ -3778,7 +3756,7 @@ def request_vpc_peering_connection( vpc_peering = conn.create_vpc_peering_connection(**peering_params) peering = vpc_peering.get("VpcPeeringConnection", {}) peering_conn_id = peering.get("VpcPeeringConnectionId", "ERROR") - msg = "VPC peering {} requested.".format(peering_conn_id) + msg = f"VPC peering {peering_conn_id} requested." log.debug(msg) if name: @@ -3787,7 +3765,7 @@ def request_vpc_peering_connection( Resources=[peering_conn_id], Tags=[{"Key": "Name", "Value": name}] ) log.debug("Applied name tag to vpc peering connection") - msg += " With name {}.".format(name) + msg += f" With name {name}." return {"msg": msg} except botocore.exceptions.ClientError as err: @@ -3989,7 +3967,7 @@ def delete_vpc_peering_connection( conn_id = _vpc_peering_conn_id_for_name(conn_name, conn) if not conn_id: raise SaltInvocationError( - "Couldn't resolve VPC peering connection {} to an ID".format(conn_name) + f"Couldn't resolve VPC peering connection {conn_name} to an ID" ) try: log.debug("Trying to delete vpc peering connection") diff --git a/salt/modules/bsd_shadow.py b/salt/modules/bsd_shadow.py index c9717d8c036..3af23b710f3 100644 --- a/salt/modules/bsd_shadow.py +++ b/salt/modules/bsd_shadow.py @@ -8,7 +8,6 @@ Manage the password database on BSD systems `. """ - import salt.utils.files import salt.utils.stringutils from salt.exceptions import CommandExecutionError, SaltInvocationError @@ -111,7 +110,7 @@ def info(name): if not isinstance(name, str): name = str(name) if ":" in name: - raise SaltInvocationError("Invalid username '{}'".format(name)) + raise SaltInvocationError(f"Invalid username '{name}'") if __salt__["cmd.has_exec"]("pw"): change, expire = __salt__["cmd.run_stdout"]( @@ -122,7 +121,7 @@ def info(name): with salt.utils.files.fopen("/etc/master.passwd", "r") as fp_: for line in fp_: line = salt.utils.stringutils.to_unicode(line) - if line.startswith("{}:".format(name)): + if line.startswith(f"{name}:"): key = line.split(":") change, expire = key[5:7] ret["passwd"] = str(key[1]) @@ -211,7 +210,7 @@ def del_password(name): salt '*' shadow.del_password username """ - cmd = "pw user mod {} -w none".format(name) + cmd = f"pw user mod {name} -w none" __salt__["cmd.run"](cmd, python_shell=False, output_loglevel="quiet") uinfo = info(name) return not uinfo["passwd"] diff --git a/salt/modules/btrfs.py b/salt/modules/btrfs.py index 4b02eb21afa..30f857de5d7 100644 --- a/salt/modules/btrfs.py +++ b/salt/modules/btrfs.py @@ -85,7 +85,7 @@ def info(device): salt '*' btrfs.info /dev/sda1 """ - out = __salt__["cmd.run_all"]("btrfs filesystem show {}".format(device)) + out = __salt__["cmd.run_all"](f"btrfs filesystem show {device}") salt.utils.fsutils._verify_run(out) return _parse_btrfs_info(out["stdout"]) @@ -111,9 +111,7 @@ def _defragment_mountpoint(mountpoint): """ Defragment only one BTRFS mountpoint. """ - out = __salt__["cmd.run_all"]( - "btrfs filesystem defragment -f {}".format(mountpoint) - ) + out = __salt__["cmd.run_all"](f"btrfs filesystem defragment -f {mountpoint}") return { "mount_point": mountpoint, "passed": not out["stderr"], @@ -140,7 +138,7 @@ def defragment(path): is_device = salt.utils.fsutils._is_device(path) mounts = salt.utils.fsutils._get_mounts("btrfs") if is_device and not mounts.get(path): - raise CommandExecutionError('Device "{}" is not mounted'.format(path)) + raise CommandExecutionError(f'Device "{path}" is not mounted') result = [] if is_device: @@ -159,9 +157,9 @@ def defragment(path): and not d_res["passed"] and "range ioctl not supported" in d_res["log"] ): - d_res[ - "log" - ] = "Range ioctl defragmentation is not supported in this kernel." + d_res["log"] = ( + "Range ioctl defragmentation is not supported in this kernel." + ) if not is_mountpoint: d_res["mount_point"] = False @@ -212,7 +210,7 @@ def _usage_overall(raw): subk = keyset[1].split("(") data[key] = subk[0].strip() subk = subk[1].replace(")", "").split(": ") - data["{}_{}".format(key, subk[0])] = subk[1] + data[f"{key}_{subk[0]}"] = subk[1] else: data[key] = keyset[1] @@ -263,7 +261,7 @@ def usage(path): salt '*' btrfs.usage /your/mountpoint """ - out = __salt__["cmd.run_all"]("btrfs filesystem usage {}".format(path)) + out = __salt__["cmd.run_all"](f"btrfs filesystem usage {path}") salt.utils.fsutils._verify_run(out) ret = {} @@ -317,9 +315,7 @@ def mkfs(*devices, **kwargs): mounts = salt.utils.fsutils._get_mounts("btrfs") for device in devices: if mounts.get(device): - raise CommandExecutionError( - 'Device "{}" should not be mounted'.format(device) - ) + raise CommandExecutionError(f'Device "{device}" should not be mounted') cmd = ["mkfs.btrfs"] @@ -332,9 +328,9 @@ def mkfs(*devices, **kwargs): cmd.append("-m single") else: if dto: - cmd.append("-d {}".format(dto)) + cmd.append(f"-d {dto}") if mto: - cmd.append("-m {}".format(mto)) + cmd.append(f"-m {mto}") for key, option in [ ("-l", "leafsize"), @@ -348,7 +344,7 @@ def mkfs(*devices, **kwargs): if option == "label" and option in kwargs: kwargs["label"] = "'{}'".format(kwargs["label"]) if kwargs.get(option): - cmd.append("{} {}".format(key, kwargs.get(option))) + cmd.append(f"{key} {kwargs.get(option)}") if kwargs.get("uuid"): cmd.append( @@ -393,12 +389,10 @@ def resize(mountpoint, size): if size == "max": if not salt.utils.fsutils._is_device(mountpoint): raise CommandExecutionError( - 'Mountpoint "{}" should be a valid device'.format(mountpoint) + f'Mountpoint "{mountpoint}" should be a valid device' ) if not salt.utils.fsutils._get_mounts("btrfs").get(mountpoint): - raise CommandExecutionError( - 'Device "{}" should be mounted'.format(mountpoint) - ) + raise CommandExecutionError(f'Device "{mountpoint}" should be mounted') elif ( len(size) < 3 or size[0] not in "-+" @@ -411,9 +405,7 @@ def resize(mountpoint, size): ) ) - out = __salt__["cmd.run_all"]( - "btrfs filesystem resize {} {}".format(size, mountpoint) - ) + out = __salt__["cmd.run_all"](f"btrfs filesystem resize {size} {mountpoint}") salt.utils.fsutils._verify_run(out) ret = {"log": out["stdout"]} @@ -441,7 +433,7 @@ def _fsck_ext(device): } return msgs.get( - __salt__["cmd.run_all"]("fsck -f -n {}".format(device))["retcode"], + __salt__["cmd.run_all"](f"fsck -f -n {device}")["retcode"], "Unknown error", ) @@ -472,7 +464,7 @@ def convert(device, permanent=False, keeplf=False): salt.utils.fsutils._verify_run(out) devices = salt.utils.fsutils._blkid_output(out["stdout"]) if not devices.get(device): - raise CommandExecutionError('The device "{}" was is not found.'.format(device)) + raise CommandExecutionError(f'The device "{device}" was is not found.') if not devices[device]["type"] in ["ext2", "ext3", "ext4"]: raise CommandExecutionError( @@ -503,7 +495,7 @@ documentation regarding this topic. """ ) - salt.utils.fsutils._verify_run(__salt__["cmd.run_all"]("umount {}".format(device))) + salt.utils.fsutils._verify_run(__salt__["cmd.run_all"](f"umount {device}")) ret = { "before": { @@ -513,11 +505,9 @@ documentation regarding this topic. } } + salt.utils.fsutils._verify_run(__salt__["cmd.run_all"](f"btrfs-convert {device}")) salt.utils.fsutils._verify_run( - __salt__["cmd.run_all"]("btrfs-convert {}".format(device)) - ) - salt.utils.fsutils._verify_run( - __salt__["cmd.run_all"]("mount {} {}".format(device, mountpoint)) + __salt__["cmd.run_all"](f"mount {device} {mountpoint}") ) # Refresh devices @@ -532,38 +522,34 @@ documentation regarding this topic. } # Post-migration procedures - image_path = "{}/ext2_saved".format(mountpoint) + image_path = f"{mountpoint}/ext2_saved" orig_fstype = ret["before"]["type"] if not os.path.exists(image_path): raise CommandExecutionError( - 'BTRFS migration went wrong: the image "{}" not found!'.format(image_path) + f'BTRFS migration went wrong: the image "{image_path}" not found!' ) if not permanent: - ret["after"]["{}_image".format(orig_fstype)] = image_path + ret["after"][f"{orig_fstype}_image"] = image_path image_info_proc = subprocess.run( - ["file", "{}/image".format(image_path)], check=True, stdout=subprocess.PIPE + ["file", f"{image_path}/image"], check=True, stdout=subprocess.PIPE ) - ret["after"][ - "{}_image_info".format(orig_fstype) - ] = image_info_proc.stdout.strip() + ret["after"][f"{orig_fstype}_image_info"] = image_info_proc.stdout.strip() else: - ret["after"]["{}_image".format(orig_fstype)] = "removed" - ret["after"]["{}_image_info".format(orig_fstype)] = "N/A" + ret["after"][f"{orig_fstype}_image"] = "removed" + ret["after"][f"{orig_fstype}_image_info"] = "N/A" salt.utils.fsutils._verify_run( - __salt__["cmd.run_all"]("btrfs subvolume delete {}".format(image_path)) + __salt__["cmd.run_all"](f"btrfs subvolume delete {image_path}") ) - out = __salt__["cmd.run_all"]("btrfs filesystem balance {}".format(mountpoint)) + out = __salt__["cmd.run_all"](f"btrfs filesystem balance {mountpoint}") salt.utils.fsutils._verify_run(out) ret["after"]["balance_log"] = out["stdout"] - lost_found = "{}/lost+found".format(mountpoint) + lost_found = f"{mountpoint}/lost+found" if os.path.exists(lost_found) and not keeplf: - salt.utils.fsutils._verify_run( - __salt__["cmd.run_all"]("rm -rf {}".format(lost_found)) - ) + salt.utils.fsutils._verify_run(__salt__["cmd.run_all"](f"rm -rf {lost_found}")) return ret @@ -576,7 +562,7 @@ def _restripe(mountpoint, direction, *devices, **kwargs): if salt.utils.fsutils._is_device(mountpoint): raise CommandExecutionError( - 'Mountpount expected, while device "{}" specified'.format(mountpoint) + f'Mountpount expected, while device "{mountpoint}" specified' ) mounted = False @@ -588,7 +574,7 @@ def _restripe(mountpoint, direction, *devices, **kwargs): if not mounted: raise CommandExecutionError( - 'No BTRFS device mounted on "{}" mountpoint'.format(mountpoint) + f'No BTRFS device mounted on "{mountpoint}" mountpoint' ) if not devices: @@ -597,9 +583,9 @@ def _restripe(mountpoint, direction, *devices, **kwargs): available_devices = __salt__["btrfs.devices"]() for device in devices: if device not in available_devices.keys(): - raise CommandExecutionError('Device "{}" is not recognized'.format(device)) + raise CommandExecutionError(f'Device "{device}" is not recognized') - cmd = ["btrfs device {}".format(direction)] + cmd = [f"btrfs device {direction}"] for device in devices: cmd.append(device) @@ -627,9 +613,7 @@ def _restripe(mountpoint, direction, *devices, **kwargs): ) ) else: - out = __salt__["cmd.run_all"]( - "btrfs filesystem balance {}".format(mountpoint) - ) + out = __salt__["cmd.run_all"](f"btrfs filesystem balance {mountpoint}") salt.utils.fsutils._verify_run(out) if out["stdout"]: fs_log.append(out["stdout"]) @@ -715,15 +699,13 @@ def properties(obj, type=None, set=None): "d", "device", ]: - raise CommandExecutionError( - 'Unknown property type: "{}" specified'.format(type) - ) + raise CommandExecutionError(f'Unknown property type: "{type}" specified') cmd = ["btrfs"] cmd.append("property") cmd.append(set and "set" or "list") if type: - cmd.append("-t{}".format(type)) + cmd.append(f"-t{type}") cmd.append(obj) if set: @@ -744,9 +726,9 @@ def properties(obj, type=None, set=None): ret = {} for prop, descr in _parse_proplist(out["stdout"]).items(): ret[prop] = {"description": descr} - value = __salt__["cmd.run_all"]( - "btrfs property get {} {}".format(obj, prop) - )["stdout"] + value = __salt__["cmd.run_all"](f"btrfs property get {obj} {prop}")[ + "stdout" + ] ret[prop]["value"] = value and value.split("=")[-1] or "N/A" return ret diff --git a/salt/modules/cabal.py b/salt/modules/cabal.py index 8b4426c1400..fb2ccb61c8c 100644 --- a/salt/modules/cabal.py +++ b/salt/modules/cabal.py @@ -85,7 +85,7 @@ def install(pkg=None, pkgs=None, user=None, install_global=False, env=None): cmd.append("--global") if pkg: - cmd.append('"{}"'.format(pkg)) + cmd.append(f'"{pkg}"') elif pkgs: cmd.append('"{}"'.format('" "'.join(pkgs))) @@ -125,7 +125,7 @@ def list_(pkg=None, user=None, installed=False, env=None): cmd.append("--installed") if pkg: - cmd.append('"{}"'.format(pkg)) + cmd.append(f'"{pkg}"') result = __salt__["cmd.run_all"](" ".join(cmd), runas=user, env=env) @@ -160,7 +160,7 @@ def uninstall(pkg, user=None, env=None): """ cmd = ["ghc-pkg unregister"] - cmd.append('"{}"'.format(pkg)) + cmd.append(f'"{pkg}"') result = __salt__["cmd.run_all"](" ".join(cmd), runas=user, env=env) diff --git a/salt/modules/capirca_acl.py b/salt/modules/capirca_acl.py index 82189e48ade..2678556a433 100644 --- a/salt/modules/capirca_acl.py +++ b/salt/modules/capirca_acl.py @@ -481,7 +481,7 @@ def _get_term_object( pillarenv=None, saltenv=None, merge_pillar=True, - **term_fields + **term_fields, ): """ Return an instance of the ``_Term`` class given the term options. @@ -558,7 +558,7 @@ def _get_policy_object( pillarenv=pillarenv, saltenv=saltenv, merge_pillar=merge_pillar, - **term_fields + **term_fields, ) filter_terms.append(term) policy_filters.append((header, filter_terms)) @@ -597,17 +597,15 @@ def _revision_tag( if "$Id:$" in line: if not revision_id: # if no explicit revision ID required continue # jump to next line, ignore this one - line = line.replace("$Id:$", "$Id: {rev_id} $".format(rev_id=revision_id)) + line = line.replace("$Id:$", f"$Id: {revision_id} $") if "$Revision:$" in line: if not revision_no: # if no explicit revision number required continue # jump to next line, ignore this one - line = line.replace( - "$Revision:$", "$Revision: {rev_no} $".format(rev_no=revision_no) - ) + line = line.replace("$Revision:$", f"$Revision: {revision_no} $") if "$Date:$" in line: if not revision_date: continue # jump - line = line.replace("$Date:$", "$Date: {ts} $".format(ts=timestamp)) + line = line.replace("$Date:$", f"$Date: {timestamp} $") new_text.append(line) return "\n".join(new_text) @@ -632,7 +630,7 @@ def get_term_config( revision_date_format="%Y/%m/%d", source_service=None, destination_service=None, - **term_fields + **term_fields, ): """ Return the configuration of a single policy term. diff --git a/salt/modules/cassandra_cql.py b/salt/modules/cassandra_cql.py index 4e5ddcee71b..38e42f42bd9 100644 --- a/salt/modules/cassandra_cql.py +++ b/salt/modules/cassandra_cql.py @@ -220,7 +220,7 @@ def _load_properties(property_name, config_option, set_default=False, default=No config_option, ) raise CommandExecutionError( - "ERROR: Cassandra {} cannot be empty.".format(config_option) + f"ERROR: Cassandra {config_option} cannot be empty." ) return loaded_property return property_name @@ -510,7 +510,7 @@ def cql_query( results = session.execute(query) except BaseException as e: log.error("Failed to execute query: %s\n reason: %s", query, e) - msg = "ERROR: Cassandra query failed: {} reason: {}".format(query, e) + msg = f"ERROR: Cassandra query failed: {query} reason: {e}" raise CommandExecutionError(msg) if results: @@ -543,7 +543,7 @@ def cql_query_with_prepare( load_balancing_policy=None, load_balancing_policy_args=None, ssl_options=None, - **kwargs + **kwargs, ): """ Run a query on a Cassandra cluster and return a dictionary. @@ -642,7 +642,7 @@ def cql_query_with_prepare( results = session.execute(bound_statement.bind(statement_arguments)) except BaseException as e: log.error("Failed to execute query: %s\n reason: %s", query, e) - msg = "ERROR: Cassandra query failed: {} reason: {}".format(query, e) + msg = f"ERROR: Cassandra query failed: {query} reason: {e}" raise CommandExecutionError(msg) if not asynchronous and results: @@ -919,13 +919,13 @@ def list_column_families( salt 'minion1' cassandra_cql.list_column_families keyspace=system """ - where_clause = "where keyspace_name = '{}'".format(keyspace) if keyspace else "" + where_clause = f"where keyspace_name = '{keyspace}'" if keyspace else "" query = { "2": "select columnfamily_name from system.schema_columnfamilies {};".format( where_clause ), - "3": "select column_name from system_schema.columns {};".format(where_clause), + "3": f"select column_name from system_schema.columns {where_clause};", } ret = {} @@ -1190,7 +1190,7 @@ def drop_keyspace( ssl_options=ssl_options, ) if existing_keyspace: - query = """drop keyspace {};""".format(keyspace) + query = f"""drop keyspace {keyspace};""" try: cql_query( query, @@ -1419,16 +1419,12 @@ def list_permissions( salt 'minion1' cassandra_cql.list_permissions username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 """ - keyspace_cql = ( - "{} {}".format(resource_type, resource) if resource else "all keyspaces" - ) - permission_cql = ( - "{} permission".format(permission) if permission else "all permissions" - ) - query = "list {} on {}".format(permission_cql, keyspace_cql) + keyspace_cql = f"{resource_type} {resource}" if resource else "all keyspaces" + permission_cql = f"{permission} permission" if permission else "all permissions" + query = f"list {permission_cql} on {keyspace_cql}" if username: - query = "{} of {}".format(query, username) + query = f"{query} of {username}" log.debug("Attempting to list permissions with query '%s'", query) @@ -1511,13 +1507,9 @@ def grant_permission( salt 'minion1' cassandra_cql.grant_permission username=joe resource=test_table resource_type=table \ permission=select contact_points=minion1 """ - permission_cql = ( - "grant {}".format(permission) if permission else "grant all permissions" - ) - resource_cql = ( - "on {} {}".format(resource_type, resource) if resource else "on all keyspaces" - ) - query = "{} {} to {}".format(permission_cql, resource_cql, username) + permission_cql = f"grant {permission}" if permission else "grant all permissions" + resource_cql = f"on {resource_type} {resource}" if resource else "on all keyspaces" + query = f"{permission_cql} {resource_cql} to {username}" log.debug("Attempting to grant permissions with query '%s'", query) try: diff --git a/salt/modules/chef.py b/salt/modules/chef.py index 698db0db560..4568e0c9458 100644 --- a/salt/modules/chef.py +++ b/salt/modules/chef.py @@ -2,7 +2,6 @@ Execute chef in server or solo mode """ - import logging import os import tempfile @@ -37,7 +36,7 @@ def _default_logfile(exe_name): logfile = logfile_tmp.name logfile_tmp.close() else: - logfile = salt.utils.path.join("/var/log", "{}.log".format(exe_name)) + logfile = salt.utils.path.join("/var/log", f"{exe_name}.log") return logfile @@ -117,7 +116,7 @@ def client(whyrun=False, localmode=False, logfile=None, **kwargs): "chef-client", "--no-color", "--once", - '--logfile "{}"'.format(logfile), + f'--logfile "{logfile}"', "--format doc", ] @@ -185,7 +184,7 @@ def solo(whyrun=False, logfile=None, **kwargs): args = [ "chef-solo", "--no-color", - '--logfile "{}"'.format(logfile), + f'--logfile "{logfile}"', "--format doc", ] @@ -200,9 +199,9 @@ def _exec_cmd(*args, **kwargs): # Compile the command arguments cmd_args = " ".join(args) cmd_kwargs = "".join( - [" --{} {}".format(k, v) for k, v in kwargs.items() if not k.startswith("__")] + [f" --{k} {v}" for k, v in kwargs.items() if not k.startswith("__")] ) - cmd_exec = "{}{}".format(cmd_args, cmd_kwargs) + cmd_exec = f"{cmd_args}{cmd_kwargs}" log.debug("Chef command: %s", cmd_exec) return __salt__["cmd.run_all"](cmd_exec, python_shell=False) diff --git a/salt/modules/chronos.py b/salt/modules/chronos.py index a76590cb4af..3bc35e06bf9 100644 --- a/salt/modules/chronos.py +++ b/salt/modules/chronos.py @@ -37,7 +37,7 @@ def _jobs(): Return the currently configured jobs. """ response = salt.utils.http.query( - "{}/scheduler/jobs".format(_base_url()), + f"{_base_url()}/scheduler/jobs", decode_type="json", decode=True, ) @@ -106,7 +106,7 @@ def update_job(name, config): data = salt.utils.json.dumps(config) try: response = salt.utils.http.query( - "{}/scheduler/iso8601".format(_base_url()), + f"{_base_url()}/scheduler/iso8601", method="POST", data=data, header_dict={"Content-Type": "application/json"}, @@ -129,7 +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), + f"{_base_url()}/scheduler/job/{name}", method="DELETE", ) return True diff --git a/salt/modules/chroot.py b/salt/modules/chroot.py index 78c974cc196..5be402f1beb 100644 --- a/salt/modules/chroot.py +++ b/salt/modules/chroot.py @@ -171,7 +171,7 @@ def call(root, function, *args, **kwargs): safe_kwargs = salt.utils.args.clean_kwargs(**kwargs) salt_argv = ( [ - "python{}".format(sys.version_info[0]), + f"python{sys.version_info[0]}", os.path.join(chroot_path, "salt-call"), "--metadata", "--local", @@ -187,7 +187,7 @@ def call(root, function, *args, **kwargs): function, ] + list(args) - + ["{}={}".format(k, v) for (k, v) in safe_kwargs.items()] + + [f"{k}={v}" for (k, v) in safe_kwargs.items()] ) ret = __salt__["cmd.run_chroot"](root, [str(x) for x in salt_argv]) diff --git a/salt/modules/cimc.py b/salt/modules/cimc.py index e555538a901..90eb2b34c6c 100644 --- a/salt/modules/cimc.py +++ b/salt/modules/cimc.py @@ -24,7 +24,6 @@ rest API. """ - import logging import salt.proxy.cimc @@ -116,7 +115,7 @@ def create_user(uid=None, username=None, password=None, priv=None): "The privilege level must be specified." ) - dn = "sys/user-ext/user-{}".format(uid) + dn = f"sys/user-ext/user-{uid}" inconfig = """""".format( @@ -607,7 +606,7 @@ def mount_share( else: mount_options = "" - dn = "sys/svc-ext/vmedia-svc/vmmap-{}".format(name) + dn = f"sys/svc-ext/vmedia-svc/vmmap-{name}" inconfig = """""".format( @@ -713,7 +712,7 @@ def set_logging_levels(remote=None, local=None): if remote: if remote in logging_options: - query += ' remoteSeverity="{}"'.format(remote) + query += f' remoteSeverity="{remote}"' else: raise salt.exceptions.CommandExecutionError( "Remote Severity option is not valid." @@ -721,14 +720,14 @@ def set_logging_levels(remote=None, local=None): if local: if local in logging_options: - query += ' localSeverity="{}"'.format(local) + query += f' localSeverity="{local}"' else: raise salt.exceptions.CommandExecutionError( "Local Severity option is not valid." ) dn = "sys/svc-ext/syslog" - inconfig = """""".format(query) + inconfig = f"""""" ret = __proxy__["cimc.set_config_modify"](dn, inconfig, False) @@ -818,7 +817,7 @@ def set_power_configuration(policy=None, delayType=None, delayValue=None): if delayType == "fixed": query += ' delayType="fixed"' if delayValue: - query += ' delay="{}"'.format(delayValue) + query += f' delay="{delayValue}"' elif delayType == "random": query += ' delayType="random"' else: @@ -924,18 +923,18 @@ def set_user(uid=None, username=None, password=None, priv=None, status=None): raise salt.exceptions.CommandExecutionError("The user ID must be specified.") if status: - conf += ' accountStatus="{}"'.format(status) + conf += f' accountStatus="{status}"' if username: - conf += ' name="{}"'.format(username) + conf += f' name="{username}"' if priv: - conf += ' priv="{}"'.format(priv) + conf += f' priv="{priv}"' if password: - conf += ' pwd="{}"'.format(password) + conf += f' pwd="{password}"' - dn = "sys/user-ext/user-{}".format(uid) + dn = f"sys/user-ext/user-{uid}" inconfig = """""".format(uid, conf) diff --git a/salt/modules/ciscoconfparse_mod.py b/salt/modules/ciscoconfparse_mod.py index 56924691245..2be0a5f482e 100644 --- a/salt/modules/ciscoconfparse_mod.py +++ b/salt/modules/ciscoconfparse_mod.py @@ -58,7 +58,7 @@ 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: - raise SaltException("{} is not available".format(config_path)) + raise SaltException(f"{config_path} is not available") if isinstance(config, str): config = config.splitlines() ccp = ciscoconfparse.CiscoConfParse(config) diff --git a/salt/modules/cloud.py b/salt/modules/cloud.py index b4f52ae3b73..dd1ededf158 100644 --- a/salt/modules/cloud.py +++ b/salt/modules/cloud.py @@ -2,7 +2,6 @@ Salt-specific interface for calling Salt Cloud directly """ - import copy import logging import os diff --git a/salt/modules/cmdmod.py b/salt/modules/cmdmod.py index 4822971d552..d603a69ba77 100644 --- a/salt/modules/cmdmod.py +++ b/salt/modules/cmdmod.py @@ -145,7 +145,7 @@ def _render_cmd(cmd, cwd, template, saltenv=None, pillarenv=None, pillar_overrid # render the path as a template using path_template_engine as the engine if template not in salt.utils.templates.TEMPLATE_REGISTRY: raise CommandExecutionError( - "Attempted to render file paths with unavailable engine {}".format(template) + f"Attempted to render file paths with unavailable engine {template}" ) kwargs = {} @@ -265,7 +265,7 @@ def _prep_powershell_cmd(shell, cmd, stack, encoded_cmd): # the shell in quotes in case there are # spaces in the paths. if salt.utils.platform.is_windows(): - shell = '"{}"'.format(shell) + shell = f'"{shell}"' # extract_stack() returns a list of tuples. # The last item in the list [-1] is the current method. @@ -277,9 +277,9 @@ def _prep_powershell_cmd(shell, cmd, stack, encoded_cmd): ) ) elif encoded_cmd: - cmd = "{} -NonInteractive -NoProfile -EncodedCommand {}".format(shell, cmd) + cmd = f"{shell} -NonInteractive -NoProfile -EncodedCommand {cmd}" else: - cmd = '{} -NonInteractive -NoProfile -Command "{}"'.format(shell, cmd) + cmd = f'{shell} -NonInteractive -NoProfile -Command "{cmd}"' return cmd @@ -318,7 +318,7 @@ def _run( success_stdout=None, success_stderr=None, windows_codepage=65001, - **kwargs + **kwargs, ): """ Do the DRY thing and only call subprocess.Popen() once @@ -368,7 +368,7 @@ def _run( change_windows_codepage = False if not salt.utils.platform.is_windows(): if not os.path.isfile(shell) or not os.access(shell, os.X_OK): - msg = "The shell {} is not available".format(shell) + msg = f"The shell {shell} is not available" raise CommandExecutionError(msg) elif use_vt: # Memozation so not much overhead raise CommandExecutionError("VT not available on windows") @@ -406,9 +406,7 @@ def _run( # checked if blacklisted if "__pub_jid" in kwargs: if not _check_avail(cmd): - raise CommandExecutionError( - 'The shell command "{}" is not permitted'.format(cmd) - ) + raise CommandExecutionError(f'The shell command "{cmd}" is not permitted') env = _parse_env(env) @@ -428,12 +426,14 @@ def _run( "'" if not isinstance(cmd, list) else "", _log_cmd(cmd), "'" if not isinstance(cmd, list) else "", - "as user '{}' ".format(runas) if runas else "", - "in group '{}' ".format(group) if group else "", + f"as user '{runas}' " if runas else "", + f"in group '{group}' " if group else "", cwd, - ". Executing command in the background, no output will be logged." - if bg - else "", + ( + ". Executing command in the background, no output will be logged." + if bg + else "" + ), ) log.info(log_callback(msg)) @@ -455,7 +455,7 @@ def _run( cmd = " ".join(map(_cmd_quote, cmd)) # Ensure directory is correct before running command - cmd = "cd -- {dir} && {{ {cmd}\n }}".format(dir=_cmd_quote(cwd), cmd=cmd) + cmd = f"cd -- {_cmd_quote(cwd)} && {{ {cmd}\n }}" # Ensure environment is correct for a newly logged-in user by running # the command under bash as a login shell @@ -472,7 +472,7 @@ def _run( # Ensure the login is simulated correctly (note: su runs sh, not bash, # which causes the environment to be initialised incorrectly, which is # fixed by the previous line of code) - cmd = "su -l {} -c {}".format(_cmd_quote(runas), _cmd_quote(cmd)) + cmd = f"su -l {_cmd_quote(runas)} -c {_cmd_quote(cmd)}" # Set runas to None, because if you try to run `su -l` after changing # user, su will prompt for the password of the user and cause salt to @@ -484,7 +484,7 @@ def _run( try: pwd.getpwnam(runas) except KeyError: - raise CommandExecutionError("User '{}' is not available".format(runas)) + raise CommandExecutionError(f"User '{runas}' is not available") if group: if salt.utils.platform.is_windows(): @@ -496,7 +496,7 @@ def _run( try: grp.getgrnam(group) except KeyError: - raise CommandExecutionError("Group '{}' is not available".format(runas)) + raise CommandExecutionError(f"Group '{runas}' is not available") else: use_sudo = True @@ -542,7 +542,7 @@ def _run( if not salt.utils.pkg.check_bundled(): if __grains__["os"] in ["FreeBSD"]: - env_cmd.extend(["{} -c {}".format(shell, sys.executable)]) + env_cmd.extend([f"{shell} -c {sys.executable}"]) else: env_cmd.extend([sys.executable]) else: @@ -556,11 +556,11 @@ def _run( ] ) else: - env_cmd.extend(["{} python {}".format(sys.executable, fp.name)]) + env_cmd.extend([f"{sys.executable} python {fp.name}"]) fp.write(py_code) shutil.chown(fp.name, runas) - msg = "env command: {}".format(env_cmd) + msg = f"env command: {env_cmd}" log.debug(log_callback(msg)) env_bytes, env_encoded_err = subprocess.Popen( env_cmd, @@ -607,7 +607,7 @@ def _run( # Fix some corner cases where shelling out to get the user's # environment returns the wrong home directory. - runas_home = os.path.expanduser("~{}".format(runas)) + runas_home = os.path.expanduser(f"~{runas}") if env_runas.get("HOME") != runas_home: env_runas["HOME"] = runas_home @@ -685,7 +685,7 @@ def _run( try: _umask = int(_umask, 8) except ValueError: - raise CommandExecutionError("Invalid umask: '{}'".format(umask)) + raise CommandExecutionError(f"Invalid umask: '{umask}'") else: _umask = None @@ -707,7 +707,7 @@ def _run( if not os.path.isabs(cwd) or not os.path.isdir(cwd): raise CommandExecutionError( - "Specified cwd '{}' either not absolute or does not exist".format(cwd) + f"Specified cwd '{cwd}' either not absolute or does not exist" ) if ( @@ -828,9 +828,9 @@ def _run( else: formatted_timeout = "" if timeout: - formatted_timeout = " (timeout: {}s)".format(timeout) + formatted_timeout = f" (timeout: {timeout}s)" if output_loglevel is not None: - msg = "Running {} in VT{}".format(cmd, formatted_timeout) + msg = f"Running {cmd} in VT{formatted_timeout}" log.debug(log_callback(msg)) stdout, stderr = "", "" now = time.time() @@ -875,7 +875,7 @@ def _run( ret["retcode"] = None break except KeyboardInterrupt: - ret["stderr"] = "SALT: User break\n{}".format(stderr) + ret["stderr"] = f"SALT: User break\n{stderr}" ret["retcode"] = 1 break except salt.utils.vt.TerminalException as exc: @@ -999,7 +999,6 @@ def _run_all_quiet( success_stderr=None, ignore_retcode=None, ): - """ Helper for running commands quietly for minion startup. Returns a dict of return data. @@ -1064,7 +1063,7 @@ def run( success_retcodes=None, success_stdout=None, success_stderr=None, - **kwargs + **kwargs, ): r""" Execute the passed command and return the output as a string @@ -1331,7 +1330,7 @@ def run( success_retcodes=success_retcodes, success_stdout=success_stdout, success_stderr=success_stderr, - **kwargs + **kwargs, ) log_callback = _check_cb(log_callback) @@ -1380,7 +1379,7 @@ def shell( success_retcodes=None, success_stdout=None, success_stderr=None, - **kwargs + **kwargs, ): """ Execute the passed command and return the output as a string. @@ -1608,7 +1607,7 @@ def shell( success_retcodes=success_retcodes, success_stdout=success_stdout, success_stderr=success_stderr, - **kwargs + **kwargs, ) @@ -1639,7 +1638,7 @@ def run_stdout( success_retcodes=None, success_stdout=None, success_stderr=None, - **kwargs + **kwargs, ): """ Execute a command, and only return the standard out @@ -1840,7 +1839,7 @@ def run_stdout( success_retcodes=success_retcodes, success_stdout=success_stdout, success_stderr=success_stderr, - **kwargs + **kwargs, ) return ret["stdout"] if not hide_output else "" @@ -1873,7 +1872,7 @@ def run_stderr( success_retcodes=None, success_stdout=None, success_stderr=None, - **kwargs + **kwargs, ): """ Execute a command and only return the standard error @@ -2074,7 +2073,7 @@ def run_stderr( success_retcodes=success_retcodes, success_stdout=success_stdout, success_stderr=success_stderr, - **kwargs + **kwargs, ) return ret["stderr"] if not hide_output else "" @@ -2109,7 +2108,7 @@ def run_all( success_retcodes=None, success_stdout=None, success_stderr=None, - **kwargs + **kwargs, ): """ Execute the passed command and return a dict of return data @@ -2354,7 +2353,7 @@ def run_all( success_retcodes=success_retcodes, success_stdout=success_stdout, success_stderr=success_stderr, - **kwargs + **kwargs, ) if hide_output: @@ -2386,7 +2385,7 @@ def retcode( success_retcodes=None, success_stdout=None, success_stderr=None, - **kwargs + **kwargs, ): """ Execute a shell command and return the command's return code. @@ -2576,7 +2575,7 @@ def retcode( success_retcodes=success_retcodes, success_stdout=success_stdout, success_stderr=success_stderr, - **kwargs + **kwargs, ) return ret["retcode"] @@ -2604,7 +2603,7 @@ def _retcode_quiet( success_retcodes=None, success_stdout=None, success_stderr=None, - **kwargs + **kwargs, ): """ Helper for running commands quietly for minion startup. Returns same as @@ -2634,7 +2633,7 @@ def _retcode_quiet( success_retcodes=success_retcodes, success_stdout=success_stdout, success_stderr=success_stderr, - **kwargs + **kwargs, ) @@ -2663,7 +2662,7 @@ def script( success_retcodes=None, success_stdout=None, success_stderr=None, - **kwargs + **kwargs, ): """ Download a script from a remote location and execute the script locally. @@ -2936,7 +2935,7 @@ def script( success_retcodes=success_retcodes, success_stdout=success_stdout, success_stderr=success_stderr, - **kwargs + **kwargs, ) _cleanup_tempfile(path) # If a temp working directory was created (Windows), let's remove that @@ -2971,7 +2970,7 @@ def script_retcode( success_retcodes=None, success_stdout=None, success_stderr=None, - **kwargs + **kwargs, ): """ Download a script from a remote location and execute the script locally. @@ -3150,7 +3149,7 @@ def script_retcode( success_retcodes=success_retcodes, success_stdout=success_stdout, success_stderr=success_stderr, - **kwargs + **kwargs, )["retcode"] @@ -3280,7 +3279,7 @@ def tty(device, echo=""): salt '*' cmd.tty pts3 'This is a test' """ if device.startswith("tty"): - teletype = "/dev/{}".format(device) + teletype = f"/dev/{device}" elif device.startswith("pts"): teletype = "/dev/{}".format(device.replace("pts", "pts/")) else: @@ -3288,9 +3287,9 @@ def tty(device, echo=""): try: with salt.utils.files.fopen(teletype, "wb") as tty_device: tty_device.write(salt.utils.stringutils.to_bytes(echo)) - return {"Success": "Message was successfully echoed to {}".format(teletype)} + return {"Success": f"Message was successfully echoed to {teletype}"} except OSError: - return {"Error": "Echoing to {} returned error".format(teletype)} + return {"Error": f"Echoing to {teletype} returned error"} def run_chroot( @@ -3321,7 +3320,7 @@ def run_chroot( success_retcodes=None, success_stdout=None, success_stderr=None, - **kwargs + **kwargs, ): """ .. versionadded:: 2014.7.0 @@ -3497,7 +3496,7 @@ def run_chroot( else: userspec = "" - cmd = "chroot {} {} {} -c {}".format(userspec, root, sh_, _cmd_quote(cmd)) + cmd = f"chroot {userspec} {root} {sh_} -c {_cmd_quote(cmd)}" run_func = __context__.pop("cmd.run_chroot.func", run_all) @@ -3710,7 +3709,7 @@ def shell_info(shell, list_modules=False): for reg_ver in pw_keys: install_data = salt.utils.win_reg.read_value( hive="HKEY_LOCAL_MACHINE", - key="Software\\Microsoft\\PowerShell\\{}".format(reg_ver), + key=f"Software\\Microsoft\\PowerShell\\{reg_ver}", vname="Install", ) if ( @@ -3861,7 +3860,7 @@ def powershell( success_retcodes=None, success_stdout=None, success_stderr=None, - **kwargs + **kwargs, ): """ Execute the passed PowerShell command and return the output as a dictionary. @@ -4064,7 +4063,7 @@ def powershell( if salt.utils.versions.version_cmp(psversion, "2.0") == 1: cmd += " | ConvertTo-JSON" if depth is not None: - cmd += " -Depth {}".format(depth) + cmd += f" -Depth {depth}" # Put the whole command inside a try / catch block # Some errors in PowerShell are not "Terminating Errors" and will not be @@ -4077,7 +4076,7 @@ def powershell( # Convert the cmd to UTF-16LE without a BOM and base64 encode. # Just base64 encoding UTF-8 or including a BOM is not valid. log.debug("Encoding PowerShell command '%s'", cmd) - cmd = "$ProgressPreference='SilentlyContinue'; {}".format(cmd) + cmd = f"$ProgressPreference='SilentlyContinue'; {cmd}" cmd_utf16 = cmd.encode("utf-16-le") cmd = base64.standard_b64encode(cmd_utf16) cmd = salt.utils.stringutils.to_str(cmd) @@ -4111,7 +4110,7 @@ def powershell( success_retcodes=success_retcodes, success_stdout=success_stdout, success_stderr=success_stderr, - **kwargs + **kwargs, ) # Sometimes Powershell returns an empty string, which isn't valid JSON @@ -4150,7 +4149,7 @@ def powershell_all( success_retcodes=None, success_stdout=None, success_stderr=None, - **kwargs + **kwargs, ): """ Execute the passed PowerShell command and return a dictionary with a result @@ -4423,13 +4422,13 @@ def powershell_all( # Append PowerShell Object formatting cmd += " | ConvertTo-JSON" if depth is not None: - cmd += " -Depth {}".format(depth) + cmd += f" -Depth {depth}" if encode_cmd: # Convert the cmd to UTF-16LE without a BOM and base64 encode. # Just base64 encoding UTF-8 or including a BOM is not valid. log.debug("Encoding PowerShell command '%s'", cmd) - cmd = "$ProgressPreference='SilentlyContinue'; {}".format(cmd) + cmd = f"$ProgressPreference='SilentlyContinue'; {cmd}" cmd_utf16 = cmd.encode("utf-16-le") cmd = base64.standard_b64encode(cmd_utf16) cmd = salt.utils.stringutils.to_str(cmd) @@ -4463,7 +4462,7 @@ def powershell_all( success_retcodes=success_retcodes, success_stdout=success_stdout, success_stderr=success_stderr, - **kwargs + **kwargs, ) stdoutput = response["stdout"] @@ -4519,7 +4518,7 @@ def run_bg( success_retcodes=None, success_stdout=None, success_stderr=None, - **kwargs + **kwargs, ): r""" .. versionadded:: 2016.3.0 @@ -4737,7 +4736,7 @@ def run_bg( success_retcodes=success_retcodes, success_stdout=success_stdout, success_stderr=success_stderr, - **kwargs + **kwargs, ) return {"pid": res["pid"]} diff --git a/salt/modules/composer.py b/salt/modules/composer.py index 7feb5d0f2ca..8e31c52a688 100644 --- a/salt/modules/composer.py +++ b/salt/modules/composer.py @@ -48,7 +48,7 @@ def did_composer_install(dir): salt '*' composer.did_composer_install /var/www/application """ - lockFile = "{}/vendor".format(dir) + lockFile = f"{dir}/vendor" if os.path.exists(lockFile): return True return False @@ -147,7 +147,7 @@ def _run_composer( # Don't need a dir for the 'selfupdate' action; all other actions do need a dir if directory is None and action != "selfupdate": raise SaltInvocationError( - "The 'directory' argument is required for composer.{}".format(action) + f"The 'directory' argument is required for composer.{action}" ) # Base Settings diff --git a/salt/modules/config.py b/salt/modules/config.py index 972a2e84c7c..044d7172c7c 100644 --- a/salt/modules/config.py +++ b/salt/modules/config.py @@ -522,10 +522,10 @@ def dot_vals(value): """ ret = {} for key, val in __pillar__.get("master", {}).items(): - if key.startswith("{}.".format(value)): + if key.startswith(f"{value}."): ret[key] = val for key, val in __opts__.items(): - if key.startswith("{}.".format(value)): + if key.startswith(f"{value}."): ret[key] = val return ret diff --git a/salt/modules/consul.py b/salt/modules/consul.py index 205cfb202bd..d1eca824b64 100644 --- a/salt/modules/consul.py +++ b/salt/modules/consul.py @@ -68,7 +68,7 @@ def _query( token = _get_token() headers = {"X-Consul-Token": token, "Content-Type": "application/json"} - base_url = urllib.parse.urljoin(consul_url, "{}/".format(api_version)) + base_url = urllib.parse.urljoin(consul_url, f"{api_version}/") url = urllib.parse.urljoin(base_url, function, False) if method == "GET": @@ -149,7 +149,7 @@ def list_(consul_url=None, token=None, key=None, **kwargs): query_params["recurse"] = "True" function = "kv/" else: - function = "kv/{}".format(key) + function = f"kv/{key}" query_params["keys"] = "True" query_params["separator"] = "/" @@ -203,7 +203,7 @@ def get(consul_url=None, key=None, token=None, recurse=False, decode=False, raw= raise SaltInvocationError('Required argument "key" is missing.') query_params = {} - function = "kv/{}".format(key) + function = f"kv/{key}" if recurse: query_params["recurse"] = "True" if raw: @@ -286,19 +286,17 @@ def put(consul_url=None, token=None, key=None, value=None, **kwargs): if "cas" in kwargs: if _current["res"]: if kwargs["cas"] == 0: - ret["message"] = "Key {} exists, index must be non-zero.".format(key) + ret["message"] = f"Key {key} exists, index must be non-zero." ret["res"] = False return ret if kwargs["cas"] != _current["data"]["ModifyIndex"]: - ret["message"] = "Key {} exists, but indexes do not match.".format(key) + ret["message"] = f"Key {key} exists, but indexes do not match." ret["res"] = False return ret query_params["cas"] = kwargs["cas"] else: - ret[ - "message" - ] = "Key {} does not exists, CAS argument can not be used.".format(key) + ret["message"] = f"Key {key} does not exists, CAS argument can not be used." ret["res"] = False return ret @@ -316,7 +314,7 @@ def put(consul_url=None, token=None, key=None, value=None, **kwargs): if _current["data"]["Session"] == kwargs["release"]: query_params["release"] = kwargs["release"] else: - ret["message"] = "{} locked by another session.".format(key) + ret["message"] = f"{key} locked by another session." ret["res"] = False return ret @@ -327,7 +325,7 @@ def put(consul_url=None, token=None, key=None, value=None, **kwargs): log.error("Key {0} does not exist. Skipping release.") data = value - function = "kv/{}".format(key) + function = f"kv/{key}" method = "PUT" res = _query( consul_url=consul_url, @@ -340,10 +338,10 @@ def put(consul_url=None, token=None, key=None, value=None, **kwargs): if res["res"]: ret["res"] = True - ret["data"] = "Added key {} with value {}.".format(key, value) + ret["data"] = f"Added key {key} with value {value}." else: ret["res"] = False - ret["data"] = "Unable to add key {} with value {}.".format(key, value) + ret["data"] = f"Unable to add key {key} with value {value}." if "error" in res: ret["error"] = res["error"] return ret @@ -396,7 +394,7 @@ def delete(consul_url=None, token=None, key=None, **kwargs): ret["res"] = False return ret - function = "kv/{}".format(key) + function = f"kv/{key}" res = _query( consul_url=consul_url, token=token, @@ -407,10 +405,10 @@ def delete(consul_url=None, token=None, key=None, **kwargs): if res["res"]: ret["res"] = True - ret["message"] = "Deleted key {}.".format(key) + ret["message"] = f"Deleted key {key}." else: ret["res"] = False - ret["message"] = "Unable to delete key {}.".format(key) + ret["message"] = f"Unable to delete key {key}." if "error" in res: ret["error"] = res["error"] return ret @@ -635,7 +633,7 @@ def agent_join(consul_url=None, token=None, address=None, **kwargs): if "wan" in kwargs: query_params["wan"] = kwargs["wan"] - function = "agent/join/{}".format(address) + function = f"agent/join/{address}" res = _query( consul_url=consul_url, function=function, @@ -680,7 +678,7 @@ def agent_leave(consul_url=None, token=None, node=None): if not node: raise SaltInvocationError('Required argument "node" is missing.') - function = "agent/force-leave/{}".format(node) + function = f"agent/force-leave/{node}" res = _query( consul_url=consul_url, function=function, @@ -690,10 +688,10 @@ def agent_leave(consul_url=None, token=None, node=None): ) if res["res"]: ret["res"] = True - ret["message"] = "Node {} put in leave state.".format(node) + ret["message"] = f"Node {node} put in leave state." else: ret["res"] = False - ret["message"] = "Unable to change state for {}.".format(node) + ret["message"] = f"Unable to change state for {node}." return ret @@ -810,11 +808,11 @@ def agent_check_deregister(consul_url=None, token=None, checkid=None): if not checkid: raise SaltInvocationError('Required argument "checkid" is missing.') - function = "agent/check/deregister/{}".format(checkid) + function = f"agent/check/deregister/{checkid}" res = _query(consul_url=consul_url, function=function, token=token, method="GET") if res["res"]: ret["res"] = True - ret["message"] = "Check {} removed from agent.".format(checkid) + ret["message"] = f"Check {checkid} removed from agent." else: ret["res"] = False ret["message"] = "Unable to remove check from agent." @@ -855,7 +853,7 @@ def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): if "note" in kwargs: query_params["note"] = kwargs["note"] - function = "agent/check/pass/{}".format(checkid) + function = f"agent/check/pass/{checkid}" res = _query( consul_url=consul_url, function=function, @@ -865,10 +863,10 @@ def agent_check_pass(consul_url=None, token=None, checkid=None, **kwargs): ) if res["res"]: ret["res"] = True - ret["message"] = "Check {} marked as passing.".format(checkid) + ret["message"] = f"Check {checkid} marked as passing." else: ret["res"] = False - ret["message"] = "Unable to update check {}.".format(checkid) + ret["message"] = f"Unable to update check {checkid}." return ret @@ -906,7 +904,7 @@ def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): if "note" in kwargs: query_params["note"] = kwargs["note"] - function = "agent/check/warn/{}".format(checkid) + function = f"agent/check/warn/{checkid}" res = _query( consul_url=consul_url, function=function, @@ -916,10 +914,10 @@ def agent_check_warn(consul_url=None, token=None, checkid=None, **kwargs): ) if res["res"]: ret["res"] = True - ret["message"] = "Check {} marked as warning.".format(checkid) + ret["message"] = f"Check {checkid} marked as warning." else: ret["res"] = False - ret["message"] = "Unable to update check {}.".format(checkid) + ret["message"] = f"Unable to update check {checkid}." return ret @@ -957,7 +955,7 @@ def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): if "note" in kwargs: query_params["note"] = kwargs["note"] - function = "agent/check/fail/{}".format(checkid) + function = f"agent/check/fail/{checkid}" res = _query( consul_url=consul_url, function=function, @@ -967,10 +965,10 @@ def agent_check_fail(consul_url=None, token=None, checkid=None, **kwargs): ) if res["res"]: ret["res"] = True - ret["message"] = "Check {} marked as critical.".format(checkid) + ret["message"] = f"Check {checkid} marked as critical." else: ret["res"] = False - ret["message"] = "Unable to update check {}.".format(checkid) + ret["message"] = f"Unable to update check {checkid}." return ret @@ -1114,16 +1112,16 @@ def agent_service_deregister(consul_url=None, token=None, serviceid=None): if not serviceid: raise SaltInvocationError('Required argument "serviceid" is missing.') - function = "agent/service/deregister/{}".format(serviceid) + function = f"agent/service/deregister/{serviceid}" res = _query( consul_url=consul_url, function=function, token=token, method="PUT", data=data ) if res["res"]: ret["res"] = True - ret["message"] = "Service {} removed from agent.".format(serviceid) + ret["message"] = f"Service {serviceid} removed from agent." else: ret["res"] = False - ret["message"] = "Unable to remove service {}.".format(serviceid) + ret["message"] = f"Unable to remove service {serviceid}." return ret @@ -1168,14 +1166,14 @@ def agent_service_maintenance(consul_url=None, token=None, serviceid=None, **kwa if "reason" in kwargs: query_params["reason"] = kwargs["reason"] - function = "agent/service/maintenance/{}".format(serviceid) + function = f"agent/service/maintenance/{serviceid}" res = _query( consul_url=consul_url, token=token, function=function, query_params=query_params ) if res["res"]: ret["res"] = True - ret["message"] = "Service {} set in maintenance mode.".format(serviceid) + ret["message"] = f"Service {serviceid} set in maintenance mode." else: ret["res"] = False ret["message"] = "Unable to set service {} to maintenance mode.".format( @@ -1255,7 +1253,7 @@ def session_create(consul_url=None, token=None, **kwargs): ret["message"] = ("TTL must be ", "between 0 and 3600.") ret["res"] = False return ret - data["TTL"] = "{}s".format(_ttl) + data["TTL"] = f"{_ttl}s" function = "session/create" res = _query( @@ -1351,7 +1349,7 @@ def session_destroy(consul_url=None, token=None, session=None, **kwargs): if "dc" in kwargs: query_params["dc"] = kwargs["dc"] - function = "session/destroy/{}".format(session) + function = f"session/destroy/{session}" res = _query( consul_url=consul_url, function=function, @@ -1361,10 +1359,10 @@ def session_destroy(consul_url=None, token=None, session=None, **kwargs): ) if res["res"]: ret["res"] = True - ret["message"] = "Destroyed Session {}.".format(session) + ret["message"] = f"Destroyed Session {session}." else: ret["res"] = False - ret["message"] = "Unable to destroy session {}.".format(session) + ret["message"] = f"Unable to destroy session {session}." return ret @@ -1402,7 +1400,7 @@ def session_info(consul_url=None, token=None, session=None, **kwargs): if "dc" in kwargs: query_params["dc"] = kwargs["dc"] - function = "session/info/{}".format(session) + function = f"session/info/{session}" ret = _query( consul_url=consul_url, function=function, token=token, query_params=query_params ) @@ -1543,9 +1541,9 @@ def catalog_register(consul_url=None, token=None, **kwargs): "warning", "critical", ): - ret[ - "message" - ] = "Check status must be unknown, passing, warning, or critical." + ret["message"] = ( + "Check status must be unknown, passing, warning, or critical." + ) ret["res"] = False return ret data["Check"]["Status"] = kwargs["check_status"] @@ -1770,7 +1768,7 @@ def catalog_service(consul_url=None, token=None, service=None, **kwargs): if "tag" in kwargs: query_params["tag"] = kwargs["tag"] - function = "catalog/service/{}".format(service) + function = f"catalog/service/{service}" ret = _query( consul_url=consul_url, function=function, token=token, query_params=query_params ) @@ -1810,7 +1808,7 @@ def catalog_node(consul_url=None, token=None, node=None, **kwargs): if "dc" in kwargs: query_params["dc"] = kwargs["dc"] - function = "catalog/node/{}".format(node) + function = f"catalog/node/{node}" ret = _query( consul_url=consul_url, function=function, token=token, query_params=query_params ) @@ -1850,7 +1848,7 @@ def health_node(consul_url=None, token=None, node=None, **kwargs): if "dc" in kwargs: query_params["dc"] = kwargs["dc"] - function = "health/node/{}".format(node) + function = f"health/node/{node}" ret = _query( consul_url=consul_url, function=function, token=token, query_params=query_params ) @@ -1890,7 +1888,7 @@ def health_checks(consul_url=None, token=None, service=None, **kwargs): if "dc" in kwargs: query_params["dc"] = kwargs["dc"] - function = "health/checks/{}".format(service) + function = f"health/checks/{service}" ret = _query( consul_url=consul_url, function=function, token=token, query_params=query_params ) @@ -1941,7 +1939,7 @@ def health_service(consul_url=None, token=None, service=None, **kwargs): if "passing" in kwargs: query_params["passing"] = kwargs["passing"] - function = "health/service/{}".format(service) + function = f"health/service/{service}" ret = _query( consul_url=consul_url, function=function, token=token, query_params=query_params ) @@ -1991,7 +1989,7 @@ def health_state(consul_url=None, token=None, state=None, **kwargs): ret["res"] = False return ret - function = "health/state/{}".format(state) + function = f"health/state/{state}" ret = _query( consul_url=consul_url, function=function, token=token, query_params=query_params ) @@ -2378,7 +2376,7 @@ def event_fire(consul_url=None, token=None, name=None, **kwargs): if "tag" in kwargs: query_params = kwargs["tag"] - function = "event/fire/{}".format(name) + function = f"event/fire/{name}" res = _query( consul_url=consul_url, token=token, @@ -2389,7 +2387,7 @@ def event_fire(consul_url=None, token=None, name=None, **kwargs): if res["res"]: ret["res"] = True - ret["message"] = "Event {} fired.".format(name) + ret["message"] = f"Event {name} fired." ret["data"] = res["data"] else: ret["res"] = False diff --git a/salt/modules/container_resource.py b/salt/modules/container_resource.py index 0a44ce3e518..5474d43a54c 100644 --- a/salt/modules/container_resource.py +++ b/salt/modules/container_resource.py @@ -8,6 +8,7 @@ These functions are not designed to be called directly, but instead from the :mod:`docker ` execution modules. They provide for common logic to be re-used for common actions. """ + import copy import functools import logging diff --git a/salt/modules/cpan.py b/salt/modules/cpan.py index b92f081d308..27b96d416eb 100644 --- a/salt/modules/cpan.py +++ b/salt/modules/cpan.py @@ -43,7 +43,7 @@ def install(module): old_info = show(module) - cmd = "cpan -i {}".format(module) + cmd = f"cpan -i {module}" out = __salt__["cmd.run"](cmd) if "don't know what it is" in out: @@ -153,7 +153,7 @@ def show(module): ret["name"] = module # This section parses out details from CPAN, if possible - cmd = "cpan -D {}".format(module) + cmd = f"cpan -D {module}" out = __salt__["cmd.run"](cmd).splitlines() mode = "skip" info = [] diff --git a/salt/modules/cron.py b/salt/modules/cron.py index dc0a229062c..660ca9c768d 100644 --- a/salt/modules/cron.py +++ b/salt/modules/cron.py @@ -113,7 +113,7 @@ def _render_tab(lst): """ ret = [] for pre in lst["pre"]: - ret.append("{}\n".format(pre)) + ret.append(f"{pre}\n") if ret: if ret[-1] != TAG: ret.append(TAG) @@ -170,10 +170,10 @@ def _get_cron_cmdstr(path, user=None): Returns a format string, to be used to build a crontab command. """ if user: - cmd = "crontab -u {}".format(user) + cmd = f"crontab -u {user}" else: cmd = "crontab" - return "{} {}".format(cmd, path) + return f"{cmd} {path}" def _check_instance_uid_match(user): @@ -343,7 +343,7 @@ def raw_cron(user): ).splitlines(True) # If Salt is running from root user it could modify any user's crontab elif _check_instance_uid_match("root"): - cmd = "crontab -u {} -l".format(user) + cmd = f"crontab -u {user} -l" # Preserve line endings lines = salt.utils.data.decode( __salt__["cmd.run_stdout"]( diff --git a/salt/modules/cryptdev.py b/salt/modules/cryptdev.py index 40c28d17f10..015272135a5 100644 --- a/salt/modules/cryptdev.py +++ b/salt/modules/cryptdev.py @@ -49,7 +49,7 @@ class _crypttab_entry: @classmethod def dict_from_line(cls, line, keys=crypttab_keys): if len(keys) != 4: - raise ValueError("Invalid key array: {}".format(keys)) + raise ValueError(f"Invalid key array: {keys}") if line.startswith("#"): raise cls.ParseError("Comment!") @@ -266,12 +266,12 @@ def set_crypttab( filterFn = lambda key: key not in _crypttab_entry.crypttab_keys invalid_keys = filter(filterFn, match_on) - msg = 'Unrecognized keys in match_on: "{}"'.format(invalid_keys) + msg = f'Unrecognized keys in match_on: "{invalid_keys}"' raise CommandExecutionError(msg) # parse file, use ret to cache status if not os.path.isfile(config): - raise CommandExecutionError('Bad config file "{}"'.format(config)) + raise CommandExecutionError(f'Bad config file "{config}"') try: with salt.utils.files.fopen(config, "r") as ifile: @@ -335,7 +335,7 @@ def open(name, device, keyfile): ) code = __salt__["cmd.retcode"]( - "cryptsetup open --key-file {} {} {}".format(keyfile, device, name) + f"cryptsetup open --key-file {keyfile} {device} {name}" ) return code == 0 @@ -350,5 +350,5 @@ def close(name): salt '*' cryptdev.close foo """ - code = __salt__["cmd.retcode"]("cryptsetup close {}".format(name)) + code = __salt__["cmd.retcode"](f"cryptsetup close {name}") return code == 0 diff --git a/salt/modules/csf.py b/salt/modules/csf.py index 1ab12cab941..b3d669547ce 100644 --- a/salt/modules/csf.py +++ b/salt/modules/csf.py @@ -37,7 +37,7 @@ def _temp_exists(method, ip): def _exists_with_port(method, rule): - path = "/etc/csf/csf.{}".format(method) + path = f"/etc/csf/csf.{method}" return __salt__["file.contains"](path, rule) @@ -71,7 +71,7 @@ def exists( ip, port, proto, direction, port_origin, ip_origin, comment ) return _exists_with_port(method, rule) - exists = __salt__["cmd.run_all"]("egrep ^'{} +' /etc/csf/csf.{}".format(ip, method)) + exists = __salt__["cmd.run_all"](f"egrep ^'{ip} +' /etc/csf/csf.{method}") return not bool(exists["retcode"]) @@ -87,7 +87,7 @@ def __csf_cmd(cmd): ret = out["stdout"] else: ret = out["stderr"] - raise CommandExecutionError("csf failed: {}".format(ret)) + raise CommandExecutionError(f"csf failed: {ret}") else: ret = out["stdout"] return ret @@ -123,9 +123,9 @@ def _build_args(method, ip, comment): Returns the cmd args for csf basic allow/deny commands. """ opt = _get_opt(method) - args = "{} {}".format(opt, ip) + args = f"{opt} {ip}" if comment: - args += " {}".format(comment) + args += f" {comment}" return args @@ -178,7 +178,7 @@ def _build_port_rule(ip, port, proto, direction, port_origin, ip_origin, comment } rule = "{proto}|{direction}|{port_origin}={port}|{ip_origin}={ip}".format(**kwargs) if comment: - rule += " #{}".format(comment) + rule += f" #{comment}" return rule @@ -207,8 +207,8 @@ def _remove_access_rule_with_port( rule = rule.replace("|", "[|]") rule = rule.replace(".", "[.]") result = __salt__["file.replace"]( - "/etc/csf/csf.{}".format(method), - pattern="^{}(( +)?\\#.*)?$\n".format(rule), # pylint: disable=W1401 + f"/etc/csf/csf.{method}", + pattern=f"^{rule}(( +)?\\#.*)?$\n", # pylint: disable=W1401 repl="", ) @@ -233,7 +233,7 @@ def split_option(option): def get_option(option): - pattern = r'^{}(\ +)?\=(\ +)?".*"$'.format(option) # pylint: disable=W1401 + pattern = rf'^{option}(\ +)?\=(\ +)?".*"$' # pylint: disable=W1401 grep = __salt__["file.grep"]("/etc/csf/csf.conf", pattern, "-E") if "stdout" in grep and grep["stdout"]: line = grep["stdout"] @@ -247,8 +247,8 @@ def set_option(option, value): return {"error": "No such option exists in csf.conf"} result = __salt__["file.replace"]( "/etc/csf/csf.conf", - pattern=r'^{}(\ +)?\=(\ +)?".*"'.format(option), # pylint: disable=W1401 - repl='{} = "{}"'.format(option, value), + pattern=rf'^{option}(\ +)?\=(\ +)?".*"', # pylint: disable=W1401 + repl=f'{option} = "{value}"', ) return result @@ -279,9 +279,9 @@ def skip_nics(nics, ipv6=False): result = __salt__["file.replace"]( "/etc/csf/csf.conf", # pylint: disable=anomalous-backslash-in-string - pattern=r'^ETH{}_DEVICE_SKIP(\ +)?\=(\ +)?".*"'.format(ipv6), + pattern=rf'^ETH{ipv6}_DEVICE_SKIP(\ +)?\=(\ +)?".*"', # pylint: enable=anomalous-backslash-in-string - repl='ETH{}_DEVICE_SKIP = "{}"'.format(ipv6, nics_csv), + repl=f'ETH{ipv6}_DEVICE_SKIP = "{nics_csv}"', ) return result @@ -326,7 +326,7 @@ def _access_rule_with_port( ip_origin=ip_origin, comment=comment, ) - path = "/etc/csf/csf.{}".format(method) + path = f"/etc/csf/csf.{method}" results[direction] = __salt__["file.append"](path, rule) return results @@ -358,13 +358,13 @@ def _build_tmp_access_args(method, ip, ttl, port, direction, comment): Builds the cmd args for temporary access/deny opts. """ opt = _get_opt(method) - args = "{} {} {}".format(opt, ip, ttl) + args = f"{opt} {ip} {ttl}" if port: - args += " -p {}".format(port) + args += f" -p {port}" if direction: - args += " -d {}".format(direction) + args += f" -d {direction}" if comment: - args += " #{}".format(comment) + args += f" #{comment}" return args @@ -515,7 +515,7 @@ def deny( def remove_temp_rule(ip): opt = _get_opt("temprm") - args = "{} {}".format(opt, ip) + args = f"{opt} {ip}" return __csf_cmd(args) @@ -608,9 +608,9 @@ def allow_ports(ports, proto="tcp", direction="in"): result = __salt__["file.replace"]( "/etc/csf/csf.conf", # pylint: disable=anomalous-backslash-in-string - pattern=r'^{}_{}(\ +)?\=(\ +)?".*"$'.format(proto, direction), + pattern=rf'^{proto}_{direction}(\ +)?\=(\ +)?".*"$', # pylint: enable=anomalous-backslash-in-string - repl='{}_{} = "{}"'.format(proto, direction, ports_csv), + repl=f'{proto}_{direction} = "{ports_csv}"', ) results.append(result) @@ -635,7 +635,7 @@ def get_ports(proto="tcp", direction="in"): _validate_direction_and_proto(direction, proto) directions = build_directions(direction) for direction in directions: - option = "{}_{}".format(proto, direction) + option = f"{proto}_{direction}" results[direction] = _csf_to_list(option) return results @@ -701,7 +701,7 @@ def _toggle_testing(val): result = __salt__["file.replace"]( "/etc/csf/csf.conf", pattern=r'^TESTING(\ +)?\=(\ +)?".*"', # pylint: disable=W1401 - repl='TESTING = "{}"'.format(val), + repl=f'TESTING = "{val}"', ) return result diff --git a/salt/modules/cyg.py b/salt/modules/cyg.py index 9f7a61af59a..b76cbeb8010 100644 --- a/salt/modules/cyg.py +++ b/salt/modules/cyg.py @@ -45,7 +45,7 @@ def _get_cyg_dir(cyg_arch="x86_64"): elif cyg_arch == "x86": return "cygwin" - raise SaltInvocationError("Invalid architecture {arch}".format(arch=cyg_arch)) + raise SaltInvocationError(f"Invalid architecture {cyg_arch}") def _check_cygwin_installed(cyg_arch="x86_64"): @@ -129,9 +129,9 @@ def _run_silent_cygwin(cyg_arch="x86_64", args=None, mirrors=None): installation up and running. """ cyg_cache_dir = os.sep.join(["c:", "cygcache"]) - cyg_setup = "setup-{}.exe".format(cyg_arch) + cyg_setup = f"setup-{cyg_arch}.exe" cyg_setup_path = os.sep.join([cyg_cache_dir, cyg_setup]) - cyg_setup_source = "http://cygwin.com/{}".format(cyg_setup) + cyg_setup_source = f"http://cygwin.com/{cyg_setup}" # cyg_setup_source_hash = 'http://cygwin.com/{0}.sig'.format(cyg_setup) # until a hash gets published that we can verify the newest setup against @@ -147,15 +147,15 @@ def _run_silent_cygwin(cyg_arch="x86_64", args=None, mirrors=None): setup_command = cyg_setup_path options = [] - options.append("--local-package-dir {}".format(cyg_cache_dir)) + options.append(f"--local-package-dir {cyg_cache_dir}") if mirrors is None: mirrors = [{DEFAULT_MIRROR: DEFAULT_MIRROR_KEY}] for mirror in mirrors: for mirror_url, key in mirror.items(): - options.append("--site {}".format(mirror_url)) + options.append(f"--site {mirror_url}") if key: - options.append("--pubkey {}".format(key)) + options.append(f"--pubkey {key}") options.append("--no-desktop") options.append("--quiet-mode") options.append("--disable-buggy-antivirus") @@ -211,7 +211,7 @@ def install(packages=None, cyg_arch="x86_64", mirrors=None): args = [] # If we want to install packages if packages is not None: - args.append("--packages {pkgs}".format(pkgs=packages)) + args.append(f"--packages {packages}") # but we don't have cygwin installed yet if not _check_cygwin_installed(cyg_arch): # install just the base system @@ -240,7 +240,7 @@ def uninstall(packages, cyg_arch="x86_64", mirrors=None): """ args = [] if packages is not None: - args.append("--remove-packages {pkgs}".format(pkgs=packages)) + args.append(f"--remove-packages {packages}") LOG.debug("args: %s", args) if not _check_cygwin_installed(cyg_arch): LOG.debug("We're convinced cygwin isn't installed") diff --git a/salt/modules/daemontools.py b/salt/modules/daemontools.py index 84a9dc2eabf..7892cb561b8 100644 --- a/salt/modules/daemontools.py +++ b/salt/modules/daemontools.py @@ -44,7 +44,7 @@ def __virtual__(): BINS = frozenset(("svc", "supervise", "svok")) if all(salt.utils.path.which(b) for b in BINS) and SERVICE_DIR: return __virtualname__ - return (False, "Missing dependency: {}".format(BINS)) + return (False, f"Missing dependency: {BINS}") def _service_path(name): @@ -53,7 +53,7 @@ def _service_path(name): """ if not SERVICE_DIR: raise CommandExecutionError("Could not find service directory.") - return "{}/{}".format(SERVICE_DIR, name) + return f"{SERVICE_DIR}/{name}" # -- states.service compatible args @@ -67,8 +67,8 @@ def start(name): salt '*' daemontools.start """ - __salt__["file.remove"]("{}/down".format(_service_path(name))) - cmd = "svc -u {}".format(_service_path(name)) + __salt__["file.remove"](f"{_service_path(name)}/down") + cmd = f"svc -u {_service_path(name)}" return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -83,8 +83,8 @@ def stop(name): salt '*' daemontools.stop """ - __salt__["file.touch"]("{}/down".format(_service_path(name))) - cmd = "svc -d {}".format(_service_path(name)) + __salt__["file.touch"](f"{_service_path(name)}/down") + cmd = f"svc -d {_service_path(name)}" return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -98,7 +98,7 @@ def term(name): salt '*' daemontools.term """ - cmd = "svc -t {}".format(_service_path(name)) + cmd = f"svc -t {_service_path(name)}" return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -158,7 +158,7 @@ def status(name, sig=None): salt '*' daemontools.status """ - cmd = "svstat {}".format(_service_path(name)) + cmd = f"svstat {_service_path(name)}" out = __salt__["cmd.run_stdout"](cmd, python_shell=False) try: pid = re.search(r"\(pid (\d+)\)", out).group(1) diff --git a/salt/modules/datadog_api.py b/salt/modules/datadog_api.py index 57ce01953f6..74ba7de0e29 100644 --- a/salt/modules/datadog_api.py +++ b/salt/modules/datadog_api.py @@ -165,7 +165,7 @@ def cancel_downtime(api_key=None, app_key=None, scope=None, id=None): ret["comment"] = "Successfully cancelled downtime" else: ret["response"] = response.text - ret["comment"] = "Status Code: {}".format(response.status_code) + ret["comment"] = f"Status Code: {response.status_code}" return ret else: raise SaltInvocationError("One of id or scope must be specified") diff --git a/salt/modules/ddns.py b/salt/modules/ddns.py index 60bccff0719..54132ae21e0 100644 --- a/salt/modules/ddns.py +++ b/salt/modules/ddns.py @@ -62,7 +62,7 @@ def _config(name, key=None, **kwargs): if name in kwargs: value = kwargs[name] else: - value = __salt__["config.option"]("ddns.{}".format(key)) + value = __salt__["config.option"](f"ddns.{key}") if not value: value = None return value @@ -85,7 +85,7 @@ def add_host( replace=True, timeout=5, port=53, - **kwargs + **kwargs, ): """ Add, replace, or update the A and PTR (reverse) records for a host. @@ -100,7 +100,7 @@ def add_host( if res is False: return False - fqdn = "{}.{}.".format(name, zone) + fqdn = f"{name}.{zone}." parts = ip.split(".")[::-1] popped = [] @@ -130,7 +130,7 @@ def delete_host(zone, name, nameserver="127.0.0.1", timeout=5, port=53, **kwargs salt ns1 ddns.delete_host example.com host1 """ - fqdn = "{}.{}".format(name, zone) + fqdn = f"{name}.{zone}" request = dns.message.make_query(fqdn, "A") answer = dns.query.udp(request, nameserver, timeout, port) try: @@ -161,7 +161,7 @@ def delete_host(zone, name, nameserver="127.0.0.1", timeout=5, port=53, **kwargs nameserver=nameserver, timeout=timeout, port=port, - **kwargs + **kwargs, ) if ptr: res = True @@ -178,7 +178,7 @@ def update( timeout=5, replace=False, port=53, - **kwargs + **kwargs, ): """ Add, replace, or update a DNS record. @@ -197,7 +197,7 @@ def update( if name[-1:] == ".": fqdn = name else: - fqdn = "{}.{}".format(name, zone) + fqdn = f"{name}.{zone}" request = dns.message.make_query(fqdn, rdtype) answer = dns.query.udp(request, nameserver, timeout, port) @@ -240,7 +240,7 @@ def delete( nameserver="127.0.0.1", timeout=5, port=53, - **kwargs + **kwargs, ): """ Delete a DNS record. @@ -256,7 +256,7 @@ def delete( if name[-1:] == ".": fqdn = name else: - fqdn = "{}.{}".format(name, zone) + fqdn = f"{name}.{zone}" request = dns.message.make_query(fqdn, (rdtype or "ANY")) answer = dns.query.udp(request, nameserver, timeout, port) diff --git a/salt/modules/deb_postgres.py b/salt/modules/deb_postgres.py index d92859562d4..ecd339e08f2 100644 --- a/salt/modules/deb_postgres.py +++ b/salt/modules/deb_postgres.py @@ -2,6 +2,7 @@ Module to provide Postgres compatibility to salt for debian family specific tools. """ + import logging import shlex @@ -74,7 +75,7 @@ def cluster_create( cmd += ["--data-checksums"] if wal_segsize: cmd += ["--wal-segsize", wal_segsize] - cmdstr = " ".join([shlex.quote(c) for c in cmd]) + cmdstr = shlex.join(cmd) ret = __salt__["cmd.run_all"](cmdstr, python_shell=False) if ret.get("retcode", 0) != 0: log.error("Error creating a Postgresql cluster %s/%s", version, name) @@ -95,7 +96,7 @@ def cluster_list(verbose=False): salt '*' postgres.cluster_list verbose=True """ cmd = [salt.utils.path.which("pg_lsclusters"), "--no-header"] - ret = __salt__["cmd.run_all"](" ".join([shlex.quote(c) for c in cmd])) + ret = __salt__["cmd.run_all"](shlex.join(cmd)) if ret.get("retcode", 0) != 0: log.error("Error listing clusters") cluster_dict = _parse_pg_lscluster(ret["stdout"]) @@ -139,7 +140,7 @@ def cluster_remove(version, name="main", stop=False): if stop: cmd += ["--stop"] cmd += [str(version), name] - cmdstr = " ".join([shlex.quote(c) for c in cmd]) + cmdstr = shlex.join(cmd) ret = __salt__["cmd.run_all"](cmdstr, python_shell=False) # FIXME - return Boolean ? if ret.get("retcode", 0) != 0: diff --git a/salt/modules/debconfmod.py b/salt/modules/debconfmod.py index b4cd3a1934b..7f7644fb84b 100644 --- a/salt/modules/debconfmod.py +++ b/salt/modules/debconfmod.py @@ -106,7 +106,7 @@ def _set_file(path): """ Execute the set selections command for debconf """ - cmd = "debconf-set-selections {}".format(path) + cmd = f"debconf-set-selections {path}" __salt__["cmd.run_stdout"](cmd, python_shell=False) @@ -127,7 +127,7 @@ def set_(package, question, type, value, *extra): fd_, fname = salt.utils.files.mkstemp(prefix="salt-", close_fd=False) - line = "{} {} {} {}".format(package, question, type, value) + line = f"{package} {question} {type} {value}" os.write(fd_, salt.utils.stringutils.to_bytes(line)) os.close(fd_) @@ -169,7 +169,7 @@ def set_template(path, template, context, defaults, saltenv="base", **kwargs): saltenv=saltenv, context=context, defaults=defaults, - **kwargs + **kwargs, ) return set_file(path, saltenv, **kwargs) diff --git a/salt/modules/debian_ip.py b/salt/modules/debian_ip.py index 4a7062c48fc..9953b5c51ef 100644 --- a/salt/modules/debian_ip.py +++ b/salt/modules/debian_ip.py @@ -5,6 +5,7 @@ References: * http://www.debian.org/doc/manuals/debian-reference/ch05.en.html """ + import functools import io import logging @@ -365,9 +366,9 @@ def __within2(value, within=None, errmsg=None, dtype=None): "__name__", hasattr(dtype, "__class__") and getattr(dtype.__class__, "name", dtype), ) - errmsg = "{} within '{}'".format(typename, within) + errmsg = f"{typename} within '{within}'" else: - errmsg = "within '{}'".format(within) + errmsg = f"within '{within}'" return (valid, _value, errmsg) @@ -386,7 +387,7 @@ def __space_delimited_list(value): return ( False, value, - "{} is not a valid space-delimited value.\n".format(value), + f"{value} is not a valid space-delimited value.\n", ) @@ -548,8 +549,7 @@ def _parse_interfaces(interface_files=None): # Add this later. if os.path.exists(_DEB_NETWORK_DIR): interface_files += [ - "{}/{}".format(_DEB_NETWORK_DIR, dir) - for dir in os.listdir(_DEB_NETWORK_DIR) + f"{_DEB_NETWORK_DIR}/{dir}" for dir in os.listdir(_DEB_NETWORK_DIR) ] if os.path.isfile(_DEB_NETWORK_FILE): @@ -689,7 +689,7 @@ def _filter_malformed_interfaces(*, adapters): if iface_name == "source": continue if "data" not in adapters[iface_name]: - msg = "Interface file malformed for interface: {}.".format(iface_name) + msg = f"Interface file malformed for interface: {iface_name}." log.error(msg) adapters.pop(iface_name) continue @@ -908,7 +908,6 @@ def _parse_settings_bond_0(opts, iface, bond_def): def _parse_settings_bond_1(opts, iface, bond_def): - """ Filters given options and outputs valid settings for bond1. If an option has a value that is not expected, this @@ -995,7 +994,6 @@ def _parse_settings_bond_2(opts, iface, bond_def): def _parse_settings_bond_3(opts, iface, bond_def): - """ Filters given options and outputs valid settings for bond3. If an option has a value that is not expected, this @@ -1082,7 +1080,6 @@ def _parse_settings_bond_4(opts, iface, bond_def): def _parse_settings_bond_5(opts, iface, bond_def): - """ Filters given options and outputs valid settings for bond5. If an option has a value that is not expected, this @@ -1121,7 +1118,6 @@ def _parse_settings_bond_5(opts, iface, bond_def): def _parse_settings_bond_6(opts, iface, bond_def): - """ Filters given options and outputs valid settings for bond6. If an option has a value that is not expected, this @@ -1201,7 +1197,7 @@ def _parse_bridge_opts(opts, iface): try: port, cost_or_prio = opts[opt].split() int(cost_or_prio) - config.update({opt: "{} {}".format(port, cost_or_prio)}) + config.update({opt: f"{port} {cost_or_prio}"}) except ValueError: _raise_error_iface(iface, opt, ["interface integer"]) @@ -1295,9 +1291,9 @@ def _parse_settings_eth(opts, iface_type, enabled, iface): tmp_ethtool = _parse_ethtool_pppoe_opts(opts, iface) if tmp_ethtool: for item in tmp_ethtool: - adapters[iface]["data"][addrfam][ - _DEB_CONFIG_PPPOE_OPTS[item] - ] = tmp_ethtool[item] + adapters[iface]["data"][addrfam][_DEB_CONFIG_PPPOE_OPTS[item]] = ( + tmp_ethtool[item] + ) iface_data[addrfam]["addrfam"] = addrfam opts.pop("mode", None) @@ -1350,7 +1346,7 @@ def _parse_settings_eth(opts, iface_type, enabled, iface): iface_data["inet6"][opt] = opts[opt] # Remove incomplete/disabled inet blocks - for (addrfam, opt) in [("inet", "enable_ipv4"), ("inet6", "enable_ipv6")]: + for addrfam, opt in [("inet", "enable_ipv4"), ("inet6", "enable_ipv6")]: if opts.get(opt, None) is False: iface_data.pop(addrfam) elif iface_data[addrfam].get("addrfam", "") != addrfam: @@ -1633,15 +1629,15 @@ def build_bond(iface, **settings): if "test" in settings and settings["test"]: return _read_temp(data) - _write_file(iface, data, _DEB_NETWORK_CONF_FILES, "{}.conf".format(iface)) - path = os.path.join(_DEB_NETWORK_CONF_FILES, "{}.conf".format(iface)) + _write_file(iface, data, _DEB_NETWORK_CONF_FILES, f"{iface}.conf") + path = os.path.join(_DEB_NETWORK_CONF_FILES, f"{iface}.conf") if deb_major == "5": for line_type in ("alias", "options"): cmd = [ "sed", "-i", "-e", - r"/^{}\s{}.*/d".format(line_type, iface), + rf"/^{line_type}\s{iface}.*/d", "/etc/modprobe.conf", ] __salt__["cmd.run"](cmd, python_shell=False) @@ -1785,7 +1781,7 @@ def get_bond(iface): salt '*' ip.get_bond bond0 """ - path = os.path.join(_DEB_NETWORK_CONF_FILES, "{}.conf".format(iface)) + path = os.path.join(_DEB_NETWORK_CONF_FILES, f"{iface}.conf") return _read_file(path) @@ -1891,10 +1887,10 @@ def get_routes(iface): salt '*' ip.get_routes eth0 """ - filename = os.path.join(_DEB_NETWORK_UP_DIR, "route-{}".format(iface)) + filename = os.path.join(_DEB_NETWORK_UP_DIR, f"route-{iface}") results = _read_file(filename) - filename = os.path.join(_DEB_NETWORK_DOWN_DIR, "route-{}".format(iface)) + filename = os.path.join(_DEB_NETWORK_DOWN_DIR, f"route-{iface}") results += _read_file(filename) return results @@ -2035,20 +2031,20 @@ def build_network_settings(**settings): for item in _read_file(_DEB_RESOLV_FILE): if domain_prog.match(item): - item = "domain {}".format(domainname) + item = f"domain {domainname}" elif search_prog.match(item): - item = "search {}".format(searchdomain) + item = f"search {searchdomain}" new_contents.append(item) # A domain line didn't exist so we'll add one in # with the new domainname if "domain" not in resolve: - new_contents.insert(0, "domain {}".format(domainname)) + new_contents.insert(0, f"domain {domainname}") # A search line didn't exist so we'll add one in # with the new search domain if "search" not in resolve: - new_contents.insert("domain" in resolve, "search {}".format(searchdomain)) + new_contents.insert("domain" in resolve, f"search {searchdomain}") new_resolv = "\n".join(new_contents) diff --git a/salt/modules/debian_service.py b/salt/modules/debian_service.py index 04c6cd5d37b..e11d9d18e7e 100644 --- a/salt/modules/debian_service.py +++ b/salt/modules/debian_service.py @@ -74,9 +74,9 @@ def get_enabled(): salt '*' service.get_enabled """ - prefix = "/etc/rc[S{}].d/S".format(_get_runlevel()) + prefix = f"/etc/rc[S{_get_runlevel()}].d/S" ret = set() - for line in [x.rsplit(os.sep, 1)[-1] for x in glob.glob("{}*".format(prefix))]: + for line in [x.rsplit(os.sep, 1)[-1] for x in glob.glob(f"{prefix}*")]: ret.add(re.split(r"\d+", line)[-1]) return sorted(ret) @@ -277,7 +277,7 @@ def disable(name, **kwargs): salt '*' service.disable """ - cmd = "update-rc.d {} disable".format(name) + cmd = f"update-rc.d {name} disable" return not __salt__["cmd.retcode"](cmd) diff --git a/salt/modules/debuild_pkgbuild.py b/salt/modules/debuild_pkgbuild.py index b63f0b3f183..cc5217b7b72 100644 --- a/salt/modules/debuild_pkgbuild.py +++ b/salt/modules/debuild_pkgbuild.py @@ -9,7 +9,6 @@ environments. This also provides a function to generate debian repositories This module implements the pkgbuild interface """ - import errno import logging import os @@ -91,9 +90,7 @@ def _check_repo_gpg_phrase_utils(): if __salt__["file.file_exists"](util_name): return True else: - raise CommandExecutionError( - "utility '{}' needs to be installed".format(util_name) - ) + raise CommandExecutionError(f"utility '{util_name}' needs to be installed") def _get_build_env(env): @@ -106,8 +103,8 @@ def _get_build_env(env): if not isinstance(env, dict): raise SaltInvocationError("'env' must be a Python dictionary") for key, value in env.items(): - env_override += "{}={}\n".format(key, value) - env_override += "export {}\n".format(key) + env_override += f"{key}={value}\n" + env_override += f"export {key}\n" return env_override @@ -140,7 +137,7 @@ def _get_repo_options_env(env): raise SaltInvocationError("'env' must be a Python dictionary") for key, value in env.items(): if key == "OPTIONS": - env_options += "{}\n".format(value) + env_options += f"{value}\n" return env_options @@ -195,7 +192,7 @@ def _get_repo_dists_env(env): if env is None: for key, value in dflts_dict.items(): if dflts_dict[key][0] == "M": - env_dists += "{}: {}\n".format(dflts_dict[key][1], dflts_dict[key][2]) + env_dists += f"{dflts_dict[key][1]}: {dflts_dict[key][2]}\n" if key == "CODENAME": codename = dflts_dict[key][2] return (codename, env_dists) @@ -211,15 +208,15 @@ def _get_repo_dists_env(env): if key == "CODENAME": codename = value if dflts_dict[key][0] != "I": - env_dists += "{}: {}\n".format(dflts_dict[key][1], value) + env_dists += f"{dflts_dict[key][1]}: {value}\n" else: - env_dists += "{}: {}\n".format(key, value) + env_dists += f"{key}: {value}\n" # ensure mandatories are included env_keys = list(env.keys()) for key in env_keys: if key in dflts_keys and dflts_dict[key][0] == "M" and key not in env_man_seen: - env_dists += "{}: {}\n".format(dflts_dict[key][1], dflts_dict[key][2]) + env_dists += f"{dflts_dict[key][1]}: {dflts_dict[key][2]}\n" if key == "CODENAME": codename = value @@ -257,7 +254,7 @@ def _create_pbuilders(env, runas="root"): Ensure the user has correct permissions to any files and directories which are to be utilized. """ - home = os.path.expanduser("~{}".format(runas)) + home = os.path.expanduser(f"~{runas}") pbuilderrc = os.path.join(home, ".pbuilderrc") if not os.path.isfile(pbuilderrc): raise SaltInvocationError("pbuilderrc environment is incorrectly setup") @@ -426,25 +423,25 @@ def make_src_pkg(dest_dir, spec, sources, env=None, saltenv="base", runas="root" debname_orig = debname + ".orig.tar.gz" abspath_debname = os.path.join(tree_base, debname) - cmd = "tar -xvzf {}".format(salttarball) + cmd = f"tar -xvzf {salttarball}" retrc = __salt__["cmd.retcode"](cmd, cwd=tree_base, runas=root_user) - cmd = "mv {} {}".format(salttar_name, debname) + cmd = f"mv {salttar_name} {debname}" retrc |= __salt__["cmd.retcode"](cmd, cwd=tree_base, runas=root_user) - cmd = "tar -cvzf {} {}".format(os.path.join(tree_base, debname_orig), debname) + cmd = f"tar -cvzf {os.path.join(tree_base, debname_orig)} {debname}" retrc |= __salt__["cmd.retcode"](cmd, cwd=tree_base, runas=root_user) - cmd = "rm -f {}".format(salttarball) + cmd = f"rm -f {salttarball}" retrc |= __salt__["cmd.retcode"](cmd, cwd=tree_base, runas=root_user, env=env) - cmd = "cp {} {}".format(spec_pathfile, abspath_debname) + cmd = f"cp {spec_pathfile} {abspath_debname}" retrc |= __salt__["cmd.retcode"](cmd, cwd=abspath_debname, runas=root_user) - cmd = "tar -xvJf {}".format(spec_pathfile) + cmd = f"tar -xvJf {spec_pathfile}" retrc |= __salt__["cmd.retcode"](cmd, cwd=abspath_debname, runas=root_user, env=env) - cmd = "rm -f {}".format(os.path.basename(spec_pathfile)) + cmd = f"rm -f {os.path.basename(spec_pathfile)}" retrc |= __salt__["cmd.retcode"](cmd, cwd=abspath_debname, runas=root_user) cmd = "debuild -S -uc -us -sa" retrc |= __salt__["cmd.retcode"]( cmd, cwd=abspath_debname, runas=root_user, python_shell=True, env=env ) - cmd = "rm -fR {}".format(abspath_debname) + cmd = f"rm -fR {abspath_debname}" retrc |= __salt__["cmd.retcode"](cmd, runas=root_user) if retrc != 0: raise SaltInvocationError( @@ -512,13 +509,13 @@ def build( # ensure pbuilder setup from runas if other than root if runas != root_user: - user_home = os.path.expanduser("~{}".format(runas)) + user_home = os.path.expanduser(f"~{runas}") root_home = os.path.expanduser("~root") - cmd = "cp {}/.pbuilderrc {}/".format(user_home, root_home) + cmd = f"cp {user_home}/.pbuilderrc {root_home}/" retrc = __salt__["cmd.retcode"]( cmd, runas=root_user, python_shell=True, env=env ) - cmd = "cp -R {}/.pbuilder-hooks {}/".format(user_home, root_home) + cmd = f"cp -R {user_home}/.pbuilder-hooks {root_home}/" retrc = __salt__["cmd.retcode"]( cmd, runas=root_user, python_shell=True, env=env ) @@ -540,7 +537,7 @@ def build( results_dir = "/var/cache/pbuilder/result" # ensure clean - cmd = "rm -fR {}".format(results_dir) + cmd = f"rm -fR {results_dir}" retrc |= __salt__["cmd.retcode"](cmd, runas=root_user, python_shell=True, env=env) # dscs should only contain salt orig and debian tarballs and dsc file @@ -559,7 +556,7 @@ def build( retrc |= __salt__["cmd.retcode"]( cmd, runas=root_user, python_shell=True, env=env ) - cmd = '/usr/sbin/pbuilder build --debbuildopts "-sa" {}'.format(dsc) + cmd = f'/usr/sbin/pbuilder build --debbuildopts "-sa" {dsc}' retrc |= __salt__["cmd.retcode"]( cmd, runas=root_user, python_shell=True, env=env ) @@ -712,15 +709,15 @@ def make_repo( phrase = "" # preset passphase and interaction with gpg-agent - gpg_info_file = "{}/gpg-agent-info-salt".format(gnupghome) - gpg_tty_info_file = "{}/gpg-tty-info-salt".format(gnupghome) + gpg_info_file = f"{gnupghome}/gpg-agent-info-salt" + gpg_tty_info_file = f"{gnupghome}/gpg-tty-info-salt" # if using older than gnupg 2.1, then env file exists older_gnupg = __salt__["file.file_exists"](gpg_info_file) if keyid is not None: with salt.utils.files.fopen(repoconfdist, "a") as fow: - fow.write(salt.utils.stringutils.to_str("SignWith: {}\n".format(keyid))) + fow.write(salt.utils.stringutils.to_str(f"SignWith: {keyid}\n")) # import_keys pkg_pub_key_file = "{}/{}".format( @@ -828,7 +825,7 @@ def make_repo( # sign_it_here if older_gnupg: if local_keyid is not None: - cmd = "debsign --re-sign -k {} {}".format(keyid, abs_file) + cmd = f"debsign --re-sign -k {keyid} {abs_file}" retrc |= __salt__["cmd.retcode"]( cmd, runas=runas, cwd=repodir, use_vt=True, env=env ) @@ -846,7 +843,7 @@ def make_repo( if local_keyid is not None: number_retries = timeout / interval times_looped = 0 - error_msg = "Failed to debsign file {}".format(abs_file) + error_msg = f"Failed to debsign file {abs_file}" if ( __grains__["os"] in ["Ubuntu"] and __grains__["osmajorrelease"] < 18 @@ -854,7 +851,7 @@ def make_repo( __grains__["os"] in ["Debian"] and __grains__["osmajorrelease"] <= 8 ): - cmd = "debsign --re-sign -k {} {}".format(keyid, abs_file) + cmd = f"debsign --re-sign -k {keyid} {abs_file}" try: proc = salt.utils.vt.Terminal( cmd, @@ -903,7 +900,7 @@ def make_repo( number_retries = timeout / interval times_looped = 0 - error_msg = "Failed to reprepro includedsc file {}".format(abs_file) + error_msg = f"Failed to reprepro includedsc file {abs_file}" cmd = ( "reprepro --ignore=wrongdistribution --component=main -Vb ." " includedsc {} {}".format(codename, abs_file) diff --git a/salt/modules/defaults.py b/salt/modules/defaults.py index c807337dc2c..48ce0b11819 100644 --- a/salt/modules/defaults.py +++ b/salt/modules/defaults.py @@ -3,7 +3,6 @@ Module to work with salt formula defaults files """ - import copy import logging import os diff --git a/salt/modules/devinfo.py b/salt/modules/devinfo.py index d6c530aa2e2..ea9d3f5da67 100644 --- a/salt/modules/devinfo.py +++ b/salt/modules/devinfo.py @@ -293,7 +293,7 @@ def hwinfo(items=None, short=True, listmd=False, devices=None): cmd = ["hwinfo"] for item in items: - cmd.append("--{}".format(item)) + cmd.append(f"--{item}") if short: cmd.append("--short") @@ -302,7 +302,7 @@ def hwinfo(items=None, short=True, listmd=False, devices=None): cmd.append("--listmd") for device in devices: - cmd.append("--only {}".format(device)) + cmd.append(f"--only {device}") out = __salt__["cmd.run_stdout"](cmd) result["hwinfo"] = _hwinfo_parse(out, short) diff --git a/salt/modules/devmap.py b/salt/modules/devmap.py index 247d0293c2e..9f14ee6c9c8 100644 --- a/salt/modules/devmap.py +++ b/salt/modules/devmap.py @@ -30,7 +30,7 @@ def multipath_flush(device): salt '*' devmap.multipath_flush mpath1 """ if not os.path.exists(device): - return "{} does not exist".format(device) + return f"{device} does not exist" - cmd = "multipath -f {}".format(device) + cmd = f"multipath -f {device}" return __salt__["cmd.run"](cmd).splitlines() diff --git a/salt/modules/dig.py b/salt/modules/dig.py index ea0463075d4..1cd7ad37e33 100644 --- a/salt/modules/dig.py +++ b/salt/modules/dig.py @@ -84,7 +84,7 @@ def A(host, nameserver=None): dig = ["dig", "+short", str(host), "A"] if nameserver is not None: - dig.append("@{}".format(nameserver)) + dig.append(f"@{nameserver}") cmd = __salt__["cmd.run_all"](dig, python_shell=False) # In this case, 0 is not the same as False @@ -116,7 +116,7 @@ def PTR(host, nameserver=None): dig = ["dig", "+short", "-x", str(host)] if nameserver is not None: - dig.append("@{}".format(nameserver)) + dig.append(f"@{nameserver}") cmd = __salt__["cmd.run_all"](dig, python_shell=False) # In this case, 0 is not the same as False @@ -145,7 +145,7 @@ def AAAA(host, nameserver=None): dig = ["dig", "+short", str(host), "AAAA"] if nameserver is not None: - dig.append("@{}".format(nameserver)) + dig.append(f"@{nameserver}") cmd = __salt__["cmd.run_all"](dig, python_shell=False) # In this case, 0 is not the same as False @@ -175,7 +175,7 @@ def CNAME(host, nameserver=None): dig = ["dig", "+short", str(host), "CNAME"] if nameserver is not None: - dig.append("@{}".format(nameserver)) + dig.append(f"@{nameserver}") cmd = __salt__["cmd.run_all"](dig, python_shell=False) # In this case, 0 is not the same as False @@ -204,7 +204,7 @@ def NS(domain, resolve=True, nameserver=None): dig = ["dig", "+short", str(domain), "NS"] if nameserver is not None: - dig.append("@{}".format(nameserver)) + dig.append(f"@{nameserver}") cmd = __salt__["cmd.run_all"](dig, python_shell=False) # In this case, 0 is not the same as False @@ -243,7 +243,7 @@ def SPF(domain, record="SPF", nameserver=None): cmd = ["dig", "+short", str(domain), record] if nameserver is not None: - cmd.append("@{}".format(nameserver)) + cmd.append(f"@{nameserver}") result = __salt__["cmd.run_all"](cmd, python_shell=False) # In this case, 0 is not the same as False @@ -300,7 +300,7 @@ def MX(domain, resolve=False, nameserver=None): dig = ["dig", "+short", str(domain), "MX"] if nameserver is not None: - dig.append("@{}".format(nameserver)) + dig.append(f"@{nameserver}") cmd = __salt__["cmd.run_all"](dig, python_shell=False) # In this case, 0 is not the same as False @@ -334,7 +334,7 @@ def TXT(host, nameserver=None): dig = ["dig", "+short", str(host), "TXT"] if nameserver is not None: - dig.append("@{}".format(nameserver)) + dig.append(f"@{nameserver}") cmd = __salt__["cmd.run_all"](dig, python_shell=False) diff --git a/salt/modules/djangomod.py b/salt/modules/djangomod.py index 17942130e80..b66479f9a32 100644 --- a/salt/modules/djangomod.py +++ b/salt/modules/djangomod.py @@ -2,7 +2,6 @@ Manage Django sites """ - import os import salt.exceptions @@ -44,7 +43,7 @@ def command( env=None, runas=None, *args, - **kwargs + **kwargs, ): """ Run arbitrary django management command @@ -56,17 +55,17 @@ def command( salt '*' django.command """ dja = _get_django_admin(bin_env) - cmd = "{} {} --settings={}".format(dja, command, settings_module) + cmd = f"{dja} {command} --settings={settings_module}" if pythonpath: - cmd = "{} --pythonpath={}".format(cmd, pythonpath) + cmd = f"{cmd} --pythonpath={pythonpath}" for arg in args: - cmd = "{} --{}".format(cmd, arg) + cmd = f"{cmd} --{arg}" for key, value in kwargs.items(): if not key.startswith("__"): - cmd = "{} --{}={}".format(cmd, key, value) + cmd = f"{cmd} --{key}={value}" return __salt__["cmd.run"](cmd, env=env, runas=runas, python_shell=False) @@ -193,9 +192,9 @@ def migrate( args.append("noinput") if app_label and migration_name: - cmd = "migrate {} {}".format(app_label, migration_name) + cmd = f"migrate {app_label} {migration_name}" elif app_label: - cmd = "migrate {}".format(app_label) + cmd = f"migrate {app_label}" else: cmd = "migrate" @@ -240,7 +239,7 @@ def createsuperuser( env, runas, *args, - **kwargs + **kwargs, ) @@ -316,5 +315,5 @@ def collectstatic( env, runas, *args, - **kwargs + **kwargs, ) diff --git a/salt/modules/dnsmasq.py b/salt/modules/dnsmasq.py index e3f1d8bfa80..5aec67f959f 100644 --- a/salt/modules/dnsmasq.py +++ b/salt/modules/dnsmasq.py @@ -2,7 +2,6 @@ Module for managing dnsmasq """ - import logging import os @@ -114,13 +113,13 @@ def set_config(config_file="/etc/dnsmasq.conf", follow=True, **kwargs): for config in includes: __salt__["file.sed"]( path=config, - before="^{}=.*".format(key), - after="{}={}".format(key, kwargs[key]), + before=f"^{key}=.*", + after=f"{key}={kwargs[key]}", ) else: - __salt__["file.append"](config_file, "{}={}".format(key, kwargs[key])) + __salt__["file.append"](config_file, f"{key}={kwargs[key]}") else: - __salt__["file.append"](config_file, "{}={}".format(key, kwargs[key])) + __salt__["file.append"](config_file, f"{key}={kwargs[key]}") return ret_kwargs @@ -161,7 +160,7 @@ def _parse_dnamasq(filename): fileopts = {} if not os.path.isfile(filename): - raise CommandExecutionError("Error: No such file '{}'".format(filename)) + raise CommandExecutionError(f"Error: No such file '{filename}'") with salt.utils.files.fopen(filename, "r") as fp_: for line in fp_: diff --git a/salt/modules/dnsutil.py b/salt/modules/dnsutil.py index bc25f3d3386..5b677d777ee 100644 --- a/salt/modules/dnsutil.py +++ b/salt/modules/dnsutil.py @@ -74,13 +74,13 @@ def hosts_append(hostsfile="/etc/hosts", ip_addr=None, entries=None): host_list.remove(host) if not host_list: - return "No additional hosts were added to {}".format(hostsfile) + return f"No additional hosts were added to {hostsfile}" append_line = "\n{} {}".format(ip_addr, " ".join(host_list)) with salt.utils.files.fopen(hostsfile, "a") as fp_: fp_.write(salt.utils.stringutils.to_str(append_line)) - return "The following line was added to {}:{}".format(hostsfile, append_line) + return f"The following line was added to {hostsfile}:{append_line}" def hosts_remove(hostsfile="/etc/hosts", entries=None): @@ -103,7 +103,7 @@ def hosts_remove(hostsfile="/etc/hosts", entries=None): with salt.utils.files.fopen(hostsfile, "w") as out_file: for line in hosts.splitlines(): if not line or line.strip().startswith("#"): - out_file.write(salt.utils.stringutils.to_str("{}\n".format(line))) + out_file.write(salt.utils.stringutils.to_str(f"{line}\n")) continue comps = line.split() for host in host_list: @@ -149,7 +149,7 @@ def parse_zone(zonefile=None, zone=None): mode = "multi" multi = "" if mode == "multi": - multi += " {}".format(line) + multi += f" {line}" if ")" in line: mode = "single" line = multi.replace("(", "").replace(")", "") @@ -267,7 +267,7 @@ def A(host, nameserver=None): ] return addresses except socket.gaierror: - return "Unable to resolve {}".format(host) + return f"Unable to resolve {host}" return "This function requires dig, which is not currently available" @@ -299,7 +299,7 @@ def AAAA(host, nameserver=None): ] return addresses except socket.gaierror: - return "Unable to resolve {}".format(host) + return f"Unable to resolve {host}" return "This function requires dig, which is not currently available" @@ -394,7 +394,7 @@ def serial(zone="", update=False): grains = {} key = "dnsserial" if zone: - key += "_{}".format(zone) + key += f"_{zone}" stored = __salt__["grains.get"](key=key) present = time.strftime("%Y%m%d01") if not update: diff --git a/salt/modules/dockercompose.py b/salt/modules/dockercompose.py index 656af8d0d04..5ddc27d3480 100644 --- a/salt/modules/dockercompose.py +++ b/salt/modules/dockercompose.py @@ -103,7 +103,6 @@ Detailed Function Documentation ------------------------------- """ - import inspect import logging import os diff --git a/salt/modules/dockermod.py b/salt/modules/dockermod.py index 1bdf22c6d6c..4bcf86ec4be 100644 --- a/salt/modules/dockermod.py +++ b/salt/modules/dockermod.py @@ -4495,9 +4495,9 @@ def load(path, repository=None, tag=None): result = tag_(top_level_images[0], repository=repository, tag=tag) ret["Image"] = tagged_image except IndexError: - ret[ - "Warning" - ] = "No top-level image layers were loaded, no image was tagged" + ret["Warning"] = ( + "No top-level image layers were loaded, no image was tagged" + ) except Exception as exc: # pylint: disable=broad-except ret["Warning"] = "Failed to tag {} as {}: {}".format( top_level_images[0], tagged_image, exc diff --git a/salt/modules/dpkg_lowpkg.py b/salt/modules/dpkg_lowpkg.py index eefd852c511..3a405862163 100644 --- a/salt/modules/dpkg_lowpkg.py +++ b/salt/modules/dpkg_lowpkg.py @@ -62,14 +62,14 @@ def bin_pkg_info(path, saltenv="base"): newpath = __salt__["cp.cache_file"](path, saltenv) if not newpath: raise CommandExecutionError( - "Unable to retrieve {} from saltenv '{}'".format(path, saltenv) + f"Unable to retrieve {path} from saltenv '{saltenv}'" ) path = newpath else: if not os.path.exists(path): - raise CommandExecutionError("{} does not exist on minion".format(path)) + raise CommandExecutionError(f"{path} does not exist on minion") elif not os.path.isabs(path): - raise SaltInvocationError("{} does not exist on minion".format(path)) + raise SaltInvocationError(f"{path} does not exist on minion") cmd = ["dpkg", "-I", path] result = __salt__["cmd.run_all"](cmd, output_loglevel="trace") @@ -99,7 +99,7 @@ def bin_pkg_info(path, saltenv="base"): osarch = __grains__.get("osarch", "") arch = ret["arch"] if arch != "all" and osarch == "amd64" and osarch != arch: - ret["name"] += ":{}".format(arch) + ret["name"] += f":{arch}" return ret @@ -120,7 +120,7 @@ def unpurge(*packages): ret = {} __salt__["cmd.run"]( ["dpkg", "--set-selections"], - stdin=r"\n".join(["{} install".format(x) for x in packages]), + stdin=r"\n".join([f"{x} install" for x in packages]), python_shell=False, output_loglevel="trace", ) @@ -317,7 +317,7 @@ def _get_pkg_license(pkg): :return: """ licenses = set() - cpr = "/usr/share/doc/{}/copyright".format(pkg) + cpr = f"/usr/share/doc/{pkg}/copyright" if os.path.exists(cpr): with salt.utils.files.fopen(cpr, errors="ignore") as fp_: for line in salt.utils.stringutils.to_unicode(fp_.read()).split(os.linesep): @@ -335,7 +335,7 @@ def _get_pkg_install_time(pkg): """ iso_time = None if pkg is not None: - location = "/var/lib/dpkg/info/{}.list".format(pkg) + location = f"/var/lib/dpkg/info/{pkg}.list" if os.path.exists(location): iso_time = ( datetime.datetime.utcfromtimestamp( diff --git a/salt/modules/drac.py b/salt/modules/drac.py index 86ff8eedd5a..cb25d91f6a0 100644 --- a/salt/modules/drac.py +++ b/salt/modules/drac.py @@ -2,7 +2,6 @@ Manage Dell DRAC """ - import logging import salt.utils.path @@ -43,7 +42,7 @@ def __execute_cmd(command): """ Execute rac commands """ - cmd = __salt__["cmd.run_all"]("racadm {}".format(command)) + cmd = __salt__["cmd.run_all"](f"racadm {command}") if cmd["retcode"] != 0: log.warning("racadm return an exit code '%s'.", cmd["retcode"]) @@ -106,7 +105,7 @@ def nameservers(*ns): for i in range(1, len(ns) + 1): if not __execute_cmd( - "config -g cfgLanNetworking -o cfgDNSServer{} {}".format(i, ns[i - 1]) + f"config -g cfgLanNetworking -o cfgDNSServer{i} {ns[i - 1]}" ): return False @@ -128,7 +127,7 @@ def syslog(server, enable=True): """ if enable and __execute_cmd("config -g cfgRemoteHosts -o cfgRhostsSyslogEnable 1"): return __execute_cmd( - "config -g cfgRemoteHosts -o cfgRhostsSyslogServer1 {}".format(server) + f"config -g cfgRemoteHosts -o cfgRhostsSyslogServer1 {server}" ) return __execute_cmd("config -g cfgRemoteHosts -o cfgRhostsSyslogEnable 0") @@ -166,9 +165,7 @@ def list_users(): _username = "" for idx in range(1, 17): - cmd = __salt__["cmd.run_all"]( - "racadm getconfig -g cfgUserAdmin -i {}".format(idx) - ) + cmd = __salt__["cmd.run_all"](f"racadm getconfig -g cfgUserAdmin -i {idx}") if cmd["retcode"] != 0: log.warning("racadm return an exit code '%s'.", cmd["retcode"]) @@ -209,7 +206,7 @@ def delete_user(username, uid=None): if uid: return __execute_cmd( - 'config -g cfgUserAdmin -o cfgUserAdminUserName -i {} ""'.format(uid) + f'config -g cfgUserAdmin -o cfgUserAdminUserName -i {uid} ""' ) else: @@ -285,7 +282,7 @@ def create_user(username, password, permissions, users=None): # Create user accountvfirst if not __execute_cmd( - "config -g cfgUserAdmin -o cfgUserAdminUserName -i {} {}".format(uid, username) + f"config -g cfgUserAdmin -o cfgUserAdminUserName -i {uid} {username}" ): delete_user(username, uid) return False @@ -303,9 +300,7 @@ def create_user(username, password, permissions, users=None): return False # Enable users admin - if not __execute_cmd( - "config -g cfgUserAdmin -o cfgUserAdminEnable -i {} 1".format(uid) - ): + if not __execute_cmd(f"config -g cfgUserAdmin -o cfgUserAdminEnable -i {uid} 1"): delete_user(username, uid) return False @@ -379,7 +374,7 @@ def set_snmp(community): salt dell drac.set_snmp public """ return __execute_cmd( - "config -g cfgOobSnmp -o cfgOobSnmpAgentCommunity {}".format(community) + f"config -g cfgOobSnmp -o cfgOobSnmpAgentCommunity {community}" ) @@ -394,7 +389,7 @@ def set_network(ip, netmask, gateway): salt dell drac.set_network [DRAC IP] [NETMASK] [GATEWAY] salt dell drac.set_network 192.168.0.2 255.255.255.0 192.168.0.1 """ - return __execute_cmd("setniccfg -s {} {} {}".format(ip, netmask, gateway)) + return __execute_cmd(f"setniccfg -s {ip} {netmask} {gateway}") def server_reboot(): diff --git a/salt/modules/dracr.py b/salt/modules/dracr.py index c790f5423b2..31a939a9267 100644 --- a/salt/modules/dracr.py +++ b/salt/modules/dracr.py @@ -4,7 +4,6 @@ Manage Dell DRAC. .. versionadded:: 2015.8.2 """ - import logging import os import re @@ -69,12 +68,12 @@ def __execute_cmd( if module.startswith("ALL_"): modswitch = "-a " + module[module.index("_") + 1 : len(module)].lower() else: - modswitch = "-m {}".format(module) + modswitch = f"-m {module}" else: modswitch = "" if not host: # This is a local call - cmd = __salt__["cmd.run_all"]("racadm {} {}".format(command, modswitch)) + cmd = __salt__["cmd.run_all"](f"racadm {command} {modswitch}") else: cmd = __salt__["cmd.run_all"]( "racadm -r {} -u {} -p {} {} {}".format( @@ -100,12 +99,12 @@ def __execute_ret( if module == "ALL": modswitch = "-a " else: - modswitch = "-m {}".format(module) + modswitch = f"-m {module}" else: modswitch = "" if not host: # This is a local call - cmd = __salt__["cmd.run_all"]("racadm {} {}".format(command, modswitch)) + cmd = __salt__["cmd.run_all"](f"racadm {command} {modswitch}") else: cmd = __salt__["cmd.run_all"]( "racadm -r {} -u {} -p {} {} {}".format( @@ -153,7 +152,7 @@ def get_dns_dracname(host=None, admin_username=None, admin_password=None): def set_dns_dracname(name, host=None, admin_username=None, admin_password=None): ret = __execute_ret( - "set iDRAC.NIC.DNSRacName {}".format(name), + f"set iDRAC.NIC.DNSRacName {name}", host=host, admin_username=admin_username, admin_password=admin_password, @@ -256,7 +255,7 @@ def network_info(host=None, admin_username=None, admin_password=None, module=Non if module not in inv.get("switch") and module not in inv.get("server"): cmd = {} cmd["retcode"] = -1 - cmd["stdout"] = "No module {} found.".format(module) + cmd["stdout"] = f"No module {module} found." return cmd cmd = __execute_ret( @@ -293,7 +292,7 @@ def nameservers(ns, host=None, admin_username=None, admin_password=None, module= for i in range(1, len(ns) + 1): if not __execute_cmd( - "config -g cfgLanNetworking -o cfgDNSServer{} {}".format(i, ns[i - 1]), + f"config -g cfgLanNetworking -o cfgDNSServer{i} {ns[i - 1]}", host=host, admin_username=admin_username, admin_password=admin_password, @@ -332,7 +331,7 @@ def syslog( module=None, ): return __execute_cmd( - "config -g cfgRemoteHosts -o cfgRhostsSyslogServer1 {}".format(server), + f"config -g cfgRemoteHosts -o cfgRhostsSyslogServer1 {server}", host=host, admin_username=admin_username, admin_password=admin_password, @@ -386,7 +385,7 @@ def list_users(host=None, admin_username=None, admin_password=None, module=None) for idx in range(1, 17): cmd = __execute_ret( - "getconfig -g cfgUserAdmin -i {}".format(idx), + f"getconfig -g cfgUserAdmin -i {idx}", host=host, admin_username=admin_username, admin_password=admin_password, @@ -434,7 +433,7 @@ def delete_user( if uid: return __execute_cmd( - "config -g cfgUserAdmin -o cfgUserAdminUserName -i {} ".format(uid), + f"config -g cfgUserAdmin -o cfgUserAdminUserName -i {uid} ", host=host, admin_username=admin_username, admin_password=admin_password, @@ -522,7 +521,7 @@ def deploy_password( on that then setting the password is much quicker. """ return __execute_cmd( - "deploy -u {} -p {}".format(username, password), + f"deploy -u {username} -p {password}", host=host, admin_username=admin_username, admin_password=admin_password, @@ -545,7 +544,7 @@ def deploy_snmp(snmp, host=None, admin_username=None, admin_password=None, modul """ return __execute_cmd( - "deploy -v SNMPv2 {} ro".format(snmp), + f"deploy -v SNMPv2 {snmp} ro", host=host, admin_username=admin_username, admin_password=admin_password, @@ -599,7 +598,7 @@ def create_user( # Create user account first if not __execute_cmd( - "config -g cfgUserAdmin -o cfgUserAdminUserName -i {} {}".format(uid, username), + f"config -g cfgUserAdmin -o cfgUserAdminUserName -i {uid} {username}", host=host, admin_username=admin_username, admin_password=admin_password, @@ -620,9 +619,7 @@ def create_user( return False # Enable users admin - if not __execute_cmd( - "config -g cfgUserAdmin -o cfgUserAdminEnable -i {} 1".format(uid) - ): + if not __execute_cmd(f"config -g cfgUserAdmin -o cfgUserAdminEnable -i {uid} 1"): delete_user(username, uid) return False @@ -703,7 +700,7 @@ def set_snmp(community, host=None, admin_username=None, admin_password=None): salt dell dracr.set_snmp public """ return __execute_cmd( - "config -g cfgOobSnmp -o cfgOobSnmpAgentCommunity {}".format(community), + f"config -g cfgOobSnmp -o cfgOobSnmpAgentCommunity {community}", host=host, admin_username=admin_username, admin_password=admin_password, @@ -767,7 +764,7 @@ def server_power( """ return __execute_cmd( - "serveraction {}".format(status), + f"serveraction {status}", host=host, admin_username=admin_username, admin_password=admin_password, @@ -1089,7 +1086,7 @@ def set_slotname(slot, name, host=None, admin_username=None, admin_password=None """ return __execute_cmd( - "config -g cfgServerInfo -o cfgServerName -i {} {}".format(slot, name), + f"config -g cfgServerInfo -o cfgServerName -i {slot} {name}", host=host, admin_username=admin_username, admin_password=admin_password, @@ -1121,7 +1118,7 @@ def set_chassis_name(name, host=None, admin_username=None, admin_password=None): """ return __execute_cmd( - "setsysinfo -c chassisname {}".format(name), + f"setsysinfo -c chassisname {name}", host=host, admin_username=admin_username, admin_password=admin_password, @@ -1265,7 +1262,7 @@ def set_chassis_location(location, host=None, admin_username=None, admin_passwor """ return __execute_cmd( - "setsysinfo -c chassislocation {}".format(location), + f"setsysinfo -c chassislocation {location}", host=host, admin_username=admin_username, admin_password=admin_password, @@ -1368,7 +1365,7 @@ def set_general( cfg_sec, cfg_var, val, host=None, admin_username=None, admin_password=None ): return __execute_cmd( - "config -g {} -o {} {}".format(cfg_sec, cfg_var, val), + f"config -g {cfg_sec} -o {cfg_var} {val}", host=host, admin_username=admin_username, admin_password=admin_password, @@ -1377,7 +1374,7 @@ def set_general( def get_general(cfg_sec, cfg_var, host=None, admin_username=None, admin_password=None): ret = __execute_ret( - "getconfig -g {} -o {}".format(cfg_sec, cfg_var), + f"getconfig -g {cfg_sec} -o {cfg_var}", host=host, admin_username=admin_username, admin_password=admin_password, @@ -1458,7 +1455,7 @@ def _update_firmware(cmd, host=None, admin_username=None, admin_password=None): def bare_rac_cmd(cmd, host=None, admin_username=None, admin_password=None): ret = __execute_ret( - "{}".format(cmd), + f"{cmd}", host=host, admin_username=admin_username, admin_password=admin_password, @@ -1488,13 +1485,13 @@ def update_firmware(filename, host=None, admin_username=None, admin_password=Non """ if os.path.exists(filename): return _update_firmware( - "update -f {}".format(filename), + f"update -f {filename}", host=None, admin_username=None, admin_password=None, ) else: - raise CommandExecutionError("Unable to find firmware file {}".format(filename)) + raise CommandExecutionError(f"Unable to find firmware file {filename}") def update_firmware_nfs_or_cifs( @@ -1533,13 +1530,13 @@ def update_firmware_nfs_or_cifs( """ if os.path.exists(filename): return _update_firmware( - "update -f {} -l {}".format(filename, share), + f"update -f {filename} -l {share}", host=None, admin_username=None, admin_password=None, ) else: - raise CommandExecutionError("Unable to find firmware file {}".format(filename)) + raise CommandExecutionError(f"Unable to find firmware file {filename}") # def get_idrac_nic() diff --git a/salt/modules/ebuildpkg.py b/salt/modules/ebuildpkg.py index 0e8fd851066..905f0339250 100644 --- a/salt/modules/ebuildpkg.py +++ b/salt/modules/ebuildpkg.py @@ -303,7 +303,7 @@ def _get_upgradable(backtrack=3): "--ask", "n", "--backtrack", - "{}".format(backtrack), + f"{backtrack}", "--pretend", "--update", "--newuse", @@ -547,7 +547,7 @@ def install( fromrepo=None, uses=None, binhost=None, - **kwargs + **kwargs, ): """ .. versionchanged:: 2015.8.12,2016.3.3,2016.11.0 @@ -680,9 +680,9 @@ def install( if not version_num: version_num = "" if slot is not None: - version_num += ":{}".format(slot) + version_num += f":{slot}" if fromrepo is not None: - version_num += "::{}".format(fromrepo) + version_num += f"::{fromrepo}" if uses is not None: version_num += "[{}]".format(",".join(uses)) pkg_params = {name: version_num} @@ -724,11 +724,11 @@ def install( # If no prefix characters were supplied and verstr contains a version, use '=' if len(verstr) > 0 and verstr[0] != ":" and verstr[0] != "[": prefix = prefix or "=" - target = "{}{}-{}".format(prefix, param, verstr) + target = f"{prefix}{param}-{verstr}" else: - target = "{}{}".format(param, verstr) + target = f"{param}{verstr}" else: - target = "{}".format(param) + target = f"{param}" if "[" in target: old = __salt__["portage_config.get_flags_from_package_conf"]( @@ -842,10 +842,10 @@ def update(pkg, slot=None, fromrepo=None, refresh=False, binhost=None, **kwargs) full_atom = pkg if slot is not None: - full_atom = "{}:{}".format(full_atom, slot) + full_atom = f"{full_atom}:{slot}" if fromrepo is not None: - full_atom = "{}::{}".format(full_atom, fromrepo) + full_atom = f"{full_atom}::{fromrepo}" if binhost == "try": bin_opts = ["-g"] @@ -950,7 +950,7 @@ def upgrade(refresh=True, binhost=None, backtrack=3, **kwargs): "n", "--quiet", "--backtrack", - "{}".format(backtrack), + f"{backtrack}", "--update", "--newuse", "--deep", @@ -1034,9 +1034,9 @@ def remove(name=None, slot=None, fromrepo=None, pkgs=None, **kwargs): ): fullatom = name if slot is not None: - targets = ["{}:{}".format(fullatom, slot)] + targets = [f"{fullatom}:{slot}"] if fromrepo is not None: - targets = ["{}::{}".format(fullatom, fromrepo)] + targets = [f"{fullatom}::{fromrepo}"] targets = [fullatom] else: targets = [x for x in pkg_params if x in old] @@ -1165,9 +1165,9 @@ def depclean(name=None, slot=None, fromrepo=None, pkgs=None): ): fullatom = name if slot is not None: - targets = ["{}:{}".format(fullatom, slot)] + targets = [f"{fullatom}:{slot}"] if fromrepo is not None: - targets = ["{}::{}".format(fullatom, fromrepo)] + targets = [f"{fullatom}::{fromrepo}"] targets = [fullatom] else: targets = [x for x in pkg_params if x in old] @@ -1245,9 +1245,9 @@ def check_extra_requirements(pkgname, pkgver): # If no prefix characters were supplied and verstr contains a version, use '=' if verstr[0] != ":" and verstr[0] != "[": prefix = prefix or "=" - atom = "{}{}-{}".format(prefix, pkgname, verstr) + atom = f"{prefix}{pkgname}-{verstr}" else: - atom = "{}{}".format(pkgname, verstr) + atom = f"{pkgname}{verstr}" else: return True diff --git a/salt/modules/elasticsearch.py b/salt/modules/elasticsearch.py index 4db9b370abc..e8a468103fe 100644 --- a/salt/modules/elasticsearch.py +++ b/salt/modules/elasticsearch.py @@ -48,7 +48,6 @@ Module to provide Elasticsearch compatibility to Salt Some functionality might be limited by elasticsearch-py and Elasticsearch server versions. """ - import logging from salt.exceptions import CommandExecutionError, SaltInvocationError diff --git a/salt/modules/eselect.py b/salt/modules/eselect.py index 9a0c1cf6756..33a1e96709b 100644 --- a/salt/modules/eselect.py +++ b/salt/modules/eselect.py @@ -2,7 +2,6 @@ Support for eselect, Gentoo's configuration and management tool. """ - import logging import salt.utils.path @@ -195,7 +194,7 @@ def set_target(module, target, module_parameter=None, action_parameter=None): salt '*' eselect.set_target kernel linux-3.17.5-gentoo """ if action_parameter: - action_parameter = "{} {}".format(action_parameter, target) + action_parameter = f"{action_parameter} {target}" else: action_parameter = target diff --git a/salt/modules/esxi.py b/salt/modules/esxi.py index e9686ea9411..dbbf1adda27 100644 --- a/salt/modules/esxi.py +++ b/salt/modules/esxi.py @@ -34,7 +34,6 @@ type manor. """ - import logging from functools import wraps diff --git a/salt/modules/esxvm.py b/salt/modules/esxvm.py index 397f6d24478..d8065ae9bf2 100644 --- a/salt/modules/esxvm.py +++ b/salt/modules/esxvm.py @@ -13,7 +13,6 @@ Module used to access the esx proxy connection methods """ - import logging from functools import wraps diff --git a/salt/modules/ethtool.py b/salt/modules/ethtool.py index 16f9c4a7b53..0fb0a16b98a 100644 --- a/salt/modules/ethtool.py +++ b/salt/modules/ethtool.py @@ -312,8 +312,8 @@ def _ethtool_command(devname, *args, **kwargs): if not ethtool: raise CommandExecutionError("Command 'ethtool' cannot be found") switches = " ".join(arg for arg in args) - params = " ".join("{} {}".format(key, val) for key, val in kwargs.items()) - cmd = "{} {} {} {}".format(ethtool, switches, devname, params).strip() + params = " ".join(f"{key} {val}" for key, val in kwargs.items()) + cmd = f"{ethtool} {switches} {devname} {params}".strip() ret = __salt__["cmd.run"](cmd, ignore_retcode=True).splitlines() if ret and ret[0].startswith("Cannot"): raise CommandExecutionError(ret[0]) @@ -336,7 +336,7 @@ def _validate_params(valid_params, kwargs): validated[key] = val if not validated: raise CommandExecutionError( - "None of the valid parameters were provided: {}".format(valid_params) + f"None of the valid parameters were provided: {valid_params}" ) return validated diff --git a/salt/modules/event.py b/salt/modules/event.py index bf6d4bde0d7..7bb64a8119a 100644 --- a/salt/modules/event.py +++ b/salt/modules/event.py @@ -3,7 +3,6 @@ Use the :ref:`Salt Event System ` to fire events from the master to the minion and vice-versa. """ - import logging import os import sys diff --git a/salt/modules/extfs.py b/salt/modules/extfs.py index 2737cbe2b72..fc5585295c1 100644 --- a/salt/modules/extfs.py +++ b/salt/modules/extfs.py @@ -2,7 +2,6 @@ Module for managing ext2/3/4 file systems """ - import logging import salt.utils.platform diff --git a/salt/modules/file.py b/salt/modules/file.py index 3a9f0669cbe..e826c435d45 100644 --- a/salt/modules/file.py +++ b/salt/modules/file.py @@ -887,9 +887,11 @@ def get_source_sum( if source_hash_sig: _check_sig( hash_fn, - signature=source_hash_sig - if isinstance(source_hash_sig, str) - else None, + signature=( + source_hash_sig + if isinstance(source_hash_sig, str) + else None + ), signed_by_any=signed_by_any, signed_by_all=signed_by_all, keyring=keyring, @@ -5060,9 +5062,11 @@ def extract_hash( if basename_searches: log.debug( "file.extract_hash: %s %s hash for file matching%s: %s", - "If no source_hash_name match found, will extract" - if source_hash_name - else "Extracting", + ( + "If no source_hash_name match found, will extract" + if source_hash_name + else "Extracting" + ), "any supported" if not hash_type else hash_type, "" if len(basename_searches) == 1 else " either of the following", ", ".join(basename_searches), diff --git a/salt/modules/firewalld.py b/salt/modules/firewalld.py index 135713d8516..878969d6d8b 100644 --- a/salt/modules/firewalld.py +++ b/salt/modules/firewalld.py @@ -4,7 +4,6 @@ Support for firewalld. .. versionadded:: 2015.2.0 """ - import logging import re @@ -40,7 +39,7 @@ def __firewall_cmd(cmd): msg = out["stdout"] else: msg = out["stderr"] - raise CommandExecutionError("firewall-cmd failed: {}".format(msg)) + raise CommandExecutionError(f"firewall-cmd failed: {msg}") return out["stdout"] @@ -49,7 +48,7 @@ def __mgmt(name, _type, action): Perform zone management """ # It's permanent because the 4 concerned functions need the permanent option, it's wrong without - cmd = "--{}-{}={} --permanent".format(action, _type, name) + cmd = f"--{action}-{_type}={name} --permanent" return __firewall_cmd(cmd) @@ -259,7 +258,7 @@ def set_default_zone(zone): salt '*' firewalld.set_default_zone damian """ - return __firewall_cmd("--set-default-zone={}".format(zone)) + return __firewall_cmd(f"--set-default-zone={zone}") def new_service(name, restart=True): @@ -333,7 +332,7 @@ def list_all(zone=None, permanent=True): salt '*' firewalld.list_all my_zone """ if zone: - cmd = "--zone={} --list-all".format(zone) + cmd = f"--zone={zone} --list-all" else: cmd = "--list-all" @@ -361,7 +360,7 @@ def list_services(zone=None, permanent=True): salt '*' firewalld.list_services my_zone """ if zone: - cmd = "--zone={} --list-services".format(zone) + cmd = f"--zone={zone} --list-services" else: cmd = "--list-services" @@ -388,9 +387,9 @@ def add_service(service, zone=None, permanent=True): salt '*' firewalld.add_service ssh my_zone """ if zone: - cmd = "--zone={} --add-service={}".format(zone, service) + cmd = f"--zone={zone} --add-service={service}" else: - cmd = "--add-service={}".format(service) + cmd = f"--add-service={service}" if permanent: cmd += " --permanent" @@ -416,9 +415,9 @@ def remove_service(service, zone=None, permanent=True): salt '*' firewalld.remove_service ssh dmz """ if zone: - cmd = "--zone={} --remove-service={}".format(zone, service) + cmd = f"--zone={zone} --remove-service={service}" else: - cmd = "--remove-service={}".format(service) + cmd = f"--remove-service={service}" if permanent: cmd += " --permanent" @@ -441,7 +440,7 @@ def add_service_port(service, port): if service not in get_services(permanent=True): raise CommandExecutionError("The service does not exist.") - cmd = "--permanent --service={} --add-port={}".format(service, port) + cmd = f"--permanent --service={service} --add-port={port}" return __firewall_cmd(cmd) @@ -460,7 +459,7 @@ def remove_service_port(service, port): if service not in get_services(permanent=True): raise CommandExecutionError("The service does not exist.") - cmd = "--permanent --service={} --remove-port={}".format(service, port) + cmd = f"--permanent --service={service} --remove-port={port}" return __firewall_cmd(cmd) @@ -476,7 +475,7 @@ def get_service_ports(service): salt '*' firewalld.get_service_ports zone """ - cmd = "--permanent --service={} --get-ports".format(service) + cmd = f"--permanent --service={service} --get-ports" return __firewall_cmd(cmd).split() @@ -492,7 +491,7 @@ def add_service_protocol(service, protocol): salt '*' firewalld.add_service_protocol zone ssh """ - cmd = "--permanent --service={} --add-protocol={}".format(service, protocol) + cmd = f"--permanent --service={service} --add-protocol={protocol}" return __firewall_cmd(cmd) @@ -508,7 +507,7 @@ def remove_service_protocol(service, protocol): salt '*' firewalld.remove_service_protocol zone ssh """ - cmd = "--permanent --service={} --remove-protocol={}".format(service, protocol) + cmd = f"--permanent --service={service} --remove-protocol={protocol}" return __firewall_cmd(cmd) @@ -524,7 +523,7 @@ def get_service_protocols(service): salt '*' firewalld.get_service_protocols zone """ - cmd = "--permanent --service={} --get-protocols".format(service) + cmd = f"--permanent --service={service} --get-protocols" return __firewall_cmd(cmd).split() @@ -567,7 +566,7 @@ def add_masquerade(zone=None, permanent=True): salt '*' firewalld.add_masquerade dmz """ if zone: - cmd = "--zone={} --add-masquerade".format(zone) + cmd = f"--zone={zone} --add-masquerade" else: cmd = "--add-masquerade" @@ -597,7 +596,7 @@ def remove_masquerade(zone=None, permanent=True): salt '*' firewalld.remove_masquerade dmz """ if zone: - cmd = "--zone={} --remove-masquerade".format(zone) + cmd = f"--zone={zone} --remove-masquerade" else: cmd = "--remove-masquerade" @@ -626,7 +625,7 @@ def add_port(zone, port, permanent=True, force_masquerade=False): if force_masquerade and not get_masquerade(zone): add_masquerade(zone) - cmd = "--zone={} --add-port={}".format(zone, port) + cmd = f"--zone={zone} --add-port={port}" if permanent: cmd += " --permanent" @@ -646,7 +645,7 @@ def remove_port(zone, port, permanent=True): salt '*' firewalld.remove_port internal 443/tcp """ - cmd = "--zone={} --remove-port={}".format(zone, port) + cmd = f"--zone={zone} --remove-port={port}" if permanent: cmd += " --permanent" @@ -666,7 +665,7 @@ def list_ports(zone, permanent=True): salt '*' firewalld.list_ports """ - cmd = "--zone={} --list-ports".format(zone) + cmd = f"--zone={zone} --list-ports" if permanent: cmd += " --permanent" @@ -741,7 +740,7 @@ def list_port_fwd(zone, permanent=True): """ ret = [] - cmd = "--zone={} --list-forward-ports".format(zone) + cmd = f"--zone={zone} --list-forward-ports" if permanent: cmd += " --permanent" @@ -781,7 +780,7 @@ def block_icmp(zone, icmp, permanent=True): log.info("ICMP block already exists") return "success" - cmd = "--zone={} --add-icmp-block={}".format(zone, icmp) + cmd = f"--zone={zone} --add-icmp-block={icmp}" if permanent: cmd += " --permanent" @@ -809,7 +808,7 @@ def allow_icmp(zone, icmp, permanent=True): log.info("ICMP Type is already permitted") return "success" - cmd = "--zone={} --remove-icmp-block={}".format(zone, icmp) + cmd = f"--zone={zone} --remove-icmp-block={icmp}" if permanent: cmd += " --permanent" @@ -829,7 +828,7 @@ def list_icmp_block(zone, permanent=True): salt '*' firewlld.list_icmp_block zone """ - cmd = "--zone={} --list-icmp-blocks".format(zone) + cmd = f"--zone={zone} --list-icmp-blocks" if permanent: cmd += " --permanent" @@ -864,7 +863,7 @@ def get_interfaces(zone, permanent=True): salt '*' firewalld.get_interfaces zone """ - cmd = "--zone={} --list-interfaces".format(zone) + cmd = f"--zone={zone} --list-interfaces" if permanent: cmd += " --permanent" @@ -887,7 +886,7 @@ def add_interface(zone, interface, permanent=True): if interface in get_interfaces(zone, permanent): log.info("Interface is already bound to zone.") - cmd = "--zone={} --add-interface={}".format(zone, interface) + cmd = f"--zone={zone} --add-interface={interface}" if permanent: cmd += " --permanent" @@ -910,7 +909,7 @@ def remove_interface(zone, interface, permanent=True): if interface not in get_interfaces(zone, permanent): log.info("Interface is not bound to zone.") - cmd = "--zone={} --remove-interface={}".format(zone, interface) + cmd = f"--zone={zone} --remove-interface={interface}" if permanent: cmd += " --permanent" @@ -930,7 +929,7 @@ def get_sources(zone, permanent=True): salt '*' firewalld.get_sources zone """ - cmd = "--zone={} --list-sources".format(zone) + cmd = f"--zone={zone} --list-sources" if permanent: cmd += " --permanent" @@ -953,7 +952,7 @@ def add_source(zone, source, permanent=True): if source in get_sources(zone, permanent): log.info("Source is already bound to zone.") - cmd = "--zone={} --add-source={}".format(zone, source) + cmd = f"--zone={zone} --add-source={source}" if permanent: cmd += " --permanent" @@ -976,7 +975,7 @@ def remove_source(zone, source, permanent=True): if source not in get_sources(zone, permanent): log.info("Source is not bound to zone.") - cmd = "--zone={} --remove-source={}".format(zone, source) + cmd = f"--zone={zone} --remove-source={source}" if permanent: cmd += " --permanent" @@ -996,7 +995,7 @@ def get_rich_rules(zone, permanent=True): salt '*' firewalld.get_rich_rules zone """ - cmd = "--zone={} --list-rich-rules".format(zone) + cmd = f"--zone={zone} --list-rich-rules" if permanent: cmd += " --permanent" @@ -1016,7 +1015,7 @@ def add_rich_rule(zone, rule, permanent=True): salt '*' firewalld.add_rich_rule zone 'rule' """ - cmd = "--zone={} --add-rich-rule='{}'".format(zone, rule) + cmd = f"--zone={zone} --add-rich-rule='{rule}'" if permanent: cmd += " --permanent" @@ -1036,7 +1035,7 @@ def remove_rich_rule(zone, rule, permanent=True): salt '*' firewalld.remove_rich_rule zone 'rule' """ - cmd = "--zone={} --remove-rich-rule='{}'".format(zone, rule) + cmd = f"--zone={zone} --remove-rich-rule='{rule}'" if permanent: cmd += " --permanent" diff --git a/salt/modules/freebsd_sysctl.py b/salt/modules/freebsd_sysctl.py index 3d6dd930ec5..ad2a6ba3eaf 100644 --- a/salt/modules/freebsd_sysctl.py +++ b/salt/modules/freebsd_sysctl.py @@ -2,7 +2,6 @@ Module for viewing and modifying sysctl parameters """ - import logging import os @@ -31,9 +30,9 @@ def __virtual__(): def _formatfor(name, value, config, tail=""): if config == "/boot/loader.conf": - return '{}="{}"{}'.format(name, value, tail) + return f'{name}="{value}"{tail}' else: - return "{}={}{}".format(name, value, tail) + return f"{name}={value}{tail}" def show(config_file=False): @@ -88,13 +87,13 @@ def show(config_file=False): out = __salt__["cmd.run"](cmd, output_loglevel="trace") value = None for line in out.splitlines(): - if any([line.startswith("{}.".format(root)) for root in roots]): + if any([line.startswith(f"{root}.") for root in roots]): if value is not None: ret[key] = "\n".join(value) (key, firstvalue) = line.split("=", 1) value = [firstvalue] elif value is not None: - value.append("{}".format(line)) + value.append(f"{line}") if value is not None: ret[key] = "\n".join(value) return ret @@ -110,7 +109,7 @@ def get(name): salt '*' sysctl.get hw.physmem """ - cmd = "sysctl -n {}".format(name) + cmd = f"sysctl -n {name}" out = __salt__["cmd.run"](cmd, python_shell=False) return out @@ -126,7 +125,7 @@ def assign(name, value): salt '*' sysctl.assign net.inet.icmp.icmplim 50 """ ret = {} - cmd = 'sysctl {}="{}"'.format(name, value) + cmd = f'sysctl {name}="{value}"' data = __salt__["cmd.run_all"](cmd, python_shell=False) if data["retcode"] != 0: @@ -154,7 +153,7 @@ def persist(name, value, config="/etc/sysctl.conf"): with salt.utils.files.fopen(config, "r") as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line).rstrip("\n") - if not line.startswith("{}=".format(name)): + if not line.startswith(f"{name}="): nlines.append(line) continue else: @@ -177,7 +176,7 @@ def persist(name, value, config="/etc/sysctl.conf"): nlines.append(new_line) edited = True if not edited: - nlines.append("{}\n".format(_formatfor(name, value, config))) + nlines.append(f"{_formatfor(name, value, config)}\n") with salt.utils.files.fopen(config, "w+") as ofile: nlines = [salt.utils.stringutils.to_str(_l) + "\n" for _l in nlines] ofile.writelines(nlines) diff --git a/salt/modules/freebsd_update.py b/salt/modules/freebsd_update.py index 26a6acd932f..71904d7230c 100644 --- a/salt/modules/freebsd_update.py +++ b/salt/modules/freebsd_update.py @@ -8,7 +8,6 @@ Support for freebsd-update utility on FreeBSD. :platform: FreeBSD """ - import logging import salt.utils.path @@ -195,7 +194,7 @@ def update(**kwargs): return ret if "stdout" in err_: stdout[mode] = err_["stdout"] - return "\n".join(["{}: {}".format(k, v) for (k, v) in stdout.items()]) + return "\n".join([f"{k}: {v}" for (k, v) in stdout.items()]) def ids(**kwargs): diff --git a/salt/modules/freebsdjail.py b/salt/modules/freebsdjail.py index fc3c3ce04f3..46c10f0be15 100644 --- a/salt/modules/freebsdjail.py +++ b/salt/modules/freebsdjail.py @@ -2,7 +2,6 @@ The jail module for FreeBSD """ - import os import re import subprocess @@ -38,7 +37,7 @@ def start(jail=""): salt '*' jail.start [] """ - cmd = "service jail onestart {}".format(jail) + cmd = f"service jail onestart {jail}" return not __salt__["cmd.retcode"](cmd) @@ -52,7 +51,7 @@ def stop(jail=""): salt '*' jail.stop [] """ - cmd = "service jail onestop {}".format(jail) + cmd = f"service jail onestop {jail}" return not __salt__["cmd.retcode"](cmd) @@ -66,7 +65,7 @@ def restart(jail=""): salt '*' jail.restart [] """ - cmd = "service jail onerestart {}".format(jail) + cmd = f"service jail onerestart {jail}" return not __salt__["cmd.retcode"](cmd) @@ -145,7 +144,7 @@ def show_config(jail): line = salt.utils.stringutils.to_unicode(line) if not line.strip(): continue - if not line.startswith("jail_{}_".format(jail)): + if not line.startswith(f"jail_{jail}_"): continue key, value = line.split("=") ret[key.split("_", 2)[2]] = value.split('"')[1] diff --git a/salt/modules/freebsdkmod.py b/salt/modules/freebsdkmod.py index 27793f758c6..db13306ceb5 100644 --- a/salt/modules/freebsdkmod.py +++ b/salt/modules/freebsdkmod.py @@ -201,7 +201,7 @@ def load(mod, persist=False): salt '*' kmod.load bhyve """ pre_mods = lsmod() - response = __salt__["cmd.run_all"]("kldload {}".format(mod), python_shell=False) + response = __salt__["cmd.run_all"](f"kldload {mod}", python_shell=False) if response["retcode"] == 0: post_mods = lsmod() mods = _new_mods(pre_mods, post_mods) @@ -217,7 +217,7 @@ def load(mod, persist=False): # It's compiled into the kernel return [None] else: - return "Module {} not found".format(mod) + return f"Module {mod} not found" def is_loaded(mod): @@ -254,7 +254,7 @@ def remove(mod, persist=False, comment=True): salt '*' kmod.remove vmm """ pre_mods = lsmod() - res = __salt__["cmd.run_all"]("kldunload {}".format(mod), python_shell=False) + res = __salt__["cmd.run_all"](f"kldunload {mod}", python_shell=False) if res["retcode"] == 0: post_mods = lsmod() mods = _rm_mods(pre_mods, post_mods) diff --git a/salt/modules/freebsdpkg.py b/salt/modules/freebsdpkg.py index 36de306b687..77ba7444cfa 100644 --- a/salt/modules/freebsdpkg.py +++ b/salt/modules/freebsdpkg.py @@ -175,20 +175,20 @@ def _match(names): cver = pkgs.get(name) if cver is not None: if len(cver) == 1: - matches.append("{}-{}".format(name, cver[0])) + matches.append(f"{name}-{cver[0]}") else: ambiguous.append(name) errors.append( "Ambiguous package '{}'. Full name/version required. " "Possible matches: {}".format( - name, ", ".join(["{}-{}".format(name, x) for x in cver]) + name, ", ".join([f"{name}-{x}" for x in cver]) ) ) # Find packages that did not match anything not_matched = set(names) - set(matches) - set(full_matches) - set(ambiguous) for name in not_matched: - errors.append("Package '{}' not found".format(name)) + errors.append(f"Package '{name}' not found") return matches + full_matches, errors diff --git a/salt/modules/freebsdports.py b/salt/modules/freebsdports.py index 3ab53e24f80..254212f0e16 100644 --- a/salt/modules/freebsdports.py +++ b/salt/modules/freebsdports.py @@ -59,13 +59,11 @@ def _check_portname(name): ports tree. """ if not isinstance(name, str) or "/" not in name: - raise SaltInvocationError( - "Invalid port name '{}' (category required)".format(name) - ) + raise SaltInvocationError(f"Invalid port name '{name}' (category required)") path = os.path.join("/usr/ports", name) if not os.path.isdir(path): - raise SaltInvocationError("Path '{}' does not exist".format(path)) + raise SaltInvocationError(f"Path '{path}' does not exist") return path @@ -109,7 +107,7 @@ def _write_options(name, configuration): try: os.makedirs(dirname) except OSError as exc: - raise CommandExecutionError("Unable to make {}: {}".format(dirname, exc)) + raise CommandExecutionError(f"Unable to make {dirname}: {exc}") with salt.utils.files.fopen(os.path.join(dirname, "options"), "w") as fp_: sorted_options = list(conf_ptr) @@ -270,7 +268,7 @@ def showconfig(name, default=False, dict_return=False): error = result if error: - msg = "Error running 'make showconfig' for {}: {}".format(name, error) + msg = f"Error running 'make showconfig' for {name}: {error}" log.error(msg) raise SaltInvocationError(msg) @@ -327,9 +325,7 @@ def config(name, reset=False, **kwargs): configuration = showconfig(name, dict_return=True) if not configuration: - raise CommandExecutionError( - "Unable to get port configuration for '{}'".format(name) - ) + raise CommandExecutionError(f"Unable to get port configuration for '{name}'") # Get top-level key for later reference pkg = next(iter(configuration)) @@ -345,7 +341,7 @@ def config(name, reset=False, **kwargs): ) ) - bad_vals = ["{}={}".format(x, y) for x, y in opts.items() if y not in ("on", "off")] + bad_vals = [f"{x}={y}" for x, y in opts.items() if y not in ("on", "off")] if bad_vals: raise SaltInvocationError( "The following key/value pairs are invalid: {}".format(", ".join(bad_vals)) @@ -396,8 +392,8 @@ def update(extract=False): except AttributeError: new_port_count = 0 - ret.append("Applied {} new patches".format(patch_count)) - ret.append("Fetched {} new ports or files".format(new_port_count)) + ret.append(f"Applied {patch_count} new patches") + ret.append(f"Fetched {new_port_count} new ports or files") if extract: result = __salt__["cmd.run_all"](_portsnap() + ["extract"], python_shell=False) diff --git a/salt/modules/freebsdservice.py b/salt/modules/freebsdservice.py index f053db695fe..a5fdc2cbad6 100644 --- a/salt/modules/freebsdservice.py +++ b/salt/modules/freebsdservice.py @@ -56,7 +56,7 @@ def _cmd(jail=None): jexec = salt.utils.path.which("jexec") if not jexec: raise CommandNotFoundError("'jexec' command not found") - service = "{} {} {}".format(jexec, jail, service) + service = f"{jexec} {jail} {service}" return service @@ -72,7 +72,7 @@ def _get_jail_path(jail): jls = salt.utils.path.which("jls") if not jls: raise CommandNotFoundError("'jls' command not found") - jails = __salt__["cmd.run_stdout"]("{} -n jid name path".format(jls)) + jails = __salt__["cmd.run_stdout"](f"{jls} -n jid name path") for j in jails.splitlines(): jid, jname, path = (x.split("=")[1].strip() for x in j.split()) if jid == jail or jname == jail: @@ -89,10 +89,10 @@ def _get_rcscript(name, jail=None): Support for jail (representing jid or jail name) keyword argument in kwargs """ - cmd = "{} -r".format(_cmd(jail)) + cmd = f"{_cmd(jail)} -r" prf = _get_jail_path(jail) if jail else "" for line in __salt__["cmd.run_stdout"](cmd, python_shell=False).splitlines(): - if line.endswith("{}{}".format(os.path.sep, name)): + if line.endswith(f"{os.path.sep}{name}"): return os.path.join(prf, line.lstrip(os.path.sep)) return None @@ -109,7 +109,7 @@ def _get_rcvar(name, jail=None): log.error("Service %s not found", name) return False - cmd = "{} {} rcvar".format(_cmd(jail), name) + cmd = f"{_cmd(jail)} {name} rcvar" for line in __salt__["cmd.run_stdout"](cmd, python_shell=False).splitlines(): if '_enable="' not in line: @@ -137,14 +137,14 @@ def get_enabled(jail=None): ret = [] service = _cmd(jail) prf = _get_jail_path(jail) if jail else "" - for svc in __salt__["cmd.run"]("{} -e".format(service)).splitlines(): + for svc in __salt__["cmd.run"](f"{service} -e").splitlines(): ret.append(os.path.basename(svc)) # This is workaround for bin/173454 bug for svc in get_all(jail): if svc in ret: continue - if not os.path.exists("{}/etc/rc.conf.d/{}".format(prf, svc)): + if not os.path.exists(f"{prf}/etc/rc.conf.d/{svc}"): continue if enabled(svc, jail=jail): ret.append(svc) @@ -199,13 +199,11 @@ def _switch(name, on, **kwargs): # pylint: disable=C0103 # pylint: disable=C01 config = kwargs.get( "config", - __salt__["config.option"]( - "service.config", default="{}/etc/rc.conf".format(chroot) - ), + __salt__["config.option"]("service.config", default=f"{chroot}/etc/rc.conf"), ) if not config: - rcdir = "{}/etc/rc.conf.d".format(chroot) + rcdir = f"{chroot}/etc/rc.conf.d" if not os.path.exists(rcdir) or not os.path.isdir(rcdir): log.error("%s not exists", rcdir) return False @@ -223,17 +221,17 @@ def _switch(name, on, **kwargs): # pylint: disable=C0103 # pylint: disable=C01 with salt.utils.files.fopen(config, "r") as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) - if not line.startswith("{}=".format(rcvar)): + if not line.startswith(f"{rcvar}="): nlines.append(line) continue rest = line[len(line.split()[0]) :] # keep comments etc - nlines.append('{}="{}"{}'.format(rcvar, val, rest)) + nlines.append(f'{rcvar}="{val}"{rest}') edited = True if not edited: # Ensure that the file ends in a \n if len(nlines) > 1 and nlines[-1][-1] != "\n": - nlines[-1] = "{}\n".format(nlines[-1]) - nlines.append('{}="{}"\n'.format(rcvar, val)) + nlines[-1] = f"{nlines[-1]}\n" + nlines.append(f'{rcvar}="{val}"\n') with salt.utils.files.fopen(config, "w") as ofile: nlines = [salt.utils.stringutils.to_str(_l) for _l in nlines] @@ -318,7 +316,7 @@ def enabled(name, **kwargs): log.error("Service %s not found", name) return False - cmd = "{} {} rcvar".format(_cmd(jail), name) + cmd = f"{_cmd(jail)} {name} rcvar" for line in __salt__["cmd.run_stdout"](cmd, python_shell=False).splitlines(): if '_enable="' not in line: @@ -395,7 +393,7 @@ def get_all(jail=None): """ ret = [] service = _cmd(jail) - for srv in __salt__["cmd.run"]("{} -l".format(service)).splitlines(): + for srv in __salt__["cmd.run"](f"{service} -l").splitlines(): if not srv.isupper(): ret.append(srv) return sorted(ret) @@ -415,7 +413,7 @@ def start(name, jail=None): salt '*' service.start """ - cmd = "{} {} onestart".format(_cmd(jail), name) + cmd = f"{_cmd(jail)} {name} onestart" return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -433,7 +431,7 @@ def stop(name, jail=None): salt '*' service.stop """ - cmd = "{} {} onestop".format(_cmd(jail), name) + cmd = f"{_cmd(jail)} {name} onestop" return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -451,7 +449,7 @@ def restart(name, jail=None): salt '*' service.restart """ - cmd = "{} {} onerestart".format(_cmd(jail), name) + cmd = f"{_cmd(jail)} {name} onerestart" return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -469,7 +467,7 @@ def reload_(name, jail=None): salt '*' service.reload """ - cmd = "{} {} onereload".format(_cmd(jail), name) + cmd = f"{_cmd(jail)} {name} onereload" return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -508,7 +506,7 @@ def status(name, sig=None, jail=None): services = [name] results = {} for service in services: - cmd = "{} {} onestatus".format(_cmd(jail), service) + cmd = f"{_cmd(jail)} {service} onestatus" results[service] = not __salt__["cmd.retcode"]( cmd, python_shell=False, ignore_retcode=True ) diff --git a/salt/modules/freezer.py b/salt/modules/freezer.py index 296a26bf5bb..329cff98c3e 100644 --- a/salt/modules/freezer.py +++ b/salt/modules/freezer.py @@ -49,8 +49,8 @@ def _paths(name=None): name = "freezer" if not name else name states_path = _states_path() return ( - os.path.join(states_path, "{}-pkgs.yml".format(name)), - os.path.join(states_path, "{}-reps.yml".format(name)), + os.path.join(states_path, f"{name}-pkgs.yml"), + os.path.join(states_path, f"{name}-reps.yml"), ) diff --git a/salt/modules/genesis.py b/salt/modules/genesis.py index 5c2be12388a..4b9dca2351a 100644 --- a/salt/modules/genesis.py +++ b/salt/modules/genesis.py @@ -153,18 +153,18 @@ def bootstrap( if not img_size: raise SaltInvocationError("An img_size must be specified for a sparse file") if not mount_dir: - mount_dir = "/opt/salt-genesis.{}".format(uuid.uuid4()) + mount_dir = f"/opt/salt-genesis.{uuid.uuid4()}" __salt__["file.mkdir"](mount_dir, "root", "root", "755") __salt__["cmd.run"](("fallocate", "-l", img_size, root), python_shell=False) _mkpart(root, fs_format, fs_opts, mount_dir) loop1 = __salt__["cmd.run"]("losetup -f") log.debug("First loop device is %s", loop1) - __salt__["cmd.run"]("losetup {} {}".format(loop1, root)) + __salt__["cmd.run"](f"losetup {loop1} {root}") loop2 = __salt__["cmd.run"]("losetup -f") log.debug("Second loop device is %s", loop2) start = str(2048 * 2048) - __salt__["cmd.run"]("losetup -o {} {} {}".format(start, loop2, loop1)) + __salt__["cmd.run"](f"losetup -o {start} {loop2} {loop1}") __salt__["mount.mount"](mount_dir, loop2) _populate_cache(platform, pkg_cache, mount_dir) @@ -206,13 +206,13 @@ def bootstrap( if img_format != "dir": blkinfo = __salt__["disk.blkid"](loop2) __salt__["file.replace"]( - "{}/boot/grub/grub.cfg".format(mount_dir), + f"{mount_dir}/boot/grub/grub.cfg", "ad4103fa-d940-47ca-8506-301d8071d467", # This seems to be the default blkinfo[loop2]["UUID"], ) __salt__["mount.umount"](root) - __salt__["cmd.run"]("losetup -d {}".format(loop2)) - __salt__["cmd.run"]("losetup -d {}".format(loop1)) + __salt__["cmd.run"](f"losetup -d {loop2}") + __salt__["cmd.run"](f"losetup -d {loop1}") __salt__["file.rmdir"](mount_dir) @@ -225,7 +225,7 @@ def _mkpart(root, fs_format, fs_opts, mount_dir): __salt__["partition.mklabel"](root, "msdos") loop1 = __salt__["cmd.run"]("losetup -f") log.debug("First loop device is %s", loop1) - __salt__["cmd.run"]("losetup {} {}".format(loop1, root)) + __salt__["cmd.run"](f"losetup {loop1} {root}") part_info = __salt__["partition.list"](loop1) start = str(2048 * 2048) + "B" end = part_info["info"]["size"] @@ -235,7 +235,7 @@ def _mkpart(root, fs_format, fs_opts, mount_dir): loop2 = __salt__["cmd.run"]("losetup -f") log.debug("Second loop device is %s", loop2) start = start.rstrip("B") - __salt__["cmd.run"]("losetup -o {} {} {}".format(start, loop2, loop1)) + __salt__["cmd.run"](f"losetup -o {start} {loop2} {loop1}") _mkfs(loop2, fs_format, fs_opts) __salt__["mount.mount"](mount_dir, loop2) __salt__["cmd.run"]( @@ -245,14 +245,14 @@ def _mkpart(root, fs_format, fs_opts, mount_dir): "--debug", "--no-floppy", "--modules=part_msdos linux", - "--boot-directory={}/boot".format(mount_dir), + f"--boot-directory={mount_dir}/boot", loop1, ), python_shell=False, ) __salt__["mount.umount"](mount_dir) - __salt__["cmd.run"]("losetup -d {}".format(loop2)) - __salt__["cmd.run"]("losetup -d {}".format(loop1)) + __salt__["cmd.run"](f"losetup -d {loop2}") + __salt__["cmd.run"](f"losetup -d {loop1}") return part_info @@ -284,7 +284,7 @@ def _populate_cache(platform, pkg_cache, mount_dir): return if platform == "pacman": - cache_dir = "{}/var/cache/pacman/pkg".format(mount_dir) + cache_dir = f"{mount_dir}/var/cache/pacman/pkg" __salt__["file.mkdir"](cache_dir, "root", "root", "755") __salt__["file.copy"](pkg_cache, cache_dir, recurse=True, remove_existing=True) @@ -361,14 +361,14 @@ def _bootstrap_yum( yum_args = [ "yum", "install", - "--installroot={}".format(shlex.quote(root)), + f"--installroot={shlex.quote(root)}", "-y", ] + pkgs __salt__["cmd.run"](yum_args, python_shell=False) if "epel-release" not in exclude_pkgs: __salt__["cmd.run"]( - ("rpm", "--root={}".format(shlex.quote(root)), "-Uvh", epel_url), + ("rpm", f"--root={shlex.quote(root)}", "-Uvh", epel_url), python_shell=False, ) @@ -462,9 +462,7 @@ def _bootstrap_deb( ), env=env, ) - __salt__["cmd.run"]( - "chroot {root} dpkg --configure -a".format(root=shlex.quote(root)), env=env - ) + __salt__["cmd.run"](f"chroot {shlex.quote(root)} dpkg --configure -a", env=env) def _bootstrap_pacman( @@ -519,25 +517,23 @@ def _bootstrap_pacman( pkgs.remove(pkg) if img_format != "dir": - __salt__["mount.mount"]("{}/proc".format(root), "/proc", fstype="", opts="bind") - __salt__["mount.mount"]("{}/dev".format(root), "/dev", fstype="", opts="bind") + __salt__["mount.mount"](f"{root}/proc", "/proc", fstype="", opts="bind") + __salt__["mount.mount"](f"{root}/dev", "/dev", fstype="", opts="bind") - __salt__["file.mkdir"]( - "{}/var/lib/pacman/local".format(root), "root", "root", "755" - ) + __salt__["file.mkdir"](f"{root}/var/lib/pacman/local", "root", "root", "755") pac_files = [rf for rf in os.listdir("/etc") if rf.startswith("pacman.")] for pac_file in pac_files: - __salt__["cmd.run"]("cp -r /etc/{} {}/etc".format(pac_file, shlex.quote(root))) + __salt__["cmd.run"](f"cp -r /etc/{pac_file} {shlex.quote(root)}/etc") __salt__["file.copy"]( - "/var/lib/pacman/sync", "{}/var/lib/pacman/sync".format(root), recurse=True + "/var/lib/pacman/sync", f"{root}/var/lib/pacman/sync", recurse=True ) pacman_args = ["pacman", "--noconfirm", "-r", shlex.quote(root), "-S"] + pkgs __salt__["cmd.run"](pacman_args, python_shell=False) if img_format != "dir": - __salt__["mount.umount"]("{}/proc".format(root)) - __salt__["mount.umount"]("{}/dev".format(root)) + __salt__["mount.umount"](f"{root}/proc") + __salt__["mount.umount"](f"{root}/dev") def _make_nodes(root): @@ -547,24 +543,24 @@ def _make_nodes(root): https://wiki.archlinux.org/index.php/Linux_Containers """ dirs = ( - ("{}/etc".format(root), "root", "root", "755"), - ("{}/dev".format(root), "root", "root", "755"), - ("{}/proc".format(root), "root", "root", "755"), - ("{}/dev/pts".format(root), "root", "root", "755"), - ("{}/dev/shm".format(root), "root", "root", "1755"), + (f"{root}/etc", "root", "root", "755"), + (f"{root}/dev", "root", "root", "755"), + (f"{root}/proc", "root", "root", "755"), + (f"{root}/dev/pts", "root", "root", "755"), + (f"{root}/dev/shm", "root", "root", "1755"), ) nodes = ( - ("{}/dev/null".format(root), "c", 1, 3, "root", "root", "666"), - ("{}/dev/zero".format(root), "c", 1, 5, "root", "root", "666"), - ("{}/dev/random".format(root), "c", 1, 8, "root", "root", "666"), - ("{}/dev/urandom".format(root), "c", 1, 9, "root", "root", "666"), - ("{}/dev/tty".format(root), "c", 5, 0, "root", "root", "666"), - ("{}/dev/tty0".format(root), "c", 4, 0, "root", "root", "666"), - ("{}/dev/console".format(root), "c", 5, 1, "root", "root", "600"), - ("{}/dev/full".format(root), "c", 1, 7, "root", "root", "666"), - ("{}/dev/initctl".format(root), "p", 0, 0, "root", "root", "600"), - ("{}/dev/ptmx".format(root), "c", 5, 2, "root", "root", "666"), + (f"{root}/dev/null", "c", 1, 3, "root", "root", "666"), + (f"{root}/dev/zero", "c", 1, 5, "root", "root", "666"), + (f"{root}/dev/random", "c", 1, 8, "root", "root", "666"), + (f"{root}/dev/urandom", "c", 1, 9, "root", "root", "666"), + (f"{root}/dev/tty", "c", 5, 0, "root", "root", "666"), + (f"{root}/dev/tty0", "c", 4, 0, "root", "root", "666"), + (f"{root}/dev/console", "c", 5, 1, "root", "root", "600"), + (f"{root}/dev/full", "c", 1, 7, "root", "root", "666"), + (f"{root}/dev/initctl", "p", 0, 0, "root", "root", "600"), + (f"{root}/dev/ptmx", "c", 5, 2, "root", "root", "666"), ) for path in dirs: @@ -636,9 +632,9 @@ def _tar(name, root, path=None, compress="bzip2"): compression, ext = _compress(compress) - tarfile = "{}/{}.tar.{}".format(path, name, ext) + tarfile = f"{path}/{name}.tar.{ext}" out = __salt__["archive.tar"]( - options="{}pcf".format(compression), + options=f"{compression}pcf", tarfile=tarfile, sources=".", dest=root, @@ -663,9 +659,9 @@ def _untar(name, dest=None, path=None, compress="bz2"): compression, ext = _compress(compress) - tarfile = "{}/{}.tar.{}".format(path, name, ext) + tarfile = f"{path}/{name}.tar.{ext}" out = __salt__["archive.tar"]( - options="{}xf".format(compression), + options=f"{compression}xf", tarfile=tarfile, dest=dest, ) diff --git a/salt/modules/gentoo_service.py b/salt/modules/gentoo_service.py index 5a35ba0fcbd..ede473e6779 100644 --- a/salt/modules/gentoo_service.py +++ b/salt/modules/gentoo_service.py @@ -9,7 +9,6 @@ to the correct service manager `. """ - import fnmatch import logging import re diff --git a/salt/modules/gentoolkitmod.py b/salt/modules/gentoolkitmod.py index 19e7b45f6fa..da8f803a786 100644 --- a/salt/modules/gentoolkitmod.py +++ b/salt/modules/gentoolkitmod.py @@ -50,7 +50,7 @@ def revdep_rebuild(lib=None): """ cmd = "revdep-rebuild -i --quiet --no-progress" if lib is not None: - cmd += " --library={}".format(lib) + cmd += f" --library={lib}" return __salt__["cmd.retcode"](cmd, python_shell=False) == 0 @@ -62,7 +62,7 @@ def _pretty_size(size): while units and size >= 1000: size = size / 1024.0 units.pop() - return "{}{}".format(round(size, 1), units[-1]) + return f"{round(size, 1)}{units[-1]}" def _parse_exclude(exclude_file): @@ -137,7 +137,7 @@ def eclean_dist( try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: - ret = {e: "Invalid exclusion file: {}".format(exclude_file)} + ret = {e: f"Invalid exclusion file: {exclude_file}"} return ret if time_limit != 0: @@ -221,7 +221,7 @@ def eclean_pkg( try: exclude = _parse_exclude(exclude_file) except excludemod.ParseExcludeFileException as e: - ret = {e: "Invalid exclusion file: {}".format(exclude_file)} + ret = {e: f"Invalid exclusion file: {exclude_file}"} return ret if time_limit != 0: diff --git a/salt/modules/github.py b/salt/modules/github.py index bc45f9cae96..54b5b1d167a 100644 --- a/salt/modules/github.py +++ b/salt/modules/github.py @@ -29,7 +29,6 @@ For example: allow_repo_privacy_changes: False """ - import logging import salt.utils.http @@ -119,7 +118,7 @@ def _get_members(organization, params=None): def _get_repos(profile, params=None, ignore_cache=False): # Use cache when no params are given org_name = _get_config_value(profile, "org_name") - key = "github.{}:repos".format(org_name) + key = f"github.{org_name}:repos" if key not in __context__ or ignore_cache or params is not None: org_name = _get_config_value(profile, "org_name") @@ -143,7 +142,7 @@ def _get_repos(profile, params=None, ignore_cache=False): next_result.append(repo) # Cache a copy of each repo for single lookups - repo_key = "github.{}:{}:repo_info".format(org_name, repo.name.lower()) + repo_key = f"github.{org_name}:{repo.name.lower()}:repo_info" __context__[repo_key] = _repo_to_dict(repo) __context__[key] = next_result @@ -171,7 +170,7 @@ def list_users(profile="github", ignore_cache=False): salt myminion github.list_users profile='my-github-profile' """ org_name = _get_config_value(profile, "org_name") - key = "github.{}:users".format(org_name) + key = f"github.{org_name}:users" if key not in __context__ or ignore_cache: client = _get_client(profile) organization = client.get_organization(org_name) @@ -1834,7 +1833,7 @@ def _query( url += action if command: - url += "/{}".format(command) + url += f"/{command}" log.debug("GitHub URL: %s", url) diff --git a/salt/modules/glanceng.py b/salt/modules/glanceng.py index 7f1b824b0f6..85a76dc650a 100644 --- a/salt/modules/glanceng.py +++ b/salt/modules/glanceng.py @@ -25,7 +25,6 @@ Example configuration identity_api_version: 3 """ - HAS_SHADE = False try: import shade diff --git a/salt/modules/glassfish.py b/salt/modules/glassfish.py index 637264e7331..a41f21e419b 100644 --- a/salt/modules/glassfish.py +++ b/salt/modules/glassfish.py @@ -70,9 +70,9 @@ def _get_url(ssl, url, port, path): Returns the URL of the endpoint """ if ssl: - return "https://{}:{}/management/domain/{}".format(url, port, path) + return f"https://{url}:{port}/management/domain/{path}" else: - return "http://{}:{}/management/domain/{}".format(url, port, path) + return f"http://{url}:{port}/management/domain/{path}" def _get_server(server): @@ -180,7 +180,7 @@ def _get_element_properties(name, element_type, server=None): Get an element's properties """ properties = {} - data = _api_get("{}/{}/property".format(element_type, name), server) + data = _api_get(f"{element_type}/{name}/property", server) # Get properties into a dict if any(data["extraProperties"]["properties"]): @@ -196,7 +196,7 @@ def _get_element(name, element_type, server=None, with_properties=True): """ element = {} name = urllib.parse.quote(name, safe="") - data = _api_get("{}/{}".format(element_type, name), server) + data = _api_get(f"{element_type}/{name}", server) # Format data, get properties if asked, and return the whole thing if any(data["extraProperties"]["entity"]): @@ -239,7 +239,7 @@ def _update_element(name, element_type, data, server=None): properties = [] for key, value in data["properties"].items(): properties.append({"name": key, "value": value}) - _api_post("{}/{}/property".format(element_type, name), properties, server) + _api_post(f"{element_type}/{name}/property", properties, server) del data["properties"] # If the element only contained properties @@ -252,10 +252,10 @@ def _update_element(name, element_type, data, server=None): update_data.update(data) else: __context__["retcode"] = salt.defaults.exitcodes.SALT_BUILD_FAIL - raise CommandExecutionError("Cannot update {}".format(name)) + raise CommandExecutionError(f"Cannot update {name}") # Finally, update the element - _api_post("{}/{}".format(element_type, name), _clean_data(update_data), server) + _api_post(f"{element_type}/{name}", _clean_data(update_data), server) return urllib.parse.unquote(name) @@ -691,4 +691,4 @@ def delete_system_properties(name, server=None): """ Delete a system property """ - _api_delete("system-properties/{}".format(name), None, server) + _api_delete(f"system-properties/{name}", None, server) diff --git a/salt/modules/glusterfs.py b/salt/modules/glusterfs.py index 5de5110df35..b1ba1e2cb8e 100644 --- a/salt/modules/glusterfs.py +++ b/salt/modules/glusterfs.py @@ -73,12 +73,10 @@ def _gluster_xml(cmd): 6, ): result = __salt__["cmd.run"]( - 'script -q -c "gluster --xml --mode=script"', stdin="{}\n\004".format(cmd) + 'script -q -c "gluster --xml --mode=script"', stdin=f"{cmd}\n\004" ) else: - result = __salt__["cmd.run"]( - "gluster --xml --mode=script", stdin="{}\n".format(cmd) - ) + result = __salt__["cmd.run"]("gluster --xml --mode=script", stdin=f"{cmd}\n") try: root = ET.fromstring(_gluster_output_cleanup(result)) @@ -206,9 +204,9 @@ def peer(name): """ if salt.utils.cloud.check_name(name, "a-zA-Z0-9._-"): - raise SaltInvocationError('Invalid characters in peer name "{}"'.format(name)) + raise SaltInvocationError(f'Invalid characters in peer name "{name}"') - cmd = "peer probe {}".format(name) + cmd = f"peer probe {name}" return _gluster(cmd) @@ -288,13 +286,9 @@ def create_volume( try: peer_name, path = brick.split(":") if not path.startswith("/"): - raise SaltInvocationError( - "Brick paths must start with / in {}".format(brick) - ) + raise SaltInvocationError(f"Brick paths must start with / in {brick}") except ValueError: - raise SaltInvocationError( - "Brick syntax is : got {}".format(brick) - ) + raise SaltInvocationError(f"Brick syntax is : got {brick}") # Validate arbiter config if arbiter and replica != 3: @@ -303,17 +297,17 @@ def create_volume( ) # Format creation call - cmd = "volume create {} ".format(name) + cmd = f"volume create {name} " if stripe: - cmd += "stripe {} ".format(stripe) + cmd += f"stripe {stripe} " if replica: - cmd += "replica {} ".format(replica) + cmd += f"replica {replica} " if arbiter: cmd += "arbiter 1 " if device_vg: cmd += "device vg " if transport != "tcp": - cmd += "transport {} ".format(transport) + cmd += f"transport {transport} " cmd += " ".join(bricks) if force: cmd += " force" @@ -358,7 +352,7 @@ def status(name): salt '*' glusterfs.status myvolume """ # Get volume status - root = _gluster_xml("volume status {}".format(name)) + root = _gluster_xml(f"volume status {name}") if not _gluster_ok(root): # Most probably non-existing volume, the error output is logged # This return value is easy to test and intuitive @@ -384,7 +378,7 @@ def status(name): hostname = node.find("hostname").text if hostname not in ("NFS Server", "Self-heal Daemon"): path = node.find("path").text - ret["bricks"]["{}:{}".format(hostname, path)] = etree_legacy_wrap(node) + ret["bricks"][f"{hostname}:{path}"] = etree_legacy_wrap(node) elif hostname == "NFS Server": peerid = node.find("peerid").text true_hostname = hostref[peerid] @@ -427,7 +421,7 @@ def info(name=None): bricks = {} for i, brick in enumerate(_iter(volume, "brick"), start=1): - brickkey = "brick{}".format(i) + brickkey = f"brick{i}" bricks[brickkey] = {"path": brick.text} for child in brick: if not child.tag == "name": @@ -461,9 +455,9 @@ def start_volume(name, force=False): salt '*' glusterfs.start mycluster """ - cmd = "volume start {}".format(name) + cmd = f"volume start {name}" if force: - cmd = "{} force".format(cmd) + cmd = f"{cmd} force" volinfo = info(name) if name not in volinfo: @@ -503,7 +497,7 @@ def stop_volume(name, force=False): log.warning("Attempt to stop already stopped volume %s", name) return True - cmd = "volume stop {}".format(name) + cmd = f"volume stop {name}" if force: cmd += " force" @@ -543,7 +537,7 @@ def delete_volume(target, stop=True): if not stop_volume(target, force=True): return False - cmd = "volume delete {}".format(target) + cmd = f"volume delete {target}" return _gluster(cmd) @@ -571,7 +565,7 @@ def add_volume_bricks(name, bricks): new_bricks = [] - cmd = "volume add-brick {}".format(name) + cmd = f"volume add-brick {name}" if isinstance(bricks, str): bricks = [bricks] @@ -588,7 +582,7 @@ def add_volume_bricks(name, bricks): if new_bricks: for brick in new_bricks: - cmd += " {}".format(brick) + cmd += f" {brick}" return _gluster(cmd) return True @@ -607,7 +601,7 @@ def enable_quota_volume(name): salt '*' glusterfs.enable_quota_volume """ - cmd = "volume quota {} enable".format(name) + cmd = f"volume quota {name} enable" if not _gluster(cmd): return False return True @@ -627,7 +621,7 @@ def disable_quota_volume(name): salt '*' glusterfs.disable_quota_volume """ - cmd = "volume quota {} disable".format(name) + cmd = f"volume quota {name} disable" if not _gluster(cmd): return False return True @@ -655,11 +649,11 @@ def set_quota_volume(name, path, size, enable_quota=False): salt '*' glusterfs.set_quota_volume enable_quota=True """ - cmd = "volume quota {}".format(name) + cmd = f"volume quota {name}" if path: - cmd += " limit-usage {}".format(path) + cmd += f" limit-usage {path}" if size: - cmd += " {}".format(size) + cmd += f" {size}" if enable_quota: if not enable_quota_volume(name): @@ -685,9 +679,9 @@ def unset_quota_volume(name, path): salt '*' glusterfs.unset_quota_volume """ - cmd = "volume quota {}".format(name) + cmd = f"volume quota {name}" if path: - cmd += " remove {}".format(path) + cmd += f" remove {path}" if not _gluster(cmd): return False @@ -707,7 +701,7 @@ def list_quota_volume(name): salt '*' glusterfs.list_quota_volume """ - cmd = "volume quota {}".format(name) + cmd = f"volume quota {name}" cmd += " list" root = _gluster_xml(cmd) @@ -738,7 +732,7 @@ def get_op_version(name): salt '*' glusterfs.get_op_version """ - cmd = "volume get {} cluster.op-version".format(name) + cmd = f"volume get {name} cluster.op-version" root = _gluster_xml(cmd) if not _gluster_ok(root): @@ -816,7 +810,7 @@ def set_op_version(version): salt '*' glusterfs.set_op_version """ - cmd = "volume set all cluster.op-version {}".format(version) + cmd = f"volume set all cluster.op-version {version}" root = _gluster_xml(cmd) if not _gluster_ok(root): diff --git a/salt/modules/gnomedesktop.py b/salt/modules/gnomedesktop.py index abefaeb8586..15553f5fe75 100644 --- a/salt/modules/gnomedesktop.py +++ b/salt/modules/gnomedesktop.py @@ -2,7 +2,6 @@ GNOME implementations """ - import logging import re @@ -78,7 +77,7 @@ class _GSettings: cmd = self.gsetting_command + ["get", str(self.SCHEMA), str(self.KEY)] environ = {} - environ["XDG_RUNTIME_DIR"] = "/run/user/{}".format(uid) + environ["XDG_RUNTIME_DIR"] = f"/run/user/{uid}" result = __salt__["cmd.run_all"]( cmd, runas=user, env=environ, python_shell=False ) @@ -103,12 +102,12 @@ class _GSettings: log.info("User does not exist") result = {} result["retcode"] = 1 - result["stdout"] = "User {} does not exist".format(user) + result["stdout"] = f"User {user} does not exist" return result cmd = self.gsetting_command + ["set", self.SCHEMA, self.KEY, value] environ = {} - environ["XDG_RUNTIME_DIR"] = "/run/user/{}".format(uid) + environ["XDG_RUNTIME_DIR"] = f"/run/user/{uid}" result = __salt__["cmd.run_all"]( cmd, runas=user, env=environ, python_shell=False ) diff --git a/salt/modules/gpg.py b/salt/modules/gpg.py index 538228214f8..cdfd6a149f4 100644 --- a/salt/modules/gpg.py +++ b/salt/modules/gpg.py @@ -652,9 +652,9 @@ def delete_key( if skey: if not delete_secret: ret["res"] = False - ret[ - "message" - ] = "Secret key exists, delete first or pass delete_secret=True." + ret["message"] = ( + "Secret key exists, delete first or pass delete_secret=True." + ) return ret else: out = __delete_key(fingerprint, True, use_passphrase) @@ -663,9 +663,9 @@ def delete_key( ret["message"] = f"Secret key for {fingerprint} deleted\n" else: ret["res"] = False - ret[ - "message" - ] = f"Failed to delete secret key for {fingerprint}: {out}" + ret["message"] = ( + f"Failed to delete secret key for {fingerprint}: {out}" + ) return ret # Delete the public key @@ -1401,9 +1401,11 @@ def verify( "username": sig.get("username"), "key_id": sig["keyid"], "fingerprint": sig["pubkey_fingerprint"], - "trust_level": VERIFY_TRUST_LEVELS[str(sig["trust_level"])] - if "trust_level" in sig - else None, + "trust_level": ( + VERIFY_TRUST_LEVELS[str(sig["trust_level"])] + if "trust_level" in sig + else None + ), "status": sig["status"], } for sig in verified.sig_info.values() @@ -1431,9 +1433,9 @@ def verify( if not any_signed: ret["res"] = False - ret[ - "message" - ] = "None of the public keys listed in signed_by_any provided a valid signature" + ret["message"] = ( + "None of the public keys listed in signed_by_any provided a valid signature" + ) return ret any_check = True @@ -1451,9 +1453,9 @@ def verify( except (KeyError, IndexError): pass ret["res"] = False - ret[ - "message" - ] = f"Public key {signer} has not provided a valid signature, but was listed in signed_by_all" + ret["message"] = ( + f"Public key {signer} has not provided a valid signature, but was listed in signed_by_all" + ) return ret all_check = True @@ -1463,9 +1465,9 @@ def verify( return ret ret["res"] = False - ret[ - "message" - ] = "Something went wrong while checking for specific signers. This is most likely a bug" + ret["message"] = ( + "Something went wrong while checking for specific signers. This is most likely a bug" + ) return ret diff --git a/salt/modules/grains.py b/salt/modules/grains.py index 9c474a94a64..f60fb1bb053 100644 --- a/salt/modules/grains.py +++ b/salt/modules/grains.py @@ -9,7 +9,6 @@ file on the minions. By default, this file is located at: ``/etc/salt/grains`` This does **NOT** override any grains set in the minion config file. """ - import collections import logging import math @@ -255,7 +254,7 @@ def setvals(grains, destructive=False, refresh_pillar=True): try: grains = salt.utils.yaml.safe_load(fp_) except salt.utils.yaml.YAMLError as exc: - return "Unable to read existing grains file: {}".format(exc) + return f"Unable to read existing grains file: {exc}" if not isinstance(grains, dict): grains = {} for key, val in new_grains.items(): @@ -351,9 +350,9 @@ def append(key, val, convert=False, delimiter=DEFAULT_TARGET_DELIM): if not isinstance(grains, list): grains = [] if grains is None else [grains] if not isinstance(grains, list): - return "The key {} is not a valid list".format(key) + return f"The key {key} is not a valid list" if val in grains: - return "The val {} was already in the list {}".format(val, key) + return f"The val {val} was already in the list {key}" if isinstance(val, list): for item in val: grains.append(item) @@ -398,9 +397,9 @@ def remove(key, val, delimiter=DEFAULT_TARGET_DELIM): """ grains = get(key, [], delimiter) if not isinstance(grains, list): - return "The key {} is not a valid list".format(key) + return f"The key {key} is not a valid list" if val not in grains: - return "The val {} was not in the list {}".format(val, key) + return f"The val {val} was not in the list {key}" grains.remove(val) while delimiter in key: diff --git a/salt/modules/grub_legacy.py b/salt/modules/grub_legacy.py index 7bb46f8be9a..08851e7954a 100644 --- a/salt/modules/grub_legacy.py +++ b/salt/modules/grub_legacy.py @@ -75,14 +75,14 @@ def conf(): if line.startswith("\n"): in_stanza = False if "title" in stanza: - stanza += "order {}".format(pos) + stanza += f"order {pos}" pos += 1 stanzas.append(stanza) stanza = "" continue if line.strip().startswith("title"): if in_stanza: - stanza += "order {}".format(pos) + stanza += f"order {pos}" pos += 1 stanzas.append(stanza) stanza = "" @@ -97,7 +97,7 @@ def conf(): if not line.endswith("\n"): line += "\n" stanza += line - stanza += "order {}".format(pos) + stanza += f"order {pos}" pos += 1 stanzas.append(stanza) except OSError as exc: diff --git a/salt/modules/haproxyconn.py b/salt/modules/haproxyconn.py index f9e156572bc..712eb018d06 100644 --- a/salt/modules/haproxyconn.py +++ b/salt/modules/haproxyconn.py @@ -4,7 +4,6 @@ Support for haproxy .. versionadded:: 2014.7.0 """ - import logging import os import stat @@ -48,9 +47,9 @@ def _get_conn(socket=DEFAULT_SOCKET_URL): """ Get connection to haproxy socket. """ - assert os.path.exists(socket), "{} does not exist.".format(socket) + assert os.path.exists(socket), f"{socket} does not exist." issock = os.stat(socket).st_mode - assert stat.S_ISSOCK(issock), "{} is not a socket.".format(socket) + assert stat.S_ISSOCK(issock), f"{socket} is not a socket." ha_conn = haproxy.conn.HaPConn(socket) return ha_conn @@ -315,6 +314,7 @@ def set_state(name, backend, state, socket=DEFAULT_SOCKET_URL): salt '*' haproxy.set_state my_proxy_server my_backend ready """ + # Pulling this in from the latest 0.5 release which is not yet in PyPi. # https://github.com/neurogeek/haproxyctl class setServerState(haproxy.cmds.Cmd): diff --git a/salt/modules/hashutil.py b/salt/modules/hashutil.py index 9e834794e4e..3517f2512ac 100644 --- a/salt/modules/hashutil.py +++ b/salt/modules/hashutil.py @@ -2,7 +2,6 @@ A collection of hashing and encoding functions """ - import base64 import hashlib import hmac diff --git a/salt/modules/heat.py b/salt/modules/heat.py index 40540fe7cf0..b26277c1488 100644 --- a/salt/modules/heat.py +++ b/salt/modules/heat.py @@ -212,7 +212,7 @@ def _parse_environment(env_str): for param in env: if param not in SECTIONS: - raise ValueError('environment has wrong section "{}"'.format(param)) + raise ValueError(f'environment has wrong section "{param}"') return env @@ -240,7 +240,7 @@ def _poll_for_events( Polling stack events """ if action: - stop_status = ("{}_FAILED".format(action), "{}_COMPLETE".format(action)) + stop_status = (f"{action}_FAILED", f"{action}_COMPLETE") stop_check = lambda a: a in stop_status else: stop_check = lambda a: a.endswith("_COMPLETE") or a.endswith("_FAILED") @@ -281,7 +281,7 @@ def _poll_for_events( time.sleep(poll_period) timeout_sec -= poll_period if timeout_sec <= 0: - stack_status = "{}_FAILED".format(action) + stack_status = f"{action}_FAILED" msg = "Timeout expired" return stack_status, msg @@ -354,7 +354,7 @@ def show_stack(name=None, profile=None): } ret["result"] = True except heatclient.exc.HTTPNotFound: - return {"result": False, "comment": "No stack {}".format(name)} + return {"result": False, "comment": f"No stack {name}"} return ret @@ -391,7 +391,7 @@ def delete_stack(name=None, poll=0, timeout=60, profile=None): h_client.stacks.delete(name) except heatclient.exc.HTTPNotFound: ret["result"] = False - ret["comment"] = "No stack {}".format(name) + ret["comment"] = f"No stack {name}" except heatclient.exc.HTTPForbidden as forbidden: log.exception(forbidden) ret["result"] = False @@ -405,19 +405,19 @@ def delete_stack(name=None, poll=0, timeout=60, profile=None): h_client, name, action="DELETE", poll_period=poll, timeout=timeout ) except heatclient.exc.CommandError: - ret["comment"] = "Deleted stack {}.".format(name) + ret["comment"] = f"Deleted stack {name}." return ret except Exception as ex: # pylint: disable=W0703 log.exception("Delete failed %s", ex) ret["result"] = False - ret["comment"] = "{}".format(ex) + ret["comment"] = f"{ex}" return ret if stack_status == "DELETE_FAILED": ret["result"] = False - ret["comment"] = "Deleted stack FAILED'{}'{}.".format(name, msg) + ret["comment"] = f"Deleted stack FAILED'{name}'{msg}." else: - ret["comment"] = "Deleted stack {}.".format(name) + ret["comment"] = f"Deleted stack {name}." return ret @@ -523,7 +523,7 @@ def create_stack( template = _parse_template(tpl) except ValueError as ex: ret["result"] = False - ret["comment"] = "Error parsing template {}".format(ex) + ret["comment"] = f"Error parsing template {ex}" else: ret["result"] = False ret["comment"] = "Can not open template: {} {}".format( @@ -542,7 +542,7 @@ def create_stack( except Exception as ex: # pylint: disable=W0703 log.exception("Template not valid %s", ex) ret["result"] = False - ret["comment"] = "Template not valid {}".format(ex) + ret["comment"] = f"Template not valid {ex}" return ret env = {} if environment: @@ -590,7 +590,7 @@ def create_stack( env = _parse_environment(env_str) except ValueError as ex: ret["result"] = False - ret["comment"] = "Error parsing template {}".format(ex) + ret["comment"] = f"Error parsing template {ex}" else: ret["result"] = False ret["comment"] = "Can not open environment: {}, {}".format( @@ -614,7 +614,7 @@ def create_stack( except Exception as ex: # pylint: disable=W0703 log.exception("Create failed %s", ex) ret["result"] = False - ret["comment"] = "{}".format(ex) + ret["comment"] = f"{ex}" return ret if poll > 0: stack_status, msg = _poll_for_events( @@ -622,9 +622,9 @@ def create_stack( ) if stack_status == "CREATE_FAILED": ret["result"] = False - ret["comment"] = "Created stack FAILED'{}'{}.".format(name, msg) + ret["comment"] = f"Created stack FAILED'{name}'{msg}." if ret["result"] is True: - ret["comment"] = "Created stack '{}'.".format(name) + ret["comment"] = f"Created stack '{name}'." return ret @@ -734,7 +734,7 @@ def update_stack( template = _parse_template(tpl) except ValueError as ex: ret["result"] = False - ret["comment"] = "Error parsing template {}".format(ex) + ret["comment"] = f"Error parsing template {ex}" else: ret["result"] = False ret["comment"] = "Can not open template: {} {}".format( @@ -753,7 +753,7 @@ def update_stack( except Exception as ex: # pylint: disable=W0703 log.exception("Template not valid %s", ex) ret["result"] = False - ret["comment"] = "Template not valid {}".format(ex) + ret["comment"] = f"Template not valid {ex}" return ret env = {} if environment: @@ -801,7 +801,7 @@ def update_stack( env = _parse_environment(env_str) except ValueError as ex: ret["result"] = False - ret["comment"] = "Error parsing template {}".format(ex) + ret["comment"] = f"Error parsing template {ex}" else: ret["result"] = False ret["comment"] = "Can not open environment: {}, {}".format( @@ -823,7 +823,7 @@ def update_stack( except Exception as ex: # pylint: disable=W0703 log.exception("Update failed %s", ex) ret["result"] = False - ret["comment"] = "Update failed {}".format(ex) + ret["comment"] = f"Update failed {ex}" return ret if poll > 0: @@ -832,9 +832,9 @@ def update_stack( ) if stack_status == "UPDATE_FAILED": ret["result"] = False - ret["comment"] = "Updated stack FAILED'{}'{}.".format(name, msg) + ret["comment"] = f"Updated stack FAILED'{name}'{msg}." if ret["result"] is True: - ret["comment"] = ("Updated stack '{}'.".format(name),) + ret["comment"] = (f"Updated stack '{name}'.",) return ret @@ -861,9 +861,9 @@ def template_stack(name=None, profile=None): try: get_template = h_client.stacks.template(name) except heatclient.exc.HTTPNotFound: - return {"result": False, "comment": "No stack with {}".format(name)} + return {"result": False, "comment": f"No stack with {name}"} except heatclient.exc.BadRequest: - return {"result": False, "comment": "Bad request fot stack {}".format(name)} + return {"result": False, "comment": f"Bad request fot stack {name}"} if "heat_template_version" in get_template: template = salt.utils.yaml.safe_dump(get_template) else: diff --git a/salt/modules/helm.py b/salt/modules/helm.py index 19790726716..960c90e87bf 100644 --- a/salt/modules/helm.py +++ b/salt/modules/helm.py @@ -32,7 +32,6 @@ Detailed Function Documentation ------------------------------- """ - import copy import logging import re @@ -1044,7 +1043,7 @@ def repo_manage( ) already_present = False - for (index, repo_present) in enumerate(repos_present): + for index, repo_present in enumerate(repos_present): if repo.get("name") == repo_present.get("name") and repo.get( "url" ) == repo_present.get("url"): diff --git a/salt/modules/hg.py b/salt/modules/hg.py index 2835a531494..9e1d9de6be1 100644 --- a/salt/modules/hg.py +++ b/salt/modules/hg.py @@ -2,7 +2,6 @@ Support for the Mercurial SCM """ - import logging import salt.utils.data @@ -23,7 +22,7 @@ def __virtual__(): def _ssh_flag(identity_path): - return ["--ssh", "ssh -i {}".format(identity_path)] + return ["--ssh", f"ssh -i {identity_path}"] def revision(cwd, rev="tip", short=False, user=None): @@ -48,7 +47,7 @@ def revision(cwd, rev="tip", short=False, user=None): salt '*' hg.revision /path/to/repo mybranch """ - cmd = ["hg", "id", "-i", "--debug" if not short else "", "-r", "{}".format(rev)] + cmd = ["hg", "id", "-i", "--debug" if not short else "", "-r", f"{rev}"] result = __salt__["cmd.run_all"](cmd, cwd=cwd, runas=user, python_shell=False) @@ -81,7 +80,7 @@ def describe(cwd, rev="tip", user=None): "hg", "log", "-r", - "{}".format(rev), + f"{rev}", "--template", "'{{latesttag}}-{{latesttagdistance}}-{{node|short}}'", ] @@ -125,16 +124,16 @@ def archive(cwd, output, rev="tip", fmt=None, prefix=None, user=None): cmd = [ "hg", "archive", - "{}".format(output), + f"{output}", "--rev", - "{}".format(rev), + f"{rev}", ] if fmt: cmd.append("--type") - cmd.append("{}".format(fmt)) + cmd.append(f"{fmt}") if prefix: cmd.append("--prefix") - cmd.append('"{}"'.format(prefix)) + cmd.append(f'"{prefix}"') return __salt__["cmd.run"](cmd, cwd=cwd, runas=user, python_shell=False) @@ -205,7 +204,7 @@ def update(cwd, rev, force=False, user=None): salt devserver1 hg.update /path/to/repo somebranch """ - cmd = ["hg", "update", "{}".format(rev)] + cmd = ["hg", "update", f"{rev}"] if force: cmd.append("-C") @@ -245,10 +244,10 @@ def clone(cwd, repository, opts=None, user=None, identity=None): salt '*' hg.clone /path/to/repo https://bitbucket.org/birkenfeld/sphinx """ - cmd = ["hg", "clone", "{}".format(repository), "{}".format(cwd)] + cmd = ["hg", "clone", f"{repository}", f"{cwd}"] if opts: for opt in opts.split(): - cmd.append("{}".format(opt)) + cmd.append(f"{opt}") if identity: cmd.extend(_ssh_flag(identity)) @@ -285,7 +284,7 @@ def status(cwd, opts=None, user=None): cmd = ["hg", "status"] if opts: for opt in opts.split(): - cmd.append("{}".format(opt)) + cmd.append(f"{opt}") out = __salt__["cmd.run_stdout"](cmd, cwd=cwd, runas=user, python_shell=False) types = { "M": "modified", diff --git a/salt/modules/highstate_doc.py b/salt/modules/highstate_doc.py index 9f0b89bffbf..a91f77b2afb 100644 --- a/salt/modules/highstate_doc.py +++ b/salt/modules/highstate_doc.py @@ -388,7 +388,7 @@ def _get_config(**kwargs): "note": None, } if "__salt__" in globals(): - config_key = "{}.config".format(__virtualname__) + config_key = f"{__virtualname__}.config" config.update(__salt__["config.get"](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(kwargs.keys()): @@ -437,7 +437,7 @@ def read_file(name): def render( jinja_template_text=None, jinja_template_function="highstate_doc.markdown_default_jinja_template", - **kwargs + **kwargs, ): """ Render highstate to a text format (default Markdown) @@ -573,13 +573,13 @@ def _format_markdown_system_file(filename, config): file_stats, whitelist=["user", "group", "mode", "uid", "gid", "size"] ) if y: - ret += "file stat {1}\n```\n{0}```\n".format(y, filename) + ret += f"file stat {filename}\n```\n{y}```\n" file_size = file_stats.get("size") if file_size <= config.get("max_render_file_size"): is_binary = True try: # TODO: this is linux only should find somthing portable - file_type = __salt__["cmd.shell"]("\\file -i '{}'".format(filename)) + file_type = __salt__["cmd.shell"](f"\\file -i '{filename}'") if "charset=binary" not in file_type: is_binary = False except Exception as ex: # pylint: disable=broad-except @@ -591,11 +591,11 @@ def _format_markdown_system_file(filename, config): with salt.utils.files.fopen(filename, "r") as f: file_data = salt.utils.stringutils.to_unicode(f.read()) file_data = _md_fix(file_data) - ret += "file data {1}\n```\n{0}\n```\n".format(file_data, filename) + ret += f"file data {filename}\n```\n{file_data}\n```\n" else: ret += "```\n{}\n```\n".format( "SKIPPED LARGE FILE!\nSet {}:max_render_file_size > {} to render.".format( - "{}.config".format(__virtualname__), file_size + f"{__virtualname__}.config", file_size ) ) return ret @@ -614,11 +614,11 @@ def _format_markdown_requisite(state, stateid, makelink=True): """ format requisite as a link users can click """ - fmt_id = "{}: {}".format(state, stateid) + fmt_id = f"{state}: {stateid}" if makelink: - return " * [{}](#{})\n".format(fmt_id, _format_markdown_link(fmt_id)) + return f" * [{fmt_id}](#{_format_markdown_link(fmt_id)})\n" else: - return " * `{}`\n".format(fmt_id) + return f" * `{fmt_id}`\n" def processor_markdown(lowstate_item, config, **kwargs): @@ -669,19 +669,19 @@ def processor_markdown(lowstate_item, config, **kwargs): if "source" in s: text = __salt__["cp.get_file_str"](s["source"]) if text: - details += "\n{}\n".format(text) + details += f"\n{text}\n" else: details += "\n{}\n".format("ERROR: opening {}".format(s["source"])) if state_function == "pkg.installed": pkgs = s.get("pkgs", s.get("name")) - details += "\n```\ninstall: {}\n```\n".format(pkgs) + details += f"\n```\ninstall: {pkgs}\n```\n" if state_function == "file.recurse": details += """recurse copy of files\n""" y = _state_data_to_yaml_string(s) if y: - details += "```\n{}\n```\n".format(y) + details += f"```\n{y}\n```\n" if "!doc_recurse" in id_full: findfiles = __salt__["file.find"](path=s.get("name"), type="f") if len(findfiles) < 10 or "!doc_recurse_force" in id_full: @@ -715,7 +715,7 @@ def processor_markdown(lowstate_item, config, **kwargs): if not details: y = _state_data_to_yaml_string(s) if y: - details += "```\n{}```\n".format(y) + details += f"```\n{y}```\n" r = { "vars": lowstate_item, diff --git a/salt/modules/hosts.py b/salt/modules/hosts.py index a8c4d412c2a..267fe056ad5 100644 --- a/salt/modules/hosts.py +++ b/salt/modules/hosts.py @@ -2,7 +2,6 @@ Manage the information in the hosts file """ - import errno import logging import os @@ -59,7 +58,7 @@ def _list_hosts(): if not line: continue if line.startswith("#"): - ret.setdefault("comment-{}".format(count), []).append(line) + ret.setdefault(f"comment-{count}", []).append(line) count += 1 continue comment = None diff --git a/salt/modules/http.py b/salt/modules/http.py index 44464eaa11b..6252b21dc16 100644 --- a/salt/modules/http.py +++ b/salt/modules/http.py @@ -5,7 +5,6 @@ like, but also useful for basic http testing. .. versionadded:: 2015.5.0 """ - import time import salt.utils.http diff --git a/salt/modules/icinga2.py b/salt/modules/icinga2.py index ef222ced217..391fb4abea7 100644 --- a/salt/modules/icinga2.py +++ b/salt/modules/icinga2.py @@ -6,7 +6,6 @@ Module to provide icinga2 compatibility to salt. :depends: - icinga2 server """ - import logging import salt.utils.path @@ -71,9 +70,9 @@ def generate_cert(domain): "--cn", domain, "--key", - "{}{}.key".format(get_certs_path(), domain), + f"{get_certs_path()}{domain}.key", "--cert", - "{}{}.crt".format(get_certs_path(), domain), + f"{get_certs_path()}{domain}.crt", ], python_shell=False, ) @@ -100,11 +99,11 @@ def save_cert(domain, master): "pki", "save-cert", "--key", - "{}{}.key".format(get_certs_path(), domain), + f"{get_certs_path()}{domain}.key", "--cert", - "{}{}.cert".format(get_certs_path(), domain), + f"{get_certs_path()}{domain}.cert", "--trustedcert", - "{}trusted-master.crt".format(get_certs_path()), + f"{get_certs_path()}trusted-master.crt", "--host", master, ], @@ -140,13 +139,13 @@ def request_cert(domain, master, ticket, port): "--ticket", ticket, "--key", - "{}{}.key".format(get_certs_path(), domain), + f"{get_certs_path()}{domain}.key", "--cert", - "{}{}.crt".format(get_certs_path(), domain), + f"{get_certs_path()}{domain}.crt", "--trustedcert", - "{}trusted-master.crt".format(get_certs_path()), + f"{get_certs_path()}trusted-master.crt", "--ca", - "{}ca.crt".format(get_certs_path()), + f"{get_certs_path()}ca.crt", ], python_shell=False, ) @@ -182,7 +181,7 @@ def node_setup(domain, master, ticket): "--master_host", master, "--trustedcert", - "{}trusted-master.crt".format(get_certs_path()), + f"{get_certs_path()}trusted-master.crt", ], python_shell=False, ) diff --git a/salt/modules/ifttt.py b/salt/modules/ifttt.py index 3c49b25a111..9126ab06b33 100644 --- a/salt/modules/ifttt.py +++ b/salt/modules/ifttt.py @@ -11,7 +11,6 @@ Requires an ``api_key`` in ``/etc/salt/minion``: secret_key: '280d4699-a817-4719-ba6f-ca56e573e44f' """ - import logging import time @@ -39,7 +38,7 @@ def _query(event=None, method="GET", args=None, header_dict=None, data=None): secret_key = __salt__["config.get"]("ifttt.secret_key") or __salt__["config.get"]( "ifttt:secret_key" ) - path = "https://maker.ifttt.com/trigger/{}/with/key/{}".format(event, secret_key) + path = f"https://maker.ifttt.com/trigger/{event}/with/key/{secret_key}" if header_dict is None: header_dict = {"Content-type": "application/json"} diff --git a/salt/modules/ilo.py b/salt/modules/ilo.py index c01e9da213c..c8d104fe797 100644 --- a/salt/modules/ilo.py +++ b/salt/modules/ilo.py @@ -47,7 +47,7 @@ def __execute_cmd(name, xml): tmpfilename = fh.name fh.write(xml) - cmd = __salt__["cmd.run_all"]("hponcfg -f {}".format(tmpfilename)) + cmd = __salt__["cmd.run_all"](f"hponcfg -f {tmpfilename}") # Clean up the temp file __salt__["file.remove"](tmpfilename) @@ -394,11 +394,7 @@ def create_user(name, password, *privileges): name, password, "\n".join( - [ - '<{} value="Y" />'.format(i.upper()) - for i in privileges - if i.upper() in _priv - ] + [f'<{i.upper()} value="Y" />' for i in privileges if i.upper() in _priv] ), ) diff --git a/salt/modules/incron.py b/salt/modules/incron.py index ad13c6de6e5..ad99b27aa3e 100644 --- a/salt/modules/incron.py +++ b/salt/modules/incron.py @@ -56,7 +56,7 @@ def _render_tab(lst): """ ret = [] for pre in lst["pre"]: - ret.append("{}\n".format(pre)) + ret.append(f"{pre}\n") for cron in lst["crons"]: ret.append( "{} {} {}\n".format( @@ -72,7 +72,7 @@ def _get_incron_cmdstr(path): """ Returns a format string, to be used to build an incrontab command. """ - return "incrontab {}".format(path) + return f"incrontab {path}" def write_incron_file(user, path): @@ -121,7 +121,7 @@ def _write_incron_lines(user, lines): with salt.utils.files.fopen(path, "wb") as fp_: fp_.writelines(salt.utils.data.encode(lines)) if user != "root": - __salt__["cmd.run"]("chown {} {}".format(user, path), python_shell=False) + __salt__["cmd.run"](f"chown {user} {path}", python_shell=False) ret = __salt__["cmd.run_all"]( _get_incron_cmdstr(path), runas=user, python_shell=False ) @@ -135,7 +135,7 @@ def _write_file(folder, filename, data): """ path = os.path.join(folder, filename) if not os.path.exists(folder): - msg = "{} cannot be written. {} does not exist".format(filename, folder) + msg = f"{filename} cannot be written. {folder} does not exist" log.error(msg) raise AttributeError(str(msg)) with salt.utils.files.fopen(path, "w") as fp_: @@ -180,7 +180,7 @@ def raw_incron(user): salt '*' incron.raw_incron root """ - cmd = "incrontab -l {}".format(user) + cmd = f"incrontab -l {user}" return __salt__["cmd.run_stdout"](cmd, rstrip=False, runas=user, python_shell=False) @@ -236,7 +236,7 @@ def set_job(user, path, mask, cmd): # Check for valid mask types for item in mask.split(","): if item not in _MASK_TYPES: - return "Invalid mask type: {}".format(item) + return f"Invalid mask type: {item}" updated = False arg_mask = mask.split(",") @@ -296,7 +296,7 @@ def rm_job(user, path, mask, cmd): # Check for valid mask types for item in mask.split(","): if item not in _MASK_TYPES: - return "Invalid mask type: {}".format(item) + return f"Invalid mask type: {item}" lst = list_tab(user) ret = "absent" diff --git a/salt/modules/influxdb08mod.py b/salt/modules/influxdb08mod.py index 8a46c7d4ef6..b48d08e0792 100644 --- a/salt/modules/influxdb08mod.py +++ b/salt/modules/influxdb08mod.py @@ -21,7 +21,6 @@ version 0.5-0.8) overwrite options passed into pillar. """ - import logging try: diff --git a/salt/modules/influxdbmod.py b/salt/modules/influxdbmod.py index 303ab044706..c8c1689d5d4 100644 --- a/salt/modules/influxdbmod.py +++ b/salt/modules/influxdbmod.py @@ -66,7 +66,7 @@ def _client( influxdb_password=None, influxdb_host=None, influxdb_port=None, - **client_args + **client_args, ): if not influxdb_user: influxdb_user = __salt__["config.option"]("influxdb.user", "root") @@ -84,7 +84,7 @@ def _client( port=influxdb_port, username=influxdb_user, password=influxdb_password, - **client_args + **client_args, ) @@ -635,7 +635,8 @@ 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: @@ -673,7 +674,7 @@ def drop_continuous_query(database, name, **client_args): """ client = _client(**client_args) - query = "DROP CONTINUOUS QUERY {} ON {}".format(name, database) + query = f"DROP CONTINUOUS QUERY {name} ON {database}" client.query(query) return True @@ -683,7 +684,7 @@ def _pull_query_results(resultset): Parses a ResultSet returned from InfluxDB into a dictionary of results, grouped by series names and optional JSON-encoded grouping tags. """ - _results = collections.defaultdict(lambda: {}) + _results = collections.defaultdict(dict) for _header, _values in resultset.items(): _header, _group_tags = _header if _group_tags: diff --git a/salt/modules/infoblox.py b/salt/modules/infoblox.py index a779b6322f9..14402e437d6 100644 --- a/salt/modules/infoblox.py +++ b/salt/modules/infoblox.py @@ -61,7 +61,7 @@ def _get_config(**api_opts): "api_key": "", } if "__salt__" in globals(): - config_key = "{}.config".format(__virtualname__) + config_key = f"{__virtualname__}.config" config.update(__salt__["config.get"](config_key, {})) # pylint: disable=C0201 for k in set(config.keys()) & set(api_opts.keys()): @@ -143,7 +143,7 @@ def update_object(objref, data, **api_opts): salt-call infoblox.update_object objref=[ref_of_object] data={} """ if "__opts__" in globals() and __opts__["test"]: - return {"Test": "Would attempt to update object: {}".format(objref)} + return {"Test": f"Would attempt to update object: {objref}"} infoblox = _get_infoblox(**api_opts) return infoblox.update_object(objref, data) @@ -159,7 +159,7 @@ def delete_object(objref, **api_opts): salt-call infoblox.delete_object objref=[ref_of_object] """ if "__opts__" in globals() and __opts__["test"]: - return {"Test": "Would attempt to delete object: {}".format(objref)} + return {"Test": f"Would attempt to delete object: {objref}"} infoblox = _get_infoblox(**api_opts) return infoblox.delete_object(objref) @@ -175,7 +175,7 @@ def create_object(object_type, data, **api_opts): salt-call infoblox.update_object object_type=record:host data={} """ if "__opts__" in globals() and __opts__["test"]: - return {"Test": "Would attempt to create object: {}".format(object_type)} + return {"Test": f"Would attempt to create object: {object_type}"} infoblox = _get_infoblox(**api_opts) return infoblox.create_object(object_type, data) @@ -186,7 +186,7 @@ def get_object( return_fields=None, max_results=None, ensure_none_or_one_result=False, - **api_opts + **api_opts, ): """ Get raw infoblox object. This is a low level api call. diff --git a/salt/modules/inspectlib/collector.py b/salt/modules/inspectlib/collector.py index 735f74d67de..d92646c9fc3 100644 --- a/salt/modules/inspectlib/collector.py +++ b/salt/modules/inspectlib/collector.py @@ -406,7 +406,7 @@ class Inspector(EnvLoader): all_links = list() for entry_path in [pth for pth in (allowed or os.listdir("/")) if pth]: if entry_path[0] != "/": - entry_path = "/{}".format(entry_path) + entry_path = f"/{entry_path}" if entry_path in ignored or os.path.islink(entry_path): continue e_files, e_dirs, e_links = self._get_all_files(entry_path, *ignored) @@ -490,7 +490,7 @@ class Inspector(EnvLoader): Take a snapshot of the system. """ if mode not in self.MODE: - raise InspectorSnapshotException("Unknown mode: '{}'".format(mode)) + raise InspectorSnapshotException(f"Unknown mode: '{mode}'") if is_alive(self.pidfile): raise CommandExecutionError("Inspection already in progress.") @@ -500,7 +500,7 @@ class Inspector(EnvLoader): subprocess.run( [ "nice", - "-{}".format(priority), + f"-{priority}", "python", __file__, os.path.dirname(self.pidfile), @@ -596,7 +596,7 @@ if __name__ == "__main__": with salt.utils.files.fopen( os.path.join(pidfile, EnvLoader.PID_FILE), "w" ) as fp_: - fp_.write("{}\n".format(pid)) + fp_.write(f"{pid}\n") sys.exit(0) except OSError as ex: sys.exit(1) diff --git a/salt/modules/inspectlib/fsdb.py b/salt/modules/inspectlib/fsdb.py index b834b8f6783..daa9a74ded4 100644 --- a/salt/modules/inspectlib/fsdb.py +++ b/salt/modules/inspectlib/fsdb.py @@ -187,7 +187,7 @@ class CsvDB: with gzip.open(os.path.join(self.db_path, obj._TABLE), "wt") as table_file: csv.writer(table_file).writerow( [ - "{col}:{type}".format(col=elm[0], type=get_type(elm[1])) + f"{elm[0]}:{get_type(elm[1])}" for elm in tuple(obj.__dict__.items()) ] ) @@ -270,7 +270,7 @@ class CsvDB: def _validate_object(self, obj): descr = self._tables.get(obj._TABLE) if descr is None: - raise Exception("Table {} not found.".format(obj._TABLE)) + raise Exception(f"Table {obj._TABLE} not found.") return obj._serialize(self._tables[obj._TABLE]) def __criteria(self, obj, matches=None, mt=None, lt=None, eq=None): diff --git a/salt/modules/inspectlib/kiwiproc.py b/salt/modules/inspectlib/kiwiproc.py index 321dfa8ff68..d3947ff5b00 100644 --- a/salt/modules/inspectlib/kiwiproc.py +++ b/salt/modules/inspectlib/kiwiproc.py @@ -247,11 +247,11 @@ class KiwiExporter: descr = etree.SubElement(node, "description") author = etree.SubElement(descr, "author") - author.text = "salt.modules.node on {}".format(hostname) + author.text = f"salt.modules.node on {hostname}" contact = etree.SubElement(descr, "contact") - contact.text = "root@{}".format(hostname) + contact.text = f"root@{hostname}" specs = etree.SubElement(descr, "specification") - specs.text = "Rebuild of {}, based on Salt inspection.".format(hostname) + specs.text = f"Rebuild of {hostname}, based on Salt inspection." return descr diff --git a/salt/modules/inspectlib/query.py b/salt/modules/inspectlib/query.py index 54494d6a104..cfc372486a0 100644 --- a/salt/modules/inspectlib/query.py +++ b/salt/modules/inspectlib/query.py @@ -35,7 +35,7 @@ class SysInfo: def __init__(self, systype): if systype.lower() == "solaris": - raise SIException("Platform {} not (yet) supported.".format(systype)) + raise SIException(f"Platform {systype} not (yet) supported.") def _grain(self, grain): """ @@ -47,7 +47,7 @@ class SysInfo: """ Get a size of a disk. """ - out = __salt__["cmd.run_all"]("df {}".format(device)) + out = __salt__["cmd.run_all"](f"df {device}") if out["retcode"]: msg = "Disk size info error: {}".format(out["stderr"]) log.error(msg) @@ -464,13 +464,13 @@ class Query(EnvLoader): fmt = fmt.lower() if fmt == "b": - return "{} Bytes".format(size) + return f"{size} Bytes" elif fmt == "kb": - return "{} Kb".format(round((float(size) / 0x400), 2)) + return f"{round((float(size) / 0x400), 2)} Kb" elif fmt == "mb": - return "{} Mb".format(round((float(size) / 0x400 / 0x400), 2)) + return f"{round((float(size) / 0x400 / 0x400), 2)} Mb" elif fmt == "gb": - return "{} Gb".format(round((float(size) / 0x400 / 0x400 / 0x400), 2)) + return f"{round((float(size) / 0x400 / 0x400 / 0x400), 2)} Gb" filter = kwargs.get("filter") offset = kwargs.get("offset", 0) @@ -478,7 +478,7 @@ class Query(EnvLoader): timeformat = kwargs.get("time", "tz") if timeformat not in ["ticks", "tz"]: raise InspectorQueryException( - 'Unknown "{}" value for parameter "time"'.format(timeformat) + f'Unknown "{timeformat}" value for parameter "time"' ) tfmt = ( lambda param: timeformat == "tz" diff --git a/salt/modules/inspector.py b/salt/modules/inspector.py index 02162cb564c..2d549e353a6 100644 --- a/salt/modules/inspector.py +++ b/salt/modules/inspector.py @@ -51,7 +51,7 @@ def _(module): import importlib - mod = importlib.import_module("salt.modules.inspectlib.{}".format(module)) + mod = importlib.import_module(f"salt.modules.inspectlib.{module}") mod.__grains__ = __grains__ mod.__pillar__ = __pillar__ mod.__salt__ = __salt__ diff --git a/salt/modules/iosconfig.py b/salt/modules/iosconfig.py index be0b58a5bd6..75d40756aee 100644 --- a/salt/modules/iosconfig.py +++ b/salt/modules/iosconfig.py @@ -166,7 +166,7 @@ def tree(config=None, path=None, with_tags=False, saltenv="base"): if path: config = __salt__["cp.get_file_str"](path, saltenv=saltenv) if config is False: - raise SaltException("{} is not available".format(path)) + raise SaltException(f"{path} is not available") config_lines = config.splitlines() return _parse_text_config(config_lines, with_tags=with_tags) diff --git a/salt/modules/ipmi.py b/salt/modules/ipmi.py index a30a8fb5a14..133b1161c6a 100644 --- a/salt/modules/ipmi.py +++ b/salt/modules/ipmi.py @@ -30,7 +30,6 @@ systems hardware through IPMI drivers. It uses a python module `pyghmi`. uid=1 """ - IMPORT_ERR = None try: from pyghmi.ipmi import command # nosec @@ -58,7 +57,7 @@ def _get_config(**kwargs): "api_login_timeout": 2, } if "__salt__" in globals(): - config_key = "{}.config".format(__virtualname__) + config_key = f"{__virtualname__}.config" config.update(__salt__["config.get"](config_key, {})) for k in set(config) & set(kwargs): config[k] = kwargs[k] @@ -198,7 +197,7 @@ def set_channel_access( access_mode="always", privilege_update_mode="non_volatile", privilege_level="administrator", - **kwargs + **kwargs, ): """ Set channel access @@ -388,7 +387,7 @@ def set_user_access( link_auth=True, ipmi_msg=True, privilege_level="administrator", - **kwargs + **kwargs, ): """ Set user access @@ -897,7 +896,7 @@ def create_user( link_auth=True, ipmi_msg=True, privilege_level="administrator", - **kwargs + **kwargs, ): """ create/ensure a user is created with provided settings. diff --git a/salt/modules/ipset.py b/salt/modules/ipset.py index c250d90e0d8..daa32dd3fb1 100644 --- a/salt/modules/ipset.py +++ b/salt/modules/ipset.py @@ -2,7 +2,6 @@ Support for ipset """ - import logging import salt.utils.path diff --git a/salt/modules/iptables.py b/salt/modules/iptables.py index 0b1177f1f54..c159dde87f3 100644 --- a/salt/modules/iptables.py +++ b/salt/modules/iptables.py @@ -73,7 +73,7 @@ def _has_option(option, family="ipv4"): _has_option('--wait') _has_option('--check', family='ipv6') """ - cmd = "{} --help".format(_iptables_cmd(family)) + cmd = f"{_iptables_cmd(family)} --help" if option in __salt__["cmd.run_stdout"](cmd, output_loglevel="quiet"): return True return False @@ -192,7 +192,7 @@ def version(family="ipv4"): IPv6: salt '*' iptables.version family=ipv6 """ - cmd = "{} --version".format(_iptables_cmd(family)) + cmd = f"{_iptables_cmd(family)} --version" out = __salt__["cmd.run_stdout"](cmd).split() return out[1] @@ -204,7 +204,7 @@ def build_rule( position="", full=None, family="ipv4", - **kwargs + **kwargs, ): """ Build a well-formatted iptables rule based on kwargs. A `table` and `chain` @@ -316,7 +316,7 @@ def build_rule( if not isinstance(match_value, list): match_value = match_value.split(",") for match in match_value: - rule.append("-m {}".format(match)) + rule.append(f"-m {match}") if "name_" in kwargs and match.strip() in ("pknock", "quota2", "recent"): rule.append("--name {}".format(kwargs["name_"])) del kwargs["name_"] @@ -335,7 +335,7 @@ def build_rule( if match_set.startswith("!") or match_set.startswith("not"): negative_match_set = "! " match_set = re.sub(bang_not_pat, "", match_set) - rule.append("-m set {}--match-set {}".format(negative_match_set, match_set)) + rule.append(f"-m set {negative_match_set}--match-set {match_set}") del kwargs["match-set"] if "connstate" in kwargs: @@ -382,7 +382,7 @@ def build_rule( else: dports = mp_value - rule.append("--{} {}".format(multiport_arg, dports)) + rule.append(f"--{multiport_arg} {dports}") del kwargs[multiport_arg] if "comment" in kwargs: @@ -526,11 +526,11 @@ def build_rule( if after_jump_argument in kwargs: value = kwargs[after_jump_argument] if value in (None, ""): # options without arguments - after_jump.append("--{}".format(after_jump_argument)) + after_jump.append(f"--{after_jump_argument}") elif any(ws_char in str(value) for ws_char in string.whitespace): - after_jump.append('--{} "{}"'.format(after_jump_argument, value)) + after_jump.append(f'--{after_jump_argument} "{value}"') else: - after_jump.append("--{} {}".format(after_jump_argument, value)) + after_jump.append(f"--{after_jump_argument} {value}") del kwargs[after_jump_argument] for key in kwargs: @@ -539,8 +539,8 @@ def build_rule( # the value in the kwargs, thus we need to fetch it after that has run value = kwargs[key] flag = "-" if len(key) == 1 else "--" - value = "" if value in (None, "") else " {}".format(value) - rule.append("{}{}{}{}".format(negation, flag, key, value)) + value = "" if value in (None, "") else f" {value}" + rule.append(f"{negation}{flag}{key}{value}") rule += after_jump @@ -704,7 +704,7 @@ def save(filename=None, family="ipv4"): parent_dir = os.path.dirname(filename) if not os.path.isdir(parent_dir): os.makedirs(parent_dir) - cmd = "{}-save".format(_iptables_cmd(family)) + cmd = f"{_iptables_cmd(family)}-save" ipt = __salt__["cmd.run_stdout"](cmd) # regex out the output if configured with filters @@ -743,26 +743,24 @@ def check(table="filter", chain=None, rule=None, family="ipv4"): ipt_cmd = _iptables_cmd(family) if _has_option("--check", family): - cmd = "{} -t {} -C {} {}".format(ipt_cmd, table, chain, rule) + cmd = f"{ipt_cmd} -t {table} -C {chain} {rule}" __salt__["cmd.run_stderr"](cmd, output_loglevel="quiet") return not __context__["retcode"] else: _chain_name = hex(uuid.getnode()) # Create temporary table - __salt__["cmd.run"]("{} -t {} -N {}".format(ipt_cmd, table, _chain_name)) - __salt__["cmd.run"]( - "{} -t {} -A {} {}".format(ipt_cmd, table, _chain_name, rule) - ) + __salt__["cmd.run"](f"{ipt_cmd} -t {table} -N {_chain_name}") + __salt__["cmd.run"](f"{ipt_cmd} -t {table} -A {_chain_name} {rule}") - out = __salt__["cmd.run_stdout"]("{}-save".format(ipt_cmd)) + out = __salt__["cmd.run_stdout"](f"{ipt_cmd}-save") # Clean up temporary table - __salt__["cmd.run"]("{} -t {} -F {}".format(ipt_cmd, table, _chain_name)) - __salt__["cmd.run"]("{} -t {} -X {}".format(ipt_cmd, table, _chain_name)) + __salt__["cmd.run"](f"{ipt_cmd} -t {table} -F {_chain_name}") + __salt__["cmd.run"](f"{ipt_cmd} -t {table} -X {_chain_name}") for i in out.splitlines(): - if i.startswith("-A {}".format(_chain_name)): + if i.startswith(f"-A {_chain_name}"): if i.replace(_chain_name, chain) in out.splitlines(): return True @@ -792,8 +790,8 @@ def check_chain(table="filter", chain=None, family="ipv4"): if not chain: return "Error: Chain needs to be specified" - cmd = "{}-save -t {}".format(_iptables_cmd(family), table) - out = __salt__["cmd.run_stdout"](cmd).find(":{} ".format(chain)) + cmd = f"{_iptables_cmd(family)}-save -t {table}" + out = __salt__["cmd.run_stdout"](cmd).find(f":{chain} ") if out != -1: out = True @@ -823,7 +821,7 @@ def new_chain(table="filter", chain=None, family="ipv4"): return "Error: Chain needs to be specified" wait = "--wait" if _has_option("--wait", family) else "" - cmd = "{} {} -t {} -N {}".format(_iptables_cmd(family), wait, table, chain) + cmd = f"{_iptables_cmd(family)} {wait} -t {table} -N {chain}" out = __salt__["cmd.run_stderr"](cmd) if not out: @@ -851,7 +849,7 @@ def delete_chain(table="filter", chain=None, family="ipv4"): return "Error: Chain needs to be specified" wait = "--wait" if _has_option("--wait", family) else "" - cmd = "{} {} -t {} -X {}".format(_iptables_cmd(family), wait, table, chain) + cmd = f"{_iptables_cmd(family)} {wait} -t {table} -X {chain}" out = __salt__["cmd.run_stderr"](cmd) if not out: @@ -889,7 +887,7 @@ def append(table="filter", chain=None, rule=None, family="ipv4"): returnCheck = check(table, chain, rule, family) if isinstance(returnCheck, bool) and returnCheck: return False - cmd = "{} {} -t {} -A {} {}".format(_iptables_cmd(family), wait, table, chain, rule) + cmd = f"{_iptables_cmd(family)} {wait} -t {table} -A {chain} {rule}" out = __salt__["cmd.run_stderr"](cmd) return not out @@ -977,7 +975,7 @@ def delete(table, chain=None, position=None, rule=None, family="ipv4"): rule = position wait = "--wait" if _has_option("--wait", family) else "" - cmd = "{} {} -t {} -D {} {}".format(_iptables_cmd(family), wait, table, chain, rule) + cmd = f"{_iptables_cmd(family)} {wait} -t {table} -D {chain} {rule}" out = __salt__["cmd.run_stderr"](cmd) return out @@ -998,7 +996,7 @@ def flush(table="filter", chain="", family="ipv4"): """ wait = "--wait" if _has_option("--wait", family) else "" - cmd = "{} {} -t {} -F {}".format(_iptables_cmd(family), wait, table, chain) + cmd = f"{_iptables_cmd(family)} {wait} -t {table} -F {chain}" out = __salt__["cmd.run_stderr"](cmd) return out @@ -1016,7 +1014,7 @@ def _parse_conf(conf_file=None, in_mem=False, family="ipv4"): with salt.utils.files.fopen(conf_file, "r") as ifile: rules = ifile.read() elif in_mem: - cmd = "{}-save".format(_iptables_cmd(family)) + cmd = f"{_iptables_cmd(family)}-save" rules = __salt__["cmd.run_stdout"](cmd) else: raise SaltException("A file was not found to parse") @@ -1057,7 +1055,7 @@ def _parse_conf(conf_file=None, in_mem=False, family="ipv4"): and args[index + 1] != "!" and not args[index + 1].startswith("-") ): - args[index] += " {}".format(args.pop(index + 1)) + args[index] += f" {args.pop(index + 1)}" index += 1 if args[-1].startswith("-"): args.append("") diff --git a/salt/modules/iwtools.py b/salt/modules/iwtools.py index aec30a8390c..198375d9850 100644 --- a/salt/modules/iwtools.py +++ b/salt/modules/iwtools.py @@ -36,10 +36,10 @@ def scan(iface, style=None): if not _valid_iface(iface): raise SaltInvocationError("The interface specified is not valid") - out = __salt__["cmd.run"]("iwlist {} scan".format(iface)) + out = __salt__["cmd.run"](f"iwlist {iface} scan") if "Network is down" in out: - __salt__["cmd.run"]("ip link set {} up".format(iface)) - out = __salt__["cmd.run"]("iwlist {} scan".format(iface)) + __salt__["cmd.run"](f"ip link set {iface} up") + out = __salt__["cmd.run"](f"iwlist {iface} scan") ret = {} tmp = {} for line in out.splitlines(): @@ -101,7 +101,7 @@ def set_mode(iface, mode): ) ) __salt__["ip.down"](iface) - out = __salt__["cmd.run"]("iwconfig {} mode {}".format(iface, mode)) + out = __salt__["cmd.run"](f"iwconfig {iface} mode {mode}") __salt__["ip.up"](iface) return mode diff --git a/salt/modules/jboss7.py b/salt/modules/jboss7.py index f43a66fb1f4..1651da7ea8f 100644 --- a/salt/modules/jboss7.py +++ b/salt/modules/jboss7.py @@ -21,7 +21,6 @@ Example: """ - import logging import re @@ -91,7 +90,7 @@ def stop_server(jboss_config, host=None): if host is None: operation = ":shutdown" else: - operation = '/host="{host}"/:shutdown'.format(host=host) + operation = f'/host="{host}"/:shutdown' shutdown_result = __salt__["jboss7_cli.run_operation"]( jboss_config, operation, fail_on_error=False ) @@ -130,7 +129,7 @@ def reload_(jboss_config, host=None): if host is None: operation = ":reload" else: - operation = '/host="{host}"/:reload'.format(host=host) + operation = f'/host="{host}"/:reload' reload_result = __salt__["jboss7_cli.run_operation"]( jboss_config, operation, fail_on_error=False ) @@ -195,7 +194,7 @@ def create_datasource(jboss_config, name, datasource_properties, profile=None): ), ) if profile is not None: - operation = '/profile="{profile}"'.format(profile=profile) + operation + operation = f'/profile="{profile}"' + operation return __salt__["jboss7_cli.run_operation"]( jboss_config, operation, fail_on_error=False @@ -214,7 +213,7 @@ def __get_properties_assignment_string(datasource_properties, ds_resource_descri def __get_single_assignment_string(key, val, ds_attributes): - return "{}={}".format(key, __format_value(key, val, ds_attributes)) + return f"{key}={__format_value(key, val, ds_attributes)}" def __format_value(key, value, ds_attributes): @@ -228,18 +227,14 @@ def __format_value(key, value, ds_attributes): else: return "false" else: - raise Exception( - "Don't know how to convert {} to BOOLEAN type".format(value) - ) + raise Exception(f"Don't know how to convert {value} to BOOLEAN type") elif type_ == "INT": return str(value) elif type_ == "STRING": - return '"{}"'.format(value) + return f'"{value}"' else: - raise Exception( - "Don't know how to format value {} of type {}".format(value, type_) - ) + raise Exception(f"Don't know how to format value {value} of type {type_}") def update_datasource(jboss_config, name, new_properties, profile=None): @@ -316,7 +311,7 @@ def __get_datasource_resource_description(jboss_config, name, profile=None): ) ) if profile is not None: - operation = '/profile="{profile}"'.format(profile=profile) + operation + operation = f'/profile="{profile}"' + operation operation_result = __salt__["jboss7_cli.run_operation"](jboss_config, operation) if operation_result["outcome"]: return operation_result["result"] @@ -382,7 +377,7 @@ def create_simple_binding(jboss_config, binding_name, value, profile=None): ) ) if profile is not None: - operation = '/profile="{profile}"'.format(profile=profile) + operation + operation = f'/profile="{profile}"' + operation return __salt__["jboss7_cli.run_operation"](jboss_config, operation) @@ -419,7 +414,7 @@ def update_simple_binding(jboss_config, binding_name, value, profile=None): ) ) if profile is not None: - operation = '/profile="{profile}"'.format(profile=profile) + operation + operation = f'/profile="{profile}"' + operation return __salt__["jboss7_cli.run_operation"](jboss_config, operation) @@ -453,7 +448,7 @@ def __read_simple_binding(jboss_config, binding_name, profile=None): binding_name=binding_name ) if profile is not None: - operation = '/profile="{profile}"'.format(profile=profile) + operation + operation = f'/profile="{profile}"' + operation return __salt__["jboss7_cli.run_operation"](jboss_config, operation) @@ -475,7 +470,7 @@ def __update_datasource_property( value=__format_value(name, value, ds_attributes), ) if profile is not None: - operation = '/profile="{profile}"'.format(profile=profile) + operation + operation = f'/profile="{profile}"' + operation return __salt__["jboss7_cli.run_operation"]( jboss_config, operation, fail_on_error=False @@ -488,7 +483,7 @@ def __read_datasource(jboss_config, name, profile=None): name=name ) if profile is not None: - operation = '/profile="{profile}"'.format(profile=profile) + operation + operation = f'/profile="{profile}"' + operation operation_result = __salt__["jboss7_cli.run_operation"](jboss_config, operation) @@ -525,9 +520,9 @@ def remove_datasource(jboss_config, name, profile=None): profile, ) - operation = "/subsystem=datasources/data-source={name}:remove".format(name=name) + operation = f"/subsystem=datasources/data-source={name}:remove" if profile is not None: - operation = '/profile="{profile}"'.format(profile=profile) + operation + operation = f'/profile="{profile}"' + operation return __salt__["jboss7_cli.run_operation"]( jboss_config, operation, fail_on_error=False @@ -553,7 +548,7 @@ def deploy(jboss_config, source_file): "======================== MODULE FUNCTION: jboss7.deploy, source_file=%s", source_file, ) - command = "deploy {source_file} --force ".format(source_file=source_file) + command = f"deploy {source_file} --force " return __salt__["jboss7_cli.run_command"]( jboss_config, command, fail_on_error=False ) @@ -601,5 +596,5 @@ def undeploy(jboss_config, deployment): "======================== MODULE FUNCTION: jboss7.undeploy, deployment=%s", deployment, ) - command = "undeploy {deployment} ".format(deployment=deployment) + command = f"undeploy {deployment} " return __salt__["jboss7_cli.run_command"](jboss_config, command) diff --git a/salt/modules/jboss7_cli.py b/salt/modules/jboss7_cli.py index 683b61662e8..bd0d7111e8e 100644 --- a/salt/modules/jboss7_cli.py +++ b/salt/modules/jboss7_cli.py @@ -35,7 +35,6 @@ Example: """ - import logging import pprint import re @@ -159,7 +158,7 @@ def _call_cli(jboss_config, command, retries=1): command_segments.append('--user="{}"'.format(jboss_config["cli_user"])) if "cli_password" in jboss_config.keys(): command_segments.append('--password="{}"'.format(jboss_config["cli_password"])) - command_segments.append('--command="{}"'.format(__escape_command(command))) + command_segments.append(f'--command="{__escape_command(command)}"') cli_script = " ".join(command_segments) cli_command_result = __salt__["cmd.run_all"](cli_script) @@ -337,7 +336,7 @@ def __process_tokens_internal(tokens, start_at=0): log.debug(" TYPE: EXPRESSION") is_expression = True else: - raise CommandExecutionError("Unknown token! Token: {}".format(token)) + raise CommandExecutionError(f"Unknown token! Token: {token}") token_no = token_no + 1 diff --git a/salt/modules/jenkinsmod.py b/salt/modules/jenkinsmod.py index d87c13c3049..3d504d9f5c8 100644 --- a/salt/modules/jenkinsmod.py +++ b/salt/modules/jenkinsmod.py @@ -22,7 +22,6 @@ Module for controlling Jenkins api_key: peWcBiMOS9HrZG15peWcBiMOS9HrZG15 """ - import logging import salt.utils.files @@ -109,7 +108,7 @@ def _retrieve_config_xml(config_xml, saltenv): ret = __salt__["cp.cache_file"](config_xml, saltenv) if not ret: - raise CommandExecutionError("Failed to retrieve {}".format(config_xml)) + raise CommandExecutionError(f"Failed to retrieve {config_xml}") return ret @@ -220,7 +219,7 @@ def get_job_info(name=None): server = _connect() if not job_exists(name): - raise CommandExecutionError("Job '{}' does not exist".format(name)) + raise CommandExecutionError(f"Job '{name}' does not exist") job_info = server.get_job_info(name) if job_info: @@ -249,14 +248,12 @@ def build_job(name=None, parameters=None): server = _connect() if not job_exists(name): - raise CommandExecutionError("Job '{}' does not exist.".format(name)) + raise CommandExecutionError(f"Job '{name}' does not exist.") try: server.build_job(name, parameters) except jenkins.JenkinsException as err: - raise CommandExecutionError( - "Encountered error building job '{}': {}".format(name, err) - ) + raise CommandExecutionError(f"Encountered error building job '{name}': {err}") return True @@ -282,7 +279,7 @@ def create_job(name=None, config_xml=None, saltenv="base"): raise SaltInvocationError("Required parameter 'name' is missing") if job_exists(name): - raise CommandExecutionError("Job '{}' already exists".format(name)) + raise CommandExecutionError(f"Job '{name}' already exists") if not config_xml: config_xml = jenkins.EMPTY_CONFIG_XML @@ -296,9 +293,7 @@ def create_job(name=None, config_xml=None, saltenv="base"): try: server.create_job(name, config_xml) except jenkins.JenkinsException as err: - raise CommandExecutionError( - "Encountered error creating job '{}': {}".format(name, err) - ) + raise CommandExecutionError(f"Encountered error creating job '{name}': {err}") return config_xml @@ -335,9 +330,7 @@ def update_job(name=None, config_xml=None, saltenv="base"): try: server.reconfig_job(name, config_xml) except jenkins.JenkinsException as err: - raise CommandExecutionError( - "Encountered error updating job '{}': {}".format(name, err) - ) + raise CommandExecutionError(f"Encountered error updating job '{name}': {err}") return config_xml @@ -361,14 +354,12 @@ def delete_job(name=None): server = _connect() if not job_exists(name): - raise CommandExecutionError("Job '{}' does not exist".format(name)) + raise CommandExecutionError(f"Job '{name}' does not exist") try: server.delete_job(name) except jenkins.JenkinsException as err: - raise CommandExecutionError( - "Encountered error deleting job '{}': {}".format(name, err) - ) + raise CommandExecutionError(f"Encountered error deleting job '{name}': {err}") return True @@ -392,14 +383,12 @@ def enable_job(name=None): server = _connect() if not job_exists(name): - raise CommandExecutionError("Job '{}' does not exist".format(name)) + raise CommandExecutionError(f"Job '{name}' does not exist") try: server.enable_job(name) except jenkins.JenkinsException as err: - raise CommandExecutionError( - "Encountered error enabling job '{}': {}".format(name, err) - ) + raise CommandExecutionError(f"Encountered error enabling job '{name}': {err}") return True @@ -424,14 +413,12 @@ def disable_job(name=None): server = _connect() if not job_exists(name): - raise CommandExecutionError("Job '{}' does not exist".format(name)) + raise CommandExecutionError(f"Job '{name}' does not exist") try: server.disable_job(name) except jenkins.JenkinsException as err: - raise CommandExecutionError( - "Encountered error disabling job '{}': {}".format(name, err) - ) + raise CommandExecutionError(f"Encountered error disabling job '{name}': {err}") return True @@ -456,7 +443,7 @@ def job_status(name=None): server = _connect() if not job_exists(name): - raise CommandExecutionError("Job '{}' does not exist".format(name)) + raise CommandExecutionError(f"Job '{name}' does not exist") return server.get_job_info("empty")["buildable"] @@ -482,7 +469,7 @@ def get_job_config(name=None): server = _connect() if not job_exists(name): - raise CommandExecutionError("Job '{}' does not exist".format(name)) + raise CommandExecutionError(f"Job '{name}' does not exist") job_info = server.get_job_config(name) return job_info diff --git a/salt/modules/junos.py b/salt/modules/junos.py index 01bcbbaa167..385aee4fac4 100644 --- a/salt/modules/junos.py +++ b/salt/modules/junos.py @@ -479,10 +479,10 @@ def set_hostname(hostname=None, **kwargs): ret["out"] = True except Exception as exception: # pylint: disable=broad-except ret["out"] = False - ret[ - "message" - ] = 'Successfully loaded host-name but commit failed with "{}"'.format( - exception + ret["message"] = ( + 'Successfully loaded host-name but commit failed with "{}"'.format( + exception + ) ) _restart_connection() return ret @@ -493,10 +493,10 @@ def set_hostname(hostname=None, **kwargs): conn.cu.rollback() except Exception as exception: # pylint: disable=broad-except ret["out"] = False - ret[ - "message" - ] = 'Successfully loaded host-name but rollback before exit failed "{}"'.format( - exception + ret["message"] = ( + 'Successfully loaded host-name but rollback before exit failed "{}"'.format( + exception + ) ) _restart_connection() @@ -579,10 +579,10 @@ def commit(**kwargs): ret["out"] = False except Exception as exception: # pylint: disable=broad-except ret["out"] = False - ret[ - "message" - ] = 'Commit check succeeded but actual commit failed with "{}"'.format( - exception + ret["message"] = ( + 'Commit check succeeded but actual commit failed with "{}"'.format( + exception + ) ) _restart_connection() else: @@ -592,10 +592,10 @@ def commit(**kwargs): conn.cu.rollback() except Exception as exception: # pylint: disable=broad-except ret["out"] = False - ret[ - "message" - ] = 'Pre-commit check failed, and exception during rollback "{}"'.format( - exception + ret["message"] = ( + 'Pre-commit check failed, and exception during rollback "{}"'.format( + exception + ) ) _restart_connection() @@ -708,10 +708,10 @@ def rollback(**kwargs): ret["out"] = True except Exception as exception: # pylint: disable=broad-except ret["out"] = False - ret[ - "message" - ] = 'Rollback successful but commit failed with error "{}"'.format( - exception + ret["message"] = ( + 'Rollback successful but commit failed with error "{}"'.format( + exception + ) ) _restart_connection() return ret @@ -1078,9 +1078,9 @@ def install_config(path=None, **kwargs): ret["out"] = True if path is None: - ret[ - "message" - ] = "Please provide the salt path where the configuration is present" + ret["message"] = ( + "Please provide the salt path where the configuration is present" + ) ret["out"] = False return ret @@ -1139,9 +1139,9 @@ def install_config(path=None, **kwargs): db_mode = op.pop("mode", "exclusive") if write_diff and db_mode in ["dynamic", "ephemeral"]: - ret[ - "message" - ] = "Write diff is not supported with dynamic/ephemeral configuration mode" + ret["message"] = ( + "Write diff is not supported with dynamic/ephemeral configuration mode" + ) ret["out"] = False return ret @@ -1153,9 +1153,9 @@ def install_config(path=None, **kwargs): try: cu.load(**op) except Exception as exception: # pylint: disable=broad-except - ret[ - "message" - ] = f'Could not load configuration due to : "{exception}"' + ret["message"] = ( + f'Could not load configuration due to : "{exception}"' + ) ret["format"] = op["format"] ret["out"] = False _restart_connection() @@ -1185,10 +1185,10 @@ def install_config(path=None, **kwargs): try: check = cu.commit_check() except Exception as exception: # pylint: disable=broad-except - ret[ - "message" - ] = 'Commit check threw the following exception: "{}"'.format( - exception + ret["message"] = ( + 'Commit check threw the following exception: "{}"'.format( + exception + ) ) ret["out"] = False _restart_connection() @@ -1199,10 +1199,10 @@ def install_config(path=None, **kwargs): cu.commit(**commit_params) ret["message"] = "Successfully loaded and committed!" except Exception as exception: # pylint: disable=broad-except - ret[ - "message" - ] = 'Commit check successful but commit failed with "{}"'.format( - exception + ret["message"] = ( + 'Commit check successful but commit failed with "{}"'.format( + exception + ) ) ret["out"] = False _restart_connection() @@ -1248,9 +1248,9 @@ def install_config(path=None, **kwargs): with salt.utils.files.fopen(write_diff, "w") as fp: fp.write(salt.utils.stringutils.to_str(config_diff)) except Exception as exception: # pylint: disable=broad-except - ret[ - "message" - ] = f"Could not write into diffs_file due to: '{exception}'" + ret["message"] = ( + f"Could not write into diffs_file due to: '{exception}'" + ) ret["out"] = False except ValueError as ex: @@ -1396,9 +1396,9 @@ def install_os(path=None, **kwargs): no_copy_ = op.get("no_copy", False) if path is None: - ret[ - "message" - ] = "Please provide the salt path where the junos image is present." + ret["message"] = ( + "Please provide the salt path where the junos image is present." + ) ret["out"] = False return ret @@ -1467,10 +1467,10 @@ def install_os(path=None, **kwargs): conn.sw.reboot(**reboot_kwargs) except Exception as exception: # pylint: disable=broad-except __proxy__["junos.reboot_clear"]() - ret[ - "message" - ] = 'Installation successful but reboot failed due to : "{}"'.format( - exception + ret["message"] = ( + 'Installation successful but reboot failed due to : "{}"'.format( + exception + ) ) ret["out"] = False _restart_connection() @@ -1666,9 +1666,9 @@ def load(path=None, **kwargs): ret["out"] = True if path is None: - ret[ - "message" - ] = "Please provide the salt path where the configuration is present" + ret["message"] = ( + "Please provide the salt path where the configuration is present" + ) ret["out"] = False return ret @@ -1862,10 +1862,10 @@ def get_table( ) globals().update(FactoryLoader().load(ret["table"])) except OSError as err: - ret[ - "message" - ] = "Uncaught exception during YAML Load - please report: {}".format( - str(err) + ret["message"] = ( + "Uncaught exception during YAML Load - please report: {}".format( + str(err) + ) ) ret["out"] = False return ret @@ -1873,18 +1873,18 @@ def get_table( data = globals()[table](conn) data.get(**get_kvargs) except KeyError as err: - ret[ - "message" - ] = "Uncaught exception during get API call - please report: {}".format( - str(err) + ret["message"] = ( + "Uncaught exception during get API call - please report: {}".format( + str(err) + ) ) ret["out"] = False return ret except ConnectClosedError: - ret[ - "message" - ] = "Got ConnectClosedError exception. Connection lost with {}".format( - conn + ret["message"] = ( + "Got ConnectClosedError exception. Connection lost with {}".format( + conn + ) ) ret["out"] = False _restart_connection() @@ -1914,10 +1914,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/kapacitor.py b/salt/modules/kapacitor.py index f3a47267a71..3cd8ff2ce9a 100644 --- a/salt/modules/kapacitor.py +++ b/salt/modules/kapacitor.py @@ -61,7 +61,7 @@ def _get_url(): host = __salt__["config.option"]("kapacitor.host", "localhost") port = __salt__["config.option"]("kapacitor.port", 9092) - return "{}://{}:{}".format(protocol, host, port) + return f"{protocol}://{host}:{port}" def get_task(name): @@ -80,9 +80,9 @@ def get_task(name): url = _get_url() if version() < "0.13": - task_url = "{}/task?name={}".format(url, name) + task_url = f"{url}/task?name={name}" else: - task_url = "{}/kapacitor/v1/tasks/{}?skip-format=true".format(url, name) + task_url = f"{url}/kapacitor/v1/tasks/{name}?skip-format=true" response = salt.utils.http.query(task_url, status=True) @@ -173,28 +173,28 @@ def define_task( return False if version() < "0.13": - cmd = "kapacitor define -name {}".format(name) + cmd = f"kapacitor define -name {name}" else: - cmd = "kapacitor define {}".format(name) + cmd = f"kapacitor define {name}" if tick_script.startswith("salt://"): tick_script = __salt__["cp.cache_file"](tick_script, __env__) - cmd += " -tick {}".format(tick_script) + cmd += f" -tick {tick_script}" if task_type: - cmd += " -type {}".format(task_type) + cmd += f" -type {task_type}" if not dbrps: dbrps = [] if database and retention_policy: - dbrp = "{}.{}".format(database, retention_policy) + dbrp = f"{database}.{retention_policy}" dbrps.append(dbrp) if dbrps: for dbrp in dbrps: - cmd += " -dbrp {}".format(dbrp) + cmd += f" -dbrp {dbrp}" return _run_cmd(cmd) @@ -212,7 +212,7 @@ def delete_task(name): salt '*' kapacitor.delete_task cpu """ - return _run_cmd("kapacitor delete tasks {}".format(name)) + return _run_cmd(f"kapacitor delete tasks {name}") def enable_task(name): @@ -228,7 +228,7 @@ def enable_task(name): salt '*' kapacitor.enable_task cpu """ - return _run_cmd("kapacitor enable {}".format(name)) + return _run_cmd(f"kapacitor enable {name}") def disable_task(name): @@ -244,4 +244,4 @@ def disable_task(name): salt '*' kapacitor.disable_task cpu """ - return _run_cmd("kapacitor disable {}".format(name)) + return _run_cmd(f"kapacitor disable {name}") diff --git a/salt/modules/kerberos.py b/salt/modules/kerberos.py index ea898a22634..e452b53b4b3 100644 --- a/salt/modules/kerberos.py +++ b/salt/modules/kerberos.py @@ -19,7 +19,6 @@ authenticate as. auth_principal: kadmin/admin """ - import logging import salt.utils.path @@ -45,7 +44,7 @@ def __execute_kadmin(cmd): if __salt__["file.file_exists"](auth_keytab) and auth_principal: return __salt__["cmd.run_all"]( - 'kadmin -k -t {} -p {} -q "{}"'.format(auth_keytab, auth_principal, cmd) + f'kadmin -k -t {auth_keytab} -p {auth_principal} -q "{cmd}"' ) else: log.error("Unable to find kerberos keytab/principal") @@ -95,7 +94,7 @@ def get_principal(name): """ ret = {} - cmd = __execute_kadmin("get_principal {}".format(name)) + cmd = __execute_kadmin(f"get_principal {name}") if cmd["retcode"] != 0 or cmd["stderr"]: ret["comment"] = cmd["stderr"].splitlines()[-1] @@ -151,7 +150,7 @@ def get_policy(name): """ ret = {} - cmd = __execute_kadmin("get_policy {}".format(name)) + cmd = __execute_kadmin(f"get_policy {name}") if cmd["retcode"] != 0 or cmd["stderr"]: ret["comment"] = cmd["stderr"].splitlines()[-1] @@ -210,9 +209,9 @@ def create_principal(name, enctypes=None): krb_cmd = "addprinc -randkey" if enctypes: - krb_cmd += " -e {}".format(enctypes) + krb_cmd += f" -e {enctypes}" - krb_cmd += " {}".format(name) + krb_cmd += f" {name}" cmd = __execute_kadmin(krb_cmd) @@ -238,7 +237,7 @@ def delete_principal(name): """ ret = {} - cmd = __execute_kadmin("delprinc -force {}".format(name)) + cmd = __execute_kadmin(f"delprinc -force {name}") if cmd["retcode"] != 0 or cmd["stderr"]: ret["comment"] = cmd["stderr"].splitlines()[-1] @@ -261,12 +260,12 @@ def create_keytab(name, keytab, enctypes=None): """ ret = {} - krb_cmd = "ktadd -k {}".format(keytab) + krb_cmd = f"ktadd -k {keytab}" if enctypes: - krb_cmd += " -e {}".format(enctypes) + krb_cmd += f" -e {enctypes}" - krb_cmd += " {}".format(name) + krb_cmd += f" {name}" cmd = __execute_kadmin(krb_cmd) diff --git a/salt/modules/kernelpkg_linux_apt.py b/salt/modules/kernelpkg_linux_apt.py index fc8684d03fa..33cef3eaaa5 100644 --- a/salt/modules/kernelpkg_linux_apt.py +++ b/salt/modules/kernelpkg_linux_apt.py @@ -53,7 +53,7 @@ def list_installed(): salt '*' kernelpkg.list_installed """ - pkg_re = re.compile(r"^{}-[\d.-]+-{}$".format(_package_prefix(), _kernel_type())) + pkg_re = re.compile(rf"^{_package_prefix()}-[\d.-]+-{_kernel_type()}$") pkgs = __salt__["pkg.list_pkgs"](versions_as_list=True) if pkgs is None: pkgs = [] @@ -79,14 +79,12 @@ def latest_available(): salt '*' kernelpkg.latest_available """ - result = __salt__["pkg.latest_version"]( - "{}-{}".format(_package_prefix(), _kernel_type()) - ) + result = __salt__["pkg.latest_version"](f"{_package_prefix()}-{_kernel_type()}") if result == "": return latest_installed() version = re.match(r"^(\d+\.\d+\.\d+)\.(\d+)", result) - return "{}-{}-{}".format(version.group(1), version.group(2), _kernel_type()) + return f"{version.group(1)}-{version.group(2)}-{_kernel_type()}" def latest_installed(): @@ -152,9 +150,7 @@ def upgrade(reboot=False, at_time=None): chance to return, resulting in errors. A minimal delay (1 minute) is useful to ensure the result is delivered to the master. """ - result = __salt__["pkg.install"]( - name="{}-{}".format(_package_prefix(), latest_available()) - ) + result = __salt__["pkg.install"](name=f"{_package_prefix()}-{latest_available()}") _needs_reboot = needs_reboot() ret = { @@ -202,14 +198,12 @@ def remove(release): salt '*' kernelpkg.remove 4.4.0-70-generic """ if release not in list_installed(): - raise CommandExecutionError( - "Kernel release '{}' is not installed".format(release) - ) + raise CommandExecutionError(f"Kernel release '{release}' is not installed") if release == active(): raise CommandExecutionError("Active kernel cannot be removed") - target = "{}-{}".format(_package_prefix(), release) + target = f"{_package_prefix()}-{release}" log.info("Removing kernel package %s", target) __salt__["pkg.purge"](target) diff --git a/salt/modules/kernelpkg_linux_yum.py b/salt/modules/kernelpkg_linux_yum.py index a144a98811d..c37f8729174 100644 --- a/salt/modules/kernelpkg_linux_yum.py +++ b/salt/modules/kernelpkg_linux_yum.py @@ -199,14 +199,12 @@ def remove(release): salt '*' kernelpkg.remove 3.10.0-327.el7 """ if release not in list_installed(): - raise CommandExecutionError( - "Kernel release '{}' is not installed".format(release) - ) + raise CommandExecutionError(f"Kernel release '{release}' is not installed") if release == active(): raise CommandExecutionError("Active kernel cannot be removed") - target = "{}-{}".format(_package_name(), release) + target = f"{_package_name()}-{release}" log.info("Removing kernel package %s", target) old = __salt__["pkg.list_pkgs"]() diff --git a/salt/modules/keyboard.py b/salt/modules/keyboard.py index 85d3e3aca93..7c15246ea95 100644 --- a/salt/modules/keyboard.py +++ b/salt/modules/keyboard.py @@ -3,7 +3,6 @@ Module for managing keyboards on supported POSIX-like systems using systemd, or such as Redhat, Debian and Gentoo. """ - import logging import salt.utils.path @@ -64,19 +63,17 @@ def set_sys(layout): salt '*' keyboard.set_sys dvorak """ if salt.utils.path.which("localectl"): - __salt__["cmd.run"]("localectl set-keymap {}".format(layout)) + __salt__["cmd.run"](f"localectl set-keymap {layout}") elif "RedHat" in __grains__["os_family"]: __salt__["file.sed"]( - "/etc/sysconfig/keyboard", "^LAYOUT=.*", "LAYOUT={}".format(layout) + "/etc/sysconfig/keyboard", "^LAYOUT=.*", f"LAYOUT={layout}" ) elif "Debian" in __grains__["os_family"]: __salt__["file.sed"]( - "/etc/default/keyboard", "^XKBLAYOUT=.*", "XKBLAYOUT={}".format(layout) + "/etc/default/keyboard", "^XKBLAYOUT=.*", f"XKBLAYOUT={layout}" ) elif "Gentoo" in __grains__["os_family"]: - __salt__["file.sed"]( - "/etc/conf.d/keymaps", "^keymap=.*", "keymap={}".format(layout) - ) + __salt__["file.sed"]("/etc/conf.d/keymaps", "^keymap=.*", f"keymap={layout}") return layout @@ -105,6 +102,6 @@ def set_x(layout): salt '*' keyboard.set_x dvorak """ - cmd = "setxkbmap {}".format(layout) + cmd = f"setxkbmap {layout}" __salt__["cmd.run"](cmd) return layout diff --git a/salt/modules/keystone.py b/salt/modules/keystone.py index b39a8b0ae5b..898180b0c33 100644 --- a/salt/modules/keystone.py +++ b/salt/modules/keystone.py @@ -201,7 +201,7 @@ def ec2_credentials_create( tenant_id=None, tenant=None, profile=None, - **connection_args + **connection_args, ): """ Create EC2-compatible credentials for user per tenant @@ -262,7 +262,7 @@ def ec2_credentials_delete( if not user_id: return {"Error": "Could not resolve User ID"} kstone.ec2.delete(user_id, access_key) - return 'ec2 key "{}" deleted under user id "{}"'.format(access_key, user_id) + return f'ec2 key "{access_key}" deleted under user id "{user_id}"' def ec2_credentials_get( @@ -355,11 +355,13 @@ def endpoint_get(service, region=None, profile=None, interface=None, **connectio e = [ _f for _f in [ - e - if e["service_id"] == service_id - and (e["region"] == region if region else True) - and (e["interface"] == interface if interface else True) - else None + ( + e + if e["service_id"] == service_id + and (e["region"] == region if region else True) + and (e["interface"] == interface if interface else True) + else None + ) for e in endpoints.values() ] if _f @@ -408,7 +410,7 @@ def endpoint_create( profile=None, url=None, interface=None, - **connection_args + **connection_args, ): """ Create an endpoint for an Openstack service @@ -481,7 +483,7 @@ def role_create(name, profile=None, **connection_args): kstone = auth(profile, **connection_args) if "Error" not in role_get(name=name, profile=profile, **connection_args): - return {"Error": 'Role "{}" already exists'.format(name)} + return {"Error": f'Role "{name}" already exists'} kstone.roles.create(name) return role_get(name=name, profile=profile, **connection_args) @@ -511,9 +513,9 @@ def role_delete(role_id=None, name=None, profile=None, **connection_args): role = kstone.roles.get(role_id) kstone.roles.delete(role) - ret = "Role ID {} deleted".format(role_id) + ret = f"Role ID {role_id} deleted" if name: - ret += " ({})".format(name) + ret += f" ({name})" return ret @@ -601,7 +603,7 @@ def service_delete(service_id=None, name=None, profile=None, **connection_args): "id" ] kstone.services.delete(service_id) - return 'Keystone service ID "{}" deleted'.format(service_id) + return f'Keystone service ID "{service_id}" deleted' def service_get(service_id=None, name=None, profile=None, **connection_args): @@ -734,10 +736,10 @@ def tenant_delete(tenant_id=None, name=None, profile=None, **connection_args): if not tenant_id: return {"Error": "Unable to resolve tenant id"} getattr(kstone, _TENANTS, None).delete(tenant_id) - ret = "Tenant ID {} deleted".format(tenant_id) + ret = f"Tenant ID {tenant_id} deleted" if name: - ret += " ({})".format(name) + ret += f" ({name})" return ret @@ -896,7 +898,7 @@ def tenant_update( description=None, enabled=None, profile=None, - **connection_args + **connection_args, ): """ Update a tenant's information (keystone tenant-update) @@ -945,7 +947,7 @@ def project_update( description=None, enabled=None, profile=None, - **connection_args + **connection_args, ): """ Update a tenant's information (keystone project-update) @@ -988,7 +990,7 @@ def project_update( description=description, enabled=enabled, profile=profile, - **connection_args + **connection_args, ) else: return False @@ -1063,7 +1065,7 @@ def user_get(user_id=None, name=None, profile=None, **connection_args): try: user = kstone.users.get(user_id) except keystoneclient.exceptions.NotFound: - msg = "Could not find user '{}'".format(user_id) + msg = f"Could not find user '{user_id}'" log.error(msg) return {"Error": msg} @@ -1089,7 +1091,7 @@ def user_create( profile=None, project_id=None, description=None, - **connection_args + **connection_args, ): """ Create a user (keystone user-create) @@ -1146,10 +1148,10 @@ def user_delete(user_id=None, name=None, profile=None, **connection_args): if not user_id: return {"Error": "Unable to resolve user id"} kstone.users.delete(user_id) - ret = "User ID {} deleted".format(user_id) + ret = f"User ID {user_id} deleted" if name: - ret += " ({})".format(name) + ret += f" ({name})" return ret @@ -1162,7 +1164,7 @@ def user_update( profile=None, project=None, description=None, - **connection_args + **connection_args, ): """ Update a user's information (keystone user-update) @@ -1228,7 +1230,7 @@ def user_update( if tenant_id: kstone.users.update_tenant(user_id, tenant_id) - ret = "Info updated for user ID {}".format(user_id) + ret = f"Info updated for user ID {user_id}" return ret @@ -1306,9 +1308,9 @@ def user_password_update( kstone.users.update(user=user_id, password=password) else: kstone.users.update_password(user=user_id, password=password) - ret = "Password updated for user ID {}".format(user_id) + ret = f"Password updated for user ID {user_id}" if name: - ret += " ({})".format(name) + ret += f" ({name})" return ret @@ -1322,7 +1324,7 @@ def user_role_add( profile=None, project_id=None, project_name=None, - **connection_args + **connection_args, ): """ Add role for user in tenant (keystone user-role-add) @@ -1393,7 +1395,7 @@ def user_role_remove( profile=None, project_id=None, project_name=None, - **connection_args + **connection_args, ): """ Remove role for user in tenant (keystone user-role-remove) @@ -1460,7 +1462,7 @@ def user_role_list( profile=None, project_id=None, project_name=None, - **connection_args + **connection_args, ): """ Return a list of available user_roles (keystone user-roles-list) diff --git a/salt/modules/keystoneng.py b/salt/modules/keystoneng.py index 77c5e7f8b01..9a4ea9a8b19 100644 --- a/salt/modules/keystoneng.py +++ b/salt/modules/keystoneng.py @@ -25,7 +25,6 @@ Example configuration identity_api_version: 3 """ - HAS_SHADE = False try: import shade @@ -69,7 +68,7 @@ def get_entity(ent_type, **kwargs): Attempt to query Keystone for more information about an entity """ try: - func = "keystoneng.{}_get".format(ent_type) + func = f"keystoneng.{ent_type}_get" ent = __salt__[func](**kwargs) except OpenStackCloudException as e: # NOTE(SamYaple): If this error was something other than Forbidden we diff --git a/salt/modules/keystore.py b/salt/modules/keystore.py index 449c78b9589..4dc0fdfc65e 100644 --- a/salt/modules/keystore.py +++ b/salt/modules/keystore.py @@ -2,7 +2,6 @@ Module to interact with keystores """ - import logging import os from datetime import datetime @@ -162,9 +161,7 @@ def add(name, keystore, passphrase, certificate, private_key=None): try: cert_string = __salt__["x509.get_pem_entry"](certificate) except SaltInvocationError: - raise SaltInvocationError( - "Invalid certificate file or string: {}".format(certificate) - ) + raise SaltInvocationError(f"Invalid certificate file or string: {certificate}") if private_key: # Accept PEM input format, but convert to DES for loading into new keystore diff --git a/salt/modules/kmod.py b/salt/modules/kmod.py index 108bc6cad82..997c25fc868 100644 --- a/salt/modules/kmod.py +++ b/salt/modules/kmod.py @@ -83,9 +83,7 @@ def _set_persistent_module(mod): return set() escape_mod = re.escape(mod) # If module is commented only uncomment it - if __salt__["file.search"]( - conf, "^#[\t ]*{}[\t ]*$".format(escape_mod), multiline=True - ): + if __salt__["file.search"](conf, f"^#[\t ]*{escape_mod}[\t ]*$", multiline=True): __salt__["file.uncomment"](conf, escape_mod) else: __salt__["file.append"](conf, mod) @@ -103,9 +101,9 @@ def _remove_persistent_module(mod, comment): return set() escape_mod = re.escape(mod) if comment: - __salt__["file.comment"](conf, "^[\t ]*{}[\t ]?".format(escape_mod)) + __salt__["file.comment"](conf, f"^[\t ]*{escape_mod}[\t ]?") else: - __salt__["file.sed"](conf, "^[\t ]*{}[\t ]?".format(escape_mod), "") + __salt__["file.sed"](conf, f"^[\t ]*{escape_mod}[\t ]?", "") return {mod_name} @@ -115,7 +113,7 @@ def _which(cmd): """ _cmd = salt.utils.path.which(cmd) if not _cmd: - raise CommandExecutionError("Command '{}' cannot be found".format(cmd)) + raise CommandExecutionError(f"Command '{cmd}' cannot be found") return _cmd diff --git a/salt/modules/launchctl_service.py b/salt/modules/launchctl_service.py index b30ce1320f4..65bc04aeb99 100644 --- a/salt/modules/launchctl_service.py +++ b/salt/modules/launchctl_service.py @@ -10,7 +10,6 @@ Module for the management of MacOS systems that use launchd/launchctl :depends: - plistlib Python module """ - import fnmatch import logging import os @@ -102,7 +101,7 @@ def _available_services(): except Exception: # pylint: disable=broad-except # If plistlib is unable to read the file we'll need to use # the system provided plutil program to do the conversion - cmd = '/usr/bin/plutil -convert xml1 -o - -- "{}"'.format(true_path) + cmd = f'/usr/bin/plutil -convert xml1 -o - -- "{true_path}"' plist_xml = __salt__["cmd.run_all"](cmd, python_shell=False)[ "stdout" ] @@ -174,9 +173,9 @@ def get_all(): def _get_launchctl_data(job_label, runas=None): if BEFORE_YOSEMITE: - cmd = "launchctl list -x {}".format(job_label) + cmd = f"launchctl list -x {job_label}" else: - cmd = "launchctl list {}".format(job_label) + cmd = f"launchctl list {job_label}" launchctl_data = __salt__["cmd.run_all"](cmd, python_shell=False, runas=runas) diff --git a/salt/modules/layman.py b/salt/modules/layman.py index 0b8474076b5..6b61c649208 100644 --- a/salt/modules/layman.py +++ b/salt/modules/layman.py @@ -48,7 +48,7 @@ def add(overlay): """ ret = list() old_overlays = list_local() - cmd = "layman --quietness=0 --add {}".format(overlay) + cmd = f"layman --quietness=0 --add {overlay}" add_attempt = __salt__["cmd.run_all"](cmd, python_shell=False, stdin="y") if add_attempt["retcode"] != 0: raise salt.exceptions.CommandExecutionError(add_attempt["stdout"]) @@ -82,7 +82,7 @@ def delete(overlay): """ ret = list() old_overlays = list_local() - cmd = "layman --quietness=0 --delete {}".format(overlay) + cmd = f"layman --quietness=0 --delete {overlay}" delete_attempt = __salt__["cmd.run_all"](cmd, python_shell=False) if delete_attempt["retcode"] != 0: raise salt.exceptions.CommandExecutionError(delete_attempt["stdout"]) @@ -114,7 +114,7 @@ def sync(overlay="ALL"): salt '*' layman.sync """ - cmd = "layman --quietness=0 --sync {}".format(overlay) + cmd = f"layman --quietness=0 --sync {overlay}" return __salt__["cmd.retcode"](cmd, python_shell=False) == 0 diff --git a/salt/modules/ldap3.py b/salt/modules/ldap3.py index a065b306b6d..d7e0834d341 100644 --- a/salt/modules/ldap3.py +++ b/salt/modules/ldap3.py @@ -10,7 +10,6 @@ This is an alternative to the ``ldap`` interface provided by the :depends: - ``ldap`` Python module """ - import logging import salt.utils.data @@ -52,7 +51,7 @@ class LDAPError(Exception): def _convert_exception(e): """Convert an ldap backend exception to an LDAPError and raise it.""" - raise LDAPError("exception in ldap backend: {!r}".format(e), e) from e + raise LDAPError(f"exception in ldap backend: {e!r}", e) from e def _bind(l, bind=None): @@ -90,7 +89,7 @@ def _format_unicode_password(pwd): :returns: A unicode string """ - return '"{}"'.format(pwd).encode("utf-16-le") + return f'"{pwd}"'.encode("utf-16-le") class _connect_ctx: @@ -266,7 +265,7 @@ def connect(connect_spec=None): if backend_name not in available_backends: raise ValueError( "unsupported backend or required Python module" - + " unavailable: {}".format(backend_name) + + f" unavailable: {backend_name}" ) url = connect_spec.get("url", "ldapi:///") try: diff --git a/salt/modules/ldapmod.py b/salt/modules/ldapmod.py index 8b1e22d994e..f611e1e287a 100644 --- a/salt/modules/ldapmod.py +++ b/salt/modules/ldapmod.py @@ -39,7 +39,6 @@ Salt interface to LDAP commands badness may ensue - you have been warned. """ - import logging import time @@ -83,7 +82,7 @@ def _config(name, key=None, **kwargs): if name in kwargs: value = kwargs[name] else: - value = __salt__["config.option"]("ldap.{}".format(key)) + value = __salt__["config.option"](f"ldap.{key}") return salt.utils.data.decode(value, to_str=True) @@ -112,7 +111,7 @@ def search( dn=None, # pylint: disable=C0103 scope=None, attrs=None, - **kwargs + **kwargs, ): """ Run an arbitrary LDAP query and return the results. @@ -191,13 +190,13 @@ class _LDAPConnection: self.bindpw = bindpw if self.uri == "": - self.uri = "ldap://{}:{}".format(self.server, self.port) + self.uri = f"ldap://{self.server}:{self.port}" try: if no_verify: ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_NEVER) - self.ldap = ldap.initialize("{}".format(self.uri)) + self.ldap = ldap.initialize(f"{self.uri}") self.ldap.protocol_version = 3 # ldap.VERSION3 self.ldap.set_option(ldap.OPT_REFERRALS, 0) # Needed for AD diff --git a/salt/modules/libcloud_compute.py b/salt/modules/libcloud_compute.py index 73171caa553..038ebd3c58c 100644 --- a/salt/modules/libcloud_compute.py +++ b/salt/modules/libcloud_compute.py @@ -26,6 +26,7 @@ Clouds include Amazon EC2, Azure, Google GCE, VMware, OpenStack Nova :depends: apache-libcloud """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 @@ -786,7 +787,7 @@ def _get_by_id(collection, id): if not matches: raise ValueError("Could not find a matching item") elif len(matches) > 1: - raise ValueError("The id matched {} items, not 1".format(len(matches))) + raise ValueError(f"The id matched {len(matches)} items, not 1") return matches[0] diff --git a/salt/modules/libcloud_dns.py b/salt/modules/libcloud_dns.py index 182b7fb7820..33779286112 100644 --- a/salt/modules/libcloud_dns.py +++ b/salt/modules/libcloud_dns.py @@ -24,6 +24,7 @@ Connection module for Apache Libcloud DNS management :depends: apache-libcloud """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 diff --git a/salt/modules/libcloud_loadbalancer.py b/salt/modules/libcloud_loadbalancer.py index 08d768ef626..3fa4fd49467 100644 --- a/salt/modules/libcloud_loadbalancer.py +++ b/salt/modules/libcloud_loadbalancer.py @@ -26,6 +26,7 @@ Clouds include Amazon ELB, ALB, Google, Aliyun, CloudStack, Softlayer :depends: apache-libcloud """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 diff --git a/salt/modules/libcloud_storage.py b/salt/modules/libcloud_storage.py index 7e055ab30e5..51fc04b5512 100644 --- a/salt/modules/libcloud_storage.py +++ b/salt/modules/libcloud_storage.py @@ -26,6 +26,7 @@ Clouds include Amazon S3, Google Storage, Aliyun, Azure Blobs, Ceph, OpenStack s :depends: apache-libcloud """ + # keep lint from choking on _get_conn and _cache_id # pylint: disable=E0602 diff --git a/salt/modules/linux_acl.py b/salt/modules/linux_acl.py index e1fcf4a9c8f..ae121e9c1b7 100644 --- a/salt/modules/linux_acl.py +++ b/salt/modules/linux_acl.py @@ -69,7 +69,7 @@ def getfacl(*args, **kwargs): if recursive: cmd += " -R" for dentry in args: - cmd += ' "{}"'.format(dentry) + cmd += f' "{dentry}"' out = __salt__["cmd.run"](cmd, python_shell=False).splitlines() dentry = "" for line in out: @@ -186,7 +186,7 @@ def wipefacls(*args, **kwargs): if recursive: cmd += " -R" for dentry in args: - cmd += ' "{}"'.format(dentry) + cmd += f' "{dentry}"' __salt__["cmd.run"](cmd, python_shell=False) return True @@ -233,10 +233,10 @@ def modfacl(acl_type, acl_name="", perms="", *args, **kwargs): cmd += " -m" - cmd = "{} {}:{}:{}".format(cmd, _acl_prefix(acl_type), acl_name, perms) + cmd = f"{cmd} {_acl_prefix(acl_type)}:{acl_name}:{perms}" for dentry in args: - cmd += ' "{}"'.format(dentry) + cmd += f' "{dentry}"' __salt__["cmd.run"](cmd, python_shell=False, raise_err=raise_err) return True @@ -265,9 +265,9 @@ def delfacl(acl_type, acl_name="", *args, **kwargs): cmd += " -x" - cmd = "{} {}:{}".format(cmd, _acl_prefix(acl_type), acl_name) + cmd = f"{cmd} {_acl_prefix(acl_type)}:{acl_name}" for dentry in args: - cmd += ' "{}"'.format(dentry) + cmd += f' "{dentry}"' __salt__["cmd.run"](cmd, python_shell=False) return True diff --git a/salt/modules/linux_ip.py b/salt/modules/linux_ip.py index 01cc0e285d5..a7f6e960da9 100644 --- a/salt/modules/linux_ip.py +++ b/salt/modules/linux_ip.py @@ -45,7 +45,7 @@ def down(iface, iface_type=None): """ # Slave devices are controlled by the master. if iface_type not in ["slave"]: - return __salt__["cmd.run"]("ip link set {} down".format(iface)) + return __salt__["cmd.run"](f"ip link set {iface} down") return None @@ -92,7 +92,7 @@ def _ip_ifaces(): at_ = comps[0] if len(comps) % 2 != 0: last = comps.pop() - comps[-1] += " {}".format(last) + comps[-1] += f" {last}" ifi = iter(comps) ret[if_][at_] = dict(list(zip(ifi, ifi))) else: @@ -114,7 +114,7 @@ def up(iface, iface_type=None): """ # Slave devices are controlled by the master. if iface_type not in ["slave"]: - return __salt__["cmd.run"]("ip link set {} up".format(iface)) + return __salt__["cmd.run"](f"ip link set {iface} up") return None diff --git a/salt/modules/linux_lvm.py b/salt/modules/linux_lvm.py index 03803497aa6..d53caa0e073 100644 --- a/salt/modules/linux_lvm.py +++ b/salt/modules/linux_lvm.py @@ -245,11 +245,11 @@ def pvcreate(devices, override=True, force=True, **kwargs): for device in devices: if not os.path.exists(device): - return "{} does not exist".format(device) + return f"{device} does not exist" if not pvdisplay(device, quiet=True): cmd.append(device) elif not override: - return 'Device "{}" is already an LVM physical volume.'.format(device) + return f'Device "{device}" is already an LVM physical volume.' if not cmd[2:]: # All specified devices are already LVM volumes @@ -270,9 +270,9 @@ def pvcreate(devices, override=True, force=True, **kwargs): no_parameter = "norestorefile" for var in kwargs: if kwargs[var] and var in valid: - cmd.extend(["--{}".format(var), kwargs[var]]) + cmd.extend([f"--{var}", kwargs[var]]) elif kwargs[var] and var in no_parameter: - cmd.append("--{}".format(var)) + cmd.append(f"--{var}") out = __salt__["cmd.run_all"](cmd, python_shell=False) if out.get("retcode"): @@ -281,7 +281,7 @@ def pvcreate(devices, override=True, force=True, **kwargs): # Verify pvcreate was successful for device in devices: if not pvdisplay(device): - return 'Device "{}" was not affected.'.format(device) + return f'Device "{device}" was not affected.' return True @@ -313,7 +313,7 @@ def pvremove(devices, override=True, force=True): if pvdisplay(device): cmd.append(device) elif not override: - return "{} is not a physical volume".format(device) + return f"{device} is not a physical volume" if not cmd[2:]: # Nothing to do @@ -326,7 +326,7 @@ def pvremove(devices, override=True, force=True): # Verify pvremove was successful for device in devices: if pvdisplay(device, quiet=True): - return 'Device "{}" was not affected.'.format(device) + return f'Device "{device}" was not affected.' return True @@ -371,14 +371,14 @@ def vgcreate(vgname, devices, force=False, **kwargs): ) for var in kwargs: if kwargs[var] and var in valid: - cmd.append("--{}".format(var)) + cmd.append(f"--{var}") cmd.append(kwargs[var]) cmd_ret = __salt__["cmd.run_all"](cmd, python_shell=False) if cmd_ret.get("retcode"): out = cmd_ret.get("stderr").strip() else: - out = 'Volume group "{}" successfully created'.format(vgname) + out = f'Volume group "{vgname}" successfully created' vgdata = vgdisplay(vgname) vgdata["Output from vgcreate"] = out @@ -415,7 +415,7 @@ def vgextend(vgname, devices, force=False): if cmd_ret.get("retcode"): out = cmd_ret.get("stderr").strip() else: - out = 'Volume group "{}" successfully extended'.format(vgname) + out = f'Volume group "{vgname}" successfully extended' vgdata = {"Output from vgextend": out} return vgdata @@ -431,7 +431,7 @@ def lvcreate( thinvolume=False, thinpool=False, force=False, - **kwargs + **kwargs, ): """ Create a new logical volume, with option for which physical volume to be used @@ -494,9 +494,9 @@ def lvcreate( if kwargs: for k, v in kwargs.items(): if k in no_parameter: - extra_arguments.append("--{}".format(k)) + extra_arguments.append(f"--{k}") elif k in valid: - extra_arguments.extend(["--{}".format(k), "{}".format(v)]) + extra_arguments.extend([f"--{k}", f"{v}"]) cmd = [salt.utils.path.which("lvcreate")] @@ -508,18 +508,18 @@ def lvcreate( cmd.extend(["-n", lvname]) if snapshot: - cmd.extend(["-s", "{}/{}".format(vgname, snapshot)]) + cmd.extend(["-s", f"{vgname}/{snapshot}"]) else: cmd.append(vgname) if size and thinvolume: - cmd.extend(["-V", "{}".format(size)]) + cmd.extend(["-V", f"{size}"]) elif extents and thinvolume: return "Error: Thin volume size cannot be specified as extents" elif size: - cmd.extend(["-L", "{}".format(size)]) + cmd.extend(["-L", f"{size}"]) elif extents: - cmd.extend(["-l", "{}".format(extents)]) + cmd.extend(["-l", f"{extents}"]) else: return "Error: Either size or extents must be specified" @@ -537,9 +537,9 @@ def lvcreate( if cmd_ret.get("retcode"): out = cmd_ret.get("stderr").strip() else: - out = 'Logical volume "{}" created.'.format(lvname) + out = f'Logical volume "{lvname}" created.' - lvdev = "/dev/{}/{}".format(vgname, lvname) + lvdev = f"/dev/{vgname}/{lvname}" lvdata = lvdisplay(lvdev) lvdata["Output from lvcreate"] = out return lvdata @@ -567,7 +567,7 @@ def vgremove(vgname, force=True): if cmd_ret.get("retcode"): out = cmd_ret.get("stderr").strip() else: - out = 'Volume group "{}" successfully removed'.format(vgname) + out = f'Volume group "{vgname}" successfully removed' return out @@ -581,7 +581,7 @@ def lvremove(lvname, vgname, force=True): salt '*' lvm.lvremove lvname vgname force=True """ - cmd = ["lvremove", "{}/{}".format(vgname, lvname)] + cmd = ["lvremove", f"{vgname}/{lvname}"] if force: cmd.append("--yes") @@ -592,7 +592,7 @@ def lvremove(lvname, vgname, force=True): if cmd_ret.get("retcode"): out = cmd_ret.get("stderr").strip() else: - out = 'Logical volume "{}" successfully removed'.format(lvname) + out = f'Logical volume "{lvname}" successfully removed' return out @@ -625,9 +625,9 @@ def lvresize(size=None, lvpath=None, extents=None, force=False, resizefs=False): cmd.append("--resizefs") if size: - cmd.extend(["-L", "{}".format(size)]) + cmd.extend(["-L", f"{size}"]) elif extents: - cmd.extend(["-l", "{}".format(extents)]) + cmd.extend(["-l", f"{extents}"]) else: log.error("Error: Either size or extents must be specified") return {} @@ -638,7 +638,7 @@ def lvresize(size=None, lvpath=None, extents=None, force=False, resizefs=False): if cmd_ret.get("retcode"): out = cmd_ret.get("stderr").strip() else: - out = 'Logical volume "{}" successfully resized.'.format(lvpath) + out = f'Logical volume "{lvpath}" successfully resized.' return {"Output from lvresize": out} @@ -671,9 +671,9 @@ def lvextend(size=None, lvpath=None, extents=None, force=False, resizefs=False): cmd.append("--resizefs") if size: - cmd.extend(["-L", "{}".format(size)]) + cmd.extend(["-L", f"{size}"]) elif extents: - cmd.extend(["-l", "{}".format(extents)]) + cmd.extend(["-l", f"{extents}"]) else: log.error("Error: Either size or extents must be specified") return {} @@ -684,7 +684,7 @@ def lvextend(size=None, lvpath=None, extents=None, force=False, resizefs=False): if cmd_ret.get("retcode"): out = cmd_ret.get("stderr").strip() else: - out = 'Logical volume "{}" successfully extended.'.format(lvpath) + out = f'Logical volume "{lvpath}" successfully extended.' return {"Output from lvextend": out} @@ -716,7 +716,7 @@ def pvresize(devices, override=True, force=True): if pvdisplay(device): cmd.append(device) elif not override: - return "{} is not a physical volume".format(device) + return f"{device} is not a physical volume" if not cmd[2:]: # Nothing to do diff --git a/salt/modules/linux_service.py b/salt/modules/linux_service.py index d26fc5a9799..4289fc6003f 100644 --- a/salt/modules/linux_service.py +++ b/salt/modules/linux_service.py @@ -43,7 +43,7 @@ def __virtual__(): return (False, "Non Linux OSes are not supported") init_grain = __grains__.get("init") if init_grain not in (None, "sysvinit", "unknown"): - return (False, "Minion is running {}".format(init_grain)) + return (False, f"Minion is running {init_grain}") elif __utils__["systemd.booted"](__context__): # Should have been caught by init grain check, but check just in case return (False, "Minion is running systemd") diff --git a/salt/modules/linux_shadow.py b/salt/modules/linux_shadow.py index aa149ac4c8e..09fe73fdb54 100644 --- a/salt/modules/linux_shadow.py +++ b/salt/modules/linux_shadow.py @@ -368,7 +368,7 @@ def set_password(name, password, use_usermod=False, root=None): # ALT Linux uses tcb to store password hashes. More information found # in manpage (http://docs.altlinux.org/manpages/tcb.5.html) if __grains__["os"] == "ALT": - s_file = "/etc/tcb/{}/shadow".format(name) + s_file = f"/etc/tcb/{name}/shadow" else: s_file = "/etc/shadow" if root: diff --git a/salt/modules/linux_sysctl.py b/salt/modules/linux_sysctl.py index fe63cb6c596..3cb77e36017 100644 --- a/salt/modules/linux_sysctl.py +++ b/salt/modules/linux_sysctl.py @@ -41,7 +41,7 @@ def _which(cmd): """ _cmd = salt.utils.path.which(cmd) if not _cmd: - raise CommandExecutionError("Command '{}' cannot be found".format(cmd)) + raise CommandExecutionError(f"Command '{cmd}' cannot be found") return _cmd @@ -137,13 +137,13 @@ def assign(name, value): tran_tab = name.translate("".maketrans("./", "/.")) - sysctl_file = "/proc/sys/{}".format(tran_tab) + sysctl_file = f"/proc/sys/{tran_tab}" if not os.path.exists(sysctl_file): - raise CommandExecutionError("sysctl {} does not exist".format(name)) + raise CommandExecutionError(f"sysctl {name} does not exist") ret = {} _sysctl = "{}".format(_which("sysctl")) - cmd = [_sysctl, "-w", "{}={}".format(name, value)] + cmd = [_sysctl, "-w", f"{name}={value}"] data = __salt__["cmd.run_all"](cmd, python_shell=False) out = data["stdout"] err = data["stderr"] @@ -151,14 +151,14 @@ def assign(name, value): # Example: # # sysctl -w net.ipv4.tcp_rmem="4096 87380 16777216" # net.ipv4.tcp_rmem = 4096 87380 16777216 - regex = re.compile(r"^{}\s+=\s+{}$".format(re.escape(name), re.escape(value))) + regex = re.compile(rf"^{re.escape(name)}\s+=\s+{re.escape(value)}$") if not regex.match(out) or "Invalid argument" in str(err): if data["retcode"] != 0 and err: error = err else: error = out - raise CommandExecutionError("sysctl -w failed: {}".format(error)) + raise CommandExecutionError(f"sysctl -w failed: {error}") new_name, new_value = out.split(" = ", 1) ret[new_name] = new_value return ret @@ -238,13 +238,13 @@ def persist(name, value, config=None): else: return "Already set" - nlines.append("{} = {}\n".format(name, value)) + nlines.append(f"{name} = {value}\n") edited = True continue else: nlines.append(line) if not edited: - nlines.append("{} = {}\n".format(name, value)) + nlines.append(f"{name} = {value}\n") try: with salt.utils.files.fopen(config, "wb") as _fh: _fh.writelines(salt.utils.data.encode(nlines)) diff --git a/salt/modules/localemod.py b/salt/modules/localemod.py index 8744535d1a1..e8cd9063ca3 100644 --- a/salt/modules/localemod.py +++ b/salt/modules/localemod.py @@ -109,11 +109,9 @@ def _localectl_set(locale=""): else _localectl_status().get("system_locale", {}) ) locale_params["LANG"] = str(locale) - args = " ".join( - ['{}="{}"'.format(k, v) for k, v in locale_params.items() if v is not None] - ) + args = " ".join([f'{k}="{v}"' for k, v in locale_params.items() if v is not None]) return not __salt__["cmd.retcode"]( - "localectl set-locale {}".format(args), python_shell=False + f"localectl set-locale {args}", python_shell=False ) @@ -204,7 +202,7 @@ def set_locale(locale): __salt__["file.replace"]( "/etc/sysconfig/language", "^RC_LANG=.*", - 'RC_LANG="{}"'.format(locale), + f'RC_LANG="{locale}"', append_if_not_found=True, ) elif "RedHat" in __grains__["os_family"]: @@ -213,7 +211,7 @@ def set_locale(locale): __salt__["file.replace"]( "/etc/sysconfig/i18n", "^LANG=.*", - 'LANG="{}"'.format(locale), + f'LANG="{locale}"', append_if_not_found=True, ) elif "Debian" in __grains__["os_family"]: @@ -227,11 +225,11 @@ def set_locale(locale): __salt__["file.replace"]( "/etc/default/locale", "^LANG=.*", - 'LANG="{}"'.format(locale), + f'LANG="{locale}"', append_if_not_found=True, ) elif "Gentoo" in __grains__["os_family"]: - cmd = "eselect --brief locale set {}".format(locale) + cmd = f"eselect --brief locale set {locale}" return __salt__["cmd.retcode"](cmd, python_shell=False) == 0 elif "Solaris" in __grains__["os_family"]: if locale not in __salt__["locale.list_avail"](): @@ -239,7 +237,7 @@ def set_locale(locale): __salt__["file.replace"]( "/etc/default/init", "^LANG=.*", - 'LANG="{}"'.format(locale), + f'LANG="{locale}"', append_if_not_found=True, ) else: @@ -319,9 +317,7 @@ def gen_locale(locale, **kwargs): if on_debian or on_gentoo: # file-based search search = "/usr/share/i18n/SUPPORTED" - valid = __salt__["file.search"]( - search, "^{}$".format(locale), flags=re.MULTILINE - ) + valid = __salt__["file.search"](search, f"^{locale}$", flags=re.MULTILINE) else: # directory-based search if on_suse: search = "/usr/share/locale" @@ -332,7 +328,7 @@ def gen_locale(locale, **kwargs): valid = locale_search_str in os.listdir(search) except OSError as ex: log.error(ex) - raise CommandExecutionError('Locale "{}" is not available.'.format(locale)) + raise CommandExecutionError(f'Locale "{locale}" is not available.') if not valid: log.error('The provided locale "%s" is not found in %s', locale, search) @@ -341,8 +337,8 @@ def gen_locale(locale, **kwargs): if os.path.exists("/etc/locale.gen"): __salt__["file.replace"]( "/etc/locale.gen", - r"^\s*#\s*{}\s*$".format(locale), - "{}\n".format(locale), + rf"^\s*#\s*{locale}\s*$", + f"{locale}\n", append_if_not_found=True, ) elif on_ubuntu: diff --git a/salt/modules/locate.py b/salt/modules/locate.py index fd4f2e3878c..aa8e1a2473c 100644 --- a/salt/modules/locate.py +++ b/salt/modules/locate.py @@ -111,13 +111,13 @@ def locate(pattern, database="", limit=0, **kwargs): if bool(kwargs[option]) is True and option in toggles: options += toggles[option] if options: - options = "-{}".format(options) + options = f"-{options}" if database: - options += " -d {}".format(database) + options += f" -d {database}" if limit > 0: - options += " -l {}".format(limit) + options += f" -l {limit}" if "regex" in kwargs and bool(kwargs["regex"]) is True: options += " --regex" - cmd = "locate {} {}".format(options, pattern) + cmd = f"locate {options} {pattern}" out = __salt__["cmd.run"](cmd, python_shell=False).splitlines() return out diff --git a/salt/modules/logadm.py b/salt/modules/logadm.py index 677e12f705b..9f50803ba40 100644 --- a/salt/modules/logadm.py +++ b/salt/modules/logadm.py @@ -119,7 +119,7 @@ def _parse_options(entry, options, include_unset=True): if "additional_options" not in log_cfg: log_cfg["additional_options"] = [] if " " in options[index]: - log_cfg["dditional_options"] = "'{}'".format(options[index]) + log_cfg["dditional_options"] = f"'{options[index]}'" else: log_cfg["additional_options"].append(options[index]) @@ -172,7 +172,7 @@ def show_conf(conf_file=default_conf, name=None): if name and name in cfg: return {name: cfg[name]} elif name: - return {name: "not found in {}".format(conf_file)} + return {name: f"not found in {conf_file}"} else: return cfg @@ -212,7 +212,7 @@ def list_conf(conf_file=default_conf, log_file=None, include_unset=False): if log_file and log_file in cfg_parsed: return {log_file: cfg_parsed[log_file]} elif log_file: - return {log_file: "not found in {}".format(conf_file)} + return {log_file: f"not found in {conf_file}"} else: return cfg_parsed @@ -286,7 +286,7 @@ def rotate(name, pattern=None, conf_file=default_conf, **kwargs): ## build command log.debug("logadm.rotate - kwargs: %s", kwargs) - command = "logadm -f {}".format(conf_file) + command = f"logadm -f {conf_file}" for arg, val in kwargs.items(): if arg in option_toggles.values() and val: command = "{} {}".format( @@ -294,7 +294,7 @@ def rotate(name, pattern=None, conf_file=default_conf, **kwargs): _arg2opt(arg), ) elif arg in option_flags.values(): - command = "{} {} {}".format(command, _arg2opt(arg), shlex.quote(str(val))) + command = f"{command} {_arg2opt(arg)} {shlex.quote(str(val))}" elif arg != "log_file": log.warning("Unknown argument %s, don't know how to map this!", arg) if "log_file" in kwargs: @@ -329,7 +329,7 @@ def remove(name, conf_file=default_conf): salt '*' logadm.remove myapplog """ - command = "logadm -f {} -r {}".format(conf_file, name) + command = f"logadm -f {conf_file} -r {name}" result = __salt__["cmd.run_all"](command, python_shell=False) if result["retcode"] != 0: return dict( diff --git a/salt/modules/logrotate.py b/salt/modules/logrotate.py index 314fc607cfc..2e29876da81 100644 --- a/salt/modules/logrotate.py +++ b/salt/modules/logrotate.py @@ -211,7 +211,7 @@ def set_(key, value, setting=None, conf_file=_DEFAULT_CONF): "flags": 8, "backup": False, "path": conf_file, - "pattern": "^{}.*".format(key), + "pattern": f"^{key}.*", "show_changes": False, } @@ -232,7 +232,7 @@ def set_(key, value, setting=None, conf_file=_DEFAULT_CONF): if value is True: new_line = key elif value: - new_line = "{} {}".format(key, value) + new_line = f"{key} {value}" kwargs.update({"prepend_if_not_found": True}) else: @@ -259,7 +259,7 @@ def set_(key, value, setting=None, conf_file=_DEFAULT_CONF): kwargs.update( { - "pattern": "^{0}.*?{{.*?}}".format(key), + "pattern": f"^{key}.*?{{.*?}}", "flags": 24, "append_if_not_found": True, } @@ -279,5 +279,5 @@ def _dict_to_stanza(key, stanza): for skey in stanza: if stanza[skey] is True: stanza[skey] = "" - ret += " {} {}\n".format(skey, stanza[skey]) - return "{0} {{\n{1}}}".format(key, ret) + ret += f" {skey} {stanza[skey]}\n" + return f"{key} {{\n{ret}}}" diff --git a/salt/modules/lvs.py b/salt/modules/lvs.py index a5f2aec02ae..212a5c6f0fc 100644 --- a/salt/modules/lvs.py +++ b/salt/modules/lvs.py @@ -192,7 +192,7 @@ def add_server( server_address=None, packet_forward_method="dr", weight=1, - **kwargs + **kwargs, ): """ @@ -228,7 +228,7 @@ def add_server( server_address=server_address, packet_forward_method=packet_forward_method, weight=weight, - **kwargs + **kwargs, ), ) out = __salt__["cmd.run_all"](cmd, python_shell=False) @@ -247,7 +247,7 @@ def edit_server( server_address=None, packet_forward_method=None, weight=None, - **kwargs + **kwargs, ): """ @@ -283,7 +283,7 @@ def edit_server( server_address=server_address, packet_forward_method=packet_forward_method, weight=weight, - **kwargs + **kwargs, ), ) out = __salt__["cmd.run_all"](cmd, python_shell=False) @@ -347,7 +347,7 @@ def clear(): salt '*' lvs.clear """ - cmd = "{} -C".format(__detect_os()) + cmd = f"{__detect_os()} -C" out = __salt__["cmd.run_all"](cmd, python_shell=False) @@ -371,7 +371,7 @@ def get_rules(): salt '*' lvs.get_rules """ - cmd = "{} -S -n".format(__detect_os()) + cmd = f"{__detect_os()} -S -n" ret = __salt__["cmd.run"](cmd, python_shell=False) return ret @@ -395,7 +395,7 @@ def list_(protocol=None, service_address=None): _build_cmd(protocol=protocol, service_address=service_address), ) else: - cmd = "{} -L -n".format(__detect_os()) + cmd = f"{__detect_os()} -L -n" out = __salt__["cmd.run_all"](cmd, python_shell=False) # A non-zero return code means fail @@ -425,7 +425,7 @@ def zero(protocol=None, service_address=None): _build_cmd(protocol=protocol, service_address=service_address), ) else: - cmd = "{} -Z".format(__detect_os()) + cmd = f"{__detect_os()} -Z" out = __salt__["cmd.run_all"](cmd, python_shell=False) # A non-zero return code means fail @@ -482,7 +482,7 @@ def check_server(protocol=None, service_address=None, server_address=None, **kwa protocol=protocol, service_address=service_address, server_address=server_address, - **kwargs + **kwargs, ) ) # Exact match diff --git a/salt/modules/lxc.py b/salt/modules/lxc.py index ba03d1f4180..a74077eacae 100644 --- a/salt/modules/lxc.py +++ b/salt/modules/lxc.py @@ -1666,9 +1666,9 @@ def init( ret["result"] = False else: if not result: - ret[ - "comment" - ] = "Bootstrap failed, see minion log for more information" + ret["comment"] = ( + "Bootstrap failed, see minion log for more information" + ) ret["result"] = False else: changes.append({"bootstrap": "Container successfully bootstrapped"}) @@ -3274,7 +3274,6 @@ def systemd_running_state(name, path=None): def test_sd_started_state(name, path=None): - """ Test if a systemd container is fully started diff --git a/salt/modules/lxd.py b/salt/modules/lxd.py index da87ca08f5a..dd0a9e49216 100644 --- a/salt/modules/lxd.py +++ b/salt/modules/lxd.py @@ -31,7 +31,6 @@ several functions to help manage it and its containers. :platform: Linux """ - import logging import os from datetime import datetime @@ -181,31 +180,31 @@ def init( salt '*' lxd.init """ - cmd = 'lxd init --auto --storage-backend="{}"'.format(storage_backend) + cmd = f'lxd init --auto --storage-backend="{storage_backend}"' if trust_password is not None: - cmd = cmd + ' --trust-password="{}"'.format(trust_password) + cmd = cmd + f' --trust-password="{trust_password}"' if network_address is not None: - cmd = cmd + ' --network-address="{}"'.format(network_address) + cmd = cmd + f' --network-address="{network_address}"' if network_port is not None: - cmd = cmd + ' --network-port="{}"'.format(network_port) + cmd = cmd + f' --network-port="{network_port}"' if storage_create_device is not None: - cmd = cmd + ' --storage-create-device="{}"'.format(storage_create_device) + cmd = cmd + f' --storage-create-device="{storage_create_device}"' if storage_create_loop is not None: - cmd = cmd + ' --storage-create-loop="{}"'.format(storage_create_loop) + cmd = cmd + f' --storage-create-loop="{storage_create_loop}"' if storage_pool is not None: - cmd = cmd + ' --storage-pool="{}"'.format(storage_pool) + cmd = cmd + f' --storage-pool="{storage_pool}"' try: output = __salt__["cmd.run"](cmd) except ValueError as e: raise CommandExecutionError( - "Failed to call: '{}', error was: {}".format(cmd, str(e)), + f"Failed to call: '{cmd}', error was: {str(e)}", ) if "error:" in output: @@ -249,7 +248,7 @@ def config_set(key, value): output[output.index("error:") + 7 :], ) - return ('Config value "{}" successfully set.'.format(key),) + return (f'Config value "{key}" successfully set.',) @salt.utils.decorators.path.which("lxd") @@ -268,7 +267,7 @@ def config_get(key): salt '*' lxd.config_get core.https_address """ - cmd = 'lxc config get "{}"'.format(key) + cmd = f'lxc config get "{key}"' output = __salt__["cmd.run"](cmd) if "error:" in output: @@ -375,7 +374,7 @@ def pylxd_client_get(remote_addr=None, cert=None, key=None, verify_cert=True): verify=verify_cert, ) except pylxd.exceptions.ClientConnectionFailed: - raise CommandExecutionError("Failed to connect to '{}'".format(remote_addr)) + raise CommandExecutionError(f"Failed to connect to '{remote_addr}'") except TypeError as e: # Happens when the verification failed. @@ -747,7 +746,7 @@ def container_get( try: containers = [client.containers.get(name)] except pylxd.exceptions.LXDAPIException: - raise SaltInvocationError("Container '{}' not found".format(name)) + raise SaltInvocationError(f"Container '{name}' not found") if _raw: return containers[0] @@ -834,9 +833,7 @@ def container_rename( container = container_get(name, remote_addr, cert, key, verify_cert, _raw=True) if container.status_code == CONTAINER_STATUS_RUNNING: - raise SaltInvocationError( - "Can't rename the running container '{}'.".format(name) - ) + raise SaltInvocationError(f"Can't rename the running container '{name}'.") container.rename(newname, wait=True) return _pylxd_model_to_dict(container) @@ -879,7 +876,7 @@ def container_state(name=None, remote_addr=None, cert=None, key=None, verify_cer try: containers = [client.containers.get(name)] except pylxd.exceptions.LXDAPIException: - raise SaltInvocationError("Container '{}' not found".format(name)) + raise SaltInvocationError(f"Container '{name}' not found") states = [] for container in containers: @@ -1387,7 +1384,7 @@ def container_device_add( cert=None, key=None, verify_cert=True, - **kwargs + **kwargs, ): """ Add a container device @@ -1567,7 +1564,7 @@ def container_file_put( # and integer, handle it as if it where a octal representation. mode = str(mode) if not mode.startswith("0"): - mode = "0{}".format(mode) + mode = f"0{mode}" container = container_get(name, remote_addr, cert, key, verify_cert, _raw=True) @@ -1577,7 +1574,7 @@ def container_file_put( if src.find("://") >= 0: cached_file = __salt__["cp.cache_file"](src, saltenv=saltenv) if not cached_file: - raise SaltInvocationError("File '{}' not found".format(src)) + raise SaltInvocationError(f"File '{src}' not found") if not os.path.isabs(cached_file): raise SaltInvocationError("File path must be absolute.") src = cached_file @@ -1588,7 +1585,7 @@ def container_file_put( src = os.path.sep if not os.path.exists(src): - raise CommandExecutionError("No such file or directory '{}'".format(src)) + raise CommandExecutionError(f"No such file or directory '{src}'") if os.path.isdir(src) and not recursive: raise SaltInvocationError( @@ -1771,7 +1768,7 @@ def container_file_get( if mode is not None: mode = str(mode) if not mode.startswith("0"): - mode = "0{}".format(mode) + mode = f"0{mode}" container = container_get(name, remote_addr, cert, key, verify_cert, _raw=True) @@ -1792,9 +1789,7 @@ def container_file_get( else: dst_path = os.path.dirname(dst) if not os.path.isdir(dst_path): - raise CommandExecutionError( - "No such file or directory '{}'".format(dst_path) - ) + raise CommandExecutionError(f"No such file or directory '{dst_path}'") # Seems to be duplicate of line 1794, produces /path/file_name/file_name # dst = os.path.join(dst, os.path.basename(src)) @@ -2075,7 +2070,7 @@ def profile_get( try: profile = client.profiles.get(name) except pylxd.exceptions.LXDAPIException: - raise SaltInvocationError("Profile '{}' not found".format(name)) + raise SaltInvocationError(f"Profile '{name}' not found") if _raw: return profile @@ -2331,7 +2326,7 @@ def profile_device_set( cert=None, key=None, verify_cert=True, - **kwargs + **kwargs, ): """Set a profile device. @@ -2532,9 +2527,7 @@ def image_get( try: image = client.images.get(fingerprint) except pylxd.exceptions.LXDAPIException: - raise SaltInvocationError( - "Image with fingerprint '{}' not found".format(fingerprint) - ) + raise SaltInvocationError(f"Image with fingerprint '{fingerprint}' not found") if _raw: return image @@ -2590,7 +2583,7 @@ def image_get_by_alias( try: image = client.images.get_by_alias(alias) except pylxd.exceptions.LXDAPIException: - raise SaltInvocationError("Image with alias '{}' not found".format(alias)) + raise SaltInvocationError(f"Image with alias '{alias}' not found") if _raw: return image @@ -3442,17 +3435,17 @@ 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: - config_changes[ - k - ] = 'Would change config key "{}" to "{}", its current value is "{}"'.format( - k, newconfig[k], obj.config[k] + config_changes[k] = ( + 'Would change config key "{}" to "{}", its current value is "{}"'.format( + k, newconfig[k], obj.config[k] + ) ) # New keys @@ -3462,7 +3455,7 @@ def sync_config_devices(obj, newconfig, newdevices, test=False): continue if not test: - config_changes[k] = 'Added config key "{}" = "{}"'.format(k, newconfig[k]) + config_changes[k] = f'Added config key "{k}" = "{newconfig[k]}"' obj.config[k] = newconfig[k] else: config_changes[k] = 'Would add config key "{}" = "{}"'.format( @@ -3489,10 +3482,10 @@ def sync_config_devices(obj, newconfig, newdevices, test=False): continue if not test: - devices_changes[k] = 'Removed device "{}"'.format(k) + devices_changes[k] = f'Removed device "{k}"' del obj.devices[k] else: - devices_changes[k] = 'Would remove device "{}"'.format(k) + devices_changes[k] = f'Would remove device "{k}"' # Changed devices for k, v in obj.devices.items(): @@ -3506,10 +3499,10 @@ def sync_config_devices(obj, newconfig, newdevices, test=False): if newdevices[k] != v: if not test: - devices_changes[k] = 'Changed device "{}"'.format(k) + devices_changes[k] = f'Changed device "{k}"' obj.devices[k] = newdevices[k] else: - devices_changes[k] = 'Would change device "{}"'.format(k) + devices_changes[k] = f'Would change device "{k}"' # New devices for k in ndk.difference(dk): @@ -3518,10 +3511,10 @@ def sync_config_devices(obj, newconfig, newdevices, test=False): continue if not test: - devices_changes[k] = 'Added device "{}"'.format(k) + devices_changes[k] = f'Added device "{k}"' obj.devices[k] = newdevices[k] else: - devices_changes[k] = 'Would add device "{}"'.format(k) + devices_changes[k] = f'Would add device "{k}"' if devices_changes: changes["devices"] = devices_changes @@ -3567,7 +3560,7 @@ def _set_property_dict_item(obj, prop, key, value): def _get_property_dict_item(obj, prop, key): attr = getattr(obj, prop) if key not in attr: - raise SaltInvocationError("'{}' doesn't exists".format(key)) + raise SaltInvocationError(f"'{key}' doesn't exists") return attr[key] @@ -3575,7 +3568,7 @@ def _get_property_dict_item(obj, prop, key): def _delete_property_dict_item(obj, prop, key): attr = getattr(obj, prop) if key not in attr: - raise SaltInvocationError("'{}' doesn't exists".format(key)) + raise SaltInvocationError(f"'{key}' doesn't exists") del attr[key] pylxd_save_object(obj) @@ -3599,7 +3592,7 @@ def _verify_image(image, remote_addr=None, cert=None, key=None, verify_cert=True except SaltInvocationError: image = image_get(name, remote_addr, cert, key, verify_cert, _raw=True) elif not hasattr(image, "fingerprint"): - raise SaltInvocationError("Invalid image '{}'".format(image)) + raise SaltInvocationError(f"Invalid image '{image}'") return image diff --git a/salt/modules/mac_desktop.py b/salt/modules/mac_desktop.py index eb58cf2888e..0c457080d28 100644 --- a/salt/modules/mac_desktop.py +++ b/salt/modules/mac_desktop.py @@ -48,7 +48,7 @@ def set_output_volume(volume): salt '*' desktop.set_output_volume """ - cmd = 'osascript -e "set volume output volume {}"'.format(volume) + cmd = f'osascript -e "set volume output volume {volume}"' call = __salt__["cmd.run_all"](cmd, output_loglevel="debug", python_shell=False) _check_cmd(call) @@ -125,6 +125,6 @@ def _check_cmd(call): if std_out: comment += std_out - raise CommandExecutionError("Error running command: {}".format(comment)) + raise CommandExecutionError(f"Error running command: {comment}") return call diff --git a/salt/modules/mac_group.py b/salt/modules/mac_group.py index 4c13f598802..0f4337cb2c3 100644 --- a/salt/modules/mac_group.py +++ b/salt/modules/mac_group.py @@ -1,6 +1,7 @@ """ Manage groups on Mac OS 10.7+ """ + import logging import salt.utils.functools @@ -57,7 +58,7 @@ def add(name, gid=None, **kwargs): ### NOTE: **kwargs isn't used here but needs to be included in this ### function for compatibility with the group.present state if info(name): - raise CommandExecutionError("Group '{}' already exists".format(name)) + raise CommandExecutionError(f"Group '{name}' already exists") if salt.utils.stringutils.contains_whitespace(name): raise SaltInvocationError("Group name cannot contain whitespace") if name.startswith("_"): @@ -71,7 +72,7 @@ def add(name, gid=None, **kwargs): # check if gid is already in use gid_list = _list_gids() if str(gid) in gid_list: - raise CommandExecutionError("gid '{}' already exists".format(gid)) + raise CommandExecutionError(f"gid '{gid}' already exists") cmd = ["dseditgroup", "-o", "create"] if gid: @@ -129,7 +130,7 @@ def adduser(group, name): Verifies if a valid username 'bar' as a member of an existing group 'foo', if not then adds it. """ - cmd = "dscl . -merge /Groups/{} GroupMembership {}".format(group, name) + cmd = f"dscl . -merge /Groups/{group} GroupMembership {name}" return __salt__["cmd.retcode"](cmd) == 0 @@ -148,7 +149,7 @@ def deluser(group, name): Removes a member user 'bar' from a group 'foo'. If group is not present then returns True. """ - cmd = "dscl . -delete /Groups/{} GroupMembership {}".format(group, name) + cmd = f"dscl . -delete /Groups/{group} GroupMembership {name}" return __salt__["cmd.retcode"](cmd) == 0 @@ -169,7 +170,7 @@ def members(name, members_list): retcode = 1 grp_info = __salt__["group.info"](name) if grp_info and name in grp_info["name"]: - cmd = "/usr/bin/dscl . -delete /Groups/{} GroupMembership".format(name) + cmd = f"/usr/bin/dscl . -delete /Groups/{name} GroupMembership" retcode = __salt__["cmd.retcode"](cmd) == 0 for user in members_list.split(","): cmd = "/usr/bin/dscl . -merge /Groups/{} GroupMembership {}".format( @@ -254,7 +255,7 @@ def chgid(name, gid): pre_gid = __salt__["file.group_to_gid"](name) pre_info = info(name) if not pre_info: - raise CommandExecutionError("Group '{}' does not exist".format(name)) + raise CommandExecutionError(f"Group '{name}' does not exist") if gid == pre_info["gid"]: return True cmd = ["dseditgroup", "-o", "edit", "-i", gid, name] diff --git a/salt/modules/mac_pkgutil.py b/salt/modules/mac_pkgutil.py index 538db2fcf61..63c4bd46b43 100644 --- a/salt/modules/mac_pkgutil.py +++ b/salt/modules/mac_pkgutil.py @@ -68,10 +68,10 @@ def _install_from_path(path): Internal function to install a package from the given path """ if not os.path.exists(path): - msg = "File not found: {}".format(path) + msg = f"File not found: {path}" raise SaltInvocationError(msg) - cmd = 'installer -pkg "{}" -target /'.format(path) + cmd = f'installer -pkg "{path}" -target /' return salt.utils.mac_utils.execute_return_success(cmd) @@ -97,7 +97,7 @@ def install(source, package_id): uri = urllib.parse.urlparse(source) if not uri.scheme == "": - msg = "Unsupported scheme for source uri: {}".format(uri.scheme) + msg = f"Unsupported scheme for source uri: {uri.scheme}" raise SaltInvocationError(msg) _install_from_path(source) @@ -125,6 +125,6 @@ def forget(package_id): salt '*' pkgutil.forget com.apple.pkg.gcc4.2Leo """ - cmd = "pkgutil --forget {}".format(package_id) + cmd = f"pkgutil --forget {package_id}" salt.utils.mac_utils.execute_return_success(cmd) return not is_installed(package_id) diff --git a/salt/modules/mac_portspkg.py b/salt/modules/mac_portspkg.py index 70cb23039fb..2113af467d3 100644 --- a/salt/modules/mac_portspkg.py +++ b/salt/modules/mac_portspkg.py @@ -62,7 +62,7 @@ def __virtual__(): def _list(query=""): - cmd = "port list {}".format(query) + cmd = f"port list {query}" out = salt.utils.mac_utils.execute_return_result(cmd) ret = {} @@ -178,7 +178,7 @@ def latest_version(*names, **kwargs): ): ret[key] = val else: - ret[key] = "{} (installed)".format(version(key)) + ret[key] = f"{version(key)} (installed)" return ret diff --git a/salt/modules/mac_shadow.py b/salt/modules/mac_shadow.py index 1297971fca2..c484d5db967 100644 --- a/salt/modules/mac_shadow.py +++ b/salt/modules/mac_shadow.py @@ -6,6 +6,7 @@ Manage macOS local directory passwords and policies Note that it is usually better to apply password policies through the creation of a configuration profile. """ + # Authentication concepts reference: # https://developer.apple.com/library/mac/documentation/Networking/Conceptual/Open_Directory/openDirectoryConcepts/openDirectoryConcepts.html#//apple_ref/doc/uid/TP40000917-CH3-CIFCAIBB diff --git a/salt/modules/mac_softwareupdate.py b/salt/modules/mac_softwareupdate.py index 0b5df536210..22d69f7199e 100644 --- a/salt/modules/mac_softwareupdate.py +++ b/salt/modules/mac_softwareupdate.py @@ -311,7 +311,7 @@ def update(name): salt '*' softwareupdate.update """ if not update_available(name): - raise SaltInvocationError("Update not available: {}".format(name)) + raise SaltInvocationError(f"Update not available: {name}") cmd = ["softwareupdate", "--install", name] salt.utils.mac_utils.execute_return_success(cmd) @@ -390,7 +390,7 @@ def download(name): salt '*' softwareupdate.download """ if not update_available(name): - raise SaltInvocationError("Update not available: {}".format(name)) + raise SaltInvocationError(f"Update not available: {name}") if name in list_downloads(): return True diff --git a/salt/modules/mac_sysctl.py b/salt/modules/mac_sysctl.py index 9fe3cc60f03..16f67e09a3b 100644 --- a/salt/modules/mac_sysctl.py +++ b/salt/modules/mac_sysctl.py @@ -66,14 +66,14 @@ def show(config_file=False): # # Yes. That's two `kern.clockrate`. # - if any([line.startswith("{}.".format(root)) for root in roots]): + if any([line.startswith(f"{root}.") for root in roots]): comps = line.split(": " if ": " in line else " = ", 1) if len(comps) == 2: ret[comps[0]] = comps[1] else: ret[comps[0]] = "" elif comps[0]: - ret[comps[0]] += "{}\n".format(line) + ret[comps[0]] += f"{line}\n" else: continue return ret @@ -92,7 +92,7 @@ def get(name): salt '*' sysctl.get hw.physmem """ - cmd = "sysctl -n {}".format(name) + cmd = f"sysctl -n {name}" out = __salt__["cmd.run"](cmd, python_shell=False) return out @@ -114,7 +114,7 @@ def assign(name, value): salt '*' sysctl.assign net.inet.icmp.icmplim 50 """ ret = {} - cmd = 'sysctl -w {}="{}"'.format(name, value) + cmd = f'sysctl -w {name}="{value}"' data = __salt__["cmd.run_all"](cmd, python_shell=False) if data["retcode"] != 0: @@ -165,7 +165,7 @@ def persist(name, value, config="/etc/sysctl.conf", apply_change=False): with salt.utils.files.fopen(config, "r") as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) - if not line.startswith("{}=".format(name)): + if not line.startswith(f"{name}="): nlines.append(line) continue else: @@ -179,10 +179,10 @@ def persist(name, value, config="/etc/sysctl.conf", apply_change=False): rest = rest[len(rest_v) :] if rest_v == value: return "Already set" - nlines.append("{}={}\n".format(name, value)) + nlines.append(f"{name}={value}\n") edited = True if not edited: - nlines.append("{}={}\n".format(name, value)) + nlines.append(f"{name}={value}\n") nlines = [salt.utils.stringutils.to_str(_l) for _l in nlines] with salt.utils.files.fopen(config, "w+") as ofile: ofile.writelines(nlines) diff --git a/salt/modules/mac_timezone.py b/salt/modules/mac_timezone.py index 5703ab08784..26549c44882 100644 --- a/salt/modules/mac_timezone.py +++ b/salt/modules/mac_timezone.py @@ -53,7 +53,7 @@ def _get_date_time_format(dt_string): return dt_format except ValueError: continue - msg = "Invalid Date/Time Format: {}".format(dt_string) + msg = f"Invalid Date/Time Format: {dt_string}" raise SaltInvocationError(msg) @@ -237,11 +237,9 @@ def set_zone(time_zone): salt '*' timezone.set_zone America/Denver """ if time_zone not in list_zones(): - raise SaltInvocationError("Invalid Timezone: {}".format(time_zone)) + raise SaltInvocationError(f"Invalid Timezone: {time_zone}") - salt.utils.mac_utils.execute_return_success( - "systemsetup -settimezone {}".format(time_zone) - ) + salt.utils.mac_utils.execute_return_success(f"systemsetup -settimezone {time_zone}") return time_zone in get_zone() @@ -303,7 +301,7 @@ def set_using_network_time(enable): """ state = salt.utils.mac_utils.validate_enabled(enable) - cmd = "systemsetup -setusingnetworktime {}".format(state) + cmd = f"systemsetup -setusingnetworktime {state}" salt.utils.mac_utils.execute_return_success(cmd) return state == salt.utils.mac_utils.validate_enabled(get_using_network_time()) @@ -349,7 +347,7 @@ def set_time_server(time_server="time.apple.com"): salt '*' timezone.set_time_server time.acme.com """ - cmd = "systemsetup -setnetworktimeserver {}".format(time_server) + cmd = f"systemsetup -setnetworktimeserver {time_server}" salt.utils.mac_utils.execute_return_success(cmd) return time_server in get_time_server() diff --git a/salt/modules/mac_user.py b/salt/modules/mac_user.py index 7e4f1b25965..d5fd6e98665 100644 --- a/salt/modules/mac_user.py +++ b/salt/modules/mac_user.py @@ -79,7 +79,7 @@ def add( shell=None, fullname=None, createhome=True, - **kwargs + **kwargs, ): """ Add a user to the minion @@ -91,7 +91,7 @@ def add( salt '*' user.add name """ if info(name): - raise CommandExecutionError("User '{}' already exists".format(name)) + raise CommandExecutionError(f"User '{name}' already exists") if salt.utils.stringutils.contains_whitespace(name): raise SaltInvocationError("Username cannot contain whitespace") @@ -101,7 +101,7 @@ def add( if gid is None: gid = 20 # gid 20 == 'staff', the default group if home is None: - home = "/Users/{}".format(name) + home = f"/Users/{name}" if shell is None: shell = "/bin/bash" if fullname is None: @@ -112,7 +112,7 @@ def add( if not isinstance(gid, int): raise SaltInvocationError("gid must be an integer") - name_path = "/Users/{}".format(name) + name_path = f"/Users/{name}" _dscl([name_path, "UniqueID", uid]) _dscl([name_path, "PrimaryGroupID", gid]) _dscl([name_path, "UserShell", shell]) @@ -155,7 +155,7 @@ def delete(name, remove=False, force=False): # group membership is managed separately from users and an entry for the # user will persist even after the user is removed. chgroups(name, ()) - ret = _dscl(["/Users/{}".format(name)], ctype="delete")["retcode"] == 0 + ret = _dscl([f"/Users/{name}"], ctype="delete")["retcode"] == 0 if ret and remove: # remove home directory from filesystem __salt__["file.remove"](user_info["home"]) @@ -196,10 +196,10 @@ def chuid(name, uid): raise SaltInvocationError("uid must be an integer") pre_info = info(name) if not pre_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") if uid == pre_info["uid"]: return True - _dscl(["/Users/{}".format(name), "UniqueID", pre_info["uid"], uid], ctype="change") + _dscl([f"/Users/{name}", "UniqueID", pre_info["uid"], uid], ctype="change") # dscl buffers changes, sleep 1 second before checking if new value # matches desired value time.sleep(1) @@ -220,11 +220,11 @@ def chgid(name, gid): raise SaltInvocationError("gid must be an integer") pre_info = info(name) if not pre_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") if gid == pre_info["gid"]: return True _dscl( - ["/Users/{}".format(name), "PrimaryGroupID", pre_info["gid"], gid], + [f"/Users/{name}", "PrimaryGroupID", pre_info["gid"], gid], ctype="change", ) # dscl buffers changes, sleep 1 second before checking if new value @@ -245,11 +245,11 @@ def chshell(name, shell): """ pre_info = info(name) if not pre_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") if shell == pre_info["shell"]: return True _dscl( - ["/Users/{}".format(name), "UserShell", pre_info["shell"], shell], + [f"/Users/{name}", "UserShell", pre_info["shell"], shell], ctype="change", ) # dscl buffers changes, sleep 1 second before checking if new value @@ -277,11 +277,11 @@ def chhome(name, home, **kwargs): pre_info = info(name) if not pre_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") if home == pre_info["home"]: return True _dscl( - ["/Users/{}".format(name), "NFSHomeDirectory", pre_info["home"], home], + [f"/Users/{name}", "NFSHomeDirectory", pre_info["home"], home], ctype="change", ) # dscl buffers changes, sleep 1 second before checking if new value @@ -303,12 +303,12 @@ def chfullname(name, fullname): fullname = salt.utils.data.decode(fullname) pre_info = info(name) if not pre_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") pre_info["fullname"] = salt.utils.data.decode(pre_info["fullname"]) if fullname == pre_info["fullname"]: return True _dscl( - ["/Users/{}".format(name), "RealName", fullname], + [f"/Users/{name}", "RealName", fullname], # use a 'create' command, because a 'change' command would fail if # current fullname is an empty string. The 'create' will just overwrite # this field. @@ -346,7 +346,7 @@ def chgroups(name, groups, append=False): ### function for compatibility with the user.present state uinfo = info(name) if not uinfo: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") if isinstance(groups, str): groups = groups.split(",") @@ -364,11 +364,11 @@ def chgroups(name, groups, append=False): return True # Add groups from which user is missing for group in desired - ugrps: - _dscl(["/Groups/{}".format(group), "GroupMembership", name], ctype="append") + _dscl([f"/Groups/{group}", "GroupMembership", name], ctype="append") if not append: # Remove from extra groups for group in ugrps - desired: - _dscl(["/Groups/{}".format(group), "GroupMembership", name], ctype="delete") + _dscl([f"/Groups/{group}", "GroupMembership", name], ctype="delete") time.sleep(1) return set(list_groups(name)) == desired @@ -472,11 +472,11 @@ def rename(name, new_name): """ current_info = info(name) if not current_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") new_info = info(new_name) if new_info: - raise CommandExecutionError("User '{}' already exists".format(new_name)) - _dscl(["/Users/{}".format(name), "RecordName", name, new_name], ctype="change") + raise CommandExecutionError(f"User '{new_name}' already exists") + _dscl([f"/Users/{name}", "RecordName", name, new_name], ctype="change") # dscl buffers changes, sleep 1 second before checking if new value # matches desired value time.sleep(1) diff --git a/salt/modules/mac_xattr.py b/salt/modules/mac_xattr.py index e2bbf1c503a..b7b742965a6 100644 --- a/salt/modules/mac_xattr.py +++ b/salt/modules/mac_xattr.py @@ -60,8 +60,8 @@ def list_(path, **kwargs): ret = salt.utils.mac_utils.execute_return_result(cmd) except CommandExecutionError as exc: if "No such file" in exc.strerror: - raise CommandExecutionError("File not found: {}".format(path)) - raise CommandExecutionError("Unknown Error: {}".format(exc.strerror)) + raise CommandExecutionError(f"File not found: {path}") + raise CommandExecutionError(f"Unknown Error: {exc.strerror}") if not ret: return {} @@ -115,10 +115,10 @@ def read(path, attribute, **kwargs): return exc.object.decode(errors="replace") except CommandExecutionError as exc: if "No such file" in exc.strerror: - raise CommandExecutionError("File not found: {}".format(path)) + raise CommandExecutionError(f"File not found: {path}") if "No such xattr" in exc.strerror: - raise CommandExecutionError("Attribute not found: {}".format(attribute)) - raise CommandExecutionError("Unknown Error: {}".format(exc.strerror)) + raise CommandExecutionError(f"Attribute not found: {attribute}") + raise CommandExecutionError(f"Unknown Error: {exc.strerror}") return ret @@ -161,8 +161,8 @@ def write(path, attribute, value, **kwargs): salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: if "No such file" in exc.strerror: - raise CommandExecutionError("File not found: {}".format(path)) - raise CommandExecutionError("Unknown Error: {}".format(exc.strerror)) + raise CommandExecutionError(f"File not found: {path}") + raise CommandExecutionError(f"Unknown Error: {exc.strerror}") return read(path, attribute, **{"hex": hex_}) == value @@ -188,15 +188,15 @@ def delete(path, attribute): salt '*' xattr.delete /path/to/file "com.test.attr" """ - cmd = 'xattr -d "{}" "{}"'.format(attribute, path) + cmd = f'xattr -d "{attribute}" "{path}"' try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: if "No such file" in exc.strerror: - raise CommandExecutionError("File not found: {}".format(path)) + raise CommandExecutionError(f"File not found: {path}") if "No such xattr" in exc.strerror: - raise CommandExecutionError("Attribute not found: {}".format(attribute)) - raise CommandExecutionError("Unknown Error: {}".format(exc.strerror)) + raise CommandExecutionError(f"Attribute not found: {attribute}") + raise CommandExecutionError(f"Unknown Error: {exc.strerror}") return attribute not in list_(path) @@ -217,12 +217,12 @@ def clear(path): salt '*' xattr.delete /path/to/file "com.test.attr" """ - cmd = 'xattr -c "{}"'.format(path) + cmd = f'xattr -c "{path}"' try: salt.utils.mac_utils.execute_return_success(cmd) except CommandExecutionError as exc: if "No such file" in exc.strerror: - raise CommandExecutionError("File not found: {}".format(path)) - raise CommandExecutionError("Unknown Error: {}".format(exc.strerror)) + raise CommandExecutionError(f"File not found: {path}") + raise CommandExecutionError(f"Unknown Error: {exc.strerror}") return list_(path) == {} diff --git a/salt/modules/macdefaults.py b/salt/modules/macdefaults.py index c805536fdd7..77f0e580afc 100644 --- a/salt/modules/macdefaults.py +++ b/salt/modules/macdefaults.py @@ -56,7 +56,7 @@ def write(domain, key, value, type="string", user=None): elif value is False: value = "FALSE" - cmd = 'defaults write "{}" "{}" -{} "{}"'.format(domain, key, type, value) + cmd = f'defaults write "{domain}" "{key}" -{type} "{value}"' return __salt__["cmd.run_all"](cmd, runas=user) @@ -82,7 +82,7 @@ def read(domain, key, user=None): The user to read the defaults as """ - cmd = 'defaults read "{}" "{}"'.format(domain, key) + cmd = f'defaults read "{domain}" "{key}"' return __salt__["cmd.run"](cmd, runas=user) @@ -108,5 +108,5 @@ def delete(domain, key, user=None): The user to delete the defaults with """ - cmd = 'defaults delete "{}" "{}"'.format(domain, key) + cmd = f'defaults delete "{domain}" "{key}"' return __salt__["cmd.run_all"](cmd, runas=user, output_loglevel="debug") diff --git a/salt/modules/makeconf.py b/salt/modules/makeconf.py index 446a72cfd31..b95d3b7bf23 100644 --- a/salt/modules/makeconf.py +++ b/salt/modules/makeconf.py @@ -42,7 +42,7 @@ def _add_var(var, value): """ makeconf = _get_makeconf() layman = "source /var/lib/layman/make.conf" - fullvar = '{}="{}"'.format(var, value) + fullvar = f'{var}="{value}"' if __salt__["file.contains"](makeconf, layman): # TODO perhaps make this a function in the file module? cmd = [ @@ -77,9 +77,7 @@ def set_var(var, value): # If var already in file, replace its value if old_value is not None: - __salt__["file.sed"]( - makeconf, "^{}=.*".format(var), '{}="{}"'.format(var, value) - ) + __salt__["file.sed"](makeconf, f"^{var}=.*", f'{var}="{value}"') else: _add_var(var, value) @@ -108,7 +106,7 @@ def remove_var(var): # If var is in file if old_value is not None: - __salt__["file.sed"](makeconf, "^{}=.*".format(var), "") + __salt__["file.sed"](makeconf, f"^{var}=.*", "") new_value = get_var(var) return {var: {"old": old_value, "new": new_value}} @@ -135,10 +133,8 @@ def append_var(var, value): # If var already in file, add to its value if old_value is not None: - appended_value = "{} {}".format(old_value, value) - __salt__["file.sed"]( - makeconf, "^{}=.*".format(var), '{}="{}"'.format(var, appended_value) - ) + appended_value = f"{old_value} {value}" + __salt__["file.sed"](makeconf, f"^{var}=.*", f'{var}="{appended_value}"') else: _add_var(var, value) diff --git a/salt/modules/mandrill.py b/salt/modules/mandrill.py index d9c7d333ecd..5896662d664 100644 --- a/salt/modules/mandrill.py +++ b/salt/modules/mandrill.py @@ -17,7 +17,6 @@ In the minion configuration file, the following block is required: .. versionadded:: 2018.3.0 """ - import logging import salt.utils.json diff --git a/salt/modules/marathon.py b/salt/modules/marathon.py index c749f28015e..6c2c73b429a 100644 --- a/salt/modules/marathon.py +++ b/salt/modules/marathon.py @@ -6,7 +6,6 @@ Currently this only works when run through a proxy minion. .. versionadded:: 2015.8.2 """ - import logging import salt.utils.http @@ -44,7 +43,7 @@ def _app_id(app_id): Make sure the app_id is in the correct format. """ if app_id[0] != "/": - app_id = "/{}".format(app_id) + app_id = f"/{app_id}" return app_id @@ -59,7 +58,7 @@ def apps(): salt marathon-minion-id marathon.apps """ response = salt.utils.http.query( - "{}/v2/apps".format(_base_url()), + f"{_base_url()}/v2/apps", decode_type="json", decode=True, ) @@ -90,7 +89,7 @@ def app(id): salt marathon-minion-id marathon.app my-app """ response = salt.utils.http.query( - "{}/v2/apps/{}".format(_base_url(), id), + f"{_base_url()}/v2/apps/{id}", decode_type="json", decode=True, ) @@ -116,7 +115,7 @@ def update_app(id, config): data = salt.utils.json.dumps(config) try: response = salt.utils.http.query( - "{}/v2/apps/{}?force=true".format(_base_url(), id), + f"{_base_url()}/v2/apps/{id}?force=true", method="PUT", decode_type="json", decode=True, @@ -144,7 +143,7 @@ def rm_app(id): salt marathon-minion-id marathon.rm_app my-app """ response = salt.utils.http.query( - "{}/v2/apps/{}".format(_base_url(), id), + f"{_base_url()}/v2/apps/{id}", method="DELETE", decode_type="json", decode=True, @@ -163,7 +162,7 @@ def info(): salt marathon-minion-id marathon.info """ response = salt.utils.http.query( - "{}/v2/info".format(_base_url()), + f"{_base_url()}/v2/info", decode_type="json", decode=True, ) @@ -202,7 +201,7 @@ def restart_app(id, restart=False, force=True): return ret try: response = salt.utils.http.query( - "{}/v2/apps/{}/restart?force={}".format(_base_url(), _app_id(id), force), + f"{_base_url()}/v2/apps/{_app_id(id)}/restart?force={force}", method="POST", decode_type="json", decode=True, diff --git a/salt/modules/mattermost.py b/salt/modules/mattermost.py index adb3cb7b676..5f821766a55 100644 --- a/salt/modules/mattermost.py +++ b/salt/modules/mattermost.py @@ -14,7 +14,6 @@ Module for sending messages to Mattermost api_url: https://example.com """ - import logging import salt.utils.json diff --git a/salt/modules/mdadm_raid.py b/salt/modules/mdadm_raid.py index e76f400a214..85e5d1e6247 100644 --- a/salt/modules/mdadm_raid.py +++ b/salt/modules/mdadm_raid.py @@ -1,6 +1,7 @@ """ Salt module to manage RAID arrays with mdadm """ + import logging import os import re @@ -142,7 +143,7 @@ def destroy(device): cfg_file = "/etc/mdadm.conf" try: - __salt__["file.replace"](cfg_file, "ARRAY {} .*".format(device), "") + __salt__["file.replace"](cfg_file, f"ARRAY {device} .*", "") except SaltInvocationError: pass @@ -229,7 +230,7 @@ def create(name, level, devices, metadata="default", test_mode=False, **kwargs): for key in kwargs: if not key.startswith("__"): - opts.append("--{}".format(key)) + opts.append(f"--{key}") if kwargs[key] is not True: opts.append(str(kwargs[key])) if key == "spare-devices": @@ -274,7 +275,7 @@ def save_config(): buggy_ubuntu_tags = ["name", "metadata"] for i, elem in enumerate(scan): for bad_tag in buggy_ubuntu_tags: - pattern = r"\s{}=\S+".format(re.escape(bad_tag)) + pattern = rf"\s{re.escape(bad_tag)}=\S+" pattern = re.compile(pattern, flags=re.I) scan[i] = re.sub(pattern, "", scan[i]) @@ -334,7 +335,7 @@ def assemble(name, devices, test_mode=False, **kwargs): opts = [] for key in kwargs: if not key.startswith("__"): - opts.append("--{}".format(key)) + opts.append(f"--{key}") if kwargs[key] is not True: opts.append(kwargs[key]) @@ -367,7 +368,7 @@ def examine(device, quiet=False): salt '*' raid.examine '/dev/sda1' """ res = __salt__["cmd.run_stdout"]( - "mdadm -Y -E {}".format(device), python_shell=False, ignore_retcode=quiet + f"mdadm -Y -E {device}", python_shell=False, ignore_retcode=quiet ) ret = {} @@ -389,7 +390,7 @@ def add(name, device): """ - cmd = "mdadm --manage {} --add {}".format(name, device) + cmd = f"mdadm --manage {name} --add {device}" if __salt__["cmd.retcode"](cmd) == 0: return True return False diff --git a/salt/modules/mdata.py b/salt/modules/mdata.py index 87f2582ce00..94415b7c39b 100644 --- a/salt/modules/mdata.py +++ b/salt/modules/mdata.py @@ -8,7 +8,6 @@ Module for managaging metadata in SmartOS Zones :platform: smartos """ - import logging import salt.utils.decorators as decorators diff --git a/salt/modules/memcached.py b/salt/modules/memcached.py index d8c2cf6d01b..4c6cc558e18 100644 --- a/salt/modules/memcached.py +++ b/salt/modules/memcached.py @@ -51,7 +51,7 @@ def _connect(host=DEFAULT_HOST, port=DEFAULT_PORT): values assigned to missing values. """ if str(port).isdigit(): - return memcache.Client(["{}:{}".format(host, port)], debug=0) + return memcache.Client([f"{host}:{port}"], debug=0) raise SaltInvocationError("port must be an integer") @@ -214,10 +214,10 @@ def increment(key, delta=1, host=DEFAULT_HOST, port=DEFAULT_PORT): cur = get(key) if cur is None: - raise CommandExecutionError("Key '{}' does not exist".format(key)) + raise CommandExecutionError(f"Key '{key}' does not exist") elif not isinstance(cur, int): raise CommandExecutionError( - "Value for key '{}' must be an integer to be incremented".format(key) + f"Value for key '{key}' must be an integer to be incremented" ) try: @@ -245,10 +245,10 @@ def decrement(key, delta=1, host=DEFAULT_HOST, port=DEFAULT_PORT): cur = get(key) if cur is None: - raise CommandExecutionError("Key '{}' does not exist".format(key)) + raise CommandExecutionError(f"Key '{key}' does not exist") elif not isinstance(cur, int): raise CommandExecutionError( - "Value for key '{}' must be an integer to be decremented".format(key) + f"Value for key '{key}' must be an integer to be decremented" ) try: diff --git a/salt/modules/mine.py b/salt/modules/mine.py index f8d55464019..758ec9e4e1d 100644 --- a/salt/modules/mine.py +++ b/salt/modules/mine.py @@ -309,7 +309,7 @@ def get(tgt, fun, tgt_type="glob", exclude_minion=False): # Load from local minion's cache if __opts__["file_client"] == "local": ret = {} - is_target = { + _targets = { "glob": __salt__["match.glob"], "pcre": __salt__["match.pcre"], "list": __salt__["match.list"], @@ -319,7 +319,8 @@ def get(tgt, fun, tgt_type="glob", exclude_minion=False): "compound": __salt__["match.compound"], "pillar": __salt__["match.pillar"], "pillar_pcre": __salt__["match.pillar_pcre"], - }[tgt_type](tgt) + } + is_target = _targets[tgt_type](tgt) if not is_target: return ret diff --git a/salt/modules/minion.py b/salt/modules/minion.py index e93b2783c80..bed8f437f75 100644 --- a/salt/modules/minion.py +++ b/salt/modules/minion.py @@ -212,12 +212,12 @@ def restart(): restart_cmd = __salt__["config.get"]("minion_restart_command") if restart_cmd: comment.append("Using configuration minion_restart_command:") - comment.extend([" {}".format(arg) for arg in restart_cmd]) + comment.extend([f" {arg}" for arg in restart_cmd]) else: if "-d" in sys.argv: restart_cmd = sys.argv comment.append("Restart using process argv:") - comment.extend([" {}".format(arg) for arg in restart_cmd]) + comment.extend([f" {arg}" for arg in restart_cmd]) else: should_restart = False comment.append( diff --git a/salt/modules/modjk.py b/salt/modules/modjk.py index 41f6253fd43..fb968a7a986 100644 --- a/salt/modules/modjk.py +++ b/salt/modules/modjk.py @@ -29,6 +29,7 @@ this module. realm: authentication realm2 for digest passwords timeout: 600 """ + import urllib.parse import urllib.request @@ -59,25 +60,25 @@ def _do_http(opts, profile="default"): ret = {} - url = __salt__["config.get"]("modjk:{}:url".format(profile), "") - user = __salt__["config.get"]("modjk:{}:user".format(profile), "") - passwd = __salt__["config.get"]("modjk:{}:pass".format(profile), "") - realm = __salt__["config.get"]("modjk:{}:realm".format(profile), "") - timeout = __salt__["config.get"]("modjk:{}:timeout".format(profile), "") + url = __salt__["config.get"](f"modjk:{profile}:url", "") + user = __salt__["config.get"](f"modjk:{profile}:user", "") + passwd = __salt__["config.get"](f"modjk:{profile}:pass", "") + realm = __salt__["config.get"](f"modjk:{profile}:realm", "") + timeout = __salt__["config.get"](f"modjk:{profile}:timeout", "") if not url: - raise Exception("missing url in profile {}".format(profile)) + raise Exception(f"missing url in profile {profile}") if user and passwd: auth = _auth(url=url, realm=realm, user=user, passwd=passwd) urllib.request.install_opener(auth) - url += "?{}".format(urllib.parse.urlencode(opts)) + url += f"?{urllib.parse.urlencode(opts)}" for line in urllib.request.urlopen(url, timeout=timeout).read().splitlines(): splt = line.split("=", 1) if splt[0] in ret: - ret[splt[0]] += ",{}".format(splt[1]) + ret[splt[0]] += f",{splt[1]}" else: ret[splt[0]] = splt[1] @@ -171,7 +172,7 @@ def list_configured_members(lbn, profile="default"): config = dump_config(profile) try: - ret = config["worker.{}.balance_workers".format(lbn)] + ret = config[f"worker.{lbn}.balance_workers"] except KeyError: return [] @@ -197,9 +198,7 @@ def workers(profile="default"): for lb in lbn: try: - worker_list.extend( - config["worker.{}.balance_workers".format(lb)].split(",") - ) + worker_list.extend(config[f"worker.{lb}.balance_workers"].split(",")) except KeyError: pass @@ -207,8 +206,8 @@ def workers(profile="default"): for worker in worker_list: ret[worker] = { - "activation": config["worker.{}.activation".format(worker)], - "state": config["worker.{}.state".format(worker)], + "activation": config[f"worker.{worker}.activation"], + "state": config[f"worker.{worker}.state"], } return ret @@ -229,7 +228,7 @@ def recover_all(lbn, profile="default"): ret = {} config = get_running(profile) try: - workers_ = config["worker.{}.balance_workers".format(lbn)].split(",") + workers_ = config[f"worker.{lbn}.balance_workers"].split(",") except KeyError: return ret @@ -417,8 +416,8 @@ def worker_status(worker, profile="default"): config = get_running(profile) try: return { - "activation": config["worker.{}.activation".format(worker)], - "state": config["worker.{}.state".format(worker)], + "activation": config[f"worker.{worker}.activation"], + "state": config[f"worker.{worker}.state"], } except KeyError: return False diff --git a/salt/modules/mongodb.py b/salt/modules/mongodb.py index 72b0ff00747..699dcfd48e9 100644 --- a/salt/modules/mongodb.py +++ b/salt/modules/mongodb.py @@ -236,7 +236,7 @@ def version( """ conn = _connect(user, password, host, port, authdb=authdb) if not conn: - err_msg = "Failed to connect to MongoDB database {}:{}".format(host, port) + err_msg = f"Failed to connect to MongoDB database {host}:{port}" log.error(err_msg) return (False, err_msg) @@ -283,7 +283,7 @@ def user_find( """ conn = _connect(user, password, host, port, authdb=authdb) if not conn: - err_msg = "Failed to connect to MongoDB database {}:{}".format(host, port) + err_msg = f"Failed to connect to MongoDB database {host}:{port}" log.error(err_msg) return (False, err_msg) @@ -993,7 +993,7 @@ def update_one( col = getattr(mdb, collection) ids = col.update_one(_id_field, {"$set": _update_doc}) nb_mod = ids.modified_count - return "{} objects updated".format(nb_mod) + return f"{nb_mod} objects updated" except pymongo.errors.PyMongoError as err: log.error("Updating object %s failed with error %s", objects, err) return err @@ -1139,7 +1139,7 @@ def remove( for count in range(0, w): res = col.delete_one(query) deleted_count += res.deleted_count - return "{} objects removed".format(deleted_count) + return f"{deleted_count} objects removed" except pymongo.errors.PyMongoError as err: log.error("Removing objects failed with error: %s", _get_error_message(err)) return _get_error_message(err) diff --git a/salt/modules/monit.py b/salt/modules/monit.py index 65d9da8286c..3f685f6f5d9 100644 --- a/salt/modules/monit.py +++ b/salt/modules/monit.py @@ -34,7 +34,7 @@ def start(name): salt '*' monit.start """ - cmd = "monit start {}".format(name) + cmd = f"monit start {name}" return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -49,7 +49,7 @@ def stop(name): salt '*' monit.stop """ - cmd = "monit stop {}".format(name) + cmd = f"monit stop {name}" return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -64,7 +64,7 @@ def restart(name): salt '*' monit.restart """ - cmd = "monit restart {}".format(name) + cmd = f"monit restart {name}" return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -79,7 +79,7 @@ def unmonitor(name): salt '*' monit.unmonitor """ - cmd = "monit unmonitor {}".format(name) + cmd = f"monit unmonitor {name}" return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -94,7 +94,7 @@ def monitor(name): salt '*' monit.monitor """ - cmd = "monit monitor {}".format(name) + cmd = f"monit monitor {name}" return not __salt__["cmd.retcode"](cmd, python_shell=False) diff --git a/salt/modules/mount.py b/salt/modules/mount.py index fd43821db49..413efb98bf0 100644 --- a/salt/modules/mount.py +++ b/salt/modules/mount.py @@ -2,7 +2,6 @@ Salt module to manage Unix mounts and the fstab file """ - import logging import os import re diff --git a/salt/modules/mssql.py b/salt/modules/mssql.py index 3b64899929c..23ca6577542 100644 --- a/salt/modules/mssql.py +++ b/salt/modules/mssql.py @@ -20,7 +20,6 @@ Module to provide MS SQL Server compatibility to salt. configs or pillars. """ - import salt.utils.json try: @@ -140,7 +139,7 @@ def db_exists(database_name, **kwargs): "SELECT database_id FROM sys.databases WHERE NAME='{}'".format( database_name ), - **kwargs + **kwargs, ) ) == 1 @@ -161,7 +160,7 @@ def db_create(database, containment="NONE", new_database_options=None, **kwargs) """ if containment not in ["NONE", "PARTIAL"]: return "CONTAINMENT can be one of NONE and PARTIAL" - sql = "CREATE DATABASE [{}] CONTAINMENT = {} ".format(database, containment) + sql = f"CREATE DATABASE [{database}] CONTAINMENT = {containment} " if new_database_options: sql += " WITH " + ", ".join(new_database_options) conn = None @@ -172,7 +171,7 @@ def db_create(database, containment="NONE", new_database_options=None, **kwargs) # cur.execute(sql) conn.cursor().execute(sql) except Exception as e: # pylint: disable=broad-except - return "Could not create the database: {}".format(e) + return f"Could not create the database: {e}" finally: if conn: conn.autocommit(False) @@ -206,18 +205,17 @@ def db_remove(database_name, **kwargs): database_name ) ) - cur.execute("DROP DATABASE {}".format(database_name)) + cur.execute(f"DROP DATABASE {database_name}") conn.autocommit(False) conn.close() return True else: return False except Exception as e: # pylint: disable=broad-except - return "Could not find the database: {}".format(e) + return f"Could not find the database: {e}" def role_list(**kwargs): - """ Lists database roles. @@ -231,7 +229,6 @@ def role_list(**kwargs): def role_exists(role, **kwargs): - """ Checks if a role exists. @@ -242,10 +239,7 @@ def role_exists(role, **kwargs): salt minion mssql.role_exists db_owner """ # We should get one, and only one row - return ( - len(tsql_query(query='sp_helprole "{}"'.format(role), as_dict=True, **kwargs)) - == 1 - ) + return len(tsql_query(query=f'sp_helprole "{role}"', as_dict=True, **kwargs)) == 1 def role_create(role, owner=None, grants=None, **kwargs): @@ -264,9 +258,9 @@ def role_create(role, owner=None, grants=None, **kwargs): if not grants: grants = [] - sql = "CREATE ROLE {}".format(role) + sql = f"CREATE ROLE {role}" if owner: - sql += " AUTHORIZATION {}".format(owner) + sql += f" AUTHORIZATION {owner}" conn = None try: conn = _get_connection(**kwargs) @@ -275,9 +269,9 @@ def role_create(role, owner=None, grants=None, **kwargs): # cur.execute(sql) conn.cursor().execute(sql) for grant in grants: - conn.cursor().execute("GRANT {} TO [{}]".format(grant, role)) + conn.cursor().execute(f"GRANT {grant} TO [{role}]") except Exception as e: # pylint: disable=broad-except - return "Could not create the role: {}".format(e) + return f"Could not create the role: {e}" finally: if conn: conn.autocommit(False) @@ -299,12 +293,12 @@ def role_remove(role, **kwargs): conn = _get_connection(**kwargs) conn.autocommit(True) cur = conn.cursor() - cur.execute("DROP ROLE {}".format(role)) + cur.execute(f"DROP ROLE {role}") conn.autocommit(True) conn.close() return True except Exception as e: # pylint: disable=broad-except - return "Could not remove the role: {}".format(e) + return f"Could not remove the role: {e}" def login_exists(login, domain="", **kwargs): @@ -319,7 +313,7 @@ def login_exists(login, domain="", **kwargs): salt minion mssql.login_exists 'LOGIN' """ if domain: - login = "{}\\{}".format(domain, login) + login = f"{domain}\\{login}" try: # We should get one, and only one row return ( @@ -328,14 +322,14 @@ def login_exists(login, domain="", **kwargs): query="SELECT name FROM sys.syslogins WHERE name='{}'".format( login ), - **kwargs + **kwargs, ) ) == 1 ) except Exception as e: # pylint: disable=broad-except - return "Could not find the login: {}".format(e) + return f"Could not find the login: {e}" def login_create( @@ -344,7 +338,7 @@ def login_create( new_login_domain="", new_login_roles=None, new_login_options=None, - **kwargs + **kwargs, ): """ Creates a new login. Does not update password of existing logins. For @@ -371,19 +365,19 @@ def login_create( if login_exists(login, new_login_domain, **kwargs): return False if new_login_domain: - login = "{}\\{}".format(new_login_domain, login) + login = f"{new_login_domain}\\{login}" if not new_login_roles: new_login_roles = [] if not new_login_options: new_login_options = [] - sql = "CREATE LOGIN [{}] ".format(login) + sql = f"CREATE LOGIN [{login}] " if new_login_domain: sql += " FROM WINDOWS " elif isinstance(new_login_password, int): - new_login_options.insert(0, "PASSWORD=0x{:x} HASHED".format(new_login_password)) + new_login_options.insert(0, f"PASSWORD=0x{new_login_password:x} HASHED") else: # Plain test password - new_login_options.insert(0, "PASSWORD=N'{}'".format(new_login_password)) + new_login_options.insert(0, f"PASSWORD=N'{new_login_password}'") if new_login_options: sql += " WITH " + ", ".join(new_login_options) conn = None @@ -394,11 +388,9 @@ def login_create( # cur.execute(sql) conn.cursor().execute(sql) for role in new_login_roles: - conn.cursor().execute( - "ALTER SERVER ROLE [{}] ADD MEMBER [{}]".format(role, login) - ) + conn.cursor().execute(f"ALTER SERVER ROLE [{role}] ADD MEMBER [{login}]") except Exception as e: # pylint: disable=broad-except - return "Could not create the login: {}".format(e) + return f"Could not create the login: {e}" finally: if conn: conn.autocommit(False) @@ -420,12 +412,12 @@ def login_remove(login, **kwargs): conn = _get_connection(**kwargs) conn.autocommit(True) cur = conn.cursor() - cur.execute("DROP LOGIN [{}]".format(login)) + cur.execute(f"DROP LOGIN [{login}]") conn.autocommit(False) conn.close() return True except Exception as e: # pylint: disable=broad-except - return "Could not remove the login: {}".format(e) + return f"Could not remove the login: {e}" def user_exists(username, domain="", database=None, **kwargs): @@ -440,15 +432,14 @@ def user_exists(username, domain="", database=None, **kwargs): salt minion mssql.user_exists 'USERNAME' [database='DBNAME'] """ if domain: - username = "{}\\{}".format(domain, username) + username = f"{domain}\\{username}" if database: kwargs["database"] = database # We should get one, and only one row return ( len( tsql_query( - query="SELECT name FROM sysusers WHERE name='{}'".format(username), - **kwargs + query=f"SELECT name FROM sysusers WHERE name='{username}'", **kwargs ) ) == 1 @@ -470,7 +461,7 @@ def user_list(**kwargs): for row in tsql_query( "SELECT name FROM sysusers where issqluser=1 or isntuser=1", as_dict=False, - **kwargs + **kwargs, ) ] @@ -492,10 +483,10 @@ def user_create( if domain and not login: return "domain cannot be set without login" if user_exists(username, domain, **kwargs): - return "User {} already exists".format(username) + return f"User {username} already exists" if domain: - username = "{}\\{}".format(domain, username) - login = "{}\\{}".format(domain, login) if login else login + username = f"{domain}\\{username}" + login = f"{domain}\\{login}" if login else login if database: kwargs["database"] = database if not roles: @@ -503,12 +494,12 @@ def user_create( if not options: options = [] - sql = "CREATE USER [{}] ".format(username) + sql = f"CREATE USER [{username}] " if login: # If the login does not exist, user creation will throw # if not login_exists(name, **kwargs): # return False - sql += " FOR LOGIN [{}]".format(login) + sql += f" FOR LOGIN [{login}]" else: # Plain test password sql += " WITHOUT LOGIN" if options: @@ -521,11 +512,9 @@ def user_create( # cur.execute(sql) conn.cursor().execute(sql) for role in roles: - conn.cursor().execute( - "ALTER ROLE [{}] ADD MEMBER [{}]".format(role, username) - ) + conn.cursor().execute(f"ALTER ROLE [{role}] ADD MEMBER [{username}]") except Exception as e: # pylint: disable=broad-except - return "Could not create the user: {}".format(e) + return f"Could not create the user: {e}" finally: if conn: conn.autocommit(False) @@ -550,9 +539,9 @@ def user_remove(username, **kwargs): conn = _get_connection(**kwargs) conn.autocommit(True) cur = conn.cursor() - cur.execute("DROP USER {}".format(username)) + cur.execute(f"DROP USER {username}") conn.autocommit(False) conn.close() return True except Exception as e: # pylint: disable=broad-except - return "Could not remove the user: {}".format(e) + return f"Could not remove the user: {e}" diff --git a/salt/modules/munin.py b/salt/modules/munin.py index ced668011f0..764135fc485 100644 --- a/salt/modules/munin.py +++ b/salt/modules/munin.py @@ -49,9 +49,7 @@ def run(plugins): if plugin not in all_plugins: continue data[plugin] = {} - muninout = __salt__["cmd.run"]( - "munin-run {}".format(plugin), python_shell=False - ) + muninout = __salt__["cmd.run"](f"munin-run {plugin}", python_shell=False) for line in muninout.split("\n"): if "value" in line: # This skips multigraph lines, etc key, val = line.split(" ") diff --git a/salt/modules/mysql.py b/salt/modules/mysql.py index d566f7b4e45..5a0820c0400 100644 --- a/salt/modules/mysql.py +++ b/salt/modules/mysql.py @@ -28,7 +28,6 @@ Module to provide MySQL compatibility to salt. Additionally, it is now possible to setup a user with no password. """ - import copy import hashlib import logging diff --git a/salt/modules/nacl.py b/salt/modules/nacl.py index ef0e1774548..ca1e54193e5 100644 --- a/salt/modules/nacl.py +++ b/salt/modules/nacl.py @@ -149,7 +149,6 @@ Optional small program to encrypt data without needing salt modules. """ - import salt.utils.nacl __virtualname__ = "nacl" diff --git a/salt/modules/nagios.py b/salt/modules/nagios.py index 29c02e4bf03..87f3ae639f7 100644 --- a/salt/modules/nagios.py +++ b/salt/modules/nagios.py @@ -2,7 +2,6 @@ Run nagios plugins/checks from salt and get the return as data. """ - import logging import os import stat @@ -33,9 +32,7 @@ def _execute_cmd(plugin, args="", run_type="cmd.retcode"): all_plugins = list_plugins() if plugin in all_plugins: - data = __salt__[run_type]( - "{}{} {}".format(PLUGINDIR, plugin, args), python_shell=False - ) + data = __salt__[run_type](f"{PLUGINDIR}{plugin} {args}", python_shell=False) return data diff --git a/salt/modules/nagios_rpc.py b/salt/modules/nagios_rpc.py index 0f7969dbf38..9aee76a10c3 100644 --- a/salt/modules/nagios_rpc.py +++ b/salt/modules/nagios_rpc.py @@ -5,7 +5,6 @@ Check Host & Service status from Nagios via JSON RPC. """ - import http.client import logging @@ -98,7 +97,7 @@ def _status_query(query, hostname, enumerate=None, service=None): elif result.get("status", None) == http.client.NOT_FOUND: ret["error"] = "URL {} was not found.".format(config["url"]) else: - ret["error"] = "Results: {}".format(result.text) + ret["error"] = f"Results: {result.text}" return ret diff --git a/salt/modules/namecheap_domains.py b/salt/modules/namecheap_domains.py index 97ec8e215a0..e12c102b913 100644 --- a/salt/modules/namecheap_domains.py +++ b/salt/modules/namecheap_domains.py @@ -364,7 +364,7 @@ def create(domain_name, years, **kwargs): for requiredkey in require_opts: if requiredkey not in opts: log.error("Missing required parameter '%s'", requiredkey) - raise Exception("Missing required parameter '{}'".format(requiredkey)) + raise Exception(f"Missing required parameter '{requiredkey}'") response_xml = salt.utils.namecheap.post_request(opts) @@ -402,9 +402,9 @@ def check(*domains_to_check): domains_checked = {} for result in response_xml.getElementsByTagName("DomainCheckResult"): available = result.getAttribute("Available") - domains_checked[ - result.getAttribute("Domain").lower() - ] = salt.utils.namecheap.string_to_value(available) + domains_checked[result.getAttribute("Domain").lower()] = ( + salt.utils.namecheap.string_to_value(available) + ) return domains_checked diff --git a/salt/modules/namecheap_domains_dns.py b/salt/modules/namecheap_domains_dns.py index ef6789ec778..24805acba6d 100644 --- a/salt/modules/namecheap_domains_dns.py +++ b/salt/modules/namecheap_domains_dns.py @@ -26,7 +26,6 @@ file, or in the Pillar data. #namecheap.url: https://api.sandbox.namecheap.xml.response """ - CAN_USE_NAMECHEAP = True diff --git a/salt/modules/napalm_bgp.py b/salt/modules/napalm_bgp.py index 84a19b27a2c..b7721397bd9 100644 --- a/salt/modules/napalm_bgp.py +++ b/salt/modules/napalm_bgp.py @@ -17,7 +17,6 @@ Dependencies .. versionadded:: 2016.11.0 """ - import logging # import NAPALM utils @@ -59,7 +58,6 @@ def __virtual__(): @proxy_napalm_wrap def config(group=None, neighbor=None, **kwargs): - """ Provides the BGP configuration on the device. @@ -169,7 +167,6 @@ def config(group=None, neighbor=None, **kwargs): @proxy_napalm_wrap def neighbors(neighbor=None, **kwargs): - """ Provides details regarding the BGP sessions configured on the network device. diff --git a/salt/modules/napalm_formula.py b/salt/modules/napalm_formula.py index 1b641d71973..c69d376cd60 100644 --- a/salt/modules/napalm_formula.py +++ b/salt/modules/napalm_formula.py @@ -292,7 +292,7 @@ def render_field(dictionary, field, prepend=None, append=None, quotes=False, **o else: append = "" if quotes: - value = '"{value}"'.format(value=value) + value = f'"{value}"' return "{prepend} {value}{append}".format( prepend=prepend, value=value, append=append ) diff --git a/salt/modules/napalm_network.py b/salt/modules/napalm_network.py index 124d70b4876..9fc5185553f 100644 --- a/salt/modules/napalm_network.py +++ b/salt/modules/napalm_network.py @@ -64,7 +64,6 @@ def __virtual__(): def _filter_list(input_list, search_key, search_value): - """ Filters a list of dictionary by a set of key-value pair. @@ -84,7 +83,6 @@ def _filter_list(input_list, search_key, search_value): def _filter_dict(input_dict, search_key, search_value): - """ Filters a dictionary of dictionaries by a key-value pair. @@ -172,7 +170,7 @@ def _config_logic( revert_in=None, revert_at=None, commit_jid=None, - **kwargs + **kwargs, ): """ Builds the config logic for `load_config` and `load_template` functions. @@ -193,7 +191,7 @@ def _config_logic( current_jid = kwargs.get("__pub_jid") if not current_jid: - current_jid = "{:%Y%m%d%H%M%S%f}".format(datetime.datetime.now()) + current_jid = f"{datetime.datetime.now():%Y%m%d%H%M%S%f}" loaded_result["already_configured"] = False @@ -248,7 +246,7 @@ def _config_logic( time_in=commit_in, time_at=commit_in ) # schedule job - scheduled_job_name = "__napalm_commit_{}".format(current_jid) + scheduled_job_name = f"__napalm_commit_{current_jid}" temp_file = salt.utils.files.mkstemp() with salt.utils.files.fopen(temp_file, "w") as fp_: fp_.write(loaded_config) @@ -310,9 +308,9 @@ def _config_logic( _comm = __salt__["napalm.junos_commit"](confirm=minutes) if not _comm["out"]: # If unable to commit confirm, should try to bail out - loaded_result[ - "comment" - ] = "Unable to commit confirm: {}".format(_comm["message"]) + loaded_result["comment"] = ( + "Unable to commit confirm: {}".format(_comm["message"]) + ) loaded_result["result"] = False # But before exiting, we must gracefully discard the config discarded = _safe_dicard_config(loaded_result, napalm_device) @@ -331,7 +329,7 @@ def _config_logic( # already done by the _safe_commit_config function), and # return with the command and other details. return loaded_result - scheduled_job_name = "__napalm_commit_{}".format(current_jid) + scheduled_job_name = f"__napalm_commit_{current_jid}" scheduled = __salt__["schedule.add"]( scheduled_job_name, function="net.load_config", @@ -694,7 +692,7 @@ def cli(*commands, **kwargs): # pylint: disable=unused-argument raw_cli_outputs = salt.utils.napalm.call( napalm_device, # pylint: disable=undefined-variable "cli", - **{"commands": list(commands)} + **{"commands": list(commands)}, ) # thus we can display the output as is # in case of errors, they'll be caught in the proxy @@ -828,7 +826,7 @@ def cli(*commands, **kwargs): # pylint: disable=unused-argument processed_command_output = command_output processed_cli_outputs[ "comment" - ] += "\nUnable to process the output from {}.".format(command) + ] += f"\nUnable to process the output from {command}." processed_cli_outputs["out"][command] = processed_command_output processed_cli_outputs["comment"] = processed_cli_outputs["comment"].strip() return processed_cli_outputs @@ -838,7 +836,6 @@ def cli(*commands, **kwargs): # pylint: disable=unused-argument def traceroute( destination, source=None, ttl=None, timeout=None, vrf=None, **kwargs ): # pylint: disable=unused-argument - """ Calls the method traceroute from the NAPALM driver object and returns a dictionary with the result of the traceroute command executed on the device. @@ -877,7 +874,7 @@ def traceroute( "ttl": ttl, "timeout": timeout, "vrf": vrf, - } + }, ) @@ -890,9 +887,8 @@ def ping( size=None, count=None, vrf=None, - **kwargs + **kwargs, ): # pylint: disable=unused-argument - """ Executes a ping on the network device and returns a dictionary as a result. @@ -939,7 +935,7 @@ def ping( "size": size, "count": count, "vrf": vrf, - } + }, ) @@ -947,7 +943,6 @@ def ping( def arp( interface="", ipaddr="", macaddr="", **kwargs ): # pylint: disable=unused-argument - """ NAPALM returns a list of dictionaries with details of the ARP entries. @@ -1008,7 +1003,6 @@ def arp( @salt.utils.napalm.proxy_napalm_wrap def ipaddrs(**kwargs): # pylint: disable=unused-argument - """ Returns IP addresses configured on the device. @@ -1065,7 +1059,6 @@ def ipaddrs(**kwargs): # pylint: disable=unused-argument @salt.utils.napalm.proxy_napalm_wrap def interfaces(**kwargs): # pylint: disable=unused-argument - """ Returns details of the interfaces on the device. @@ -1109,7 +1102,6 @@ def interfaces(**kwargs): # pylint: disable=unused-argument @salt.utils.napalm.proxy_napalm_wrap def lldp(interface="", **kwargs): # pylint: disable=unused-argument - """ Returns a detailed view of the LLDP neighbors. @@ -1151,7 +1143,7 @@ def lldp(interface="", **kwargs): # pylint: disable=unused-argument proxy_output = salt.utils.napalm.call( napalm_device, # pylint: disable=undefined-variable "get_lldp_neighbors_detail", - **{} + **{}, ) if not proxy_output.get("result"): @@ -1169,7 +1161,6 @@ def lldp(interface="", **kwargs): # pylint: disable=unused-argument @salt.utils.napalm.proxy_napalm_wrap def mac(address="", interface="", vlan=0, **kwargs): # pylint: disable=unused-argument - """ Returns the MAC Address Table on the device. @@ -1214,7 +1205,7 @@ def mac(address="", interface="", vlan=0, **kwargs): # pylint: disable=unused-a proxy_output = salt.utils.napalm.call( napalm_device, # pylint: disable=undefined-variable "get_mac_address_table", - **{} + **{}, ) if not proxy_output.get("result"): @@ -1283,7 +1274,7 @@ def config(source=None, **kwargs): # pylint: disable=unused-argument return salt.utils.napalm.call( napalm_device, # pylint: disable=undefined-variable "get_config", - **{"retrieve": source} + **{"retrieve": source}, ) @@ -1350,7 +1341,7 @@ def load_config( commit_jid=None, inherit_napalm_device=None, saltenv="base", - **kwargs + **kwargs, ): # pylint: disable=unused-argument """ Applies configuration changes on the device. It can be loaded from a file or from inline string. @@ -1563,10 +1554,10 @@ def load_config( # When using salt:// or https://, if the resource is not available, # it will either raise an exception, or return False. ret = {"result": False, "out": None} - ret[ - "comment" - ] = "Unable to read from {}. Please specify a valid file or text.".format( - filename + ret["comment"] = ( + "Unable to read from {}. Please specify a valid file or text.".format( + filename + ) ) log.error(ret["comment"]) return ret @@ -1591,7 +1582,7 @@ def load_config( revert_in=revert_in, revert_at=revert_at, commit_jid=commit_jid, - **kwargs + **kwargs, ) @@ -1615,7 +1606,7 @@ def load_template( revert_in=None, revert_at=None, inherit_napalm_device=None, # pylint: disable=unused-argument - **template_vars + **template_vars, ): """ Renders a configuration template (default: Jinja) and loads the result on the device. @@ -2077,7 +2068,7 @@ def load_template( _loaded = salt.utils.napalm.call( napalm_device, # pylint: disable=undefined-variable fun, - **{"config": _rendered} + **{"config": _rendered}, ) return _config_logic( napalm_device, # pylint: disable=undefined-variable @@ -2091,13 +2082,12 @@ def load_template( commit_in=commit_in, revert_in=revert_in, revert_at=revert_at, - **template_vars + **template_vars, ) @salt.utils.napalm.proxy_napalm_wrap def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument - """ Commits the configuration changes made on the network device. @@ -2117,7 +2107,6 @@ def commit(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argu def discard_config( inherit_napalm_device=None, **kwargs ): # pylint: disable=unused-argument - """ Discards the changes applied. @@ -2137,7 +2126,6 @@ def discard_config( def compare_config( inherit_napalm_device=None, **kwargs ): # pylint: disable=unused-argument - """ Returns the difference between the running config and the candidate config. @@ -2155,7 +2143,6 @@ def compare_config( @salt.utils.napalm.proxy_napalm_wrap def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-argument - """ Rollbacks the configuration. @@ -2175,7 +2162,6 @@ def rollback(inherit_napalm_device=None, **kwargs): # pylint: disable=unused-ar def config_changed( inherit_napalm_device=None, **kwargs ): # pylint: disable=unused-argument - """ Will prompt if the configuration has been changed. @@ -2210,7 +2196,6 @@ def config_changed( def config_control( inherit_napalm_device=None, **kwargs ): # pylint: disable=unused-argument - """ Will check if the configuration was changed. If differences found, will try to commit. @@ -2270,13 +2255,13 @@ def cancel_commit(jid): salt '*' net.cancel_commit 20180726083540640360 """ - job_name = "__napalm_commit_{}".format(jid) + job_name = f"__napalm_commit_{jid}" removed = __salt__["schedule.delete"](job_name) if removed["result"]: saved = __salt__["schedule.save"]() - removed["comment"] = "Commit #{jid} cancelled.".format(jid=jid) + removed["comment"] = f"Commit #{jid} cancelled." else: - removed["comment"] = "Unable to find commit #{jid}.".format(jid=jid) + removed["comment"] = f"Unable to find commit #{jid}." return removed @@ -2305,7 +2290,7 @@ def confirm_commit(jid): else: confirmed = cancel_commit(jid) if confirmed["result"]: - confirmed["comment"] = "Commit #{jid} confirmed.".format(jid=jid) + confirmed["comment"] = f"Commit #{jid} confirmed." return confirmed @@ -2343,7 +2328,7 @@ def save_config(source=None, path=None): return { "result": True, "out": path, - "comment": "{source} config saved to {path}".format(source=source, path=path), + "comment": f"{source} config saved to {path}", } @@ -2679,7 +2664,7 @@ def patch( return { "out": None, "result": False, - "comment": 'The file "{}" does not exist.'.format(patchfile), + "comment": f'The file "{patchfile}" does not exist.', } replace_pattern = __salt__["file.patch"](path, patchfile_cache, options=options) with salt.utils.files.fopen(path, "r") as fh_: diff --git a/salt/modules/napalm_ntp.py b/salt/modules/napalm_ntp.py index 125c36dfb47..d737c149e23 100644 --- a/salt/modules/napalm_ntp.py +++ b/salt/modules/napalm_ntp.py @@ -20,7 +20,6 @@ Dependencies .. versionadded:: 2016.11.0 """ - import logging # import NAPALM utils @@ -62,7 +61,6 @@ def __virtual__(): @proxy_napalm_wrap def peers(**kwargs): # pylint: disable=unused-argument - """ Returns a list the NTP peers configured on the network device. @@ -103,7 +101,6 @@ def peers(**kwargs): # pylint: disable=unused-argument @proxy_napalm_wrap def servers(**kwargs): # pylint: disable=unused-argument - """ Returns a list of the configured NTP servers on the device. @@ -141,7 +138,6 @@ def servers(**kwargs): # pylint: disable=unused-argument @proxy_napalm_wrap def stats(peer=None, **kwargs): # pylint: disable=unused-argument - """ Returns a dictionary containing synchronization details of the NTP peers. @@ -208,7 +204,6 @@ def stats(peer=None, **kwargs): # pylint: disable=unused-argument @proxy_napalm_wrap def set_peers(*peers, **options): - """ Configures a list of NTP peers on the device. @@ -285,7 +280,6 @@ def set_servers(*servers, **options): @proxy_napalm_wrap def delete_peers(*peers, **options): - """ Removes NTP peers configured on the device. @@ -325,7 +319,6 @@ def delete_peers(*peers, **options): @proxy_napalm_wrap def delete_servers(*servers, **options): - """ Removes NTP servers configured on the device. diff --git a/salt/modules/napalm_probes.py b/salt/modules/napalm_probes.py index 7f798391a75..132b984d6b1 100644 --- a/salt/modules/napalm_probes.py +++ b/salt/modules/napalm_probes.py @@ -60,7 +60,6 @@ def __virtual__(): @proxy_napalm_wrap def config(**kwargs): # pylint: disable=unused-argument - """ Returns the configuration of the RPM probes. @@ -103,7 +102,6 @@ def config(**kwargs): # pylint: disable=unused-argument @proxy_napalm_wrap def results(**kwargs): # pylint: disable=unused-argument - """ Provides the results of the measurements of the RPM/SLA probes. @@ -270,7 +268,6 @@ def set_probes( def delete_probes( probes, test=False, commit=True, **kwargs ): # pylint: disable=unused-argument - """ Removes RPM/SLA probes from the network device. Calls the configuration template 'delete_probes' from the NAPALM library, @@ -327,7 +324,6 @@ def delete_probes( def schedule_probes( probes, test=False, commit=True, **kwargs ): # pylint: disable=unused-argument - """ Will schedule the probes. On Cisco devices, it is not enough to define the probes, it is also necessary to schedule them. diff --git a/salt/modules/napalm_route.py b/salt/modules/napalm_route.py index 41d8d74987e..1f88345c4fd 100644 --- a/salt/modules/napalm_route.py +++ b/salt/modules/napalm_route.py @@ -16,7 +16,6 @@ Dependencies .. versionadded:: 2016.11.0 """ - import logging # import NAPALM utils @@ -58,7 +57,6 @@ def __virtual__(): @proxy_napalm_wrap def show(destination, protocol=None, **kwargs): # pylint: disable=unused-argument - """ Displays all details for a certain route learned via a specific protocol. If the protocol is not specified, will return all possible routes. diff --git a/salt/modules/napalm_snmp.py b/salt/modules/napalm_snmp.py index dbcbb4ad700..2e72c03fa69 100644 --- a/salt/modules/napalm_snmp.py +++ b/salt/modules/napalm_snmp.py @@ -20,7 +20,6 @@ Dependencies .. versionadded:: 2016.11.0 """ - import logging # import NAPALM utils @@ -62,7 +61,6 @@ def __virtual__(): @proxy_napalm_wrap def config(**kwargs): # pylint: disable=unused-argument - """ Returns the SNMP configuration @@ -90,7 +88,6 @@ def remove_config( commit=True, **kwargs ): # pylint: disable=unused-argument - """ Removes a configuration element from the SNMP configuration. @@ -157,7 +154,6 @@ def update_config( commit=True, **kwargs ): # pylint: disable=unused-argument - """ Updates the SNMP configuration. diff --git a/salt/modules/napalm_users.py b/salt/modules/napalm_users.py index 170e441ba98..40603097102 100644 --- a/salt/modules/napalm_users.py +++ b/salt/modules/napalm_users.py @@ -19,7 +19,6 @@ Dependencies .. versionadded:: 2016.11.0 """ - import logging # import NAPALM utils @@ -61,7 +60,6 @@ def __virtual__(): @proxy_napalm_wrap def config(**kwargs): # pylint: disable=unused-argument - """ Returns the configuration of the users on the device @@ -100,7 +98,6 @@ def config(**kwargs): # pylint: disable=unused-argument def set_users( users, test=False, commit=True, **kwargs ): # pylint: disable=unused-argument - """ Configures users on network devices. @@ -149,7 +146,6 @@ def set_users( def delete_users( users, test=False, commit=True, **kwargs ): # pylint: disable=unused-argument - """ Removes users from the configuration of network devices. diff --git a/salt/modules/netaddress.py b/salt/modules/netaddress.py index 7c528c92a9e..86b7b1aae97 100644 --- a/salt/modules/netaddress.py +++ b/salt/modules/netaddress.py @@ -6,7 +6,6 @@ Module for getting information about network addresses. :depends: netaddr """ - __virtualname__ = "netaddress" try: diff --git a/salt/modules/netbox.py b/salt/modules/netbox.py index 656087d0cb0..13b1ff63a71 100644 --- a/salt/modules/netbox.py +++ b/salt/modules/netbox.py @@ -190,7 +190,7 @@ def get_(app, endpoint, id=None, **kwargs): endpoint, id=id, auth_required=True if app in AUTH_ENDPOINTS else False, - **kwargs + **kwargs, ) ) @@ -1014,7 +1014,7 @@ def create_circuit_provider(name, asn=None): else: log.error("Duplicate provider with different ASN: %s: %s", name, asn) raise CommandExecutionError( - "Duplicate provider with different ASN: {}: {}".format(name, asn) + f"Duplicate provider with different ASN: {name}: {asn}" ) else: payload = {"name": name, "slug": slugify(name)} diff --git a/salt/modules/netmiko_mod.py b/salt/modules/netmiko_mod.py index 1769471f82b..d3cd44e10cd 100644 --- a/salt/modules/netmiko_mod.py +++ b/salt/modules/netmiko_mod.py @@ -486,7 +486,7 @@ def send_config( context=None, defaults=None, saltenv="base", - **kwargs + **kwargs, ): """ Send configuration commands down the SSH channel. @@ -564,7 +564,7 @@ def send_config( if config_file: file_str = __salt__["cp.get_file_str"](config_file, saltenv=saltenv) if file_str is False: - raise CommandExecutionError("Source file {} not found".format(config_file)) + raise CommandExecutionError(f"Source file {config_file} not found") elif config_commands: if isinstance(config_commands, ((str,), str)): config_commands = [config_commands] diff --git a/salt/modules/netscaler.py b/salt/modules/netscaler.py index e4d684c4088..94949f3527c 100644 --- a/salt/modules/netscaler.py +++ b/salt/modules/netscaler.py @@ -118,7 +118,7 @@ def _connect(**kwargs): name = name[len(prefix) :] except IndexError: return - val = __salt__["config.option"]("netscaler.{}".format(name), None) + val = __salt__["config.option"](f"netscaler.{name}", None) if val is not None: connargs[key] = val elif default is not None: diff --git a/salt/modules/neutronng.py b/salt/modules/neutronng.py index daf91f49ff7..3aa2817985c 100644 --- a/salt/modules/neutronng.py +++ b/salt/modules/neutronng.py @@ -25,7 +25,6 @@ Example configuration identity_api_version: 3 """ - HAS_SHADE = False try: import shade diff --git a/salt/modules/nexus.py b/salt/modules/nexus.py index 06a44f38a22..e8e212ce8f5 100644 --- a/salt/modules/nexus.py +++ b/salt/modules/nexus.py @@ -94,7 +94,7 @@ def get_latest_snapshot( headers = {} if username and password: headers["Authorization"] = "Basic {}".format( - base64.encodestring("{}:{}".format(username, password)).replace("\n", "") + base64.encodestring(f"{username}:{password}").replace("\n", "") ) artifact_metadata = _get_artifact_metadata( nexus_url=nexus_url, @@ -175,7 +175,7 @@ def get_snapshot( headers = {} if username and password: headers["Authorization"] = "Basic {}".format( - base64.encodestring("{}:{}".format(username, password)).replace("\n", "") + base64.encodestring(f"{username}:{password}").replace("\n", "") ) snapshot_url, file_name = _get_snapshot_url( nexus_url=nexus_url, @@ -241,7 +241,7 @@ def get_snapshot_version_string( headers = {} if username and password: headers["Authorization"] = "Basic {}".format( - base64.encodestring("{}:{}".format(username, password)).replace("\n", "") + base64.encodestring(f"{username}:{password}").replace("\n", "") ) return _get_snapshot_url( nexus_url=nexus_url, @@ -306,7 +306,7 @@ def get_latest_release( headers = {} if username and password: headers["Authorization"] = "Basic {}".format( - base64.encodestring("{}:{}".format(username, password)).replace("\n", "") + base64.encodestring(f"{username}:{password}").replace("\n", "") ) artifact_metadata = _get_artifact_metadata( nexus_url=nexus_url, @@ -379,7 +379,7 @@ def get_release( headers = {} if username and password: headers["Authorization"] = "Basic {}".format( - base64.encodestring("{}:{}".format(username, password)).replace("\n", "") + base64.encodestring(f"{username}:{password}").replace("\n", "") ) release_url, file_name = _get_release_url( repository, group_id, artifact_id, packaging, version, nexus_url, classifier @@ -688,7 +688,7 @@ def __save_artifact(artifact_url, target_file, headers): local_file.write(salt.utils.stringutils.to_bytes(f.read())) result["status"] = True result["comment"] = __append_comment( - "Artifact downloaded from URL: {}".format(artifact_url), + f"Artifact downloaded from URL: {artifact_url}", result["comment"], ) result["changes"]["downloaded_file"] = target_file diff --git a/salt/modules/nfs3.py b/salt/modules/nfs3.py index 048c8b18456..d692c5fb01e 100644 --- a/salt/modules/nfs3.py +++ b/salt/modules/nfs3.py @@ -125,8 +125,8 @@ def _write_exports(exports, edict): for perms in edict[export]: hosts = perms["hosts"] options = ",".join(perms["options"]) - line += " {}({})".format(hosts, options) - efh.write("{}\n".format(line)) + line += f" {hosts}({options})" + efh.write(f"{line}\n") def reload_exports(): diff --git a/salt/modules/nftables.py b/salt/modules/nftables.py index 8cfa92e3751..11ac05915bd 100644 --- a/salt/modules/nftables.py +++ b/salt/modules/nftables.py @@ -572,10 +572,10 @@ def check(table="filter", chain=None, rule=None, family="ipv4"): out = __salt__["cmd.run"](cmd, python_shell=False).find(search_rule) if out == -1: - ret[ - "comment" - ] = "Rule {} in chain {} in table {} in family {} does not exist".format( - rule, chain, table, family + ret["comment"] = ( + "Rule {} in chain {} in table {} in family {} does not exist".format( + rule, chain, table, family + ) ) else: ret["comment"] = "Rule {} in chain {} in table {} in family {} exists".format( @@ -795,10 +795,10 @@ def new_chain( ) ret["result"] = True else: - ret[ - "comment" - ] = "Chain {} in table {} in family {} could not be created".format( - chain, table, family + ret["comment"] = ( + "Chain {} in table {} in family {} could not be created".format( + chain, table, family + ) ) return ret @@ -846,10 +846,10 @@ def delete_chain(table="filter", chain=None, family="ipv4"): ) ret["result"] = True else: - ret[ - "comment" - ] = "Chain {} in table {} in family {} could not be deleted".format( - chain, table, family + ret["comment"] = ( + "Chain {} in table {} in family {} could not be deleted".format( + chain, table, family + ) ) return ret @@ -900,10 +900,10 @@ def append(table="filter", chain=None, rule=None, family="ipv4"): res = check(table, chain, rule, family=family) if res["result"]: - ret[ - "comment" - ] = "Rule {} chain {} in table {} in family {} already exists".format( - rule, chain, table, family + ret["comment"] = ( + "Rule {} chain {} in table {} in family {} already exists".format( + rule, chain, table, family + ) ) return ret @@ -919,10 +919,10 @@ def append(table="filter", chain=None, rule=None, family="ipv4"): rule, chain, table, family ) else: - ret[ - "comment" - ] = 'Failed to add rule "{}" chain {} in table {} in family {}.'.format( - rule, chain, table, family + ret["comment"] = ( + 'Failed to add rule "{}" chain {} in table {} in family {}.'.format( + rule, chain, table, family + ) ) return ret @@ -980,10 +980,10 @@ def insert(table="filter", chain=None, position=None, rule=None, family="ipv4"): res = check(table, chain, rule, family=family) if res["result"]: - ret[ - "comment" - ] = "Rule {} chain {} in table {} in family {} already exists".format( - rule, chain, table, family + ret["comment"] = ( + "Rule {} chain {} in table {} in family {} already exists".format( + rule, chain, table, family + ) ) return ret @@ -1004,10 +1004,10 @@ def insert(table="filter", chain=None, position=None, rule=None, family="ipv4"): rule, chain, table, family ) else: - ret[ - "comment" - ] = 'Failed to add rule "{}" chain {} in table {} in family {}.'.format( - rule, chain, table, family + ret["comment"] = ( + 'Failed to add rule "{}" chain {} in table {} in family {}.'.format( + rule, chain, table, family + ) ) return ret @@ -1057,10 +1057,10 @@ def delete(table, chain=None, position=None, rule=None, family="ipv4"): res = check(table, chain, rule, family=family) if not res["result"]: - ret[ - "comment" - ] = "Rule {} chain {} in table {} in family {} does not exist".format( - rule, chain, table, family + ret["comment"] = ( + "Rule {} chain {} in table {} in family {} does not exist".format( + rule, chain, table, family + ) ) return ret @@ -1077,16 +1077,16 @@ def delete(table, chain=None, position=None, rule=None, family="ipv4"): if not out: ret["result"] = True - ret[ - "comment" - ] = 'Deleted rule "{}" in chain {} in table {} in family {}.'.format( - rule, chain, table, family + ret["comment"] = ( + 'Deleted rule "{}" in chain {} in table {} in family {}.'.format( + rule, chain, table, family + ) ) else: - ret[ - "comment" - ] = 'Failed to delete rule "{}" in chain {} table {} in family {}'.format( - rule, chain, table, family + ret["comment"] = ( + 'Failed to delete rule "{}" in chain {} table {} in family {}'.format( + rule, chain, table, family + ) ) return ret diff --git a/salt/modules/nginx.py b/salt/modules/nginx.py index b684df5f6ff..21332816a5d 100644 --- a/salt/modules/nginx.py +++ b/salt/modules/nginx.py @@ -39,7 +39,7 @@ def version(): salt '*' nginx.version """ - cmd = "{} -v".format(__detect_os()) + cmd = f"{__detect_os()} -v" out = __salt__["cmd.run"](cmd).splitlines() ret = out[0].rsplit("/", maxsplit=1) return ret[-1] @@ -56,7 +56,7 @@ def build_info(): salt '*' nginx.build_info """ ret = {"info": []} - out = __salt__["cmd.run"]("{} -V".format(__detect_os())) + out = __salt__["cmd.run"](f"{__detect_os()} -V") for i in out.splitlines(): if i.startswith("configure argument"): @@ -80,7 +80,7 @@ def configtest(): """ ret = {} - cmd = "{} -t".format(__detect_os()) + cmd = f"{__detect_os()} -t" out = __salt__["cmd.run_all"](cmd) if out["retcode"] != 0: @@ -116,7 +116,7 @@ def signal(signal=None): if signal == "start": arguments = "" else: - arguments = " -s {}".format(signal) + arguments = f" -s {signal}" cmd = __detect_os() + arguments out = __salt__["cmd.run_all"](cmd) @@ -130,7 +130,7 @@ def signal(signal=None): ret = out["stdout"].strip() # No output for something like: nginxctl graceful else: - ret = 'Command: "{}" completed successfully!'.format(cmd) + ret = f'Command: "{cmd}" completed successfully!' return ret diff --git a/salt/modules/nilrt_ip.py b/salt/modules/nilrt_ip.py index 84612d7a17d..27243f2c70f 100644 --- a/salt/modules/nilrt_ip.py +++ b/salt/modules/nilrt_ip.py @@ -86,9 +86,7 @@ def _get_state(): except KeyError: return "offline" except dbus.DBusException as exc: - raise salt.exceptions.CommandExecutionError( - "Connman daemon error: {}".format(exc) - ) + raise salt.exceptions.CommandExecutionError(f"Connman daemon error: {exc}") def _get_technologies(): @@ -143,7 +141,7 @@ def _space_delimited_list(value): if valid: return True, "space-delimited string" - return False, "{} is not a valid list.\n".format(value) + return False, f"{value} is not a valid list.\n" def _validate_ipv4(value): @@ -152,13 +150,13 @@ def _validate_ipv4(value): """ if len(value) == 3: if not salt.utils.validate.net.ipv4_addr(value[0].strip()): - return False, "Invalid ip address: {} for ipv4 option".format(value[0]) + return False, f"Invalid ip address: {value[0]} for ipv4 option" if not salt.utils.validate.net.netmask(value[1].strip()): - return False, "Invalid netmask: {} for ipv4 option".format(value[1]) + return False, f"Invalid netmask: {value[1]} for ipv4 option" if not salt.utils.validate.net.ipv4_addr(value[2].strip()): - return False, "Invalid gateway: {} for ipv4 option".format(value[2]) + return False, f"Invalid gateway: {value[2]} for ipv4 option" else: - return False, "Invalid value: {} for ipv4 option".format(value) + return False, f"Invalid value: {value} for ipv4 option" return True, "" @@ -322,10 +320,8 @@ def _get_possible_adapter_modes(interface, blacklist): protocols = _load_config("lvrt", ["AdditionalNetworkProtocols"])[ "AdditionalNetworkProtocols" ].lower() - sys_interface_path = os.readlink("/sys/class/net/{}".format(interface)) - with salt.utils.files.fopen( - "/sys/class/net/{}/uevent".format(interface) - ) as uevent_file: + sys_interface_path = os.readlink(f"/sys/class/net/{interface}") + with salt.utils.files.fopen(f"/sys/class/net/{interface}/uevent") as uevent_file: uevent_lines = uevent_file.readlines() uevent_devtype = "" for line in uevent_lines: @@ -554,7 +550,7 @@ def _change_state_legacy(interface, new_state): if initial_mode == "ethercat": __salt__["system.set_reboot_required_witnessed"]() else: - out = __salt__["cmd.run_all"]("ip link set {} {}".format(interface, new_state)) + out = __salt__["cmd.run_all"](f"ip link set {interface} {new_state}") if out["retcode"] != 0: msg = "Couldn't {} interface {}. Error: {}".format( "enable" if new_state == "up" else "disable", interface, out["stderr"] @@ -582,22 +578,22 @@ def _change_dhcp_config(interface, enable_dhcp=True, filename=INTERFACES_CONFIG) interface = pyiface.Interface(name=interface) hwaddr = interface.hwaddr[:-1] hwaddr_section_number = "".join(hwaddr.split(":")) - if parser.has_section("service_{}".format(hwaddr_section_number)): - parser.remove_section("service_{}".format(hwaddr_section_number)) - parser.add_section("service_{}".format(hwaddr_section_number)) - parser.set("service_{}".format(hwaddr_section_number), "MAC", hwaddr) + if parser.has_section(f"service_{hwaddr_section_number}"): + parser.remove_section(f"service_{hwaddr_section_number}") + parser.add_section(f"service_{hwaddr_section_number}") + parser.set(f"service_{hwaddr_section_number}", "MAC", hwaddr) parser.set( - "service_{}".format(hwaddr_section_number), + f"service_{hwaddr_section_number}", "Name", - "ethernet_cable_{}".format(hwaddr_section_number), + f"ethernet_cable_{hwaddr_section_number}", ) - parser.set("service_{}".format(hwaddr_section_number), "Type", "ethernet") + parser.set(f"service_{hwaddr_section_number}", "Type", "ethernet") if enable_dhcp: - parser.set("service_{}".format(hwaddr_section_number), "IPv4.Method", "dhcp") - parser.set("service_{}".format(hwaddr_section_number), "AutoConnect", "true") - parser.set("service_{}".format(hwaddr_section_number), "Nameservers", "''") + parser.set(f"service_{hwaddr_section_number}", "IPv4.Method", "dhcp") + parser.set(f"service_{hwaddr_section_number}", "AutoConnect", "true") + parser.set(f"service_{hwaddr_section_number}", "Nameservers", "''") else: - parser.set("service_{}".format(hwaddr_section_number), "IPv4", "off") + parser.set(f"service_{hwaddr_section_number}", "IPv4", "off") with salt.utils.files.fopen(filename, "w") as config_file: parser.write(config_file) return True @@ -622,9 +618,7 @@ def _change_state(interface, new_state): if new_state == "up" else _change_dhcp_config(interface, False) ) - raise salt.exceptions.CommandExecutionError( - "Invalid interface name: {}".format(interface) - ) + raise salt.exceptions.CommandExecutionError(f"Invalid interface name: {interface}") def up(interface, iface_type=None): # pylint: disable=invalid-name,unused-argument @@ -708,9 +702,9 @@ def _save_config(section, token, value): Helper function to persist a configuration in the ini file """ cmd = NIRTCFG_PATH - cmd += " --set section={},token='{}',value='{}'".format(section, token, value) + cmd += f" --set section={section},token='{token}',value='{value}'" if __salt__["cmd.run_all"](cmd)["retcode"] != 0: - exc_msg = "Error: could not set {} to {} for {}\n".format(token, value, section) + exc_msg = f"Error: could not set {token} to {value} for {section}\n" raise salt.exceptions.CommandExecutionError(exc_msg) @@ -775,9 +769,7 @@ def set_dhcp_linklocal_all(interface): return True if interface in [x.name for x in pyiface.getIfaces()]: return _change_dhcp_config(interface) - raise salt.exceptions.CommandExecutionError( - "Invalid interface name: {}".format(interface) - ) + raise salt.exceptions.CommandExecutionError(f"Invalid interface name: {interface}") def set_dhcp_only_all(interface): @@ -863,24 +855,24 @@ def _configure_static_interface(interface, **settings): pass hwaddr = interface.hwaddr[:-1] hwaddr_section_number = "".join(hwaddr.split(":")) - if parser.has_section("service_{}".format(hwaddr_section_number)): - parser.remove_section("service_{}".format(hwaddr_section_number)) - parser.add_section("service_{}".format(hwaddr_section_number)) + if parser.has_section(f"service_{hwaddr_section_number}"): + parser.remove_section(f"service_{hwaddr_section_number}") + parser.add_section(f"service_{hwaddr_section_number}") ip_address = settings.get("ip", "0.0.0.0") netmask = settings.get("netmask", "0.0.0.0") gateway = settings.get("gateway", "0.0.0.0") dns_servers = settings.get("dns", "''") - name = settings.get("name", "ethernet_cable_{}".format(hwaddr_section_number)) + name = settings.get("name", f"ethernet_cable_{hwaddr_section_number}") parser.set( - "service_{}".format(hwaddr_section_number), + f"service_{hwaddr_section_number}", "IPv4", - "{}/{}/{}".format(ip_address, netmask, gateway), + f"{ip_address}/{netmask}/{gateway}", ) - parser.set("service_{}".format(hwaddr_section_number), "Nameservers", dns_servers) - parser.set("service_{}".format(hwaddr_section_number), "Name", name) - parser.set("service_{}".format(hwaddr_section_number), "MAC", hwaddr) - parser.set("service_{}".format(hwaddr_section_number), "Type", "ethernet") - parser.set("service_{}".format(hwaddr_section_number), "IPv4.method", "manual") + parser.set(f"service_{hwaddr_section_number}", "Nameservers", dns_servers) + parser.set(f"service_{hwaddr_section_number}", "Name", name) + parser.set(f"service_{hwaddr_section_number}", "MAC", hwaddr) + parser.set(f"service_{hwaddr_section_number}", "Type", "ethernet") + parser.set(f"service_{hwaddr_section_number}", "IPv4.method", "manual") with salt.utils.files.fopen(INTERFACES_CONFIG, "w") as config_file: parser.write(config_file) return True @@ -941,23 +933,23 @@ def set_static_all(interface, address, netmask, gateway, nameservers=None): "dns": ",".join(nameservers) if nameservers else "", "netmask": netmask, "gateway": gateway, - } + }, ) raise salt.exceptions.CommandExecutionError( - "Invalid interface name: {}".format(interface) + f"Invalid interface name: {interface}" ) service = pyconnman.ConnService(os.path.join(SERVICE_PATH, service)) ipv4 = service.get_property("IPv4.Configuration") ipv4["Method"] = dbus.String("manual", variant_level=1) - ipv4["Address"] = dbus.String("{}".format(address), variant_level=1) - ipv4["Netmask"] = dbus.String("{}".format(netmask), variant_level=1) - ipv4["Gateway"] = dbus.String("{}".format(gateway), variant_level=1) + ipv4["Address"] = dbus.String(f"{address}", variant_level=1) + ipv4["Netmask"] = dbus.String(f"{netmask}", variant_level=1) + ipv4["Gateway"] = dbus.String(f"{gateway}", variant_level=1) try: service.set_property("IPv4.Configuration", ipv4) if nameservers: service.set_property( "Nameservers.Configuration", - [dbus.String("{}".format(d)) for d in nameservers], + [dbus.String(f"{d}") for d in nameservers], ) except Exception as exc: # pylint: disable=broad-except exc_msg = "Couldn't set manual settings for service: {}\nError: {}\n".format( @@ -998,7 +990,7 @@ def build_interface(iface, iface_type, enabled, **settings): raise salt.exceptions.CommandExecutionError("Not supported in this version.") if iface_type != "eth": raise salt.exceptions.CommandExecutionError( - "Interface type not supported: {}:".format(iface_type) + f"Interface type not supported: {iface_type}:" ) if ( @@ -1049,7 +1041,7 @@ def build_network_settings(**settings): old_hostname = __salt__["network.get_hostname"] if new_hostname != old_hostname: __salt__["network.mod_hostname"](new_hostname) - changes.append("hostname={}".format(new_hostname)) + changes.append(f"hostname={new_hostname}") return changes @@ -1068,9 +1060,9 @@ def get_network_settings(): raise salt.exceptions.CommandExecutionError("Not supported in this version.") settings = [] networking = "no" if _get_state() == "offline" else "yes" - settings.append("networking={}".format(networking)) + settings.append(f"networking={networking}") hostname = __salt__["network.get_hostname"] - settings.append("hostname={}".format(hostname)) + settings.append(f"hostname={hostname}") return settings diff --git a/salt/modules/nix.py b/salt/modules/nix.py index d5331cb7a97..b0e95afc2d1 100644 --- a/salt/modules/nix.py +++ b/salt/modules/nix.py @@ -18,7 +18,6 @@ For more information on nix, see the `nix documentation`_. .. _`nix-daemon`: https://nixos.org/nix/manual/#ssec-multi-user """ - import itertools import logging import os diff --git a/salt/modules/npm.py b/salt/modules/npm.py index edbb7b4ae1d..f7a40043de4 100644 --- a/salt/modules/npm.py +++ b/salt/modules/npm.py @@ -47,9 +47,7 @@ def _check_valid_version(): npm_path = salt.utils.path.which("npm") # pylint: disable=no-member - res = salt.modules.cmdmod.run( - "{npm} --version".format(npm=npm_path), output_loglevel="quiet" - ) + res = salt.modules.cmdmod.run(f"{npm_path} --version", output_loglevel="quiet") npm_version = Version(res) valid_version = Version("1.2") # pylint: enable=no-member @@ -151,7 +149,7 @@ def install( cwd = dir if registry: - cmd.append('--registry="{}"'.format(registry)) + cmd.append(f'--registry="{registry}"') if dry_run: cmd.append("--dry-run") @@ -222,7 +220,7 @@ def uninstall(pkg, dir=None, runas=None, env=None): if uid: env.update({"SUDO_UID": uid, "SUDO_USER": ""}) - cmd = ["npm", "uninstall", '"{}"'.format(pkg)] + cmd = ["npm", "uninstall", f'"{pkg}"'] if not dir: cmd.append("--global") @@ -291,14 +289,14 @@ def list_(pkg=None, dir=None, runas=None, env=None, depth=None): if depth is not None: if not isinstance(depth, (int, float)): raise salt.exceptions.SaltInvocationError( - "Error: depth {} must be a number".format(depth) + f"Error: depth {depth} must be a number" ) - cmd.append("--depth={}".format(int(depth))) + cmd.append(f"--depth={int(depth)}") if pkg: # Protect against injection pkg = shlex.quote(pkg) - cmd.append('"{}"'.format(pkg)) + cmd.append(f'"{pkg}"') cmd = " ".join(cmd) result = __salt__["cmd.run_all"]( diff --git a/salt/modules/nspawn.py b/salt/modules/nspawn.py index 3c8e8c0f76f..a99a8f9fc8b 100644 --- a/salt/modules/nspawn.py +++ b/salt/modules/nspawn.py @@ -20,7 +20,6 @@ Minions running systemd >= 219 will place new containers in package. """ - import errno import functools import logging diff --git a/salt/modules/nxos_api.py b/salt/modules/nxos_api.py index 2513d9b0ff9..b787043f354 100644 --- a/salt/modules/nxos_api.py +++ b/salt/modules/nxos_api.py @@ -181,7 +181,7 @@ def _cli_command(commands, method="cli", **kwargs): ) raise SaltException(msg) else: - msg = 'Invalid command: "{cmd}".'.format(cmd=cmd) + msg = f'Invalid command: "{cmd}".' raise SaltException(msg) txt_responses.append(rpc_reponse["result"]) return txt_responses @@ -313,7 +313,7 @@ def config( context=None, defaults=None, saltenv="base", - **kwargs + **kwargs, ): """ Configures the Nexus switch with the specified commands. @@ -401,7 +401,7 @@ def config( if config_file: file_str = __salt__["cp.get_file_str"](config_file, saltenv=saltenv) if file_str is False: - raise CommandExecutionError("Source file {} not found".format(config_file)) + raise CommandExecutionError(f"Source file {config_file} not found") elif commands: if isinstance(commands, str): commands = [commands] diff --git a/salt/modules/nxos_upgrade.py b/salt/modules/nxos_upgrade.py index 69ce8d2b5c4..25f662db8ee 100644 --- a/salt/modules/nxos_upgrade.py +++ b/salt/modules/nxos_upgrade.py @@ -114,7 +114,7 @@ def check_upgrade_impact(system_image, kickstart_image=None, issu=True, **kwargs if ki is not None: cmd = cmd + " kickstart {0}:{1} system {0}:{2}".format(dev, ki, si) else: - cmd = cmd + " nxos {}:{}".format(dev, si) + cmd = cmd + f" nxos {dev}:{si}" if issu and ki is None: cmd = cmd + " non-disruptive" @@ -254,14 +254,14 @@ def _upgrade(system_image, kickstart_image, issu, **kwargs): if ki is None: logmsg = "Upgrading device using combined system/kickstart image." - logmsg += "\nSystem Image: {}".format(si) - cmd = cmd + " nxos {}:{}".format(dev, si) + logmsg += f"\nSystem Image: {si}" + cmd = cmd + f" nxos {dev}:{si}" if issu: cmd = cmd + " non-disruptive" else: logmsg = "Upgrading device using separate system/kickstart images." - logmsg += "\nSystem Image: {}".format(si) - logmsg += "\nKickstart Image: {}".format(ki) + logmsg += f"\nSystem Image: {si}" + logmsg += f"\nKickstart Image: {ki}" if not issu: log.info("Attempting upgrade using force option") cmd = cmd + " force" @@ -367,7 +367,7 @@ def _parse_upgrade_data(data): g3 = mo.group(3) g4 = mo.group(4) g5 = mo.group(5) - mk = "module {}:image {}".format(g1, g2) # module key + mk = f"module {g1}:image {g2}" # module key upgrade_result[bk][mk] = {} upgrade_result[bk][mk]["running_version"] = g3 upgrade_result[bk][mk]["new_version"] = g4 diff --git a/salt/modules/omapi.py b/salt/modules/omapi.py index c63d94d3dae..e5d01260012 100644 --- a/salt/modules/omapi.py +++ b/salt/modules/omapi.py @@ -11,7 +11,6 @@ config or pillar: :depends: pypureomapi Python module """ - import logging import struct @@ -87,9 +86,9 @@ def add_host(mac, name=None, ip=None, ddns=False, group=None, supersede_host=Fal if group: msg.obj.append((b"group", salt.utils.stringutils.to_bytes(group))) if supersede_host: - statements += 'option host-name "{}"; '.format(name) + statements += f'option host-name "{name}"; ' if ddns and name: - statements += 'ddns-hostname "{}"; '.format(name) + statements += f'ddns-hostname "{name}"; ' if statements: msg.obj.append((b"statements", salt.utils.stringutils.to_bytes(statements))) response = o.query_server(msg) diff --git a/salt/modules/openbsd_sysctl.py b/salt/modules/openbsd_sysctl.py index 35a49297404..348d164efd0 100644 --- a/salt/modules/openbsd_sysctl.py +++ b/salt/modules/openbsd_sysctl.py @@ -61,7 +61,7 @@ def get(name): salt '*' sysctl.get hw.physmem """ - cmd = "sysctl -n {}".format(name) + cmd = f"sysctl -n {name}" out = __salt__["cmd.run"](cmd) return out @@ -77,7 +77,7 @@ def assign(name, value): salt '*' sysctl.assign net.inet.ip.forwarding 1 """ ret = {} - cmd = 'sysctl {}="{}"'.format(name, value) + cmd = f'sysctl {name}="{value}"' data = __salt__["cmd.run_all"](cmd) # Certain values cannot be set from this console, at the current @@ -119,7 +119,7 @@ def persist(name, value, config="/etc/sysctl.conf"): with salt.utils.files.fopen(config, "r") as ifile: for line in ifile: line = salt.utils.stringutils.to_unicode(line) - if not line.startswith("{}=".format(name)): + if not line.startswith(f"{name}="): nlines.append(line) continue else: @@ -133,11 +133,11 @@ def persist(name, value, config="/etc/sysctl.conf"): rest = rest[len(rest_v) :] if rest_v == value: return "Already set" - new_line = "{}={}{}".format(key, value, rest) + new_line = f"{key}={value}{rest}" nlines.append(new_line) edited = True if not edited: - nlines.append("{}={}\n".format(name, value)) + nlines.append(f"{name}={value}\n") with salt.utils.files.fopen(config, "wb") as ofile: ofile.writelines(salt.utils.data.encode(nlines)) diff --git a/salt/modules/openbsdpkg.py b/salt/modules/openbsdpkg.py index 3cbdc0cadf1..57d28ed96b5 100644 --- a/salt/modules/openbsdpkg.py +++ b/salt/modules/openbsdpkg.py @@ -95,7 +95,7 @@ def list_pkgs(versions_as_list=False, **kwargs): pkgname, pkgver, flavor = __PKG_RE.match(line).groups() except AttributeError: continue - pkgname += "--{}".format(flavor) if flavor else "" + pkgname += f"--{flavor}" if flavor else "" __salt__["pkg_resource.add_pkg"](ret, pkgname, pkgver) __salt__["pkg_resource.sort_pkglist"](ret) @@ -129,7 +129,7 @@ def latest_version(*names, **kwargs): ret[name] = "" # Query the repository for the package name - cmd = "pkg_info -Q {}".format(name) + cmd = f"pkg_info -Q {name}" out = __salt__["cmd.run_stdout"]( cmd, python_shell=False, output_loglevel="trace" ) @@ -153,8 +153,8 @@ def latest_version(*names, **kwargs): # First check if we need to look for flavors before # looking at unflavored packages. - if "{}--{}".format(pkgname, flavor) == name: - pkgname += "--{}".format(flavor) + if f"{pkgname}--{flavor}" == name: + pkgname += f"--{flavor}" elif pkgname == name: pass else: @@ -233,8 +233,8 @@ def install(name=None, pkgs=None, sources=None, **kwargs): if pkg_type == "repository": stem, branch = (pkg.split("%") + [""])[:2] base, flavor = (stem.split("--") + [""])[:2] - pkg = "{}--{}%{}".format(base, flavor, branch) - cmd = "pkg_add -x -I {}".format(pkg) + pkg = f"{base}--{flavor}%{branch}" + cmd = f"pkg_add -x -I {pkg}" out = __salt__["cmd.run_all"](cmd, python_shell=False, output_loglevel="trace") if out["retcode"] != 0 and out["stderr"]: errors.append(out["stderr"]) diff --git a/salt/modules/openbsdrcctl_service.py b/salt/modules/openbsdrcctl_service.py index 4baa0a4c56a..8a80cf57acd 100644 --- a/salt/modules/openbsdrcctl_service.py +++ b/salt/modules/openbsdrcctl_service.py @@ -56,7 +56,7 @@ def available(name): salt '*' service.available sshd """ - cmd = "{} get {}".format(_cmd(), name) + cmd = f"{_cmd()} get {name}" if __salt__["cmd.retcode"](cmd, ignore_retcode=True) == 2: return False return True @@ -88,7 +88,7 @@ def get_all(): """ ret = [] service = _cmd() - for svc in __salt__["cmd.run"]("{} ls all".format(service)).splitlines(): + for svc in __salt__["cmd.run"](f"{service} ls all").splitlines(): ret.append(svc) return sorted(ret) @@ -105,7 +105,7 @@ def get_disabled(): """ ret = [] service = _cmd() - for svc in __salt__["cmd.run"]("{} ls off".format(service)).splitlines(): + for svc in __salt__["cmd.run"](f"{service} ls off").splitlines(): ret.append(svc) return sorted(ret) @@ -122,7 +122,7 @@ def get_enabled(): """ ret = [] service = _cmd() - for svc in __salt__["cmd.run"]("{} ls on".format(service)).splitlines(): + for svc in __salt__["cmd.run"](f"{service} ls on").splitlines(): ret.append(svc) return sorted(ret) @@ -137,7 +137,7 @@ def start(name): salt '*' service.start """ - cmd = "{} -f start {}".format(_cmd(), name) + cmd = f"{_cmd()} -f start {name}" return not __salt__["cmd.retcode"](cmd) @@ -151,7 +151,7 @@ def stop(name): salt '*' service.stop """ - cmd = "{} stop {}".format(_cmd(), name) + cmd = f"{_cmd()} stop {name}" return not __salt__["cmd.retcode"](cmd) @@ -165,7 +165,7 @@ def restart(name): salt '*' service.restart """ - cmd = "{} -f restart {}".format(_cmd(), name) + cmd = f"{_cmd()} -f restart {name}" return not __salt__["cmd.retcode"](cmd) @@ -179,7 +179,7 @@ def reload_(name): salt '*' service.reload """ - cmd = "{} reload {}".format(_cmd(), name) + cmd = f"{_cmd()} reload {name}" return not __salt__["cmd.retcode"](cmd) @@ -197,7 +197,7 @@ def status(name, sig=None): if sig: return bool(__salt__["status.pid"](sig)) - cmd = "{} check {}".format(_cmd(), name) + cmd = f"{_cmd()} check {name}" return not __salt__["cmd.retcode"](cmd, ignore_retcode=True) @@ -217,14 +217,14 @@ def enable(name, **kwargs): salt '*' service.enable salt '*' service.enable flags= """ - stat_cmd = "{} set {} status on".format(_cmd(), name) + stat_cmd = f"{_cmd()} set {name} status on" stat_retcode = __salt__["cmd.retcode"](stat_cmd) flag_retcode = None # only (re)set flags for services that have an rc.d(8) script - if os.path.exists("/etc/rc.d/{}".format(name)): + if os.path.exists(f"/etc/rc.d/{name}"): flags = _get_flags(**kwargs) - flag_cmd = "{} set {} flags {}".format(_cmd(), name, flags) + flag_cmd = f"{_cmd()} set {name} flags {flags}" flag_retcode = __salt__["cmd.retcode"](flag_cmd) return not any([stat_retcode, flag_retcode]) @@ -240,7 +240,7 @@ def disable(name, **kwargs): salt '*' service.disable """ - cmd = "{} set {} status off".format(_cmd(), name) + cmd = f"{_cmd()} set {name} status off" return not __salt__["cmd.retcode"](cmd) @@ -254,7 +254,7 @@ def disabled(name): salt '*' service.disabled """ - cmd = "{} get {} status".format(_cmd(), name) + cmd = f"{_cmd()} get {name} status" return not __salt__["cmd.retcode"](cmd, ignore_retcode=True) == 0 @@ -273,18 +273,16 @@ def enabled(name, **kwargs): salt '*' service.enabled salt '*' service.enabled flags= """ - cmd = "{} get {} status".format(_cmd(), name) + cmd = f"{_cmd()} get {name} status" if not __salt__["cmd.retcode"](cmd, ignore_retcode=True): # also consider a service disabled if the current flags are different # than the configured ones so we have a chance to update them flags = _get_flags(**kwargs) - cur_flags = __salt__["cmd.run_stdout"]("{} get {} flags".format(_cmd(), name)) + cur_flags = __salt__["cmd.run_stdout"](f"{_cmd()} get {name} flags") if format(flags) == format(cur_flags): return True if not flags: - def_flags = __salt__["cmd.run_stdout"]( - "{} getdef {} flags".format(_cmd(), name) - ) + def_flags = __salt__["cmd.run_stdout"](f"{_cmd()} getdef {name} flags") if format(cur_flags) == format(def_flags): return True diff --git a/salt/modules/openbsdservice.py b/salt/modules/openbsdservice.py index b68d217b448..70fe9981f54 100644 --- a/salt/modules/openbsdservice.py +++ b/salt/modules/openbsdservice.py @@ -8,7 +8,6 @@ The service module for OpenBSD `. """ - import fnmatch import logging import os @@ -56,7 +55,7 @@ def start(name): salt '*' service.start """ - cmd = "/etc/rc.d/{} -f start".format(name) + cmd = f"/etc/rc.d/{name} -f start" return not __salt__["cmd.retcode"](cmd) @@ -70,7 +69,7 @@ def stop(name): salt '*' service.stop """ - cmd = "/etc/rc.d/{} -f stop".format(name) + cmd = f"/etc/rc.d/{name} -f stop" return not __salt__["cmd.retcode"](cmd) @@ -84,7 +83,7 @@ def restart(name): salt '*' service.restart """ - cmd = "/etc/rc.d/{} -f restart".format(name) + cmd = f"/etc/rc.d/{name} -f restart" return not __salt__["cmd.retcode"](cmd) @@ -121,7 +120,7 @@ def status(name, sig=None): services = [name] results = {} for service in services: - cmd = "/etc/rc.d/{} -f check".format(service) + cmd = f"/etc/rc.d/{service} -f check" results[service] = not __salt__["cmd.retcode"](cmd, ignore_retcode=True) if contains_globbing: return results @@ -140,7 +139,7 @@ def reload_(name): salt '*' service.reload """ - cmd = "/etc/rc.d/{} -f reload".format(name) + cmd = f"/etc/rc.d/{name} -f reload" return not __salt__["cmd.retcode"](cmd) @@ -220,7 +219,7 @@ def available(name): salt '*' service.available sshd """ - path = "/etc/rc.d/{}".format(name) + path = f"/etc/rc.d/{name}" return os.path.isfile(path) and os.access(path, os.X_OK) diff --git a/salt/modules/opkg.py b/salt/modules/opkg.py index 98882c85e96..7176c865347 100644 --- a/salt/modules/opkg.py +++ b/salt/modules/opkg.py @@ -107,7 +107,7 @@ def _update_nilrt_restart_state(): if os.path.exists(nisysapi_conf_d_path): with salt.utils.files.fopen( - "{}/sysapi.conf.d.count".format(NILRT_RESTARTCHECK_STATE_PATH), "w" + f"{NILRT_RESTARTCHECK_STATE_PATH}/sysapi.conf.d.count", "w" ) as fcount: fcount.write(str(len(os.listdir(nisysapi_conf_d_path)))) @@ -135,7 +135,7 @@ def _fingerprint_file(*, filename, fingerprint_dir): ) ) __salt__["cmd.shell"]( - "md5sum {} > {}/{}.md5sum".format(filename, fingerprint_dir, filename.name) + f"md5sum {filename} > {fingerprint_dir}/{filename.name}.md5sum" ) @@ -532,7 +532,7 @@ def install( else: to_install.append(pkgname) else: - pkgstr = "{}={}".format(pkgname, version_num) + pkgstr = f"{pkgname}={version_num}" cver = old.get(pkgname, "") if ( reinstall @@ -839,15 +839,15 @@ def hold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W0613 state = _get_state(target) if not state: - ret[target]["comment"] = "Package {} not currently held.".format(target) + ret[target]["comment"] = f"Package {target} not currently held." elif state != "hold": if "test" in __opts__ and __opts__["test"]: ret[target].update(result=None) - ret[target]["comment"] = "Package {} is set to be held.".format(target) + ret[target]["comment"] = f"Package {target} is set to be held." else: result = _set_state(target, "hold") ret[target].update(changes=result[target], result=True) - ret[target]["comment"] = "Package {} is now being held.".format(target) + ret[target]["comment"] = f"Package {target} is now being held." else: ret[target].update(result=True) ret[target]["comment"] = "Package {} is already set to be held.".format( @@ -902,11 +902,11 @@ def unhold(name=None, pkgs=None, sources=None, **kwargs): # pylint: disable=W06 state = _get_state(target) if not state: - ret[target]["comment"] = "Package {} does not have a state.".format(target) + ret[target]["comment"] = f"Package {target} does not have a state." elif state == "hold": if "test" in __opts__ and __opts__["test"]: ret[target].update(result=None) - ret["comment"] = "Package {} is set not to be held.".format(target) + ret["comment"] = f"Package {target} is set not to be held." else: result = _set_state(target, "ok") ret[target].update(changes=result[target], result=True) @@ -960,7 +960,7 @@ def _set_state(pkg, state): ret = {} valid_states = ("hold", "noprune", "user", "ok", "installed", "unpacked") if state not in valid_states: - raise SaltInvocationError("Invalid state: {}".format(state)) + raise SaltInvocationError(f"Invalid state: {state}") oldstate = _get_state(pkg) cmd = ["opkg", "flag"] cmd.append(state) @@ -1466,7 +1466,7 @@ def del_repo(repo, **kwargs): # pylint: disable=unused-argument refresh_db() return ret - return "Repo {} doesn't exist in the opkg repo lists".format(repo) + return f"Repo {repo} doesn't exist in the opkg repo lists" def mod_repo(repo, **kwargs): @@ -1514,9 +1514,9 @@ def mod_repo(repo, **kwargs): repostr += "src/gz" if source["compressed"] else "src" repo_alias = kwargs["alias"] if "alias" in kwargs else repo if " " in repo_alias: - repostr += ' "{}"'.format(repo_alias) + repostr += f' "{repo_alias}"' else: - repostr += " {}".format(repo_alias) + repostr += f" {repo_alias}" repostr += " {}".format(kwargs["uri"] if "uri" in kwargs else source["uri"]) trusted = kwargs.get("trusted") repostr = ( diff --git a/salt/modules/osquery.py b/salt/modules/osquery.py index 93c3774dc18..0bb7b6c994f 100644 --- a/salt/modules/osquery.py +++ b/salt/modules/osquery.py @@ -36,7 +36,7 @@ def _table_attrs(table): """ Helper function to find valid table attributes """ - cmd = ["osqueryi"] + ["--json"] + ["pragma table_info({})".format(table)] + cmd = ["osqueryi"] + ["--json"] + [f"pragma table_info({table})"] res = __salt__["cmd.run_all"](cmd) if res["retcode"] == 0: attrs = [] @@ -81,14 +81,14 @@ def _osquery_cmd(table, attrs=None, where=None, format="json"): for a in attrs: if a not in valid_attrs: ret["result"] = False - ret[ - "comment" - ] = "{} is not a valid attribute for table {}".format(a, table) + ret["comment"] = ( + f"{a} is not a valid attribute for table {table}" + ) return ret _attrs = ",".join(attrs) else: ret["result"] = False - ret["comment"] = "Invalid table {}.".format(table) + ret["comment"] = f"Invalid table {table}." return ret else: ret["comment"] = "attrs must be specified as a list." @@ -97,12 +97,12 @@ def _osquery_cmd(table, attrs=None, where=None, format="json"): else: _attrs = "*" - sql = "select {} from {}".format(_attrs, table) + sql = f"select {_attrs} from {table}" if where: - sql = "{} where {}".format(sql, where) + sql = f"{sql} where {where}" - sql = "{};".format(sql) + sql = f"{sql};" res = _osquery(sql) if res["result"]: diff --git a/salt/modules/pacmanpkg.py b/salt/modules/pacmanpkg.py index 298b3e7313a..857f6d07dfc 100644 --- a/salt/modules/pacmanpkg.py +++ b/salt/modules/pacmanpkg.py @@ -8,6 +8,7 @@ A module to wrap pacman calls, since Arch is the best *'pkg.install' is not available*), see :ref:`here `. """ + import copy import fnmatch import logging @@ -363,7 +364,6 @@ def group_info(name): def group_diff(name): - """ .. versionadded:: 2016.11.0 diff --git a/salt/modules/pagerduty_util.py b/salt/modules/pagerduty_util.py index 642e2ce2a5a..76e508b5e10 100644 --- a/salt/modules/pagerduty_util.py +++ b/salt/modules/pagerduty_util.py @@ -345,7 +345,7 @@ def create_or_update_resource( resource_id = _get_resource_id(resource) return _query( method="PUT", - action="{}/{}".format(resource_name, resource_id), + action=f"{resource_name}/{resource_id}", data=data_to_update, profile=profile, subdomain=subdomain, @@ -383,7 +383,7 @@ def delete_resource( resource_id = _get_resource_id(resource) return _query( method="DELETE", - action="{}/{}".format(resource_name, resource_id), + action=f"{resource_name}/{resource_id}", profile=profile, subdomain=subdomain, api_key=api_key, @@ -399,7 +399,7 @@ def resource_present( profile="pagerduty", subdomain=None, api_key=None, - **kwargs + **kwargs, ): """ Generic resource.present state method. Pagerduty state modules should be a thin wrapper over this method, @@ -442,7 +442,7 @@ def resource_absent( profile="pagerduty", subdomain=None, api_key=None, - **kwargs + **kwargs, ): """ Generic resource.absent state method. Pagerduty state modules should be a thin wrapper over this method, @@ -467,7 +467,7 @@ def resource_absent( ) if result is None: ret["result"] = True - ret["comment"] = "{} deleted".format(v) + ret["comment"] = f"{v} deleted" return ret elif result is True: continue diff --git a/salt/modules/pam.py b/salt/modules/pam.py index 58254917e35..50b09262856 100644 --- a/salt/modules/pam.py +++ b/salt/modules/pam.py @@ -54,7 +54,7 @@ def _parse(contents=None, file_name=None): position += 1 break else: - control_flag += " {}".format(part) + control_flag += f" {part}" else: control_flag = comps[1] position += 1 diff --git a/salt/modules/panos.py b/salt/modules/panos.py index 64be78723de..73dd05bd92f 100644 --- a/salt/modules/panos.py +++ b/salt/modules/panos.py @@ -27,7 +27,6 @@ through the XML API or through a brokered connection to Panorama. """ - import logging import time @@ -229,7 +228,7 @@ def delete_license(key_name=None): else: query = { "type": "op", - "cmd": "{}".format(key_name), + "cmd": f"{key_name}", } return __proxy__["panos.call"](query) @@ -775,7 +774,7 @@ def get_interface_counters(name="all"): """ query = { "type": "op", - "cmd": "{}".format(name), + "cmd": f"{name}", } return __proxy__["panos.call"](query) @@ -798,7 +797,7 @@ def get_interfaces(name="all"): """ query = { "type": "op", - "cmd": "{}".format(name), + "cmd": f"{name}", } return __proxy__["panos.call"](query) @@ -821,7 +820,7 @@ def get_job(jid=None): if not jid: raise CommandExecutionError("ID option must not be none.") - query = {"type": "op", "cmd": "{}".format(jid)} + query = {"type": "op", "cmd": f"{jid}"} return __proxy__["panos.call"](query) @@ -1170,7 +1169,7 @@ def get_predefined_application(application=None): query = { "type": "config", "action": "get", - "xpath": "/config/predefined/application/entry[@name='{}']".format(application), + "xpath": f"/config/predefined/application/entry[@name='{application}']", } return __proxy__["panos.call"](query) @@ -1800,7 +1799,7 @@ def save_device_config(filename=None): query = { "type": "op", - "cmd": "{}".format(filename), + "cmd": f"{filename}", } return __proxy__["panos.call"](query) @@ -1894,7 +1893,7 @@ def set_hostname(hostname=None, deploy=False): "xpath": ( "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system" ), - "element": "{}".format(hostname), + "element": f"{hostname}", } ret.update(__proxy__["panos.call"](query)) @@ -1938,7 +1937,7 @@ def set_management_icmp(enabled=True, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/service", - "element": "{}".format(value), + "element": f"{value}", } ret.update(__proxy__["panos.call"](query)) @@ -1982,7 +1981,7 @@ def set_management_http(enabled=True, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/service", - "element": "{}".format(value), + "element": f"{value}", } ret.update(__proxy__["panos.call"](query)) @@ -2026,7 +2025,7 @@ def set_management_https(enabled=True, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/service", - "element": "{}".format(value), + "element": f"{value}", } ret.update(__proxy__["panos.call"](query)) @@ -2070,7 +2069,7 @@ def set_management_ocsp(enabled=True, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/service", - "element": "{}".format(value), + "element": f"{value}", } ret.update(__proxy__["panos.call"](query)) @@ -2114,7 +2113,7 @@ def set_management_snmp(enabled=True, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/service", - "element": "{}".format(value), + "element": f"{value}", } ret.update(__proxy__["panos.call"](query)) @@ -2158,7 +2157,7 @@ def set_management_ssh(enabled=True, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/service", - "element": "{}".format(value), + "element": f"{value}", } ret.update(__proxy__["panos.call"](query)) @@ -2202,7 +2201,7 @@ def set_management_telnet(enabled=True, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/service", - "element": "{}".format(value), + "element": f"{value}", } ret.update(__proxy__["panos.call"](query)) @@ -2447,7 +2446,7 @@ def set_permitted_ip(address=None, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/permitted-ip", - "element": "".format(address), + "element": f"", } ret.update(__proxy__["panos.call"](query)) @@ -2485,7 +2484,7 @@ def set_timezone(tz=None, deploy=False): "type": "config", "action": "set", "xpath": "/config/devices/entry[@name='localhost.localdomain']/deviceconfig/system/timezone", - "element": "{}".format(tz), + "element": f"{tz}", } ret.update(__proxy__["panos.call"](query)) @@ -2535,10 +2534,10 @@ def test_fib_route(ip=None, vr="vr1"): xpath = "" if ip: - xpath += "{}".format(ip) + xpath += f"{ip}" if vr: - xpath += "{}".format(vr) + xpath += f"{vr}" xpath += "" @@ -2594,35 +2593,35 @@ def test_security_policy( xpath = "" if sourcezone: - xpath += "{}".format(sourcezone) + xpath += f"{sourcezone}" if destinationzone: - xpath += "{}".format(destinationzone) + xpath += f"{destinationzone}" if source: - xpath += "{}".format(source) + xpath += f"{source}" if destination: - xpath += "{}".format(destination) + xpath += f"{destination}" if protocol: - xpath += "{}".format(protocol) + xpath += f"{protocol}" if port: - xpath += "{}".format(port) + xpath += f"{port}" if application: - xpath += "{}".format(application) + xpath += f"{application}" if category: - xpath += "{}".format(category) + xpath += f"{category}" if allrules: xpath += "yes" xpath += "" - query = {"type": "op", "vsys": "vsys{}".format(vsys), "cmd": xpath} + query = {"type": "op", "vsys": f"vsys{vsys}", "cmd": xpath} return __proxy__["panos.call"](query) diff --git a/salt/modules/parallels.py b/salt/modules/parallels.py index 27f187bacae..2f8ddf80556 100644 --- a/salt/modules/parallels.py +++ b/salt/modules/parallels.py @@ -277,7 +277,7 @@ def exists(name, runas=None): """ vm_info = list_vms(name, info=True, runas=runas).splitlines() for info_line in vm_info: - if "Name: {}".format(name) in info_line: + if f"Name: {name}" in info_line: return True return False @@ -453,7 +453,7 @@ def snapshot_id_to_name(name, snap_id, strict=False, runas=None): name = salt.utils.data.decode(name) if not re.match(GUID_REGEX, snap_id): raise SaltInvocationError( - 'Snapshot ID "{}" is not a GUID'.format(salt.utils.data.decode(snap_id)) + f'Snapshot ID "{salt.utils.data.decode(snap_id)}" is not a GUID' ) # Get the snapshot information of the snapshot having the requested ID @@ -461,9 +461,7 @@ def snapshot_id_to_name(name, snap_id, strict=False, runas=None): # Parallels desktop returned no information for snap_id if not info: - raise SaltInvocationError( - 'No snapshots for VM "{}" have ID "{}"'.format(name, snap_id) - ) + raise SaltInvocationError(f'No snapshots for VM "{name}" have ID "{snap_id}"') # Try to interpret the information try: @@ -540,7 +538,7 @@ def snapshot_name_to_id(name, snap_name, strict=False, runas=None): # non-singular names if not named_ids: raise SaltInvocationError( - 'No snapshots for VM "{}" have name "{}"'.format(name, snap_name) + f'No snapshots for VM "{name}" have name "{snap_name}"' ) elif len(named_ids) == 1: return named_ids[0] @@ -634,7 +632,7 @@ def list_snapshots(name, snap_name=None, tree=False, names=False, runas=None): ret = "{:<38} {}\n".format("Snapshot ID", "Snapshot Name") for snap_id in snap_ids: snap_name = snapshot_id_to_name(name, snap_id, runas=runas) - ret += "{{{0}}} {1}\n".format(snap_id, salt.utils.data.decode(snap_name)) + ret += f"{{{snap_id}}} {salt.utils.data.decode(snap_name)}\n" return ret # Return information directly from parallels desktop diff --git a/salt/modules/parted_partition.py b/salt/modules/parted_partition.py index 02c5ab5a49d..1c9a135b7b8 100644 --- a/salt/modules/parted_partition.py +++ b/salt/modules/parted_partition.py @@ -140,9 +140,7 @@ def _validate_partition_boundary(boundary): unit = match.group(2) if not unit or unit in VALID_UNITS: return - raise CommandExecutionError( - 'Invalid partition boundary passed: "{}"'.format(boundary) - ) + raise CommandExecutionError(f'Invalid partition boundary passed: "{boundary}"') def probe(*devices): @@ -186,9 +184,9 @@ def list_(device, unit=None): if unit: if unit not in VALID_UNITS: raise CommandExecutionError("Invalid unit passed to partition.part_list") - cmd = "parted -m -s {} unit {} print".format(device, unit) + cmd = f"parted -m -s {device} unit {unit} print" else: - cmd = "parted -m -s {} print".format(device) + cmd = f"parted -m -s {device} print" out = __salt__["cmd.run_stdout"](cmd).splitlines() ret = {"info": {}, "partitions": {}} @@ -268,7 +266,7 @@ def align_check(device, part_type, partition): except Exception: # pylint: disable=broad-except raise CommandExecutionError("Invalid partition passed to partition.align_check") - cmd = "parted -m {} align-check {} {}".format(device, part_type, partition) + cmd = f"parted -m {device} align-check {part_type} {partition}" out = __salt__["cmd.run"](cmd).splitlines() return out @@ -290,7 +288,7 @@ def check(device, minor): except Exception: # pylint: disable=broad-except raise CommandExecutionError("Invalid minor number passed to partition.check") - cmd = "parted -m -s {} check {}".format(device, minor) + cmd = f"parted -m -s {device} check {minor}" out = __salt__["cmd.run"](cmd).splitlines() return out @@ -315,7 +313,7 @@ def cp(device, from_minor, to_minor): # pylint: disable=C0103 except Exception: # pylint: disable=broad-except raise CommandExecutionError("Invalid minor number passed to partition.cp") - cmd = "parted -m -s {} cp {} {}".format(device, from_minor, to_minor) + cmd = f"parted -m -s {device} cp {from_minor} {to_minor}" out = __salt__["cmd.run"](cmd).splitlines() return out @@ -344,7 +342,7 @@ def get_id(device, minor): except Exception: # pylint: disable=broad-except raise CommandExecutionError("Invalid minor number passed to partition.get_id") - cmd = "sfdisk --print-id {} {}".format(device, minor) + cmd = f"sfdisk --print-id {device} {minor}" out = __salt__["cmd.run"](cmd).splitlines() return out @@ -376,7 +374,7 @@ def set_id(device, minor, system_id): if system_id not in system_types(): raise CommandExecutionError("Invalid system_id passed to partition.set_id") - cmd = "sfdisk --change-id {} {} {}".format(device, minor, system_id) + cmd = f"sfdisk --change-id {device} {minor} {system_id}" out = __salt__["cmd.run"](cmd).splitlines() return out @@ -451,11 +449,11 @@ def mkfs(device, fs_type): if fs_type == "linux-swap": mkfs_cmd = "mkswap" else: - mkfs_cmd = "mkfs.{}".format(fs_type) + mkfs_cmd = f"mkfs.{fs_type}" if not salt.utils.path.which(mkfs_cmd): - return "Error: {} is unavailable.".format(mkfs_cmd) - cmd = "{} {}".format(mkfs_cmd, device) + return f"Error: {mkfs_cmd} is unavailable." + cmd = f"{mkfs_cmd} {device}" out = __salt__["cmd.run"](cmd).splitlines() return out @@ -582,7 +580,7 @@ def name(device, partition, name): if letter not in valid: raise CommandExecutionError("Invalid characters passed to partition.name") - cmd = '''parted -m -s {} name {} "'{}'"'''.format(device, partition, name) + cmd = f'''parted -m -s {device} name {partition} "'{name}'"''' out = __salt__["cmd.run"](cmd).splitlines() return out @@ -603,7 +601,7 @@ def rescue(device, start, end): _validate_partition_boundary(start) _validate_partition_boundary(end) - cmd = "parted -m -s {} rescue {} {}".format(device, start, end) + cmd = f"parted -m -s {device} rescue {start} {end}" out = __salt__["cmd.run"](cmd).splitlines() return out @@ -633,9 +631,7 @@ def resize(device, minor, start, end): _validate_partition_boundary(start) _validate_partition_boundary(end) - out = __salt__["cmd.run"]( - "parted -m -s -- {} resize {} {} {}".format(device, minor, start, end) - ) + out = __salt__["cmd.run"](f"parted -m -s -- {device} resize {minor} {start} {end}") return out.splitlines() @@ -656,7 +652,7 @@ def rm(device, minor): # pylint: disable=C0103 except Exception: # pylint: disable=broad-except raise CommandExecutionError("Invalid minor number passed to partition.rm") - cmd = "parted -m -s {} rm {}".format(device, minor) + cmd = f"parted -m -s {device} rm {minor}" out = __salt__["cmd.run"](cmd).splitlines() return out @@ -709,7 +705,7 @@ def set_(device, minor, flag, state): if state not in {"on", "off"}: raise CommandExecutionError("Invalid state passed to partition.set") - cmd = "parted -m -s {} set {} {} {}".format(device, minor, flag, state) + cmd = f"parted -m -s {device} set {minor} {flag} {state}" out = __salt__["cmd.run"](cmd).splitlines() return out @@ -737,7 +733,7 @@ def toggle(device, partition, flag): if flag not in VALID_PARTITION_FLAGS: raise CommandExecutionError("Invalid flag passed to partition.toggle") - cmd = "parted -m -s {} toggle {} {}".format(device, partition, flag) + cmd = f"parted -m -s {device} toggle {partition} {flag}" out = __salt__["cmd.run"](cmd).splitlines() return out diff --git a/salt/modules/pcs.py b/salt/modules/pcs.py index 4e3c74158a3..78415307dda 100644 --- a/salt/modules/pcs.py +++ b/salt/modules/pcs.py @@ -10,7 +10,6 @@ Pacemaker/Cororsync conifguration system (PCS) .. versionadded:: 2016.3.0 """ - import logging import salt.utils.path @@ -160,7 +159,7 @@ def item_create( if isinstance(extra_args, (list, tuple)): # constraint command needs item_id in format 'id=", "").split(";") - out = __salt__["cmd.run"]( - "networksetup -getproxybypassdomains {}".format(network_service) - ) + out = __salt__["cmd.run"](f"networksetup -getproxybypassdomains {network_service}") return out.split("\n") diff --git a/salt/modules/ps.py b/salt/modules/ps.py index d79d8c932c1..b2eccab73d2 100644 --- a/salt/modules/ps.py +++ b/salt/modules/ps.py @@ -6,7 +6,6 @@ See http://code.google.com/p/psutil. - python-utmp package (optional) """ - import datetime import re import time diff --git a/salt/modules/publish.py b/salt/modules/publish.py index cc424cc3835..c3aa8757b2f 100644 --- a/salt/modules/publish.py +++ b/salt/modules/publish.py @@ -94,7 +94,7 @@ def _publish( matching_master_uris = [ master for master in __opts__["master_uri_list"] - if "//{}:".format(via_master) in master + if f"//{via_master}:" in master ] if not matching_master_uris: @@ -144,7 +144,7 @@ def _publish( try: peer_data = channel.send(load) except SaltReqTimeoutError: - return "'{}' publish timed out".format(fun) + return f"'{fun}' publish timed out" if not peer_data: return {} # CLI args are passed as strings, re-cast to keep time.sleep happy @@ -348,4 +348,4 @@ def runner(fun, arg=None, timeout=5): try: return channel.send(load) except SaltReqTimeoutError: - return "'{}' runner publish timed out".format(fun) + return f"'{fun}' runner publish timed out" diff --git a/salt/modules/puppet.py b/salt/modules/puppet.py index b97eaa3ff60..82df2986f2c 100644 --- a/salt/modules/puppet.py +++ b/salt/modules/puppet.py @@ -2,7 +2,6 @@ Execute puppet routines """ - import datetime import logging import os @@ -85,15 +84,15 @@ class _Puppet: ) args = " ".join(self.subcmd_args) - args += "".join([" --{}".format(k) for k in self.args]) # single spaces - args += "".join([" --{} {}".format(k, v) for k, v in self.kwargs.items()]) + args += "".join([f" --{k}" for k in self.args]) # single spaces + args += "".join([f" --{k} {v}" for k, v in self.kwargs.items()]) # Ensure that the puppet call will return 0 in case of exit code 2 if salt.utils.platform.is_windows(): return "cmd /V:ON /c {} {} ^& if !ERRORLEVEL! EQU 2 (EXIT 0) ELSE (EXIT /B)".format( cmd, args ) - return "({} {}) || test $? -eq 2".format(cmd, args) + return f"({cmd} {args}) || test $? -eq 2" def arguments(self, args=None): """ @@ -194,7 +193,7 @@ def enable(): try: os.remove(puppet.disabled_lockfile) except OSError as exc: - msg = "Failed to enable: {}".format(exc) + msg = f"Failed to enable: {exc}" log.error(msg) raise CommandExecutionError(msg) else: @@ -230,7 +229,7 @@ def disable(message=None): try: # Puppet chokes when no valid json is found msg = ( - '{{"disabled_message":"{0}"}}'.format(message) + f'{{"disabled_message":"{message}"}}' if message is not None else "{}" ) @@ -238,7 +237,7 @@ def disable(message=None): lockfile.close() return True except OSError as exc: - msg = "Failed to disable: {}".format(exc) + msg = f"Failed to disable: {exc}" log.error(msg) raise CommandExecutionError(msg) @@ -320,11 +319,9 @@ def summary(): result["resources"] = report["resources"] except salt.utils.yaml.YAMLError as exc: - raise CommandExecutionError( - "YAML error parsing puppet run summary: {}".format(exc) - ) + raise CommandExecutionError(f"YAML error parsing puppet run summary: {exc}") except OSError as exc: - raise CommandExecutionError("Unable to read puppet run summary: {}".format(exc)) + raise CommandExecutionError(f"Unable to read puppet run summary: {exc}") return result @@ -358,7 +355,7 @@ def facts(puppet=False): """ ret = {} opt_puppet = "--puppet" if puppet else "" - cmd_ret = __salt__["cmd.run_all"]("facter {}".format(opt_puppet)) + cmd_ret = __salt__["cmd.run_all"](f"facter {opt_puppet}") if cmd_ret["retcode"] != 0: raise CommandExecutionError(cmd_ret["stderr"]) @@ -389,9 +386,7 @@ def fact(name, puppet=False): salt '*' puppet.fact kernel """ opt_puppet = "--puppet" if puppet else "" - ret = __salt__["cmd.run_all"]( - "facter {} {}".format(opt_puppet, name), python_shell=False - ) + ret = __salt__["cmd.run_all"](f"facter {opt_puppet} {name}", python_shell=False) if ret["retcode"] != 0: raise CommandExecutionError(ret["stderr"]) diff --git a/salt/modules/purefb.py b/salt/modules/purefb.py index 787c77446b8..cf9cdb4e2e0 100644 --- a/salt/modules/purefb.py +++ b/salt/modules/purefb.py @@ -150,7 +150,7 @@ def _get_snapshot(name, suffix, blade): or None """ try: - filt = "source='{}' and suffix='{}'".format(name, suffix) + filt = f"source='{name}' and suffix='{suffix}'" res = blade.file_system_snapshots.list_file_system_snapshots(filter=filt) return res.items[0] except rest.ApiException: diff --git a/salt/modules/pushbullet.py b/salt/modules/pushbullet.py index b716e667d04..ff58bbda489 100644 --- a/salt/modules/pushbullet.py +++ b/salt/modules/pushbullet.py @@ -21,7 +21,6 @@ For example: """ - import logging try: diff --git a/salt/modules/pushover_notify.py b/salt/modules/pushover_notify.py index a3448b80dcc..ad06f4870cd 100644 --- a/salt/modules/pushover_notify.py +++ b/salt/modules/pushover_notify.py @@ -15,7 +15,6 @@ Module for sending messages to Pushover (https://www.pushover.net) token: abAHuZyCLtdH8P4zhmFZmgUHUsv1ei8 """ - import logging import urllib.parse diff --git a/salt/modules/pw_group.py b/salt/modules/pw_group.py index 99128d196bd..7c6d1fd5292 100644 --- a/salt/modules/pw_group.py +++ b/salt/modules/pw_group.py @@ -64,8 +64,8 @@ def add(name, gid=None, **kwargs): cmd = "pw groupadd " if gid: - cmd += "-g {} ".format(gid) - cmd = "{} -n {}".format(cmd, name) + cmd += f"-g {gid} " + cmd = f"{cmd} -n {name}" ret = __salt__["cmd.run_all"](cmd, python_shell=False) return not ret["retcode"] @@ -81,7 +81,7 @@ def delete(name): salt '*' group.delete foo """ - ret = __salt__["cmd.run_all"]("pw groupdel {}".format(name), python_shell=False) + ret = __salt__["cmd.run_all"](f"pw groupdel {name}", python_shell=False) return not ret["retcode"] @@ -142,7 +142,7 @@ def chgid(name, gid): pre_gid = __salt__["file.group_to_gid"](name) if gid == pre_gid: return True - cmd = "pw groupmod {} -g {}".format(name, gid) + cmd = f"pw groupmod {name} -g {gid}" __salt__["cmd.run"](cmd, python_shell=False) post_gid = __salt__["file.group_to_gid"](name) if post_gid != pre_gid: @@ -165,7 +165,7 @@ def adduser(name, username): """ # Note: pw exits with code 65 if group is unknown retcode = __salt__["cmd.retcode"]( - "pw groupmod {} -m {}".format(name, username), python_shell=False + f"pw groupmod {name} -m {username}", python_shell=False ) return not retcode @@ -191,7 +191,7 @@ def deluser(name, username): # Note: pw exits with code 65 if group is unknown retcode = __salt__["cmd.retcode"]( - "pw groupmod {} -d {}".format(name, username), python_shell=False + f"pw groupmod {name} -d {username}", python_shell=False ) return not retcode @@ -214,7 +214,7 @@ def members(name, members_list): """ retcode = __salt__["cmd.retcode"]( - "pw groupmod {} -M {}".format(name, members_list), python_shell=False + f"pw groupmod {name} -M {members_list}", python_shell=False ) return not retcode diff --git a/salt/modules/pw_user.py b/salt/modules/pw_user.py index 6506452db56..cebb46c993b 100644 --- a/salt/modules/pw_user.py +++ b/salt/modules/pw_user.py @@ -75,7 +75,7 @@ def _get_gecos(name): try: gecos_field = pwd.getpwnam(name).pw_gecos.split(",", 3) except KeyError: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") if not gecos_field: return {} else: @@ -136,7 +136,7 @@ def add( homephone="", createhome=True, loginclass=None, - **kwargs + **kwargs, ): """ Add a user to the minion @@ -238,7 +238,7 @@ def chuid(name, uid): """ pre_info = info(name) if not pre_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") if uid == pre_info["uid"]: return True cmd = ["pw", "usermod", "-u", uid, "-n", name] @@ -258,7 +258,7 @@ def chgid(name, gid): """ pre_info = info(name) if not pre_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") if gid == pre_info["gid"]: return True cmd = ["pw", "usermod", "-g", gid, "-n", name] @@ -278,7 +278,7 @@ def chshell(name, shell): """ pre_info = info(name) if not pre_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") if shell == pre_info["shell"]: return True cmd = ["pw", "usermod", "-s", shell, "-n", name] @@ -309,7 +309,7 @@ def chhome(name, home, persist=False): """ pre_info = info(name) if not pre_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") if home == pre_info["home"]: return True cmd = ["pw", "usermod", name, "-d", home] @@ -419,7 +419,7 @@ def chloginclass(name, loginclass, root=None): if loginclass == get_loginclass(name): return True - cmd = ["pw", "usermod", "-L", "{}".format(loginclass), "-n", "{}".format(name)] + cmd = ["pw", "usermod", "-L", f"{loginclass}", "-n", f"{name}"] __salt__["cmd.run"](cmd, python_shell=False) @@ -518,10 +518,10 @@ def rename(name, new_name): """ current_info = info(name) if not current_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") new_info = info(new_name) if new_info: - raise CommandExecutionError("User '{}' already exists".format(new_name)) + raise CommandExecutionError(f"User '{new_name}' already exists") cmd = ["pw", "usermod", "-l", new_name, "-n", name] __salt__["cmd.run"](cmd) post_info = info(new_name) diff --git a/salt/modules/pyenv.py b/salt/modules/pyenv.py index df39db80333..30d569b5700 100644 --- a/salt/modules/pyenv.py +++ b/salt/modules/pyenv.py @@ -32,14 +32,12 @@ def _pyenv_exec(command, args="", env=None, runas=None, ret=None): path = _pyenv_path(runas) if env: - env = " {}".format(env) + env = f" {env}" env = env or "" - binary = "env PYENV_ROOT={}{} {}".format(path, env, binary) + binary = f"env PYENV_ROOT={path}{env} {binary}" - result = __salt__["cmd.run_all"]( - "{} {} {}".format(binary, command, args), runas=runas - ) + result = __salt__["cmd.run_all"](f"{binary} {command} {args}", runas=runas) if isinstance(ret, dict): ret.update(result) @@ -53,7 +51,7 @@ def _pyenv_exec(command, args="", env=None, runas=None, ret=None): def _pyenv_bin(runas=None): path = _pyenv_path(runas) - return "{}/bin/pyenv".format(path) + return f"{path}/bin/pyenv" def _pyenv_path(runas=None): @@ -61,7 +59,7 @@ def _pyenv_path(runas=None): if runas in (None, "root"): path = __salt__["config.option"]("pyenv.root") or "/usr/local/pyenv" else: - path = __salt__["config.option"]("pyenv.root") or "~{}/.pyenv".format(runas) + path = __salt__["config.option"]("pyenv.root") or f"~{runas}/.pyenv" return os.path.expanduser(path) @@ -71,7 +69,7 @@ def _install_pyenv(path, runas=None): return True return 0 == __salt__["cmd.retcode"]( - "git clone https://github.com/yyuu/pyenv.git {}".format(path), runas=runas + f"git clone https://github.com/yyuu/pyenv.git {path}", runas=runas ) @@ -80,17 +78,17 @@ def _update_pyenv(path, runas=None): return False return 0 == __salt__["cmd.retcode"]( - "cd {} && git pull".format(shlex.quote(path)), runas=runas + f"cd {shlex.quote(path)} && git pull", runas=runas ) def _update_python_build(path, runas=None): - path = "{}/plugins/python-build".format(path) + path = f"{path}/plugins/python-build" if not os.path.isdir(path): return False return 0 == __salt__["cmd.retcode"]( - "cd {} && git pull".format(shlex.quote(path)), runas=runas + f"cd {shlex.quote(path)} && git pull", runas=runas ) @@ -193,7 +191,7 @@ def uninstall_python(python, runas=None): """ python = re.sub(r"^python-", "", python) - args = "--force {}".format(python) + args = f"--force {python}" _pyenv_exec("uninstall", args, runas=runas) return True @@ -287,7 +285,7 @@ def do(cmdline=None, runas=None): for cmd in cmd_split: quoted_line = quoted_line + " " + shlex.quote(cmd) result = __salt__["cmd.run_all"]( - "env PATH={}/shims:$PATH {}".format(shlex.quote(path), quoted_line), + f"env PATH={shlex.quote(path)}/shims:$PATH {quoted_line}", runas=runas, python_shell=True, ) @@ -311,7 +309,7 @@ def do_with_python(python, cmdline, runas=None): salt '*' pyenv.do_with_python 2.0.0-p0 'gem list bundler' deploy """ if python: - cmd = "PYENV_VERSION={} {}".format(python, cmdline) + cmd = f"PYENV_VERSION={python} {cmdline}" else: cmd = cmdline diff --git a/salt/modules/qemu_img.py b/salt/modules/qemu_img.py index 1424929e45a..4f4b0dde628 100644 --- a/salt/modules/qemu_img.py +++ b/salt/modules/qemu_img.py @@ -42,7 +42,7 @@ 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), + f"qemu-img create -f {fmt} {location} {size}M", python_shell=False, ): return location diff --git a/salt/modules/qemu_nbd.py b/salt/modules/qemu_nbd.py index 9a76d68cad5..375cbdeb3ab 100644 --- a/salt/modules/qemu_nbd.py +++ b/salt/modules/qemu_nbd.py @@ -5,7 +5,6 @@ The qemu system comes with powerful tools, such as qemu-img and qemu-nbd which are used here to build up kvm images. """ - import glob import logging import os @@ -52,14 +51,14 @@ def connect(image): fdisk = "fdisk -l" __salt__["cmd.run"]("modprobe nbd max_part=63") for nbd in glob.glob("/dev/nbd?"): - if __salt__["cmd.retcode"]("{} {}".format(fdisk, nbd)): + if __salt__["cmd.retcode"](f"{fdisk} {nbd}"): while True: # Sometimes nbd does not "take hold", loop until we can verify __salt__["cmd.run"]( - "qemu-nbd -c {} {}".format(nbd, image), + f"qemu-nbd -c {nbd} {image}", python_shell=False, ) - if not __salt__["cmd.retcode"]("{} {}".format(fdisk, nbd)): + if not __salt__["cmd.retcode"](f"{fdisk} {nbd}"): break return nbd log.warning("Could not connect image: %s", image) @@ -78,13 +77,13 @@ def mount(nbd, root=None): salt '*' qemu_nbd.mount /dev/nbd0 """ __salt__["cmd.run"]( - "partprobe {}".format(nbd), + f"partprobe {nbd}", python_shell=False, ) ret = {} if root is None: root = os.path.join(tempfile.gettempdir(), "nbd", os.path.basename(nbd)) - for part in glob.glob("{}p*".format(nbd)): + for part in glob.glob(f"{nbd}p*"): m_pt = os.path.join(root, os.path.basename(part)) time.sleep(1) mnt = __salt__["mount.mount"](m_pt, part, True) @@ -133,5 +132,5 @@ def clear(mnt): if ret: return ret for nbd in nbds: - __salt__["cmd.run"]("qemu-nbd -d {}".format(nbd), python_shell=False) + __salt__["cmd.run"](f"qemu-nbd -d {nbd}", python_shell=False) return ret diff --git a/salt/modules/quota.py b/salt/modules/quota.py index 931ae63d0ab..ec9f20ca3fd 100644 --- a/salt/modules/quota.py +++ b/salt/modules/quota.py @@ -48,7 +48,7 @@ def _parse_quota(mount, opts): """ Parse the output from repquota. Requires that -u -g are passed in """ - cmd = "repquota -vp {} {}".format(opts, mount) + cmd = f"repquota -vp {opts} {mount}" out = __salt__["cmd.run"](cmd, python_shell=False).splitlines() mode = "header" @@ -200,7 +200,7 @@ def on(device): salt '*' quota.on """ - cmd = "quotaon {}".format(device) + cmd = f"quotaon {device}" __salt__["cmd.run"](cmd, python_shell=False) return True @@ -215,7 +215,7 @@ def off(device): salt '*' quota.off """ - cmd = "quotaoff {}".format(device) + cmd = f"quotaoff {device}" __salt__["cmd.run"](cmd, python_shell=False) return True @@ -231,7 +231,7 @@ def get_mode(device): salt '*' quota.get_mode """ ret = {} - cmd = "quotaon -p {}".format(device) + cmd = f"quotaon -p {device}" out = __salt__["cmd.run"](cmd, python_shell=False) for line in out.splitlines(): comps = line.strip().split() diff --git a/salt/modules/rabbitmq.py b/salt/modules/rabbitmq.py index e0a9304bd54..5ad42678489 100644 --- a/salt/modules/rabbitmq.py +++ b/salt/modules/rabbitmq.py @@ -44,11 +44,9 @@ def __virtual__(): ) (dir_path, value_type) = winreg.QueryValueEx(key, "Install_Dir") if value_type != winreg.REG_SZ: - raise TypeError( - "Invalid RabbitMQ Server directory type: {}".format(value_type) - ) + raise TypeError(f"Invalid RabbitMQ Server directory type: {value_type}") if not os.path.isdir(dir_path): - raise OSError("RabbitMQ directory not found: {}".format(dir_path)) + raise OSError(f"RabbitMQ directory not found: {dir_path}") subdir_match = "" for name in os.listdir(dir_path): if name.startswith("rabbitmq_server-"): @@ -58,7 +56,7 @@ def __virtual__(): subdir_match = subdir_path if not subdir_match: raise OSError( - '"rabbitmq_server-*" subdirectory not found in: {}'.format(dir_path) + f'"rabbitmq_server-*" subdirectory not found in: {dir_path}' ) RABBITMQCTL = os.path.join(subdir_match, "sbin", "rabbitmqctl.bat") RABBITMQ_PLUGINS = os.path.join( @@ -86,7 +84,7 @@ def _check_response(response): ) else: if "Error" in response: - raise CommandExecutionError("RabbitMQ command failed: {}".format(response)) + raise CommandExecutionError(f"RabbitMQ command failed: {response}") def _format_response(response, msg): @@ -99,7 +97,7 @@ def _format_response(response, msg): response = response["stdout"] else: if "Error" in response: - raise CommandExecutionError("RabbitMQ command failed: {}".format(response)) + raise CommandExecutionError(f"RabbitMQ command failed: {response}") return {msg: response} @@ -237,8 +235,8 @@ def list_users(runas=None): ) # func to get tags from string such as "[admin, monitoring]" - func = ( - lambda string: [x.strip() for x in string[1:-1].split(",")] + func = lambda string: ( + [x.strip() for x in string[1:-1].split(",")] if "," in string else [x for x in string[1:-1].split(" ")] ) @@ -378,7 +376,7 @@ def add_user(name, password=None, runas=None): # command,\r\noperable program or batch file. # Work around this by using a shell and a quoted command. python_shell = True - cmd = '"{}" add_user "{}" "{}"'.format(RABBITMQCTL, name, password) + cmd = f'"{RABBITMQCTL}" add_user "{name}" "{password}"' else: python_shell = False cmd = [RABBITMQCTL, "add_user", name, password] @@ -448,7 +446,7 @@ def change_password(name, password, runas=None): # command,\r\noperable program or batch file. # Work around this by using a shell and a quoted command. python_shell = True - cmd = '"{}" change_password "{}" "{}"'.format(RABBITMQCTL, name, password) + cmd = f'"{RABBITMQCTL}" change_password "{name}" "{password}"' else: python_shell = False cmd = [RABBITMQCTL, "change_password", name, password] @@ -539,7 +537,7 @@ def check_password(name, password, runas=None): # command,\r\noperable program or batch file. # Work around this by using a shell and a quoted command. python_shell = True - cmd = '"{}" authenticate_user "{}" "{}"'.format(RABBITMQCTL, name, password) + cmd = f'"{RABBITMQCTL}" authenticate_user "{name}" "{password}"' else: python_shell = False cmd = [RABBITMQCTL, "authenticate_user", name, password] @@ -786,7 +784,7 @@ def join_cluster(host, user="rabbit", ram_node=None, runas=None): cmd = [RABBITMQCTL, "join_cluster"] if ram_node: cmd.append("--ram") - cmd.append("{}@{}".format(user, host)) + cmd.append(f"{user}@{host}") if runas is None and not salt.utils.platform.is_windows(): runas = salt.utils.user.get_user() diff --git a/salt/modules/rallydev.py b/salt/modules/rallydev.py index 6461fb133f5..dc92ae93185 100644 --- a/salt/modules/rallydev.py +++ b/salt/modules/rallydev.py @@ -12,7 +12,6 @@ Requires a ``username`` and a ``password`` in ``/etc/salt/minion``: password: 123pass """ - import logging import salt.utils.http @@ -81,7 +80,7 @@ def _query( path += action if command: - path += "/{}".format(command) + path += f"/{command}" log.debug("RallyDev URL: %s", path) diff --git a/salt/modules/random_org.py b/salt/modules/random_org.py index 494c323eba5..91db8756a41 100644 --- a/salt/modules/random_org.py +++ b/salt/modules/random_org.py @@ -15,6 +15,7 @@ Module for retrieving random information from Random.org api_key: 7be1402d-5719-5bd3-a306-3def9f135da5 api_version: 1 """ + import http.client import logging import urllib.request @@ -205,7 +206,7 @@ def generateIntegers(api_key=None, api_version=None, **kwargs): for item in ["number", "minimum", "maximum"]: if item not in kwargs: ret["res"] = False - ret["message"] = "Rquired argument, {} is missing.".format(item) + ret["message"] = f"Rquired argument, {item} is missing." return ret if not _numeric(kwargs["number"]) or not 1 <= kwargs["number"] <= 10000: @@ -218,9 +219,9 @@ def generateIntegers(api_key=None, api_version=None, **kwargs): or not -1000000000 <= kwargs["minimum"] <= 1000000000 ): ret["res"] = False - ret[ - "message" - ] = "Minimum argument must be between -1,000,000,000 and 1,000,000,000" + ret["message"] = ( + "Minimum argument must be between -1,000,000,000 and 1,000,000,000" + ) return ret if ( @@ -228,9 +229,9 @@ def generateIntegers(api_key=None, api_version=None, **kwargs): or not -1000000000 <= kwargs["maximum"] <= 1000000000 ): ret["res"] = False - ret[ - "message" - ] = "Maximum argument must be between -1,000,000,000 and 1,000,000,000" + ret["message"] = ( + "Maximum argument must be between -1,000,000,000 and 1,000,000,000" + ) return ret if "base" in kwargs: @@ -331,7 +332,7 @@ def generateStrings(api_key=None, api_version=None, **kwargs): for item in ["number", "length", "characters"]: if item not in kwargs: ret["res"] = False - ret["message"] = "Required argument, {} is missing.".format(item) + ret["message"] = f"Required argument, {item} is missing." return ret if not _numeric(kwargs["number"]) or not 1 <= kwargs["number"] <= 10000: @@ -421,7 +422,7 @@ def generateUUIDs(api_key=None, api_version=None, **kwargs): for item in ["number"]: if item not in kwargs: ret["res"] = False - ret["message"] = "Required argument, {} is missing.".format(item) + ret["message"] = f"Required argument, {item} is missing." return ret if isinstance(api_version, int): @@ -502,7 +503,7 @@ def generateDecimalFractions(api_key=None, api_version=None, **kwargs): for item in ["number", "decimalPlaces"]: if item not in kwargs: ret["res"] = False - ret["message"] = "Required argument, {} is missing.".format(item) + ret["message"] = f"Required argument, {item} is missing." return ret if not isinstance(kwargs["number"], int) or not 1 <= kwargs["number"] <= 10000: @@ -596,7 +597,7 @@ def generateGaussians(api_key=None, api_version=None, **kwargs): for item in ["number", "mean", "standardDeviation", "significantDigits"]: if item not in kwargs: ret["res"] = False - ret["message"] = "Required argument, {} is missing.".format(item) + ret["message"] = f"Required argument, {item} is missing." return ret if not _numeric(kwargs["number"]) or not 1 <= kwargs["number"] <= 10000: @@ -614,9 +615,9 @@ def generateGaussians(api_key=None, api_version=None, **kwargs): or not -1000000 <= kwargs["standardDeviation"] <= 1000000 ): ret["res"] = False - ret[ - "message" - ] = "The distribution's standard deviation must be between -1000000 and 1000000" + ret["message"] = ( + "The distribution's standard deviation must be between -1000000 and 1000000" + ) return ret if ( @@ -696,7 +697,7 @@ def generateBlobs(api_key=None, api_version=None, **kwargs): for item in ["number", "size"]: if item not in kwargs: ret["res"] = False - ret["message"] = "Required argument, {} is missing.".format(item) + ret["message"] = f"Required argument, {item} is missing." return ret if not _numeric(kwargs["number"]) or not 1 <= kwargs["number"] <= 100: diff --git a/salt/modules/rbenv.py b/salt/modules/rbenv.py index e0bc1e82503..1f3ee003818 100644 --- a/salt/modules/rbenv.py +++ b/salt/modules/rbenv.py @@ -9,7 +9,6 @@ http://misheska.com/blog/2013/06/15/using-rbenv-to-manage-multiple-versions-of-r .. versionadded:: 0.16.0 """ - import logging import os import re @@ -76,7 +75,7 @@ def _parse_env(env): def _rbenv_bin(runas=None): path = _rbenv_path(runas) - return "{}/bin/rbenv".format(path) + return f"{path}/bin/rbenv" def _rbenv_path(runas=None): @@ -84,7 +83,7 @@ def _rbenv_path(runas=None): if runas in (None, "root"): path = __salt__["config.option"]("rbenv.root") or "/usr/local/rbenv" else: - path = __salt__["config.option"]("rbenv.root") or "~{}/.rbenv".format(runas) + path = __salt__["config.option"]("rbenv.root") or f"~{runas}/.rbenv" return os.path.expanduser(path) @@ -120,7 +119,7 @@ def _install_rbenv(path, runas=None): def _install_ruby_build(path, runas=None): - path = "{}/plugins/ruby-build".format(path) + path = f"{path}/plugins/ruby-build" if os.path.isdir(path): return True @@ -141,7 +140,7 @@ def _update_rbenv(path, runas=None): def _update_ruby_build(path, runas=None): - path = "{}/plugins/ruby-build".format(path) + path = f"{path}/plugins/ruby-build" if not os.path.isdir(path): return False diff --git a/salt/modules/rdp.py b/salt/modules/rdp.py index e0c4a5d21a5..81dc1c77c6a 100644 --- a/salt/modules/rdp.py +++ b/salt/modules/rdp.py @@ -50,9 +50,7 @@ def _psrdp(cmd): "-Namespace root\\CIMV2\\TerminalServices -Computer . " "-Authentication 6 -ErrorAction Stop" ) - return __salt__["cmd.run"]( - "{} ; {}".format(rdp, cmd), shell="powershell", python_shell=True - ) + return __salt__["cmd.run"](f"{rdp} ; {cmd}", shell="powershell", python_shell=True) def enable(): diff --git a/salt/modules/reg.py b/salt/modules/reg.py index 229998e27a9..5afaad95716 100644 --- a/salt/modules/reg.py +++ b/salt/modules/reg.py @@ -64,6 +64,7 @@ Value: :depends: - salt.utils.win_reg """ + # When production windows installer is using Python 3, Python 2 code can be removed import logging @@ -558,13 +559,13 @@ def import_file(source, use_32bit_registry=False): """ cache_path = __salt__["cp.cache_file"](source) if not cache_path: - error_msg = "File/URL '{}' probably invalid.".format(source) + error_msg = f"File/URL '{source}' probably invalid." raise ValueError(error_msg) if use_32bit_registry: word_sz_txt = "32" else: word_sz_txt = "64" - cmd = 'reg import "{}" /reg:{}'.format(cache_path, word_sz_txt) + cmd = f'reg import "{cache_path}" /reg:{word_sz_txt}' cmd_ret_dict = __salt__["cmd.run_all"](cmd, python_shell=True) retcode = cmd_ret_dict["retcode"] if retcode != 0: diff --git a/salt/modules/restartcheck.py b/salt/modules/restartcheck.py index 287b9bd3b38..9f355df48cd 100644 --- a/salt/modules/restartcheck.py +++ b/salt/modules/restartcheck.py @@ -9,6 +9,7 @@ https://packages.debian.org/debian-goodies) and psdel by Sam Morris. :codeauthor: Jiri Kotlin """ + import os import re import subprocess @@ -329,7 +330,7 @@ def _kernel_versions_nilrt(): Get kernel version from a binary image or None if detection fails """ kvregex = r"[0-9]+\.[0-9]+\.[0-9]+-rt\S+" - kernel_strings = __salt__["cmd.run"]("strings {}".format(kbin)) + kernel_strings = __salt__["cmd.run"](f"strings {kbin}") re_result = re.search(kvregex, kernel_strings) return None if re_result is None else re_result.group(0) @@ -346,7 +347,7 @@ def _kernel_versions_nilrt(): itb_path, compressed_kernel ) ) - __salt__["cmd.run"]("gunzip -f {}".format(compressed_kernel)) + __salt__["cmd.run"](f"gunzip -f {compressed_kernel}") kver = _get_kver_from_bin(uncompressed_kernel) else: # the kernel bzImage is copied to rootfs without package management or @@ -387,8 +388,8 @@ def _file_changed_nilrt(full_filepath): """ rs_state_dir = "/var/lib/salt/restartcheck_state" base_filename = os.path.basename(full_filepath) - timestamp_file = os.path.join(rs_state_dir, "{}.timestamp".format(base_filename)) - md5sum_file = os.path.join(rs_state_dir, "{}.md5sum".format(base_filename)) + timestamp_file = os.path.join(rs_state_dir, f"{base_filename}.timestamp") + md5sum_file = os.path.join(rs_state_dir, f"{base_filename}.md5sum") if not os.path.exists(timestamp_file) or not os.path.exists(md5sum_file): return True @@ -401,9 +402,7 @@ def _file_changed_nilrt(full_filepath): return True return bool( - __salt__["cmd.retcode"]( - "md5sum -cs {}".format(md5sum_file), output_loglevel="quiet" - ) + __salt__["cmd.retcode"](f"md5sum -cs {md5sum_file}", output_loglevel="quiet") ) @@ -418,7 +417,7 @@ def _kernel_modules_changed_nilrt(kernelversion): - True if modules.dep was modified/touched, False otherwise. """ if kernelversion is not None: - return _file_changed_nilrt("/lib/modules/{}/modules.dep".format(kernelversion)) + return _file_changed_nilrt(f"/lib/modules/{kernelversion}/modules.dep") return False @@ -446,7 +445,7 @@ def _sysapi_changed_nilrt(): ) if os.path.exists(nisysapi_conf_d_path): - rs_count_file = "{}/sysapi.conf.d.count".format(restartcheck_state_dir) + rs_count_file = f"{restartcheck_state_dir}/sysapi.conf.d.count" if not os.path.exists(rs_count_file): return True @@ -457,7 +456,7 @@ def _sysapi_changed_nilrt(): return True for fexpert in os.listdir(nisysapi_conf_d_path): - if _file_changed_nilrt("{}/{}".format(nisysapi_conf_d_path, fexpert)): + if _file_changed_nilrt(f"{nisysapi_conf_d_path}/{fexpert}"): return True return False @@ -578,7 +577,7 @@ def restartcheck(ignorelist=None, blacklist=None, excludepid=None, **kwargs): if path in blacklist or pid in excludepid: continue try: - readlink = os.readlink("/proc/{}/exe".format(pid)) + readlink = os.readlink(f"/proc/{pid}/exe") except OSError: excludepid.append(pid) continue diff --git a/salt/modules/restconf.py b/salt/modules/restconf.py index 3007adc225d..b99187c87f3 100644 --- a/salt/modules/restconf.py +++ b/salt/modules/restconf.py @@ -7,7 +7,6 @@ Execution module for RESTCONF Proxy minions """ - import logging __proxyenabled__ = ["restconf"] @@ -18,7 +17,7 @@ log = logging.getLogger(__file__) def __virtual__(): if __opts__.get("proxy", {}).get("proxytype") != __virtualname__: - return False, "Proxytype does not match: {}".format(__virtualname__) + return False, f"Proxytype does not match: {__virtualname__}" return True diff --git a/salt/modules/ret.py b/salt/modules/ret.py index 9210eb4d7ed..1885b92a8b5 100644 --- a/salt/modules/ret.py +++ b/salt/modules/ret.py @@ -16,7 +16,7 @@ def get_jid(returner, jid): salt '*' ret.get_jid redis 20421104181954700505 """ returners = salt.loader.returners(__opts__, __salt__) - return returners["{}.get_jid".format(returner)](jid) + return returners[f"{returner}.get_jid"](jid) def get_fun(returner, fun): @@ -30,7 +30,7 @@ def get_fun(returner, fun): salt '*' ret.get_fun mysql network.interfaces """ returners = salt.loader.returners(__opts__, __salt__) - return returners["{}.get_fun".format(returner)](fun) + return returners[f"{returner}.get_fun"](fun) def get_jids(returner): @@ -44,7 +44,7 @@ def get_jids(returner): salt '*' ret.get_jids mysql """ returners = salt.loader.returners(__opts__, __salt__) - return returners["{}.get_jids".format(returner)]() + return returners[f"{returner}.get_jids"]() def get_minions(returner): @@ -58,4 +58,4 @@ def get_minions(returner): salt '*' ret.get_minions mysql """ returners = salt.loader.returners(__opts__, __salt__) - return returners["{}.get_minions".format(returner)]() + return returners[f"{returner}.get_minions"]() diff --git a/salt/modules/rh_ip.py b/salt/modules/rh_ip.py index e476bbd3f6e..f1d823b1a82 100644 --- a/salt/modules/rh_ip.py +++ b/salt/modules/rh_ip.py @@ -202,7 +202,7 @@ def _parse_ethtool_opts(opts, iface): _raise_error_iface(iface, "advertise", valid) if "channels" in opts: - channels_cmd = "-L {}".format(iface.strip()) + channels_cmd = f"-L {iface.strip()}" channels_params = [] for option in ("rx", "tx", "other", "combined"): if option in opts["channels"]: @@ -372,7 +372,6 @@ def _parse_settings_bond_0(opts, iface): def _parse_settings_bond_1(opts, iface): - """ Filters given options and outputs valid settings for bond1. If an option has a value that is not expected, this @@ -418,7 +417,6 @@ def _parse_settings_bond_2(opts, iface): def _parse_settings_bond_3(opts, iface): - """ Filters given options and outputs valid settings for bond3. If an option has a value that is not expected, this @@ -491,7 +489,6 @@ def _parse_settings_bond_4(opts, iface): def _parse_settings_bond_5(opts, iface): - """ Filters given options and outputs valid settings for bond5. If an option has a value that is not expected, this @@ -511,7 +508,6 @@ def _parse_settings_bond_5(opts, iface): def _parse_settings_bond_6(opts, iface): - """ Filters given options and outputs valid settings for bond6. If an option has a value that is not expected, this @@ -531,7 +527,6 @@ def _parse_settings_bond_6(opts, iface): def _parse_settings_vlan(opts, iface): - """ Filters given options and outputs valid settings for a vlan """ @@ -589,9 +584,7 @@ def _parse_settings_eth(opts, iface_type, enabled, iface): if iface_type not in ("bridge",): ethtool = _parse_ethtool_opts(opts, iface) if ethtool: - result["ethtool"] = " ".join( - ["{} {}".format(x, y) for x, y in ethtool.items()] - ) + result["ethtool"] = " ".join([f"{x} {y}" for x, y in ethtool.items()]) if iface_type == "slave": result["proto"] = "none" @@ -614,9 +607,7 @@ def _parse_settings_eth(opts, iface_type, enabled, iface): raise AttributeError(msg) bonding = _parse_settings_bond(opts, iface) if bonding: - result["bonding"] = " ".join( - ["{}={}".format(x, y) for x, y in bonding.items()] - ) + result["bonding"] = " ".join([f"{x}={y}" for x, y in bonding.items()]) result["devtype"] = "Bond" if iface_type == "vlan": @@ -1081,7 +1072,7 @@ def build_interface(iface, iface_type, enabled, **settings): ): opts = _parse_settings_eth(settings, iface_type, enabled, iface) try: - template = JINJA.get_template("rh{}_eth.jinja".format(rh_major)) + template = JINJA.get_template(f"rh{rh_major}_eth.jinja") except jinja2.exceptions.TemplateNotFound: log.error("Could not load template rh%s_eth.jinja", rh_major) return "" @@ -1091,7 +1082,7 @@ def build_interface(iface, iface_type, enabled, **settings): return _read_temp(ifcfg) _write_file_iface(iface, ifcfg, _RH_NETWORK_SCRIPT_DIR, "ifcfg-{0}") - path = os.path.join(_RH_NETWORK_SCRIPT_DIR, "ifcfg-{}".format(iface)) + path = os.path.join(_RH_NETWORK_SCRIPT_DIR, f"ifcfg-{iface}") return _read_file(path) @@ -1144,8 +1135,8 @@ def build_routes(iface, **settings): _write_file_iface(iface, routecfg, _RH_NETWORK_SCRIPT_DIR, "route-{0}") _write_file_iface(iface, routecfg6, _RH_NETWORK_SCRIPT_DIR, "route6-{0}") - path = os.path.join(_RH_NETWORK_SCRIPT_DIR, "route-{}".format(iface)) - path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, "route6-{}".format(iface)) + path = os.path.join(_RH_NETWORK_SCRIPT_DIR, f"route-{iface}") + path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, f"route6-{iface}") routes = _read_file(path) routes.extend(_read_file(path6)) @@ -1164,7 +1155,7 @@ def down(iface, iface_type): """ # Slave devices are controlled by the master. if iface_type.lower() not in ("slave", "teamport"): - return __salt__["cmd.run"]("ifdown {}".format(iface)) + return __salt__["cmd.run"](f"ifdown {iface}") return None @@ -1178,7 +1169,7 @@ def get_interface(iface): salt '*' ip.get_interface eth0 """ - path = os.path.join(_RH_NETWORK_SCRIPT_DIR, "ifcfg-{}".format(iface)) + path = os.path.join(_RH_NETWORK_SCRIPT_DIR, f"ifcfg-{iface}") return _read_file(path) @@ -1194,7 +1185,7 @@ def up(iface, iface_type): # pylint: disable=C0103 """ # Slave devices are controlled by the master. if iface_type.lower() not in ("slave", "teamport"): - return __salt__["cmd.run"]("ifup {}".format(iface)) + return __salt__["cmd.run"](f"ifup {iface}") return None @@ -1208,8 +1199,8 @@ def get_routes(iface): salt '*' ip.get_routes eth0 """ - path = os.path.join(_RH_NETWORK_SCRIPT_DIR, "route-{}".format(iface)) - path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, "route6-{}".format(iface)) + path = os.path.join(_RH_NETWORK_SCRIPT_DIR, f"route-{iface}") + path6 = os.path.join(_RH_NETWORK_SCRIPT_DIR, f"route6-{iface}") routes = _read_file(path) routes.extend(_read_file(path6)) return routes diff --git a/salt/modules/riak.py b/salt/modules/riak.py index 197d8689971..f8d893a8451 100644 --- a/salt/modules/riak.py +++ b/salt/modules/riak.py @@ -21,7 +21,7 @@ def __execute_cmd(name, cmd): """ Execute Riak commands """ - return __salt__["cmd.run_all"]("{} {}".format(salt.utils.path.which(name), cmd)) + return __salt__["cmd.run_all"](f"{salt.utils.path.which(name)} {cmd}") def start(): @@ -89,7 +89,7 @@ def cluster_join(username, hostname): """ ret = {"comment": "", "success": False} - cmd = __execute_cmd("riak-admin", "cluster join {}@{}".format(username, hostname)) + cmd = __execute_cmd("riak-admin", f"cluster join {username}@{hostname}") if cmd["retcode"] != 0: ret["comment"] = cmd["stdout"] @@ -117,7 +117,7 @@ def cluster_leave(username, hostname): """ ret = {"comment": "", "success": False} - cmd = __execute_cmd("riak-admin", "cluster leave {}@{}".format(username, hostname)) + cmd = __execute_cmd("riak-admin", f"cluster leave {username}@{hostname}") if cmd["retcode"] != 0: ret["comment"] = cmd["stdout"] diff --git a/salt/modules/rpm_lowpkg.py b/salt/modules/rpm_lowpkg.py index 4cd137c258f..59bf0fa9fb4 100644 --- a/salt/modules/rpm_lowpkg.py +++ b/salt/modules/rpm_lowpkg.py @@ -110,14 +110,14 @@ def bin_pkg_info(path, saltenv="base"): newpath = __salt__["cp.cache_file"](path, saltenv) if not newpath: raise CommandExecutionError( - "Unable to retrieve {} from saltenv '{}'".format(path, saltenv) + f"Unable to retrieve {path} from saltenv '{saltenv}'" ) path = newpath else: if not os.path.exists(path): - raise CommandExecutionError("{} does not exist on minion".format(path)) + raise CommandExecutionError(f"{path} does not exist on minion") elif not os.path.isabs(path): - raise SaltInvocationError("{} does not exist on minion".format(path)) + raise SaltInvocationError(f"{path} does not exist on minion") # REPOID is not a valid tag for the rpm command. Remove it and replace it # with 'none' @@ -495,7 +495,7 @@ def diff(package_path, path): ) res = __salt__["cmd.shell"](cmd.format(package_path, path), output_loglevel="trace") if res and res.startswith("Binary file"): - return "File '{}' is binary and its content has been modified.".format(path) + return f"File '{path}' is binary and its content has been modified." return res @@ -762,7 +762,7 @@ def version_cmp(ver1, ver2, ignore_epoch=False): # rpmdev-vercmp always uses epochs, even when zero def _ensure_epoch(ver): def _prepend(ver): - return "0:{}".format(ver) + return f"0:{ver}" try: if ":" not in ver: @@ -818,7 +818,7 @@ def version_cmp(ver1, ver2, ignore_epoch=False): ) if cmp_result not in (-1, 0, 1): raise CommandExecutionError( - "Comparison result '{}' is invalid".format(cmp_result) + f"Comparison result '{cmp_result}' is invalid" ) return cmp_result diff --git a/salt/modules/rpmbuild_pkgbuild.py b/salt/modules/rpmbuild_pkgbuild.py index 1532817222f..135afab975c 100644 --- a/salt/modules/rpmbuild_pkgbuild.py +++ b/salt/modules/rpmbuild_pkgbuild.py @@ -9,7 +9,6 @@ environments. This also provides a function to generate yum repositories This module implements the pkgbuild interface """ - import errno import functools import logging @@ -83,7 +82,7 @@ def _create_rpmmacros(runas="root"): rpmmacros = os.path.join(home, ".rpmmacros") with salt.utils.files.fopen(rpmmacros, "w") as afile: - afile.write(salt.utils.stringutils.to_str("%_topdir {}\n".format(rpmbuilddir))) + afile.write(salt.utils.stringutils.to_str(f"%_topdir {rpmbuilddir}\n")) afile.write("%signature gpg\n") afile.write("%_source_filedigest_algorithm 8\n") afile.write("%_binary_filedigest_algorithm 8\n") @@ -133,9 +132,9 @@ def _get_distset(tgt): # consistent naming on Centos and Redhat, and allow for Amazon naming tgtattrs = tgt.split("-") if tgtattrs[0] == "amzn2": - distset = '--define "dist .{}"'.format(tgtattrs[0]) + distset = f'--define "dist .{tgtattrs[0]}"' elif tgtattrs[1] in ["6", "7", "8"]: - distset = '--define "dist .el{}"'.format(tgtattrs[1]) + distset = f'--define "dist .el{tgtattrs[1]}"' else: distset = "" @@ -162,7 +161,7 @@ def _get_deps(deps, tree_base, saltenv="base"): else: shutil.copy(deprpm, dest) - deps_list += " {}".format(dest) + deps_list += f" {dest}" return deps_list @@ -175,9 +174,7 @@ def _check_repo_gpg_phrase_utils(): if __salt__["file.file_exists"](util_name): return True else: - raise CommandExecutionError( - "utility '{}' needs to be installed".format(util_name) - ) + raise CommandExecutionError(f"utility '{util_name}' needs to be installed") def _get_gpg_key_resources(keyid, env, use_passphrase, gnupghome, runas): @@ -326,7 +323,7 @@ def _get_gpg_key_resources(keyid, env, use_passphrase, gnupghome, runas): ) # need to update rpm with public key - cmd = "rpm --import {}".format(pkg_pub_key_file) + cmd = f"rpm --import {pkg_pub_key_file}" retrc = __salt__["cmd.retcode"](cmd, runas=runas, use_vt=True) if retrc != 0: raise SaltInvocationError( @@ -349,9 +346,9 @@ def _sign_file(runas, define_gpg_name, phrase, abs_file, timeout): interval = 0.5 number_retries = timeout / interval times_looped = 0 - error_msg = "Failed to sign file {}".format(abs_file) + error_msg = f"Failed to sign file {abs_file}" - cmd = "rpm {} --addsign {}".format(define_gpg_name, abs_file) + cmd = f"rpm {define_gpg_name} --addsign {abs_file}" preexec_fn = functools.partial(salt.utils.user.chugid_and_umask, runas, None) try: stdout, stderr = None, None @@ -396,7 +393,7 @@ def _sign_files_with_gpg_agent(runas, local_keyid, abs_file, repodir, env, timeo """ Sign file with provided key utilizing gpg-agent """ - cmd = "rpmsign --verbose --key-id={} --addsign {}".format(local_keyid, abs_file) + cmd = f"rpmsign --verbose --key-id={local_keyid} --addsign {abs_file}" retrc = __salt__["cmd.retcode"](cmd, runas=runas, cwd=repodir, use_vt=True, env=env) if retrc != 0: raise SaltInvocationError( @@ -548,7 +545,7 @@ def build( try: __salt__["file.chown"](path=dbase, user=runas, group="mock") __salt__["file.chown"](path=results_dir, user=runas, group="mock") - cmd = "mock --root={} --resultdir={} --init".format(tgt, results_dir) + cmd = f"mock --root={tgt} --resultdir={results_dir} --init" retrc |= __salt__["cmd.retcode"](cmd, runas=runas) if deps_list and not deps_list.isspace(): cmd = "mock --root={} --resultdir={} --install {} {}".format( @@ -565,7 +562,7 @@ def build( "rpm", "-qp", "--queryformat", - "{0}/%{{name}}/%{{version}}-%{{release}}".format(log_dir), + f"{log_dir}/%{{name}}/%{{version}}-%{{release}}", srpm, ] log_dest = __salt__["cmd.run_stdout"](cmdlist, python_shell=False) @@ -753,6 +750,6 @@ def make_repo( else: _sign_file(runas, define_gpg_name, phrase, abs_file, timeout) - cmd = "createrepo --update {}".format(repodir) + cmd = f"createrepo --update {repodir}" retrc = __salt__["cmd.run_all"](cmd, runas=runas) return retrc diff --git a/salt/modules/rsync.py b/salt/modules/rsync.py index ffecb3dfb89..311a51cf8a7 100644 --- a/salt/modules/rsync.py +++ b/salt/modules/rsync.py @@ -47,7 +47,7 @@ def _check(delete, force, update, passwordfile, exclude, excludefrom, dryrun, rs if update: options.append("--update") if rsh: - options.append("--rsh={}".format(rsh)) + options.append(f"--rsh={rsh}") if passwordfile: options.extend(["--password-file", passwordfile]) if excludefrom: @@ -182,16 +182,16 @@ def rsync( # get the contents not the tmpdir # itself. if not src.endswith("/"): - src = "{}/".format(src) + src = f"{src}/" else: - raise CommandExecutionError("{} does not exist".format(src)) + raise CommandExecutionError(f"{src} does not exist") else: tmp_src = salt.utils.files.mkstemp() file_src = __salt__["cp.get_file"](_src, tmp_src, saltenv) if file_src: src = tmp_src else: - raise CommandExecutionError("{} does not exist".format(src)) + raise CommandExecutionError(f"{src} does not exist") option = _check( delete, force, update, passwordfile, exclude, excludefrom, dryrun, rsh @@ -261,16 +261,14 @@ def config(conf_path="/etc/rsyncd.conf"): ret += salt.utils.stringutils.to_unicode(line) except OSError as exc: if exc.errno == errno.ENOENT: - raise CommandExecutionError("{} does not exist".format(conf_path)) + raise CommandExecutionError(f"{conf_path} does not exist") elif exc.errno == errno.EACCES: - raise CommandExecutionError( - "Unable to read {}, access denied".format(conf_path) - ) + raise CommandExecutionError(f"Unable to read {conf_path}, access denied") elif exc.errno == errno.EISDIR: raise CommandExecutionError( - "Unable to read {}, path is a directory".format(conf_path) + f"Unable to read {conf_path}, path is a directory" ) else: - raise CommandExecutionError("Error {}: {}".format(exc.errno, exc.strerror)) + raise CommandExecutionError(f"Error {exc.errno}: {exc.strerror}") else: return ret diff --git a/salt/modules/rvm.py b/salt/modules/rvm.py index 28669a26511..92d9b92983d 100644 --- a/salt/modules/rvm.py +++ b/salt/modules/rvm.py @@ -21,8 +21,8 @@ __opts__ = { def _get_rvm_location(runas=None): if runas: - runas_home = os.path.expanduser("~{}".format(runas)) - rvmpath = "{}/.rvm/bin/rvm".format(runas_home) + runas_home = os.path.expanduser(f"~{runas}") + rvmpath = f"{runas_home}/.rvm/bin/rvm" if os.path.exists(rvmpath): return [rvmpath] return ["/usr/local/rvm/bin/rvm"] @@ -87,7 +87,7 @@ def install(runas=None): ret = __salt__["cmd.run_all"]( # the RVM installer automatically does a multi-user install when it is # invoked with root privileges - "curl -Ls {installer} | bash -s stable".format(installer=installer), + f"curl -Ls {installer} | bash -s stable", runas=runas, python_shell=True, ) diff --git a/salt/modules/s6.py b/salt/modules/s6.py index 23edface5a5..3f1c4656520 100644 --- a/salt/modules/s6.py +++ b/salt/modules/s6.py @@ -40,7 +40,7 @@ def _service_path(name): """ if not SERVICE_DIR: raise CommandExecutionError("Could not find service directory.") - return "{}/{}".format(SERVICE_DIR, name) + return f"{SERVICE_DIR}/{name}" def start(name): @@ -53,7 +53,7 @@ def start(name): salt '*' s6.start """ - cmd = "s6-svc -u {}".format(_service_path(name)) + cmd = f"s6-svc -u {_service_path(name)}" return not __salt__["cmd.retcode"](cmd) @@ -67,7 +67,7 @@ def stop(name): salt '*' s6.stop """ - cmd = "s6-svc -d {}".format(_service_path(name)) + cmd = f"s6-svc -d {_service_path(name)}" return not __salt__["cmd.retcode"](cmd) @@ -81,7 +81,7 @@ def term(name): salt '*' s6.term """ - cmd = "s6-svc -t {}".format(_service_path(name)) + cmd = f"s6-svc -t {_service_path(name)}" return not __salt__["cmd.retcode"](cmd) @@ -95,7 +95,7 @@ def reload_(name): salt '*' s6.reload """ - cmd = "s6-svc -h {}".format(_service_path(name)) + cmd = f"s6-svc -h {_service_path(name)}" return not __salt__["cmd.retcode"](cmd) @@ -109,7 +109,7 @@ def restart(name): salt '*' s6.restart """ - cmd = "s6-svc -t {}".format(_service_path(name)) + cmd = f"s6-svc -t {_service_path(name)}" return not __salt__["cmd.retcode"](cmd) @@ -136,7 +136,7 @@ def status(name, sig=None): salt '*' s6.status """ - cmd = "s6-svstat {}".format(_service_path(name)) + cmd = f"s6-svstat {_service_path(name)}" out = __salt__["cmd.run_stdout"](cmd) try: pid = re.search(r"up \(pid (\d+)\)", out).group(1) diff --git a/salt/modules/salt_proxy.py b/salt/modules/salt_proxy.py index 315abf4314d..70572ba1f33 100644 --- a/salt/modules/salt_proxy.py +++ b/salt/modules/salt_proxy.py @@ -33,7 +33,7 @@ def _write_proxy_conf(proxyfile): proxy_conf.write( salt.utils.stringutils.to_str("master: {}".format(__grains__["master"])) ) - msg = "Wrote proxy file {}".format(proxyfile) + msg = f"Wrote proxy file {proxyfile}" log.debug(msg) return msg @@ -50,18 +50,18 @@ def _proxy_conf_file(proxyfile, test): try: if not test: changes_new.append(_write_proxy_conf(proxyfile)) - msg = "Salt Proxy: Wrote proxy conf {}".format(proxyfile) + msg = f"Salt Proxy: Wrote proxy conf {proxyfile}" else: - msg = "Salt Proxy: Update required to proxy conf {}".format(proxyfile) + msg = f"Salt Proxy: Update required to proxy conf {proxyfile}" except OSError as err: success = False - msg = "Salt Proxy: Error writing proxy file {}".format(err) + msg = f"Salt Proxy: Error writing proxy file {err}" log.error(msg) changes_new.append(msg) changes_new.append(msg) log.debug(msg) else: - msg = "Salt Proxy: {} already exists, skipping".format(proxyfile) + msg = f"Salt Proxy: {proxyfile} already exists, skipping" changes_old.append(msg) log.debug(msg) return success, changes_new, changes_old @@ -90,18 +90,14 @@ def _proxy_process(proxyname, test): if not _is_proxy_running(proxyname): if not test: __salt__["cmd.run_all"]( - "salt-proxy --proxyid={} -l info -d".format(shlex.quote(proxyname)), + f"salt-proxy --proxyid={shlex.quote(proxyname)} -l info -d", timeout=5, ) - changes_new.append( - "Salt Proxy: Started proxy process for {}".format(proxyname) - ) + changes_new.append(f"Salt Proxy: Started proxy process for {proxyname}") else: - changes_new.append( - "Salt Proxy: process {} will be started".format(proxyname) - ) + changes_new.append(f"Salt Proxy: process {proxyname} will be started") else: - changes_old.append("Salt Proxy: already running for {}".format(proxyname)) + changes_old.append(f"Salt Proxy: already running for {proxyname}") return True, changes_new, changes_old diff --git a/salt/modules/salt_version.py b/salt/modules/salt_version.py index 99dae5f61a5..56dde8f708c 100644 --- a/salt/modules/salt_version.py +++ b/salt/modules/salt_version.py @@ -30,7 +30,6 @@ A simple example might be something like the following: """ - import logging import salt.utils.versions diff --git a/salt/modules/saltcheck.py b/salt/modules/saltcheck.py index 4b4ebee9cd1..816860f16c8 100644 --- a/salt/modules/saltcheck.py +++ b/salt/modules/saltcheck.py @@ -297,7 +297,6 @@ Supported assertions ``saltcheck.run_highstate_tests`` are needed. """ - import copy import logging import multiprocessing @@ -927,12 +926,12 @@ class SaltCheck: else: assertion_section_repr_title = "" assertion_section_repr_value = "" - value[ - f"module.function [args]{assertion_section_repr_title}" - ] = "{} {}{}".format( - mod_and_func, - dumps(args), - assertion_section_repr_value, + value[f"module.function [args]{assertion_section_repr_title}"] = ( + "{} {}{}".format( + mod_and_func, + dumps(args), + assertion_section_repr_value, + ) ) value["saltcheck assertion"] = "{}{} {}".format( ("" if expected_return is None else f"{expected_return} "), diff --git a/salt/modules/saltcloudmod.py b/salt/modules/saltcloudmod.py index acaed51519b..29a549490e0 100644 --- a/salt/modules/saltcloudmod.py +++ b/salt/modules/saltcloudmod.py @@ -40,7 +40,7 @@ def create(name, profile): salt saltcloud.create webserver rackspace_centos_512 """ - cmd = "salt-cloud --out json -p {} {}".format(profile, name) + cmd = f"salt-cloud --out json -p {profile} {name}" out = __salt__["cmd.run_stdout"](cmd, python_shell=False) try: ret = salt.utils.json.loads(out) diff --git a/salt/modules/saltutil.py b/salt/modules/saltutil.py index 6505a9b2d0b..0095871116b 100644 --- a/salt/modules/saltutil.py +++ b/salt/modules/saltutil.py @@ -1646,7 +1646,7 @@ def regen_keys(): path = os.path.join(__opts__["pki_dir"], fn_) try: os.remove(path) - except os.error: + except OSError: pass # TODO: move this into a channel function? Or auth? # create a channel again, this will force the key regen @@ -1752,9 +1752,11 @@ def _exec( old_ret, fcn_ret = fcn_ret, {} for key, value in old_ret.items(): fcn_ret[key] = { - "out": value.get("out", "highstate") - if isinstance(value, dict) - else "highstate", + "out": ( + value.get("out", "highstate") + if isinstance(value, dict) + else "highstate" + ), "ret": value, } diff --git a/salt/modules/schedule.py b/salt/modules/schedule.py index 50ec9846ba6..42458fb1c25 100644 --- a/salt/modules/schedule.py +++ b/salt/modules/schedule.py @@ -7,7 +7,6 @@ Requires that python-dateutil is installed on the minion. """ - import copy as pycopy import datetime import logging @@ -423,10 +422,10 @@ def delete(name, **kwargs): ) ret["changes"][name] = "removed" else: - ret[ - "comment" - ] = "Failed to delete job {} from schedule.".format( - name + ret["comment"] = ( + "Failed to delete job {} from schedule.".format( + name + ) ) return ret except KeyError: @@ -967,9 +966,9 @@ def disable_job(name, **kwargs): ret["changes"][name] = "disabled" else: ret["result"] = False - ret[ - "comment" - ] = f"Failed to disable job {name} in schedule." + ret["comment"] = ( + f"Failed to disable job {name} in schedule." + ) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system @@ -1391,9 +1390,9 @@ def postpone_job(name, current_time, new_time, **kwargs): ) else: ret["result"] = False - ret[ - "comment" - ] = f"Failed to postpone job {name} in schedule." + ret["comment"] = ( + f"Failed to postpone job {name} in schedule." + ) return ret except KeyError: # Effectively a no-op, since we can't really return without an event system @@ -1520,9 +1519,9 @@ def show_next_fire_time(name, **kwargs): except KeyError: # Effectively a no-op, since we can't really return without an event system ret = {} - ret[ - "comment" - ] = "Event module not available. Schedule show next fire time failed." + ret["comment"] = ( + "Event module not available. Schedule show next fire time failed." + ) ret["result"] = True return ret @@ -1547,9 +1546,11 @@ def job_status(name, time_fmt="%Y-%m-%dT%H:%M:%S"): def convert_datetime_objects_in_dict_to_string(data_dict, time_fmt): return { - key: value.strftime(time_fmt) - if isinstance(value, datetime.datetime) - else value + key: ( + value.strftime(time_fmt) + if isinstance(value, datetime.datetime) + else value + ) for key, value in data_dict.items() } diff --git a/salt/modules/scp_mod.py b/salt/modules/scp_mod.py index 4121bdbf4a7..d7525b28c73 100644 --- a/salt/modules/scp_mod.py +++ b/salt/modules/scp_mod.py @@ -9,8 +9,6 @@ Module to copy files via `SCP `_ import logging -# Import salt modules - try: import paramiko import scp @@ -55,7 +53,7 @@ def _prepare_connection(**kwargs): paramiko_kwargs, scp_kwargs = _select_kwargs(**kwargs) ssh = paramiko.SSHClient() if paramiko_kwargs.pop("auto_add_policy", False): - ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # nosec ssh.connect(**paramiko_kwargs) scp_client = scp.SCPClient(ssh.get_transport(), **scp_kwargs) return scp_client diff --git a/salt/modules/scsi.py b/salt/modules/scsi.py index e405865806a..83a3e8b169d 100644 --- a/salt/modules/scsi.py +++ b/salt/modules/scsi.py @@ -47,7 +47,7 @@ def ls_(get_size=True): __context__["retcode"] = rc error = res.get("stderr", "").split("\n")[0] if error == "lsscsi: invalid option -- 's'": - return "{} - try get_size=False".format(error) + return f"{error} - try get_size=False" return res.get("stderr", "").split("\n")[0] data = res.get("stdout", "") @@ -93,8 +93,8 @@ def rescan_all(host): salt '*' scsi.rescan_all 0 """ - if os.path.isdir("/sys/class/scsi_host/host{}".format(host)): - cmd = 'echo "- - -" > /sys/class/scsi_host/host{}/scan'.format(host) + if os.path.isdir(f"/sys/class/scsi_host/host{host}"): + cmd = f'echo "- - -" > /sys/class/scsi_host/host{host}/scan' else: - return "Host {} does not exist".format(host) + return f"Host {host} does not exist" return __salt__["cmd.run"](cmd).splitlines() diff --git a/salt/modules/sdb.py b/salt/modules/sdb.py index 6dc4457b1f8..1182d6dc934 100644 --- a/salt/modules/sdb.py +++ b/salt/modules/sdb.py @@ -3,7 +3,6 @@ Module for Manipulating Data via the Salt DB API ================================================ """ - import salt.utils.sdb __func_alias__ = { diff --git a/salt/modules/seed.py b/salt/modules/seed.py index 7b985249cac..657c7bccd64 100644 --- a/salt/modules/seed.py +++ b/salt/modules/seed.py @@ -2,7 +2,6 @@ Virtual machine image management tools """ - import logging import os import shutil @@ -42,7 +41,7 @@ def prep_bootstrap(mpt): """ # Verify that the boostrap script is downloaded bs_ = __salt__["config.gather_bootstrap_script"]() - fpd_ = os.path.join(mpt, "tmp", "{}".format(uuid.uuid4())) + fpd_ = os.path.join(mpt, "tmp", f"{uuid.uuid4()}") if not os.path.exists(fpd_): os.makedirs(fpd_) os.chmod(fpd_, 0o700) @@ -136,7 +135,7 @@ def apply_( """ stats = __salt__["file.stats"](path, follow_symlinks=True) if not stats: - return "{} does not exist".format(path) + return f"{path} does not exist" ftype = stats["type"] path = stats["target"] log.debug("Mounting %s at %s", ftype, path) @@ -149,7 +148,7 @@ def apply_( mpt = _mount(path, ftype, mount_point) if not mpt: - return "{} could not be mounted".format(path) + return f"{path} could not be mounted" tmp = os.path.join(mpt, "tmp") log.debug("Attempting to create directory %s", tmp) @@ -300,6 +299,6 @@ def _check_install(root): sh_ = "/bin/bash" cmd = "if ! type salt-minion; then exit 1; fi" - cmd = "chroot '{}' {} -c '{}'".format(root, sh_, cmd) + cmd = f"chroot '{root}' {sh_} -c '{cmd}'" return not __salt__["cmd.retcode"](cmd, output_loglevel="quiet", python_shell=True) diff --git a/salt/modules/sensehat.py b/salt/modules/sensehat.py index 71c5630703c..c3f3e2f0a6d 100644 --- a/salt/modules/sensehat.py +++ b/salt/modules/sensehat.py @@ -19,7 +19,6 @@ Example: """ - import logging try: diff --git a/salt/modules/sensors.py b/salt/modules/sensors.py index b96c3a32a4c..53b1970bf8f 100644 --- a/salt/modules/sensors.py +++ b/salt/modules/sensors.py @@ -42,7 +42,7 @@ def sense(chip, fahrenheit=False): if fahrenheit is True: extra_args = "-f" sensors = __salt__["cmd.run"]( - "/usr/bin/sensors {} {}".format(chip, extra_args), python_shell=False + f"/usr/bin/sensors {chip} {extra_args}", python_shell=False ).splitlines() ret = {} for sensor in sensors: diff --git a/salt/modules/serverdensity_device.py b/salt/modules/serverdensity_device.py index 27a4c0b0a32..7b653d9bcb8 100644 --- a/salt/modules/serverdensity_device.py +++ b/salt/modules/serverdensity_device.py @@ -5,7 +5,6 @@ Wrapper around Server Density API .. versionadded:: 2014.7.0 """ - import logging import os import tempfile @@ -49,14 +48,14 @@ def get_sd_auth(val, sd_auth_pillar_name="serverdensity"): if not sd_pillar: log.error("Could not load %s pillar", sd_auth_pillar_name) raise CommandExecutionError( - "{} pillar is required for authentication".format(sd_auth_pillar_name) + f"{sd_auth_pillar_name} pillar is required for authentication" ) try: return sd_pillar[val] except KeyError: log.error("Could not find value %s in pillar", val) - raise CommandExecutionError("{} value was not found in pillar".format(val)) + raise CommandExecutionError(f"{val} value was not found in pillar") def _clean_salt_variables(params, variable_prefix="__"): @@ -98,7 +97,7 @@ def create(name, **params): except ValueError: log.error("Could not parse API Response content: %s", api_response.content) raise CommandExecutionError( - "Failed to create, API Response: {}".format(api_response) + f"Failed to create, API Response: {api_response}" ) else: return None @@ -129,7 +128,7 @@ def delete(device_id): except ValueError: log.error("Could not parse API Response content: %s", api_response.content) raise CommandExecutionError( - "Failed to create, API Response: {}".format(api_response) + f"Failed to create, API Response: {api_response}" ) else: return None @@ -166,7 +165,7 @@ def ls(**params): params[key] = str(val) api_response = requests.get( - "https://api.serverdensity.io/inventory/{}".format(endpoint), + f"https://api.serverdensity.io/inventory/{endpoint}", params={ "token": get_sd_auth("api_token"), "filter": salt.utils.json.dumps(params), @@ -183,7 +182,7 @@ def ls(**params): api_response.content, ) raise CommandExecutionError( - "Failed to create, Server Density API Response: {}".format(api_response) + f"Failed to create, Server Density API Response: {api_response}" ) else: return None @@ -221,7 +220,7 @@ def update(device_id, **params): api_response.content, ) raise CommandExecutionError( - "Failed to create, API Response: {}".format(api_response) + f"Failed to create, API Response: {api_response}" ) else: return None @@ -255,10 +254,8 @@ def install_agent(agent_key, agent_version=1): account = get_sd_auth(account_field) - __salt__["cmd.run"]( - cmd="curl -L {} -o {}".format(url, install_filename), cwd=work_dir - ) - __salt__["cmd.run"](cmd="chmod +x {}".format(install_filename), cwd=work_dir) + __salt__["cmd.run"](cmd=f"curl -L {url} -o {install_filename}", cwd=work_dir) + __salt__["cmd.run"](cmd=f"chmod +x {install_filename}", cwd=work_dir) return __salt__["cmd.run"]( cmd="{filename} -a {account} -k {agent_key}".format( diff --git a/salt/modules/servicenow.py b/salt/modules/servicenow.py index 5ac48ee72c6..04cff9cb6b6 100644 --- a/salt/modules/servicenow.py +++ b/salt/modules/servicenow.py @@ -137,7 +137,7 @@ def non_structured_query(table, query=None, **kwargs): # try and assemble a query by keyword query_parts = [] for key, value in kwargs.items(): - query_parts.append("{}={}".format(key, value)) + query_parts.append(f"{key}={value}") query = "^".join(query_parts) query = str(query) response = client.get(query) diff --git a/salt/modules/slack_notify.py b/salt/modules/slack_notify.py index d0d32fabe18..b82367176e8 100644 --- a/salt/modules/slack_notify.py +++ b/salt/modules/slack_notify.py @@ -15,7 +15,6 @@ Module for sending messages to Slack api_key: peWcBiMOS9HrZG15peWcBiMOS9HrZG15 """ - import logging import urllib.parse @@ -205,7 +204,7 @@ def post_message( channel, channel, ) - channel = "#{}".format(channel) + channel = f"#{channel}" if not from_name: log.error("from_name is a required option.") diff --git a/salt/modules/slsutil.py b/salt/modules/slsutil.py index 51abe5b390d..cf8afa76c37 100644 --- a/salt/modules/slsutil.py +++ b/salt/modules/slsutil.py @@ -2,7 +2,6 @@ Utility functions for use with or in SLS files """ - import os import posixpath import textwrap diff --git a/salt/modules/smartos_imgadm.py b/salt/modules/smartos_imgadm.py index f390bdcb7d0..10ced9fe024 100644 --- a/salt/modules/smartos_imgadm.py +++ b/salt/modules/smartos_imgadm.py @@ -42,8 +42,8 @@ def _exit_status(retcode, stderr=None): 1: "An error occurred." if not stderr else stderr, 2: "Usage error.", 3: "Image not installed.", - }[retcode] - return ret + } + return ret[retcode] def _parse_image_meta(image=None, detail=False): diff --git a/salt/modules/smartos_nictagadm.py b/salt/modules/smartos_nictagadm.py index 439db5ab498..fb67c9602b3 100644 --- a/salt/modules/smartos_nictagadm.py +++ b/salt/modules/smartos_nictagadm.py @@ -170,9 +170,11 @@ def add(name, mac, mtu=1500): return True else: return { - "Error": "failed to create nictag." - if "stderr" not in res and res["stderr"] == "" - else res["stderr"] + "Error": ( + "failed to create nictag." + if "stderr" not in res and res["stderr"] == "" + else res["stderr"] + ) } @@ -226,9 +228,11 @@ def update(name, mac=None, mtu=None): return True else: return { - "Error": "failed to update nictag." - if "stderr" not in res and res["stderr"] == "" - else res["stderr"] + "Error": ( + "failed to update nictag." + if "stderr" not in res and res["stderr"] == "" + else res["stderr"] + ) } @@ -259,7 +263,9 @@ def delete(name, force=False): return True else: return { - "Error": "failed to delete nictag." - if "stderr" not in res and res["stderr"] == "" - else res["stderr"] + "Error": ( + "failed to delete nictag." + if "stderr" not in res and res["stderr"] == "" + else res["stderr"] + ) } diff --git a/salt/modules/smartos_virt.py b/salt/modules/smartos_virt.py index 2f29fcefd5f..54aa8841822 100644 --- a/salt/modules/smartos_virt.py +++ b/salt/modules/smartos_virt.py @@ -22,7 +22,7 @@ def __virtual__(): return __virtualname__ return ( False, - "{} module can only be loaded on SmartOS compute nodes".format(__virtualname__), + f"{__virtualname__} module can only be loaded on SmartOS compute nodes", ) @@ -185,9 +185,7 @@ def vm_virt_type(domain): salt '*' virt.vm_virt_type """ - ret = __salt__["vmadm.lookup"]( - search="uuid={uuid}".format(uuid=domain), order="type" - ) + ret = __salt__["vmadm.lookup"](search=f"uuid={domain}", order="type") if not ret: raise CommandExecutionError("We can't determine the type of this VM") @@ -232,9 +230,7 @@ def get_macs(domain): salt '*' virt.get_macs """ macs = [] - ret = __salt__["vmadm.lookup"]( - search="uuid={uuid}".format(uuid=domain), order="nics" - ) + ret = __salt__["vmadm.lookup"](search=f"uuid={domain}", order="nics") if not ret: raise CommandExecutionError("We can't find the MAC address of this VM") else: diff --git a/salt/modules/smartos_vmadm.py b/salt/modules/smartos_vmadm.py index 83d64e361dd..e757a660e5c 100644 --- a/salt/modules/smartos_vmadm.py +++ b/salt/modules/smartos_vmadm.py @@ -43,10 +43,12 @@ def _exit_status(retcode): """ Translate exit status of vmadm """ - ret = {0: "Successful completion.", 1: "An error occurred.", 2: "Usage error."}[ - retcode - ] - return ret + ret = { + 0: "Successful completion.", + 1: "An error occurred.", + 2: "Usage error.", + } + return ret[retcode] def _create_update_from_file(mode="create", uuid=None, path=None): diff --git a/salt/modules/smbios.py b/salt/modules/smbios.py index b27a2aeb2d3..9e6f7192ac0 100644 --- a/salt/modules/smbios.py +++ b/salt/modules/smbios.py @@ -75,7 +75,7 @@ def get(string, clean=True): salt '*' smbios.get system-uuid clean=False """ - val = _dmidecoder("-s {}".format(string)).strip() + val = _dmidecoder(f"-s {string}").strip() # Cleanup possible comments in strings. val = "\n".join([v for v in val.split("\n") if not v.startswith("#")]) @@ -158,7 +158,7 @@ def records(rec_type=None, fields=None, clean=True): if rec_type is None: smbios = _dmi_parse(_dmidecoder(), clean, fields) else: - smbios = _dmi_parse(_dmidecoder("-t {}".format(rec_type)), clean, fields) + smbios = _dmi_parse(_dmidecoder(f"-t {rec_type}"), clean, fields) return smbios @@ -334,6 +334,6 @@ def _dmidecoder(args=None): if not args: out = salt.modules.cmdmod._run_quiet(dmidecoder) else: - out = salt.modules.cmdmod._run_quiet("{} {}".format(dmidecoder, args)) + out = salt.modules.cmdmod._run_quiet(f"{dmidecoder} {args}") return out diff --git a/salt/modules/smf_service.py b/salt/modules/smf_service.py index 5c3d948b9d9..4314c84c88f 100644 --- a/salt/modules/smf_service.py +++ b/salt/modules/smf_service.py @@ -9,7 +9,6 @@ that use SMF also. (e.g. SmartOS) `. """ - import fnmatch import re @@ -112,7 +111,7 @@ def available(name): salt '*' service.available net-snmp """ - cmd = "/usr/bin/svcs -H -o FMRI {}".format(name) + cmd = f"/usr/bin/svcs -H -o FMRI {name}" name = __salt__["cmd.run"](cmd, python_shell=False) return name in get_all() @@ -129,7 +128,7 @@ def missing(name): salt '*' service.missing net-snmp """ - cmd = "/usr/bin/svcs -H -o FMRI {}".format(name) + cmd = f"/usr/bin/svcs -H -o FMRI {name}" name = __salt__["cmd.run"](cmd, python_shell=False) return name not in get_all() @@ -165,7 +164,7 @@ def start(name): salt '*' service.start """ - cmd = "/usr/sbin/svcadm enable -s -t {}".format(name) + cmd = f"/usr/sbin/svcadm enable -s -t {name}" retcode = __salt__["cmd.retcode"](cmd, python_shell=False) if not retcode: return True @@ -173,7 +172,7 @@ def start(name): # Return code 3 means there was a problem with the service # A common case is being in the 'maintenance' state # Attempt a clear and try one more time - clear_cmd = "/usr/sbin/svcadm clear {}".format(name) + clear_cmd = f"/usr/sbin/svcadm clear {name}" __salt__["cmd.retcode"](clear_cmd, python_shell=False) return not __salt__["cmd.retcode"](cmd, python_shell=False) return False @@ -189,7 +188,7 @@ def stop(name): salt '*' service.stop """ - cmd = "/usr/sbin/svcadm disable -s -t {}".format(name) + cmd = f"/usr/sbin/svcadm disable -s -t {name}" return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -203,7 +202,7 @@ def restart(name): salt '*' service.restart """ - cmd = "/usr/sbin/svcadm restart {}".format(name) + cmd = f"/usr/sbin/svcadm restart {name}" if not __salt__["cmd.retcode"](cmd, python_shell=False): # calling restart doesn't clear maintenance # or tell us that the service is in the 'online' state @@ -221,7 +220,7 @@ def reload_(name): salt '*' service.reload """ - cmd = "/usr/sbin/svcadm refresh {}".format(name) + cmd = f"/usr/sbin/svcadm refresh {name}" if not __salt__["cmd.retcode"](cmd, python_shell=False): # calling reload doesn't clear maintenance # or tell us that the service is in the 'online' state @@ -259,7 +258,7 @@ def status(name, sig=None): services = [name] results = {} for service in services: - cmd = "/usr/bin/svcs -H -o STATE {}".format(service) + cmd = f"/usr/bin/svcs -H -o STATE {service}" line = __salt__["cmd.run"](cmd, python_shell=False) results[service] = line == "online" if contains_globbing: @@ -277,7 +276,7 @@ def enable(name, **kwargs): salt '*' service.enable """ - cmd = "/usr/sbin/svcadm enable {}".format(name) + cmd = f"/usr/sbin/svcadm enable {name}" return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -291,7 +290,7 @@ def disable(name, **kwargs): salt '*' service.disable """ - cmd = "/usr/sbin/svcadm disable {}".format(name) + cmd = f"/usr/sbin/svcadm disable {name}" return not __salt__["cmd.retcode"](cmd, python_shell=False) @@ -308,9 +307,9 @@ def enabled(name, **kwargs): # The property that reveals whether a service is enabled # can only be queried using the full FMRI # We extract the FMRI and then do the query - fmri_cmd = "/usr/bin/svcs -H -o FMRI {}".format(name) + fmri_cmd = f"/usr/bin/svcs -H -o FMRI {name}" fmri = __salt__["cmd.run"](fmri_cmd, python_shell=False) - cmd = "/usr/sbin/svccfg -s {} listprop general/enabled".format(fmri) + cmd = f"/usr/sbin/svccfg -s {fmri} listprop general/enabled" comps = __salt__["cmd.run"](cmd, python_shell=False).split() if comps[2] == "true": return True diff --git a/salt/modules/smtp.py b/salt/modules/smtp.py index 8eaa6bb0a73..fc9d55f0cbb 100644 --- a/salt/modules/smtp.py +++ b/salt/modules/smtp.py @@ -40,7 +40,6 @@ Module for Sending Messages via SMTP """ - import logging import os import socket @@ -157,7 +156,7 @@ def send_msg( name = os.path.basename(f) with salt.utils.files.fopen(f, "rb") as fin: att = email.mime.application.MIMEApplication(fin.read(), Name=name) - att["Content-Disposition"] = 'attachment; filename="{}"'.format(name) + att["Content-Disposition"] = f'attachment; filename="{name}"' msg.attach(att) try: diff --git a/salt/modules/snapper.py b/salt/modules/snapper.py index 4968dbc329d..f97d3d5f598 100644 --- a/salt/modules/snapper.py +++ b/salt/modules/snapper.py @@ -11,6 +11,7 @@ Module to manage filesystem snapshots with snapper :maturity: new :platform: Linux """ + import difflib import logging import os @@ -333,7 +334,7 @@ def create_config( def raise_arg_error(argname): raise CommandExecutionError( - 'You must provide a "{}" for the new configuration'.format(argname) + f'You must provide a "{argname}" for the new configuration' ) if not name: @@ -365,7 +366,7 @@ def create_snapshot( description=None, cleanup_algorithm="number", userdata=None, - **kwargs + **kwargs, ): """ Creates an snapshot @@ -407,7 +408,7 @@ def create_snapshot( jid = kwargs.get("__pub_jid") if description is None and jid is not None: - description = "salt job {}".format(jid) + description = f"salt job {jid}" if jid is not None: userdata["salt_jid"] = jid @@ -432,9 +433,7 @@ def create_snapshot( config, pre_number, description, cleanup_algorithm, userdata ) else: - raise CommandExecutionError( - "Invalid snapshot type '{}'".format(snapshot_type) - ) + raise CommandExecutionError(f"Invalid snapshot type '{snapshot_type}'") except dbus.DBusException as exc: raise CommandExecutionError( "Error encountered while listing changed files: {}".format( @@ -524,9 +523,9 @@ def modify_snapshot( try: # Updating only the explicitly provided attributes by the user updated_opts = { - "description": description - if description is not None - else snapshot["description"], + "description": ( + description if description is not None else snapshot["description"] + ), "cleanup": cleanup if cleanup is not None else snapshot["cleanup"], "userdata": userdata if userdata is not None else snapshot["userdata"], } @@ -559,7 +558,7 @@ def _is_text_file(filename): ["file", "-bi", filename], check=False, stdout=subprocess.PIPE, - universal_newlines=True, + text=True, ).stdout return type_of_file.startswith("text") @@ -605,7 +604,7 @@ def run(function, *args, **kwargs): salt '*' snapper.run file.append args='["/etc/motd", "some text"]' """ config = kwargs.pop("config", "root") - description = kwargs.pop("description", "snapper.run[{}]".format(function)) + description = kwargs.pop("description", f"snapper.run[{function}]") cleanup_algorithm = kwargs.pop("cleanup_algorithm", "number") userdata = kwargs.pop("userdata", {}) @@ -618,11 +617,11 @@ def run(function, *args, **kwargs): description=description, cleanup_algorithm=cleanup_algorithm, userdata=userdata, - **kwargs + **kwargs, ) if function not in __salt__: - raise CommandExecutionError('function "{}" does not exist'.format(function)) + raise CommandExecutionError(f'function "{function}" does not exist') try: ret = __salt__[function](*args, **func_kwargs) @@ -636,7 +635,7 @@ def run(function, *args, **kwargs): description=description, cleanup_algorithm=cleanup_algorithm, userdata=userdata, - **kwargs + **kwargs, ) return ret @@ -754,7 +753,7 @@ def undo(config="root", files=None, num_pre=None, num_post=None): return ret except ValueError as exc: raise CommandExecutionError( - "Error while processing Snapper response: {}".format(cmdret) + f"Error while processing Snapper response: {cmdret}" ) @@ -772,7 +771,7 @@ def _get_jid_snapshots(jid, config="root"): post_snapshot = [x for x in jid_snapshots if x["type"] == "post"] if not pre_snapshot or not post_snapshot: - raise CommandExecutionError("Jid '{}' snapshots not found".format(jid)) + raise CommandExecutionError(f"Jid '{jid}' snapshots not found") return (pre_snapshot[0]["id"], post_snapshot[0]["id"]) diff --git a/salt/modules/solaris_group.py b/salt/modules/solaris_group.py index 31663be1846..7e9fc1d074f 100644 --- a/salt/modules/solaris_group.py +++ b/salt/modules/solaris_group.py @@ -54,7 +54,7 @@ def add(name, gid=None, **kwargs): cmd = "groupadd " if gid: - cmd += "-g {} ".format(gid) + cmd += f"-g {gid} " cmd += name ret = __salt__["cmd.run_all"](cmd, python_shell=False) @@ -72,7 +72,7 @@ def delete(name): salt '*' group.delete foo """ - ret = __salt__["cmd.run_all"]("groupdel {}".format(name), python_shell=False) + ret = __salt__["cmd.run_all"](f"groupdel {name}", python_shell=False) return not ret["retcode"] @@ -134,7 +134,7 @@ def chgid(name, gid): pre_gid = __salt__["file.group_to_gid"](name) if gid == pre_gid: return True - cmd = "groupmod -g {} {}".format(gid, name) + cmd = f"groupmod -g {gid} {name}" __salt__["cmd.run"](cmd, python_shell=False) post_gid = __salt__["file.group_to_gid"](name) if post_gid != pre_gid: diff --git a/salt/modules/solaris_shadow.py b/salt/modules/solaris_shadow.py index 65d20f2e9e1..fcf7e934cfd 100644 --- a/salt/modules/solaris_shadow.py +++ b/salt/modules/solaris_shadow.py @@ -144,7 +144,7 @@ def info(name): # 5. Maximum age # 6. Warning period - output = __salt__["cmd.run_all"]("passwd -s {}".format(name), python_shell=False) + output = __salt__["cmd.run_all"](f"passwd -s {name}", python_shell=False) if output["retcode"] != 0: return ret @@ -183,7 +183,7 @@ def set_maxdays(name, maxdays): pre_info = info(name) if maxdays == pre_info["max"]: return True - cmd = "passwd -x {} {}".format(maxdays, name) + cmd = f"passwd -x {maxdays} {name}" __salt__["cmd.run"](cmd, python_shell=False) post_info = info(name) if post_info["max"] != pre_info["max"]: @@ -203,7 +203,7 @@ def set_mindays(name, mindays): pre_info = info(name) if mindays == pre_info["min"]: return True - cmd = "passwd -n {} {}".format(mindays, name) + cmd = f"passwd -n {mindays} {name}" __salt__["cmd.run"](cmd, python_shell=False) post_info = info(name) if post_info["min"] != pre_info["min"]: @@ -265,7 +265,7 @@ def del_password(name): salt '*' shadow.del_password username """ - cmd = "passwd -d {}".format(name) + cmd = f"passwd -d {name}" __salt__["cmd.run"](cmd, python_shell=False, output_loglevel="quiet") uinfo = info(name) return not uinfo["passwd"] @@ -296,7 +296,7 @@ def set_password(name, password): continue comps[1] = password line = ":".join(comps) - lines.append("{}\n".format(line)) + lines.append(f"{line}\n") with salt.utils.files.fopen(s_file, "w+") as ofile: lines = [salt.utils.stringutils.to_str(_l) for _l in lines] ofile.writelines(lines) @@ -318,7 +318,7 @@ def set_warndays(name, warndays): pre_info = info(name) if warndays == pre_info["warn"]: return True - cmd = "passwd -w {} {}".format(warndays, name) + cmd = f"passwd -w {warndays} {name}" __salt__["cmd.run"](cmd, python_shell=False) post_info = info(name) if post_info["warn"] != pre_info["warn"]: diff --git a/salt/modules/solaris_user.py b/salt/modules/solaris_user.py index e8d7d0b2bc4..be705b2f0a6 100644 --- a/salt/modules/solaris_user.py +++ b/salt/modules/solaris_user.py @@ -10,7 +10,6 @@ Manage users with the useradd command """ - import copy import logging @@ -109,7 +108,7 @@ def add( workphone="", homephone="", createhome=True, - **kwargs + **kwargs, ): """ Add a user to the minion @@ -219,7 +218,7 @@ def chuid(name, uid): """ pre_info = info(name) if not pre_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") if uid == pre_info["uid"]: return True cmd = ["usermod", "-u", uid, name] @@ -239,7 +238,7 @@ def chgid(name, gid): """ pre_info = info(name) if not pre_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") if gid == pre_info["gid"]: return True cmd = ["usermod", "-g", gid, name] @@ -259,7 +258,7 @@ def chshell(name, shell): """ pre_info = info(name) if not pre_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") if shell == pre_info["shell"]: return True cmd = ["usermod", "-s", shell, name] @@ -290,7 +289,7 @@ def chhome(name, home, persist=False): """ pre_info = info(name) if not pre_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") if home == pre_info["home"]: return True cmd = ["usermod", "-d", home] @@ -458,10 +457,10 @@ def rename(name, new_name): """ current_info = info(name) if not current_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") new_info = info(new_name) if new_info: - raise CommandExecutionError("User '{}' already exists".format(new_name)) + raise CommandExecutionError(f"User '{new_name}' already exists") cmd = ["usermod", "-l", new_name, name] __salt__["cmd.run"](cmd, python_shell=False) return info(new_name).get("name") == new_name diff --git a/salt/modules/solarisipspkg.py b/salt/modules/solarisipspkg.py index 6e6e4f6610f..1d720db0656 100644 --- a/salt/modules/solarisipspkg.py +++ b/salt/modules/solarisipspkg.py @@ -539,19 +539,19 @@ def install(name=None, refresh=False, pkgs=None, version=None, test=False, **kwa if getattr(pkg, "items", False): if list(pkg.items())[0][1]: # version specified pkg2inst.append( - "{}@{}".format(list(pkg.items())[0][0], list(pkg.items())[0][1]) + f"{list(pkg.items())[0][0]}@{list(pkg.items())[0][1]}" ) else: pkg2inst.append(list(pkg.items())[0][0]) else: - pkg2inst.append("{}".format(pkg)) + pkg2inst.append(f"{pkg}") log.debug("Installing these packages instead of %s: %s", name, pkg2inst) else: # install single package if version: - pkg2inst = "{}@{}".format(name, version) + pkg2inst = f"{name}@{version}" else: - pkg2inst = "{}".format(name) + pkg2inst = f"{name}" cmd = ["pkg", "install", "-v", "--accept"] if test: diff --git a/salt/modules/solarispkg.py b/salt/modules/solarispkg.py index fd0ab8d1add..370981b0e7e 100644 --- a/salt/modules/solarispkg.py +++ b/salt/modules/solarispkg.py @@ -65,17 +65,17 @@ def _write_adminfile(kwargs): fp_.write(salt.utils.stringutils.to_str(line)) with salt.utils.files.fopen(adminfile, "w") as fp_: - _write_line(fp_, "email={}\n".format(email)) - _write_line(fp_, "instance={}\n".format(instance)) - _write_line(fp_, "partial={}\n".format(partial)) - _write_line(fp_, "runlevel={}\n".format(runlevel)) - _write_line(fp_, "idepend={}\n".format(idepend)) - _write_line(fp_, "rdepend={}\n".format(rdepend)) - _write_line(fp_, "space={}\n".format(space)) - _write_line(fp_, "setuid={}\n".format(setuid)) - _write_line(fp_, "conflict={}\n".format(conflict)) - _write_line(fp_, "action={}\n".format(action)) - _write_line(fp_, "basedir={}\n".format(basedir)) + _write_line(fp_, f"email={email}\n") + _write_line(fp_, f"instance={instance}\n") + _write_line(fp_, f"partial={partial}\n") + _write_line(fp_, f"runlevel={runlevel}\n") + _write_line(fp_, f"idepend={idepend}\n") + _write_line(fp_, f"rdepend={rdepend}\n") + _write_line(fp_, f"space={space}\n") + _write_line(fp_, f"setuid={setuid}\n") + _write_line(fp_, f"conflict={conflict}\n") + _write_line(fp_, f"action={action}\n") + _write_line(fp_, f"basedir={basedir}\n") return adminfile diff --git a/salt/modules/solr.py b/salt/modules/solr.py index 373aee65b20..9654bd36f6c 100644 --- a/salt/modules/solr.py +++ b/salt/modules/solr.py @@ -58,7 +58,6 @@ verbose : True Get verbose output """ - import os import urllib.request @@ -206,7 +205,7 @@ def _format_url(handler, host=None, core_name=None, extra=None): baseurl = __salt__["config.option"]("solr.baseurl") if _get_none_or_value(core_name) is None: if extra is None or len(extra) == 0: - return "http://{}:{}{}/{}?wt=json".format(host, port, baseurl, handler) + return f"http://{host}:{port}{baseurl}/{handler}?wt=json" else: return "http://{}:{}{}/{}?wt=json&{}".format( host, port, baseurl, handler, "&".join(extra) @@ -261,7 +260,7 @@ def _http_request(url, request_timeout=None): data = salt.utils.json.load(urllib.request.urlopen(url, **kwargs)) return _get_return_dict(True, data, []) except Exception as err: # pylint: disable=broad-except - return _get_return_dict(False, {}, ["{} : {}".format(url, err)]) + return _get_return_dict(False, {}, [f"{url} : {err}"]) def _replication_request(command, host=None, core_name=None, params=None): @@ -287,7 +286,7 @@ def _replication_request(command, host=None, core_name=None, params=None): {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} """ params = [] if params is None else params - extra = ["command={}".format(command)] + params + extra = [f"command={command}"] + params url = _format_url("replication", host=host, core_name=core_name, extra=extra) return _http_request(url) @@ -312,7 +311,7 @@ def _get_admin_info(command, host=None, core_name=None): {'success':boolean, 'data':dict, 'errors':list, 'warnings':list} """ - url = _format_url("admin/{}".format(command), host, core_name=core_name) + url = _format_url(f"admin/{command}", host, core_name=core_name) resp = _http_request(url) return resp @@ -391,10 +390,10 @@ def _pre_index_check(handler, host=None, core_name=None): warn = ["An indexing process is already running."] return _get_return_dict(True, warnings=warn) if status != "idle": - errors = ['Unknown status: "{}"'.format(status)] + errors = [f'Unknown status: "{status}"'] return _get_return_dict(False, data=resp["data"], errors=errors) else: - errors = ["Status check failed. Response details: {}".format(resp)] + errors = [f"Status check failed. Response details: {resp}"] return _get_return_dict(False, data=resp["data"], errors=errors) return resp @@ -422,7 +421,7 @@ def _find_value(ret_dict, key, path=None): if path is None: path = key else: - path = "{}:{}".format(path, key) + path = f"{path}:{key}" ret = [] for ikey, val in ret_dict.items(): @@ -740,7 +739,7 @@ def match_index_versions(host=None, core_name=None): if "ERROR" in slave: error = slave["ERROR"] success = False - err = "{}: {} - {}".format(core, error, master_url) + err = f"{core}: {error} - {master_url}" resp["errors"].append(err) # if there was an error return the entire response so the # alterer can get what it wants @@ -865,8 +864,8 @@ def backup(host=None, core_name=None, append_core_to_path=False): params = [] if path is not None: path = path + name if append_core_to_path else path - params.append("&location={}".format(path + name)) - params.append("&numberToKeep={}".format(num_backups)) + params.append(f"&location={path + name}") + params.append(f"&numberToKeep={num_backups}") resp = _replication_request( "backup", host=host, core_name=name, params=params ) @@ -882,8 +881,8 @@ def backup(host=None, core_name=None, append_core_to_path=False): if append_core_to_path: path += core_name if path is not None: - params = ["location={}".format(path)] - params.append("&numberToKeep={}".format(num_backups)) + params = [f"location={path}"] + params.append(f"&numberToKeep={num_backups}") resp = _replication_request( "backup", host=host, core_name=core_name, params=params ) @@ -1059,7 +1058,7 @@ def reload_core(host=None, core_name=None): ret, success, data, resp["errors"], resp["warnings"] ) return ret - extra = ["action=RELOAD", "core={}".format(core_name)] + extra = ["action=RELOAD", f"core={core_name}"] url = _format_url("admin/cores", host=host, core_name=None, extra=extra) return _http_request(url) @@ -1100,7 +1099,7 @@ def core_status(host=None, core_name=None): ret, success, data, resp["errors"], resp["warnings"] ) return ret - extra = ["action=STATUS", "core={}".format(core_name)] + extra = ["action=STATUS", f"core={core_name}"] url = _format_url("admin/cores", host=host, core_name=None, extra=extra) return _http_request(url) @@ -1242,7 +1241,7 @@ def full_import(handler, host=None, core_name=None, options=None, extra=None): return _get_return_dict(False, errors=errors) params = ["command=full-import"] for key, val in options.items(): - params.append("&{}={}".format(key, val)) + params.append(f"&{key}={val}") url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) @@ -1295,7 +1294,7 @@ def delta_import(handler, host=None, core_name=None, options=None, extra=None): return _get_return_dict(False, errors=errors) params = ["command=delta-import"] for key, val in options.items(): - params.append("{}={}".format(key, val)) + params.append(f"{key}={val}") url = _format_url(handler, host=host, core_name=core_name, extra=params + extra) return _http_request(url) diff --git a/salt/modules/solrcloud.py b/salt/modules/solrcloud.py index fda16a1ef55..7b594e3292f 100644 --- a/salt/modules/solrcloud.py +++ b/salt/modules/solrcloud.py @@ -314,7 +314,7 @@ def alias_set_collections(alias_name, collections=None, **kwargs): "admin/collections?action=CREATEALIAS&name={alias}&wt=json&collections={collections}".format( alias=alias_name, collections=", ".join(collections) ), - **kwargs + **kwargs, ) @@ -337,7 +337,7 @@ def collection_reload(collection, **kwargs): "admin/collections?action=RELOAD&name={collection}&wt=json".format( collection=collection ), - **kwargs + **kwargs, ) @@ -398,7 +398,7 @@ def collection_backup(collection_name, location, backup_name=None, **kwargs): raise ValueError("Collection doesn't exists") if backup_name is not None: - backup_name = "&name={}".format(backup_name) + backup_name = f"&name={backup_name}" else: backup_name = "" @@ -406,7 +406,7 @@ def collection_backup(collection_name, location, backup_name=None, **kwargs): "{collection}/replication?command=BACKUP&location={location}{backup_name}&wt=json".format( collection=collection_name, backup_name=backup_name, location=location ), - **kwargs + **kwargs, ) @@ -436,7 +436,7 @@ def collection_backup_all(location, backup_name=None, **kwargs): "{collection}/replication?command=BACKUP&location={location}{backup_name}&wt=json".format( collection=collection_name, backup_name=backup_name, location=location ), - **kwargs + **kwargs, ) @@ -481,7 +481,7 @@ def collection_create(collection_name, options=None, **kwargs): "admin/collections?action=CREATE&wt=json&name=" + collection_name + options_string, - **kwargs + **kwargs, ) @@ -566,5 +566,5 @@ def collection_set_options(collection_name, options, **kwargs): "admin/collections?action=MODIFYCOLLECTION&wt=json&collection=" + collection_name + options_string, - **kwargs + **kwargs, ) diff --git a/salt/modules/splunk_search.py b/salt/modules/splunk_search.py index 560874cd23e..d6de25eba63 100644 --- a/salt/modules/splunk_search.py +++ b/salt/modules/splunk_search.py @@ -130,7 +130,7 @@ def update(name, profile="splunk", **kwargs): if old_value != new_value: update_set[key] = new_value update_needed = True - diffs.append("{}: '{}' => '{}'".format(key, old_value, new_value)) + diffs.append(f"{key}: '{old_value}' => '{new_value}'") if update_needed: search.update(**update_set).refresh() return update_set, diffs @@ -286,7 +286,7 @@ def list_all( d = [{"name": name}] # add the rest of the splunk settings, ignoring any defaults description = "" - for (k, v) in sorted(search.content.items()): + for k, v in sorted(search.content.items()): if k in readonly_keys: continue if k.startswith("display."): diff --git a/salt/modules/ssh.py b/salt/modules/ssh.py index 44e7c67da16..0701e963867 100644 --- a/salt/modules/ssh.py +++ b/salt/modules/ssh.py @@ -83,7 +83,7 @@ def _refine_enc(enc): elif enc in also_allowed: return enc else: - raise CommandExecutionError("Incorrect encryption key type '{}'.".format(enc)) + raise CommandExecutionError(f"Incorrect encryption key type '{enc}'.") def _format_auth_line(key, enc, comment, options): @@ -93,7 +93,7 @@ def _format_auth_line(key, enc, comment, options): line = "" if options: line += "{} ".format(",".join(options)) - line += "{} {} {}\n".format(enc, key, comment) + line += f"{enc} {key} {comment}\n" return line @@ -134,7 +134,7 @@ def _get_config_file(user, config): """ uinfo = __salt__["user.info"](user) if not uinfo: - raise CommandExecutionError("User '{}' does not exist".format(user)) + raise CommandExecutionError(f"User '{user}' does not exist") home = uinfo["home"] config = _expand_authorized_keys_path(config, user, home) if not os.path.isabs(config): @@ -183,9 +183,7 @@ def _replace_auth_key( # Write out any changes _fh.writelines(salt.utils.data.encode(lines)) except OSError as exc: - raise CommandExecutionError( - "Problem reading or writing to key file: {}".format(exc) - ) + raise CommandExecutionError(f"Problem reading or writing to key file: {exc}") def _validate_keys(key_file, fingerprint_hash_type): @@ -241,7 +239,7 @@ def _validate_keys(key_file, fingerprint_hash_type): "fingerprint": fingerprint, } except OSError: - raise CommandExecutionError("Problem reading ssh key file {}".format(key_file)) + raise CommandExecutionError(f"Problem reading ssh key file {key_file}") return ret @@ -277,7 +275,7 @@ def _fingerprint(public_key, fingerprint_hash_type): hash_func = getattr(hashlib, hash_type) except AttributeError: raise CommandExecutionError( - "The fingerprint_hash_type {} is not supported.".format(hash_type) + f"The fingerprint_hash_type {hash_type} is not supported." ) try: @@ -305,7 +303,7 @@ def _get_known_hosts_file(config=None, user=None): if not uinfo: return { "status": "error", - "error": "User {} does not exist".format(user), + "error": f"User {user} does not exist", } full = os.path.join(uinfo["home"], config) else: @@ -433,7 +431,7 @@ def check_key_file( return {} s_keys = _validate_keys(keyfile, fingerprint_hash_type) if not s_keys: - err = "No keys detected in {}. Is file properly formatted?".format(source) + err = f"No keys detected in {source}. Is file properly formatted?" log.error(err) __context__["ssh_auth.error"] = err return {} @@ -526,7 +524,7 @@ def rm_auth_key_from_file( s_keys = _validate_keys(lfile, fingerprint_hash_type) if not s_keys: - err = "No keys detected in {}. Is file properly formatted?".format(source) + err = f"No keys detected in {source}. Is file properly formatted?" log.error(err) __context__["ssh_auth.error"] = err return "fail" @@ -568,7 +566,7 @@ def rm_auth_key(user, key, config=".ssh/authorized_keys", fingerprint_hash_type= # Return something sensible if the file doesn't exist if not os.path.isfile(full): - return "Authorized keys file {} not present".format(full) + return f"Authorized keys file {full} not present" lines = [] try: @@ -644,7 +642,7 @@ def set_auth_key_from_file( s_keys = _validate_keys(lfile, fingerprint_hash_type) if not s_keys: - err = "No keys detected in {}. Is file properly formatted?".format(source) + err = f"No keys detected in {source}. Is file properly formatted?" log.error(err) __context__["ssh_auth.error"] = err return "fail" @@ -1009,7 +1007,7 @@ def rm_known_host(user=None, hostname=None, config=None, port=None): if not os.path.isfile(full): return { "status": "error", - "error": "Known hosts file {} does not exist".format(full), + "error": f"Known hosts file {full} does not exist", } ssh_hostname = _hostname_and_port_to_ssh_hostname(hostname, port) @@ -1252,7 +1250,7 @@ def set_known_host( ofile.writelines(salt.utils.data.encode(lines)) except OSError as exception: raise CommandExecutionError( - "Couldn't append to known hosts file: '{}'".format(exception) + f"Couldn't append to known hosts file: '{exception}'" ) if not salt.utils.platform.is_windows(): @@ -1378,7 +1376,7 @@ def hash_known_hosts(user=None, config=None): if not os.path.isfile(full): return { "status": "error", - "error": "Known hosts file {} does not exist".format(full), + "error": f"Known hosts file {full} does not exist", } origmode = os.stat(full).st_mode cmd = ["ssh-keygen", "-H", "-f", full] @@ -1396,7 +1394,7 @@ def _hostname_and_port_to_ssh_hostname(hostname, port=DEFAULT_SSH_PORT): if not port or port == DEFAULT_SSH_PORT: return hostname else: - return "[{}]:{}".format(hostname, port) + return f"[{hostname}]:{port}" def key_is_encrypted(key): diff --git a/salt/modules/state.py b/salt/modules/state.py index 6f23b6f2db3..6440d347ffe 100644 --- a/salt/modules/state.py +++ b/salt/modules/state.py @@ -2345,7 +2345,7 @@ def pkg(pkg_path, pkg_sum, hash_type, test=None, **kwargs): return {} elif f"..{os.sep}" in salt.utils.stringutils.to_unicode(member.path): return {} - s_pkg.extractall(root) + s_pkg.extractall(root) # nosec s_pkg.close() lowstate_json = os.path.join(root, "lowstate.json") with salt.utils.files.fopen(lowstate_json, "r") as fp_: diff --git a/salt/modules/status.py b/salt/modules/status.py index 4b0a3b0d400..ba4567cd48a 100644 --- a/salt/modules/status.py +++ b/salt/modules/status.py @@ -221,9 +221,7 @@ def uptime(): if salt.utils.platform.is_linux(): ut_path = "/proc/uptime" if not os.path.exists(ut_path): - raise CommandExecutionError( - "File {ut_path} was not found.".format(ut_path=ut_path) - ) + raise CommandExecutionError(f"File {ut_path} was not found.") with salt.utils.files.fopen(ut_path) as rfh: seconds = int(float(rfh.read().split()[0])) elif salt.utils.platform.is_sunos(): @@ -267,7 +265,7 @@ def uptime(): "since_iso": boot_time.isoformat(), "since_t": int(curr_seconds - seconds), "days": up_time.days, - "time": "{}:{}".format(up_time.seconds // 3600, up_time.seconds % 3600 // 60), + "time": f"{up_time.seconds // 3600}:{up_time.seconds % 3600 // 60}", } if salt.utils.path.which("who"): @@ -569,7 +567,7 @@ def meminfo(): procn = len(ret["svmon"]) ret["svmon"].append({}) comps = line.split() - pg_space = "{} {}".format(comps[0], comps[1]) + pg_space = f"{comps[0]} {comps[1]}" ret["svmon"][procn][pg_space] = {} for idx, field in enumerate(fields): if len(comps) > idx + 2: @@ -760,7 +758,7 @@ def cpuinfo(): ret["psrinfo"][procn]["family"] = _number(line[4]) ret["psrinfo"][procn]["model"] = _number(line[6]) ret["psrinfo"][procn]["step"] = _number(line[8]) - ret["psrinfo"][procn]["clock"] = "{} {}".format(line[10], line[11][:-1]) + ret["psrinfo"][procn]["clock"] = f"{line[10]} {line[11][:-1]}" return ret def aix_cpuinfo(): @@ -1383,10 +1381,10 @@ def netdev(): ): # fetch device info netstat_ipv4 = __salt__["cmd.run"]( - "netstat -i -I {dev} -n -f inet".format(dev=dev) + f"netstat -i -I {dev} -n -f inet" ).splitlines() netstat_ipv6 = __salt__["cmd.run"]( - "netstat -i -I {dev} -n -f inet6".format(dev=dev) + f"netstat -i -I {dev} -n -f inet6" ).splitlines() # prepare data @@ -1401,14 +1399,14 @@ def netdev(): if val == "Name": continue if val in ["Address", "Net/Dest"]: - ret[dev]["IPv4 {field}".format(field=val)] = val + ret[dev][f"IPv4 {val}"] = val else: ret[dev][val] = _number(val) for val in netstat_ipv6[0][:-1]: if val == "Name": continue if val in ["Address", "Net/Dest"]: - ret[dev]["IPv6 {field}".format(field=val)] = val + ret[dev][f"IPv6 {val}"] = val else: ret[dev][val] = _number(val) @@ -1434,10 +1432,10 @@ def netdev(): # en0 1500 link#3 e2.eb.32.42.84.c 10029731 0 446499 0 0 netstat_ipv4 = __salt__["cmd.run"]( - "netstat -i -n -I {dev} -f inet".format(dev=dev) + f"netstat -i -n -I {dev} -f inet" ).splitlines() netstat_ipv6 = __salt__["cmd.run"]( - "netstat -i -n -I {dev} -f inet6".format(dev=dev) + f"netstat -i -n -I {dev} -f inet6" ).splitlines() # add data diff --git a/salt/modules/statuspage.py b/salt/modules/statuspage.py index 0a38e84102b..09b8cd0b2d6 100644 --- a/salt/modules/statuspage.py +++ b/salt/modules/statuspage.py @@ -18,7 +18,6 @@ In the minion configuration file, the following block is required: .. versionadded:: 2017.7.0 """ - import logging # import third party diff --git a/salt/modules/supervisord.py b/salt/modules/supervisord.py index eee4a9f42cf..1e97e3b7632 100644 --- a/salt/modules/supervisord.py +++ b/salt/modules/supervisord.py @@ -3,7 +3,6 @@ Provide the service module for system supervisord or supervisord in a virtualenv """ - import configparser import os @@ -27,7 +26,7 @@ def _get_supervisorctl_bin(bin_env): if not bin_env: which_result = __salt__["cmd.which_bin"]([cmd]) if which_result is None: - raise CommandNotFoundError("Could not find a `{}` binary".format(cmd)) + raise CommandNotFoundError(f"Could not find a `{cmd}` binary") return which_result # try to get binary from env @@ -35,7 +34,7 @@ def _get_supervisorctl_bin(bin_env): cmd_bin = os.path.join(bin_env, "bin", cmd) if os.path.isfile(cmd_bin): return cmd_bin - raise CommandNotFoundError("Could not find a `{}` binary".format(cmd)) + raise CommandNotFoundError(f"Could not find a `{cmd}` binary") return bin_env @@ -58,7 +57,7 @@ def _get_return(ret): if ret["retcode"] != 0: # This is a non 0 exit code if "ERROR" not in retmsg: - retmsg = "ERROR: {}".format(retmsg) + retmsg = f"ERROR: {retmsg}" return retmsg @@ -372,7 +371,7 @@ def _read_config(conf_file=None): try: config.read(conf_file) except OSError as exc: - raise CommandExecutionError("Unable to read from {}: {}".format(conf_file, exc)) + raise CommandExecutionError(f"Unable to read from {conf_file}: {exc}") return config @@ -394,9 +393,9 @@ def options(name, conf_file=None): salt '*' supervisord.options foo """ config = _read_config(conf_file) - section_name = "program:{}".format(name) + section_name = f"program:{name}" if section_name not in config.sections(): - raise CommandExecutionError("Process '{}' not found".format(name)) + raise CommandExecutionError(f"Process '{name}' not found") ret = {} for key, val in config.items(section_name): val = salt.utils.stringutils.to_num(val.split(";")[0].strip()) @@ -438,7 +437,7 @@ def status_bool(name, expected_state=None, user=None, conf_file=None, bin_env=No salt '*' supervisord.status_bool nginx expected_state='RUNNING' """ - cmd = "status {}".format(name) + cmd = f"status {name}" for line in custom(cmd, user, conf_file, bin_env).splitlines(): if len(line.split()) > 2: process, state, reason = line.split(None, 2) diff --git a/salt/modules/suse_ip.py b/salt/modules/suse_ip.py index 9422c0d91b2..fdff55e37a4 100644 --- a/salt/modules/suse_ip.py +++ b/salt/modules/suse_ip.py @@ -197,7 +197,7 @@ def _parse_ethtool_opts(opts, iface): _raise_error_iface(iface, "advertise", valid) if "channels" in opts: - channels_cmd = "-L {}".format(iface.strip()) + channels_cmd = f"-L {iface.strip()}" channels_params = [] for option in ("rx", "tx", "other", "combined"): if option in opts["channels"]: @@ -557,9 +557,7 @@ def _parse_settings_eth(opts, iface_type, enabled, iface): if iface_type not in ("bridge",): ethtool = _parse_ethtool_opts(opts, iface) if ethtool: - result["ethtool"] = " ".join( - ["{} {}".format(x, y) for x, y in ethtool.items()] - ) + result["ethtool"] = " ".join([f"{x} {y}" for x, y in ethtool.items()]) if iface_type == "slave": result["proto"] = "none" @@ -571,9 +569,7 @@ def _parse_settings_eth(opts, iface_type, enabled, iface): raise AttributeError(msg) bonding = _parse_settings_bond(opts, iface) if bonding: - result["bonding"] = " ".join( - ["{}={}".format(x, y) for x, y in bonding.items()] - ) + result["bonding"] = " ".join([f"{x}={y}" for x, y in bonding.items()]) result["devtype"] = "Bond" if "slaves" in opts: if isinstance(opts["slaves"], list): @@ -667,14 +663,14 @@ def _parse_settings_eth(opts, iface_type, enabled, iface): ) or salt.utils.validate.net.ipv6_addr(opt): result["ipaddrs"].append(opt) else: - msg = "{} is invalid ipv4 or ipv6 CIDR".format(opt) + msg = f"{opt} is invalid ipv4 or ipv6 CIDR" log.error(msg) raise AttributeError(msg) if "ipv6addr" in opts: if salt.utils.validate.net.ipv6_addr(opts["ipv6addr"]): result["ipaddrs"].append(opts["ipv6addr"]) else: - msg = "{} is invalid ipv6 CIDR".format(opt) + msg = f"{opt} is invalid ipv6 CIDR" log.error(msg) raise AttributeError(msg) if "ipv6addrs" in opts: @@ -682,7 +678,7 @@ def _parse_settings_eth(opts, iface_type, enabled, iface): if salt.utils.validate.net.ipv6_addr(opt): result["ipaddrs"].append(opt) else: - msg = "{} is invalid ipv6 CIDR".format(opt) + msg = f"{opt} is invalid ipv6 CIDR" log.error(msg) raise AttributeError(msg) @@ -878,7 +874,7 @@ def _write_file_iface(iface, data, folder, pattern): """ filename = os.path.join(folder, pattern.format(iface)) if not os.path.exists(folder): - msg = "{} cannot be written. {} does not exist".format(filename, folder) + msg = f"{filename} cannot be written. {folder} does not exist" log.error(msg) raise AttributeError(msg) with salt.utils.files.fopen(filename, "w") as fp_: @@ -987,7 +983,7 @@ def build_interface(iface, iface_type, enabled, **settings): return _get_non_blank_lines(ifcfg) _write_file_iface(iface, ifcfg, _SUSE_NETWORK_SCRIPT_DIR, "ifcfg-{}") - path = os.path.join(_SUSE_NETWORK_SCRIPT_DIR, "ifcfg-{}".format(iface)) + path = os.path.join(_SUSE_NETWORK_SCRIPT_DIR, f"ifcfg-{iface}") return _read_file(path) @@ -1036,7 +1032,7 @@ def build_routes(iface, **settings): if iface == "routes": path = _SUSE_NETWORK_ROUTES_FILE else: - path = os.path.join(_SUSE_NETWORK_SCRIPT_DIR, "ifroute-{}".format(iface)) + path = os.path.join(_SUSE_NETWORK_SCRIPT_DIR, f"ifroute-{iface}") _write_file_network(routecfg, path) @@ -1068,7 +1064,7 @@ def down(iface, iface_type=None): """ # Slave devices are controlled by the master. if not iface_type or iface_type.lower() != "slave": - return __salt__["cmd.run"]("ifdown {}".format(iface)) + return __salt__["cmd.run"](f"ifdown {iface}") return None @@ -1089,7 +1085,7 @@ def get_interface(iface): salt '*' ip.get_interface eth0 """ - path = os.path.join(_SUSE_NETWORK_SCRIPT_DIR, "ifcfg-{}".format(iface)) + path = os.path.join(_SUSE_NETWORK_SCRIPT_DIR, f"ifcfg-{iface}") return _read_file(path) @@ -1118,7 +1114,7 @@ def up(iface, iface_type=None): """ # Slave devices are controlled by the master. if not iface_type or iface_type.lower() != "slave": - return __salt__["cmd.run"]("ifup {}".format(iface)) + return __salt__["cmd.run"](f"ifup {iface}") return None @@ -1142,7 +1138,7 @@ def get_routes(iface): if iface == "routes": path = _SUSE_NETWORK_ROUTES_FILE else: - path = os.path.join(_SUSE_NETWORK_SCRIPT_DIR, "ifroute-{}".format(iface)) + path = os.path.join(_SUSE_NETWORK_SCRIPT_DIR, f"ifroute-{iface}") return _read_file(path) diff --git a/salt/modules/sysbench.py b/salt/modules/sysbench.py index 9e56ddbbe71..1f44e77fb2a 100644 --- a/salt/modules/sysbench.py +++ b/salt/modules/sysbench.py @@ -79,7 +79,7 @@ def cpu(): # Test beings! for primes in max_primes: - key = "Prime numbers limit: {}".format(primes) + key = f"Prime numbers limit: {primes}" run_command = test_command.format(primes) result = __salt__["cmd.run"](run_command) ret_val[key] = _parser(result) @@ -110,7 +110,7 @@ def threads(): # Test begins! for yields, locks in zip(thread_yields, thread_locks): - key = "Yields: {} Locks: {}".format(yields, locks) + key = f"Yields: {yields} Locks: {locks}" run_command = test_command.format(yields, locks) result = __salt__["cmd.run"](run_command) ret_val[key] = _parser(result) @@ -149,7 +149,7 @@ def mutex(): # Test begins! for num, locks, loops in zip(mutex_num, mutex_locks, mutex_loops): - key = "Mutex: {} Locks: {} Loops: {}".format(num, locks, loops) + key = f"Mutex: {num} Locks: {locks} Loops: {loops}" run_command = test_command.format(num, locks, loops) result = __salt__["cmd.run"](run_command) ret_val[key] = _parser(result) @@ -187,7 +187,7 @@ def memory(): # Test begins! for oper in memory_oper: for scope in memory_scope: - key = "Operation: {} Scope: {}".format(oper, scope) + key = f"Operation: {oper} Scope: {scope}" run_command = test_command.format(oper, scope) result = __salt__["cmd.run"](run_command) ret_val[key] = _parser(result) @@ -228,7 +228,7 @@ def fileio(): # Test begins! for mode in test_modes: - key = "Mode: {}".format(mode) + key = f"Mode: {mode}" # Prepare phase run_command = (test_command + "prepare").format(mode) diff --git a/salt/modules/sysfs.py b/salt/modules/sysfs.py index 0192c038612..f86136c2060 100644 --- a/salt/modules/sysfs.py +++ b/salt/modules/sysfs.py @@ -62,7 +62,7 @@ def write(key, value): key = target(key) log.trace("Writing %s to %s", value, key) with salt.utils.files.fopen(key, "w") as twriter: - twriter.write(salt.utils.stringutils.to_str("{}\n".format(value))) + twriter.write(salt.utils.stringutils.to_str(f"{value}\n")) return True except Exception: # pylint: disable=broad-except return False diff --git a/salt/modules/syslog_ng.py b/salt/modules/syslog_ng.py index 9e8e8829df7..d215d8057b0 100644 --- a/salt/modules/syslog_ng.py +++ b/salt/modules/syslog_ng.py @@ -24,7 +24,6 @@ configuration file. """ - import logging import os import os.path @@ -80,7 +79,7 @@ def _indent(value): """ Returns the indented parameter. """ - return "{}{}".format(_INDENT, value) + return f"{_INDENT}{value}" def _indentln(string): @@ -162,9 +161,9 @@ class Statement(Buildable): def build_header(self): if self.has_name: - return _indentln("{0} {1} {{".format(self.type, self.id)) + return _indentln(f"{self.type} {self.id} {{") else: - return _indentln("{0} {{".format(self.type)) + return _indentln(f"{self.type} {{") def build_tail(self): return _indentln("};") @@ -232,7 +231,7 @@ class Option(Buildable): self.iterable = self.params def build(self): - header = _indentln("{}(".format(self.type)) + header = _indentln(f"{self.type}(") tail = _indentln(");") body = self.build_body() @@ -305,7 +304,7 @@ class TypedParameter(Parameter): self.iterable = self.values def build(self): - header = _indentln("{}(".format(self.type)) + header = _indentln(f"{self.type}(") tail = _indent(")") body = self.build_body() @@ -373,7 +372,7 @@ class TypedParameterValue(ParameterValue): self.iterable = self.arguments def build(self): - header = _indentln("{}(".format(self.type)) + header = _indentln(f"{self.type}(") tail = _indent(")") body = self.build_body() @@ -823,7 +822,7 @@ def config_test(syslog_ng_sbin_dir=None, cfgfile=None): """ params = ["--syntax-only"] if cfgfile: - params.append("--cfgfile={}".format(cfgfile)) + params.append(f"--cfgfile={cfgfile}") try: ret = _run_command_in_extended_path(syslog_ng_sbin_dir, "syslog-ng", params) @@ -937,7 +936,7 @@ def _add_cli_param(params, key, value): Adds key and value as a command line parameter to params. """ if value is not None: - params.append("--{}={}".format(key, value)) + params.append(f"--{key}={value}") def _add_boolean_cli_param(params, key, value): @@ -945,7 +944,7 @@ def _add_boolean_cli_param(params, key, value): Adds key as a command line parameter to params. """ if value is True: - params.append("--{}".format(key)) + params.append(f"--{key}") def stop(name=None): @@ -1041,7 +1040,7 @@ def start( command = [syslog_ng_binary] + params if __opts__.get("test", False): - comment = "Syslog_ng state module will start {}".format(command) + comment = f"Syslog_ng state module will start {command}" return _format_state_result(name, result=None, comment=comment) result = __salt__["cmd.run_all"](command, python_shell=False) @@ -1049,7 +1048,7 @@ def start( command = ["syslog-ng"] + params if __opts__.get("test", False): - comment = "Syslog_ng state module will start {}".format(command) + comment = f"Syslog_ng state module will start {command}" return _format_state_result(name, result=None, comment=comment) result = __salt__["cmd.run_all"](command, python_shell=False) @@ -1157,7 +1156,7 @@ def write_version(name): salt '*' syslog_ng.write_version name="3.6" """ - line = "@version: {}".format(name) + line = f"@version: {name}" try: if os.path.exists(__SYSLOG_NG_CONFIG_FILE): log.debug( diff --git a/salt/modules/system_profiler.py b/salt/modules/system_profiler.py index 5cbb4998a8c..aa3af692a37 100644 --- a/salt/modules/system_profiler.py +++ b/salt/modules/system_profiler.py @@ -8,7 +8,6 @@ information about package receipts and installed applications. """ - import plistlib import subprocess diff --git a/salt/modules/telegram.py b/salt/modules/telegram.py index 79230b5e049..13fceb4cfff 100644 --- a/salt/modules/telegram.py +++ b/salt/modules/telegram.py @@ -104,7 +104,7 @@ def _post_message(message, chat_id, token): :param token: The Telegram API token. :return: Boolean if message was sent successfully. """ - url = "https://api.telegram.org/bot{}/sendMessage".format(token) + url = f"https://api.telegram.org/bot{token}/sendMessage" parameters = dict() if chat_id: diff --git a/salt/modules/telemetry.py b/salt/modules/telemetry.py index 20dcf08c185..450ff383b28 100644 --- a/salt/modules/telemetry.py +++ b/salt/modules/telemetry.py @@ -72,7 +72,7 @@ def _auth(api_key=None, profile="telemetry"): def _update_cache(deployment_id, metric_name, alert): - key = "telemetry.{}.alerts".format(deployment_id) + key = f"telemetry.{deployment_id}.alerts" if key in __context__: alerts = __context__[key] @@ -133,7 +133,7 @@ def get_alert_config( auth = _auth(profile=profile) alert = False - key = "telemetry.{}.alerts".format(deployment_id) + key = f"telemetry.{deployment_id}.alerts" if key not in __context__: try: @@ -209,9 +209,7 @@ def get_notification_channel_id(notify_channel, profile="telemetry"): notification_channel_id = response.json().get("_id") __context__["telemetry.channels"][notify_channel] = notification_channel_id else: - raise Exception( - "Failed to created notification channel {}".format(notify_channel) - ) + raise Exception(f"Failed to created notification channel {notify_channel}") return notification_channel_id @@ -233,8 +231,7 @@ def get_alarms(deployment_id, profile="telemetry"): try: response = requests.get( - _get_telemetry_base(profile) - + "/alerts?deployment={}".format(deployment_id), + _get_telemetry_base(profile) + f"/alerts?deployment={deployment_id}", headers=auth, ) except requests.exceptions.RequestException as e: @@ -247,7 +244,7 @@ def get_alarms(deployment_id, profile="telemetry"): if alarms: return alarms - return "No alarms defined for deployment: {}".format(deployment_id) + return f"No alarms defined for deployment: {deployment_id}" else: # Non 200 response, sent back the error response' return { @@ -275,7 +272,7 @@ def create_alarm(deployment_id, metric_name, data, api_key=None, profile="teleme auth = _auth(api_key, profile) request_uri = _get_telemetry_base(profile) + "/alerts" - key = "telemetry.{}.alerts".format(deployment_id) + key = f"telemetry.{deployment_id}.alerts" # set the notification channels if not already set post_body = { @@ -421,12 +418,12 @@ def delete_alarms( if not alert_ids: return ( False, - "failed to find alert associated with deployment: {}".format(deployment_id), + f"failed to find alert associated with deployment: {deployment_id}", ) failed_to_delete = [] for id in alert_ids: - delete_url = _get_telemetry_base(profile) + "/alerts/{}".format(id) + delete_url = _get_telemetry_base(profile) + f"/alerts/{id}" try: response = requests.delete(delete_url, headers=auth) diff --git a/salt/modules/testinframod.py b/salt/modules/testinframod.py index eb7254a09d6..bac95da5c65 100644 --- a/salt/modules/testinframod.py +++ b/salt/modules/testinframod.py @@ -150,7 +150,7 @@ def _apply_assertion(expected, result): raise return comparison(expected["expected"], result) else: - raise TypeError("Expected bool or dict but received {}".format(type(expected))) + raise TypeError(f"Expected bool or dict but received {type(expected)}") # This does not currently generate documentation from the underlying modules diff --git a/salt/modules/textfsm_mod.py b/salt/modules/textfsm_mod.py index 0e0d390b87d..e11dd5afbb7 100644 --- a/salt/modules/textfsm_mod.py +++ b/salt/modules/textfsm_mod.py @@ -195,20 +195,20 @@ def extract(template_path, raw_text=None, raw_text_file=None, saltenv="base"): fsm_handler = textfsm.TextFSM(tpl_file_handle) except textfsm.TextFSMTemplateError as tfte: log.error("Unable to parse the TextFSM template", exc_info=True) - ret[ - "comment" - ] = "Unable to parse the TextFSM template from {}: {}. Please check the logs.".format( - template_path, tfte + ret["comment"] = ( + "Unable to parse the TextFSM template from {}: {}. Please check the logs.".format( + template_path, tfte + ) ) return ret if not raw_text and raw_text_file: log.debug("Trying to read the raw input from %s", raw_text_file) raw_text = __salt__["cp.get_file_str"](raw_text_file, saltenv=saltenv) if raw_text is False: - ret[ - "comment" - ] = "Unable to read from {}. Please specify a valid input file or text.".format( - raw_text_file + ret["comment"] = ( + "Unable to read from {}. Please specify a valid input file or text.".format( + raw_text_file + ) ) log.error(ret["comment"]) return ret @@ -393,17 +393,17 @@ def index( ) platform = __grains__.get(platform_grain_name) if not platform: - ret[ - "comment" - ] = "Unable to identify the platform name using the {} grain.".format( - platform_grain_name + ret["comment"] = ( + "Unable to identify the platform name using the {} grain.".format( + platform_grain_name + ) ) return ret log.info("Using platform: %s", platform) else: - ret[ - "comment" - ] = "No platform specified, no platform grain identifier configured." + ret["comment"] = ( + "No platform specified, no platform grain identifier configured." + ) log.error(ret["comment"]) return ret if not textfsm_path: @@ -431,10 +431,10 @@ def index( ) log.debug("Cache fun return:\n%s", textfsm_cachedir_ret) if not textfsm_cachedir_ret: - ret[ - "comment" - ] = "Unable to fetch from {}. Is the TextFSM path correctly specified?".format( - textfsm_path + ret["comment"] = ( + "Unable to fetch from {}. Is the TextFSM path correctly specified?".format( + textfsm_path + ) ) log.error(ret["comment"]) return ret @@ -457,10 +457,10 @@ def index( log.debug("Processing the output from %s", output_file) output = __salt__["cp.get_file_str"](output_file, saltenv=saltenv) if output is False: - ret[ - "comment" - ] = "Unable to read from {}. Please specify a valid file or text.".format( - output_file + ret["comment"] = ( + "Unable to read from {}. Please specify a valid file or text.".format( + output_file + ) ) log.error(ret["comment"]) return ret @@ -476,5 +476,5 @@ def index( ret["result"] = True except clitable.CliTableError as cterr: log.error("Unable to proces the CliTable", exc_info=True) - ret["comment"] = "Unable to process the output: {}".format(cterr) + ret["comment"] = f"Unable to process the output: {cterr}" return ret diff --git a/salt/modules/timezone.py b/salt/modules/timezone.py index 9835e0551f6..115ec06eeef 100644 --- a/salt/modules/timezone.py +++ b/salt/modules/timezone.py @@ -2,7 +2,6 @@ Module for managing timezone on POSIX-like systems. """ - import errno import filecmp import logging diff --git a/salt/modules/tls.py b/salt/modules/tls.py index b74b765cfbb..2cc3c09119a 100644 --- a/salt/modules/tls.py +++ b/salt/modules/tls.py @@ -169,7 +169,7 @@ def _microtime(): """ val1, val2 = math.modf(time.time()) val2 = int(val2) - return "{:f}{}".format(val1, val2) + return f"{val1:f}{val2}" def _context_or_config(key): @@ -249,7 +249,7 @@ def _new_serial(ca_name): # record the hash somewhere cachedir = __opts__["cachedir"] log.debug("cachedir: %s", cachedir) - serial_file = "{}/{}.serial".format(cachedir, ca_name) + serial_file = f"{cachedir}/{ca_name}.serial" if not os.path.exists(cachedir): os.makedirs(cachedir) if not os.path.exists(serial_file): @@ -271,9 +271,9 @@ def _get_basic_info(ca_name, cert, ca_dir=None): Get basic info to write out to the index.txt """ if ca_dir is None: - ca_dir = "{}/{}".format(_cert_base_path(), ca_name) + ca_dir = f"{_cert_base_path()}/{ca_name}" - index_file = "{}/index.txt".format(ca_dir) + index_file = f"{ca_dir}/index.txt" cert = _read_cert(cert) expire_date = _four_digit_year_to_two_digit(_get_expiration_date(cert)) @@ -283,9 +283,7 @@ def _get_basic_info(ca_name, cert, ca_dir=None): subject = "/" # then we can add the rest of the subject - subject += "/".join( - ["{}={}".format(x, y) for x, y in cert.get_subject().get_components()] - ) + subject += "/".join([f"{x}={y}" for x, y in cert.get_subject().get_components()]) subject += "\n" return (index_file, expire_date, serial_number, subject) @@ -302,7 +300,7 @@ def _write_cert_to_database(ca_name, cert, cacert_path=None, status="V"): certificate to be recorded """ set_ca_path(cacert_path) - ca_dir = "{}/{}".format(cert_base_path(), ca_name) + ca_dir = f"{cert_base_path()}/{ca_name}" index_file, expire_date, serial_number, subject = _get_basic_info( ca_name, cert, ca_dir ) @@ -338,9 +336,9 @@ def maybe_fix_ssl_version(ca_name, cacert_path=None, ca_filename=None): """ set_ca_path(cacert_path) if not ca_filename: - ca_filename = "{}_ca_cert".format(ca_name) - certp = "{}/{}/{}.crt".format(cert_base_path(), ca_name, ca_filename) - ca_keyp = "{}/{}/{}.key".format(cert_base_path(), ca_name, ca_filename) + ca_filename = f"{ca_name}_ca_cert" + certp = f"{cert_base_path()}/{ca_name}/{ca_filename}.crt" + ca_keyp = f"{cert_base_path()}/{ca_name}/{ca_filename}.key" with salt.utils.files.fopen(certp) as fic: cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, fic.read()) if cert.get_version() == 3: @@ -398,8 +396,8 @@ def ca_exists(ca_name, cacert_path=None, ca_filename=None): """ set_ca_path(cacert_path) if not ca_filename: - ca_filename = "{}_ca_cert".format(ca_name) - certp = "{}/{}/{}.crt".format(cert_base_path(), ca_name, ca_filename) + ca_filename = f"{ca_name}_ca_cert" + certp = f"{cert_base_path()}/{ca_name}/{ca_filename}.crt" if os.path.exists(certp): maybe_fix_ssl_version(ca_name, cacert_path=cacert_path, ca_filename=ca_filename) return True @@ -431,7 +429,7 @@ def get_ca(ca_name, as_text=False, cacert_path=None): set_ca_path(cacert_path) certp = "{0}/{1}/{1}_ca_cert.crt".format(cert_base_path(), ca_name) if not os.path.exists(certp): - raise ValueError("Certificate does not exist for {}".format(ca_name)) + raise ValueError(f"Certificate does not exist for {ca_name}") else: if as_text: with salt.utils.files.fopen(certp) as fic: @@ -468,9 +466,9 @@ def get_ca_signed_cert( if not cert_filename: cert_filename = CN - certp = "{}/{}/certs/{}.crt".format(cert_base_path(), ca_name, cert_filename) + certp = f"{cert_base_path()}/{ca_name}/certs/{cert_filename}.crt" if not os.path.exists(certp): - raise ValueError("Certificate does not exists for {}".format(CN)) + raise ValueError(f"Certificate does not exists for {CN}") else: if as_text: with salt.utils.files.fopen(certp) as fic: @@ -512,9 +510,9 @@ def get_ca_signed_key( if not key_filename: key_filename = CN - keyp = "{}/{}/certs/{}.key".format(cert_base_path(), ca_name, key_filename) + keyp = f"{cert_base_path()}/{ca_name}/certs/{key_filename}.key" if not os.path.exists(keyp): - raise ValueError("Certificate does not exists for {}".format(CN)) + raise ValueError(f"Certificate does not exists for {CN}") else: if as_text: with salt.utils.files.fopen(keyp) as fic: @@ -559,10 +557,10 @@ def validate(cert, ca_name, crl_file): cert_obj = _read_cert(cert) if cert_obj is None: raise CommandExecutionError( - "Failed to read cert from {}, see log for details".format(cert) + f"Failed to read cert from {cert}, see log for details" ) - ca_dir = "{}/{}".format(cert_base_path(), ca_name) - ca_cert = _read_cert("{}/{}_ca_cert.crt".format(ca_dir, ca_name)) + ca_dir = f"{cert_base_path()}/{ca_name}" + ca_cert = _read_cert(f"{ca_dir}/{ca_name}_ca_cert.crt") store.add_cert(ca_cert) # These flags tell OpenSSL to check the leaf as well as the # entire cert chain. @@ -594,7 +592,7 @@ def _get_expiration_date(cert): if cert_obj is None: raise CommandExecutionError( - "Failed to read cert from {}, see log for details".format(cert) + f"Failed to read cert from {cert}, see log for details" ) return datetime.strptime( @@ -734,18 +732,18 @@ def create_ca( set_ca_path(cacert_path) if not ca_filename: - ca_filename = "{}_ca_cert".format(ca_name) + ca_filename = f"{ca_name}_ca_cert" - certp = "{}/{}/{}.crt".format(cert_base_path(), ca_name, ca_filename) - ca_keyp = "{}/{}/{}.key".format(cert_base_path(), ca_name, ca_filename) + certp = f"{cert_base_path()}/{ca_name}/{ca_filename}.crt" + ca_keyp = f"{cert_base_path()}/{ca_name}/{ca_filename}.key" if not replace and not fixmode and ca_exists(ca_name, ca_filename=ca_filename): - return 'Certificate for CA named "{}" already exists'.format(ca_name) + return f'Certificate for CA named "{ca_name}" already exists' if fixmode and not os.path.exists(certp): - raise ValueError("{} does not exists, can't fix".format(certp)) + raise ValueError(f"{certp} does not exists, can't fix") - if not os.path.exists("{}/{}".format(cert_base_path(), ca_name)): - os.makedirs("{}/{}".format(cert_base_path(), ca_name)) + if not os.path.exists(f"{cert_base_path()}/{ca_name}"): + os.makedirs(f"{cert_base_path()}/{ca_name}") # try to reuse existing ssl key key = None @@ -932,9 +930,7 @@ def get_extensions(cert_type): # possible user-defined profile or a typo if cert_type not in ext: try: - ext[cert_type] = __salt__["pillar.get"]( - "tls.extensions:{}".format(cert_type) - ) + ext[cert_type] = __salt__["pillar.get"](f"tls.extensions:{cert_type}") except NameError as e: log.debug( "pillar, tls:extensions:%s not available or " @@ -1071,7 +1067,7 @@ def create_csr( set_ca_path(cacert_path) if not ca_filename: - ca_filename = "{}_ca_cert".format(ca_name) + ca_filename = f"{ca_name}_ca_cert" if not ca_exists(ca_name, ca_filename=ca_filename): return 'Certificate for CA named "{}" does not exist, please create it first.'.format( @@ -1079,20 +1075,20 @@ def create_csr( ) if not csr_path: - csr_path = "{}/{}/certs/".format(cert_base_path(), ca_name) + csr_path = f"{cert_base_path()}/{ca_name}/certs/" if not os.path.exists(csr_path): os.makedirs(csr_path) - CN_ext = "_{}".format(cert_type) if type_ext else "" + CN_ext = f"_{cert_type}" if type_ext else "" if not csr_filename: - csr_filename = "{}{}".format(CN, CN_ext) + csr_filename = f"{CN}{CN_ext}" - csr_f = "{}/{}.csr".format(csr_path, csr_filename) + csr_f = f"{csr_path}/{csr_filename}.csr" if not replace and os.path.exists(csr_f): - return 'Certificate Request "{}" already exists'.format(csr_f) + return f'Certificate Request "{csr_f}" already exists' key = OpenSSL.crypto.PKey() key.generate_key(OpenSSL.crypto.TYPE_RSA, bits) @@ -1153,7 +1149,7 @@ def create_csr( req.sign(key, salt.utils.stringutils.to_str(digest)) # Write private key and request - priv_keyp = "{}/{}.key".format(csr_path, csr_filename) + priv_keyp = f"{csr_path}/{csr_filename}.key" fp = os.open(priv_keyp, os.O_CREAT | os.O_RDWR, 0o600) with salt.utils.files.fopen(fp, "wb+") as priv_key: priv_key.write( @@ -1171,8 +1167,8 @@ def create_csr( ) ) - ret = 'Created Private Key: "{}{}.key" '.format(csr_path, csr_filename) - ret += 'Created CSR for "{}": "{}{}.csr"'.format(CN, csr_path, csr_filename) + ret = f'Created Private Key: "{csr_path}{csr_filename}.key" ' + ret += f'Created CSR for "{CN}": "{csr_path}{csr_filename}.csr"' return ret @@ -1255,16 +1251,16 @@ def create_self_signed_cert( """ set_ca_path(cacert_path) - if not os.path.exists("{}/{}/certs/".format(cert_base_path(), tls_dir)): - os.makedirs("{}/{}/certs/".format(cert_base_path(), tls_dir)) + if not os.path.exists(f"{cert_base_path()}/{tls_dir}/certs/"): + os.makedirs(f"{cert_base_path()}/{tls_dir}/certs/") if not cert_filename: cert_filename = CN if not replace and os.path.exists( - "{}/{}/certs/{}.crt".format(cert_base_path(), tls_dir, cert_filename) + f"{cert_base_path()}/{tls_dir}/certs/{cert_filename}.crt" ): - return 'Certificate "{}" already exists'.format(cert_filename) + return f'Certificate "{cert_filename}" already exists' key = OpenSSL.crypto.PKey() key.generate_key(OpenSSL.crypto.TYPE_RSA, bits) @@ -1303,7 +1299,7 @@ def create_self_signed_cert( ) ) - crt_path = "{}/{}/certs/{}.crt".format(cert_base_path(), tls_dir, cert_filename) + crt_path = f"{cert_base_path()}/{tls_dir}/certs/{cert_filename}.crt" with salt.utils.files.fopen(crt_path, "wb+") as crt: crt.write( salt.utils.stringutils.to_bytes( @@ -1431,10 +1427,10 @@ def create_ca_signed_cert( set_ca_path(cacert_path) if not ca_filename: - ca_filename = "{}_ca_cert".format(ca_name) + ca_filename = f"{ca_name}_ca_cert" if not cert_path: - cert_path = "{}/{}/certs".format(cert_base_path(), ca_name) + cert_path = f"{cert_base_path()}/{ca_name}/certs" if type_ext: if not cert_type: @@ -1443,14 +1439,14 @@ def create_ca_signed_cert( ) return ret elif cert_type: - CN_ext = "_{}".format(cert_type) + CN_ext = f"_{cert_type}" else: CN_ext = "" - csr_filename = "{}{}".format(CN, CN_ext) + csr_filename = f"{CN}{CN_ext}" if not cert_filename: - cert_filename = "{}{}".format(CN, CN_ext) + cert_filename = f"{CN}{CN_ext}" if not replace and os.path.exists( os.path.join( @@ -1461,29 +1457,29 @@ def create_ca_signed_cert( ) ) ): - return 'Certificate "{}" already exists'.format(cert_filename) + return f'Certificate "{cert_filename}" already exists' try: maybe_fix_ssl_version(ca_name, cacert_path=cacert_path, ca_filename=ca_filename) with salt.utils.files.fopen( - "{}/{}/{}.crt".format(cert_base_path(), ca_name, ca_filename) + f"{cert_base_path()}/{ca_name}/{ca_filename}.crt" ) as fhr: ca_cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, fhr.read() ) with salt.utils.files.fopen( - "{}/{}/{}.key".format(cert_base_path(), ca_name, ca_filename) + f"{cert_base_path()}/{ca_name}/{ca_filename}.key" ) as fhr: ca_key = OpenSSL.crypto.load_privatekey( OpenSSL.crypto.FILETYPE_PEM, fhr.read() ) except OSError: ret["retcode"] = 1 - ret["comment"] = 'There is no CA named "{}"'.format(ca_name) + ret["comment"] = f'There is no CA named "{ca_name}"' return ret try: - csr_path = "{}/{}.csr".format(cert_path, csr_filename) + csr_path = f"{cert_path}/{csr_filename}.csr" with salt.utils.files.fopen(csr_path) as fhr: req = OpenSSL.crypto.load_certificate_request( OpenSSL.crypto.FILETYPE_PEM, fhr.read() @@ -1539,7 +1535,7 @@ def create_ca_signed_cert( cert.sign(ca_key, salt.utils.stringutils.to_str(digest)) - cert_full_path = "{}/{}.crt".format(cert_path, cert_filename) + cert_full_path = f"{cert_path}/{cert_filename}.crt" with salt.utils.files.fopen(cert_full_path, "wb+") as crt: crt.write( @@ -1590,10 +1586,8 @@ def create_pkcs12(ca_name, CN, passphrase="", cacert_path=None, replace=False): salt '*' tls.create_pkcs12 test localhost """ set_ca_path(cacert_path) - if not replace and os.path.exists( - "{}/{}/certs/{}.p12".format(cert_base_path(), ca_name, CN) - ): - return 'Certificate "{}" already exists'.format(CN) + if not replace and os.path.exists(f"{cert_base_path()}/{ca_name}/certs/{CN}.p12"): + return f'Certificate "{CN}" already exists' try: with salt.utils.files.fopen( @@ -1603,23 +1597,23 @@ def create_pkcs12(ca_name, CN, passphrase="", cacert_path=None, replace=False): OpenSSL.crypto.FILETYPE_PEM, fhr.read() ) except OSError: - return 'There is no CA named "{}"'.format(ca_name) + return f'There is no CA named "{ca_name}"' try: with salt.utils.files.fopen( - "{}/{}/certs/{}.crt".format(cert_base_path(), ca_name, CN) + f"{cert_base_path()}/{ca_name}/certs/{CN}.crt" ) as fhr: cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, fhr.read() ) with salt.utils.files.fopen( - "{}/{}/certs/{}.key".format(cert_base_path(), ca_name, CN) + f"{cert_base_path()}/{ca_name}/certs/{CN}.key" ) as fhr: key = OpenSSL.crypto.load_privatekey( OpenSSL.crypto.FILETYPE_PEM, fhr.read() ) except OSError: - return 'There is no certificate that matches the CN "{}"'.format(CN) + return f'There is no certificate that matches the CN "{CN}"' pkcs12 = OpenSSL.crypto.PKCS12() @@ -1628,7 +1622,7 @@ def create_pkcs12(ca_name, CN, passphrase="", cacert_path=None, replace=False): pkcs12.set_privatekey(key) with salt.utils.files.fopen( - "{}/{}/certs/{}.p12".format(cert_base_path(), ca_name, CN), "wb" + f"{cert_base_path()}/{ca_name}/certs/{CN}.p12", "wb" ) as ofile: ofile.write( pkcs12.export(passphrase=salt.utils.stringutils.to_bytes(passphrase)) @@ -1780,29 +1774,29 @@ def create_empty_crl( set_ca_path(cacert_path) if not ca_filename: - ca_filename = "{}_ca_cert".format(ca_name) + ca_filename = f"{ca_name}_ca_cert" if not crl_file: - crl_file = "{}/{}/crl.pem".format(_cert_base_path(), ca_name) + crl_file = f"{_cert_base_path()}/{ca_name}/crl.pem" - if os.path.exists("{}".format(crl_file)): - return 'CRL "{}" already exists'.format(crl_file) + if os.path.exists(f"{crl_file}"): + return f'CRL "{crl_file}" already exists' try: with salt.utils.files.fopen( - "{}/{}/{}.crt".format(cert_base_path(), ca_name, ca_filename) + f"{cert_base_path()}/{ca_name}/{ca_filename}.crt" ) as fp_: ca_cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, fp_.read() ) with salt.utils.files.fopen( - "{}/{}/{}.key".format(cert_base_path(), ca_name, ca_filename) + f"{cert_base_path()}/{ca_name}/{ca_filename}.key" ) as fp_: ca_key = OpenSSL.crypto.load_privatekey( OpenSSL.crypto.FILETYPE_PEM, fp_.read() ) except OSError: - return 'There is no CA named "{}"'.format(ca_name) + return f'There is no CA named "{ca_name}"' crl = OpenSSL.crypto.CRL() crl_text = crl.export( @@ -1814,7 +1808,7 @@ def create_empty_crl( with salt.utils.files.fopen(crl_file, "w") as f: f.write(salt.utils.stringutils.to_str(crl_text)) - return 'Created an empty CRL: "{}"'.format(crl_file) + return f'Created an empty CRL: "{crl_file}"' def revoke_cert( @@ -1870,43 +1864,43 @@ def revoke_cert( """ set_ca_path(cacert_path) - ca_dir = "{}/{}".format(cert_base_path(), ca_name) + ca_dir = f"{cert_base_path()}/{ca_name}" if ca_filename is None: - ca_filename = "{}_ca_cert".format(ca_name) + ca_filename = f"{ca_name}_ca_cert" if cert_path is None: - cert_path = "{}/{}/certs".format(_cert_base_path(), ca_name) + cert_path = f"{_cert_base_path()}/{ca_name}/certs" if cert_filename is None: - cert_filename = "{}".format(CN) + cert_filename = f"{CN}" try: with salt.utils.files.fopen( - "{}/{}/{}.crt".format(cert_base_path(), ca_name, ca_filename) + f"{cert_base_path()}/{ca_name}/{ca_filename}.crt" ) as fp_: ca_cert = OpenSSL.crypto.load_certificate( OpenSSL.crypto.FILETYPE_PEM, fp_.read() ) with salt.utils.files.fopen( - "{}/{}/{}.key".format(cert_base_path(), ca_name, ca_filename) + f"{cert_base_path()}/{ca_name}/{ca_filename}.key" ) as fp_: ca_key = OpenSSL.crypto.load_privatekey( OpenSSL.crypto.FILETYPE_PEM, fp_.read() ) except OSError: - return 'There is no CA named "{}"'.format(ca_name) + return f'There is no CA named "{ca_name}"' - client_cert = _read_cert("{}/{}.crt".format(cert_path, cert_filename)) + client_cert = _read_cert(f"{cert_path}/{cert_filename}.crt") if client_cert is None: - return 'There is no client certificate named "{}"'.format(CN) + return f'There is no client certificate named "{CN}"' index_file, expire_date, serial_number, subject = _get_basic_info( ca_name, client_cert, ca_dir ) - index_serial_subject = "{}\tunknown\t{}".format(serial_number, subject) - index_v_data = "V\t{}\t\t{}".format(expire_date, index_serial_subject) + index_serial_subject = f"{serial_number}\tunknown\t{subject}" + index_v_data = f"V\t{expire_date}\t\t{index_serial_subject}" index_r_data_pattern = re.compile( r"R\t" + expire_date + r"\t\d{12}Z\t" + re.escape(index_serial_subject) ) @@ -1929,10 +1923,10 @@ def revoke_cert( ) except ValueError: ret["retcode"] = 1 - ret[ - "comment" - ] = "Revocation date '{}' does not matchformat '{}'".format( - revoke_date, two_digit_year_fmt + ret["comment"] = ( + "Revocation date '{}' does not matchformat '{}'".format( + revoke_date, two_digit_year_fmt + ) ) return ret elif index_serial_subject in line: @@ -1963,11 +1957,11 @@ def revoke_cert( ) if crl_file is None: - crl_file = "{}/{}/crl.pem".format(_cert_base_path(), ca_name) + crl_file = f"{_cert_base_path()}/{ca_name}/crl.pem" if os.path.isdir(crl_file): ret["retcode"] = 1 - ret["comment"] = 'crl_file "{}" is an existing directory'.format(crl_file) + ret["comment"] = f'crl_file "{crl_file}" is an existing directory' return ret with salt.utils.files.fopen(crl_file, "w") as fp_: diff --git a/salt/modules/tomcat.py b/salt/modules/tomcat.py index 46451508c50..1a15fa83627 100644 --- a/salt/modules/tomcat.py +++ b/salt/modules/tomcat.py @@ -214,11 +214,11 @@ def _wget(cmd, opts=None, url="http://localhost:8080/manager", timeout=180): if url[-1] != "/": url += "/" url6 = url - url += "text/{}".format(cmd) - url6 += "{}".format(cmd) + url += f"text/{cmd}" + url6 += f"{cmd}" if opts: - url += "?{}".format(urllib.parse.urlencode(opts)) - url6 += "?{}".format(urllib.parse.urlencode(opts)) + url += f"?{urllib.parse.urlencode(opts)}" + url6 += f"?{urllib.parse.urlencode(opts)}" # Make the HTTP request urllib.request.install_opener(auth) @@ -257,7 +257,7 @@ def _simple_cmd(cmd, app, url="http://localhost:8080/manager", timeout=180): opts = {"path": app, "version": ls(url)[app]["version"]} return "\n".join(_wget(cmd, opts, url, timeout=timeout)["msg"]) except Exception: # pylint: disable=broad-except - return "FAIL - No context exists for path {}".format(app) + return f"FAIL - No context exists for path {app}" # Functions @@ -565,10 +565,10 @@ def deploy_war( salt '*' tomcat.deploy_war /tmp/application.war /api yes http://localhost:8080/manager """ # Decide the location to copy the war for the deployment - tfile = "salt.{}".format(os.path.basename(war)) + tfile = f"salt.{os.path.basename(war)}" if temp_war_location is not None: if not os.path.isdir(temp_war_location): - return 'Error - "{}" is not a directory'.format(temp_war_location) + return f'Error - "{temp_war_location}" is not a directory' tfile = os.path.join(temp_war_location, tfile) else: tfile = os.path.join(tempfile.gettempdir(), tfile) @@ -589,7 +589,7 @@ def deploy_war( # Prepare options opts = { - "war": "file:{}".format(tfile), + "war": f"file:{tfile}", "path": context, } @@ -710,7 +710,7 @@ def signal(signal=None): if signal not in valid_signals: return - cmd = "{}/bin/catalina.sh {}".format(__catalina_home(), valid_signals[signal]) + cmd = f"{__catalina_home()}/bin/catalina.sh {valid_signals[signal]}" __salt__["cmd.run"](cmd) diff --git a/salt/modules/travisci.py b/salt/modules/travisci.py index 70672403b5b..100890e103a 100644 --- a/salt/modules/travisci.py +++ b/salt/modules/travisci.py @@ -3,6 +3,7 @@ Commands for working with travisci. :depends: pyOpenSSL >= 16.0.0 """ + import base64 import urllib.parse diff --git a/salt/modules/udev.py b/salt/modules/udev.py index 9a734edf4b7..0e4a7473eda 100644 --- a/salt/modules/udev.py +++ b/salt/modules/udev.py @@ -97,7 +97,7 @@ def info(dev): else: qtype = "name" - cmd = "udevadm info --export --query=all --{}={}".format(qtype, dev) + cmd = f"udevadm info --export --query=all --{qtype}={dev}" udev_result = __salt__["cmd.run_all"](cmd, output_loglevel="quiet") if udev_result["retcode"] != 0: diff --git a/salt/modules/upstart_service.py b/salt/modules/upstart_service.py index ee47f6d002a..c59da325e3d 100644 --- a/salt/modules/upstart_service.py +++ b/salt/modules/upstart_service.py @@ -159,7 +159,7 @@ def _runlevel(): ret = _default_runlevel() utmp = _find_utmp() if utmp: - out = __salt__["cmd.run"](["runlevel", "{}".format(utmp)], python_shell=False) + out = __salt__["cmd.run"](["runlevel", f"{utmp}"], python_shell=False) try: ret = out.split()[1] except IndexError: @@ -180,7 +180,7 @@ def _service_is_upstart(name): Jobs are defined in files placed in /etc/init, the name of the job is the filename under this directory without the .conf extension. """ - return os.access("/etc/init/{}.conf".format(name), os.R_OK) + return os.access(f"/etc/init/{name}.conf", os.R_OK) def _upstart_is_disabled(name): @@ -190,7 +190,7 @@ def _upstart_is_disabled(name): NOTE: An Upstart service can also be disabled by placing "manual" in /etc/init/[name].conf. """ - files = ["/etc/init/{}.conf".format(name), "/etc/init/{}.override".format(name)] + files = [f"/etc/init/{name}.conf", f"/etc/init/{name}.override"] for file_name in filter(os.path.isfile, files): with salt.utils.files.fopen(file_name) as fp_: if re.search( @@ -217,7 +217,7 @@ def _service_is_sysv(name): to Upstart's /lib/init/upstart-job, and anything that isn't an executable, like README or skeleton. """ - script = "/etc/init.d/{}".format(name) + script = f"/etc/init.d/{name}" return not _service_is_upstart(name) and os.access(script, os.X_OK) @@ -227,7 +227,7 @@ def _sysv_is_disabled(name): start-up link (starts with "S") to its script in /etc/init.d in the current runlevel. """ - return not bool(glob.glob("/etc/rc{}.d/S*{}".format(_runlevel(), name))) + return not bool(glob.glob(f"/etc/rc{_runlevel()}.d/S*{name}")) def _sysv_is_enabled(name): @@ -508,7 +508,7 @@ def _upstart_disable(name): """ if _upstart_is_disabled(name): return _upstart_is_disabled(name) - override = "/etc/init/{}.override".format(name) + override = f"/etc/init/{name}.override" with salt.utils.files.fopen(override, "a") as ofile: ofile.write(salt.utils.stringutils.to_str("manual\n")) return _upstart_is_disabled(name) @@ -520,8 +520,8 @@ def _upstart_enable(name): """ if _upstart_is_enabled(name): return _upstart_is_enabled(name) - override = "/etc/init/{}.override".format(name) - files = ["/etc/init/{}.conf".format(name), override] + override = f"/etc/init/{name}.override" + files = [f"/etc/init/{name}.conf", override] for file_name in filter(os.path.isfile, files): with salt.utils.files.fopen(file_name, "r+") as fp_: new_text = re.sub( @@ -552,7 +552,7 @@ def enable(name, **kwargs): if _service_is_upstart(name): return _upstart_enable(name) executable = _get_service_exec() - cmd = "{} -f {} defaults".format(executable, name) + cmd = f"{executable} -f {name} defaults" return not __salt__["cmd.retcode"](cmd, python_shell=False) diff --git a/salt/modules/uptime.py b/salt/modules/uptime.py index 8e40717fa8a..e3549cc305e 100644 --- a/salt/modules/uptime.py +++ b/salt/modules/uptime.py @@ -3,7 +3,6 @@ Wrapper around uptime API ========================= """ - import logging from salt.exceptions import CommandExecutionError @@ -43,15 +42,15 @@ def create(name, **params): """ if check_exists(name): - msg = "Trying to create check that already exists : {}".format(name) + msg = f"Trying to create check that already exists : {name}" log.error(msg) raise CommandExecutionError(msg) application_url = _get_application_url() log.debug("[uptime] trying PUT request") params.update(url=name) - req = requests.put("{}/api/checks".format(application_url), data=params) + req = requests.put(f"{application_url}/api/checks", data=params) if not req.ok: - raise CommandExecutionError("request to uptime failed : {}".format(req.reason)) + raise CommandExecutionError(f"request to uptime failed : {req.reason}") log.debug("[uptime] PUT request successful") return req.json()["_id"] @@ -67,16 +66,16 @@ def delete(name): salt '*' uptime.delete http://example.org """ if not check_exists(name): - msg = "Trying to delete check that doesn't exists : {}".format(name) + msg = f"Trying to delete check that doesn't exists : {name}" log.error(msg) raise CommandExecutionError(msg) application_url = _get_application_url() log.debug("[uptime] trying DELETE request") - jcontent = requests.get("{}/api/checks".format(application_url)).json() + jcontent = requests.get(f"{application_url}/api/checks").json() url_id = [x["_id"] for x in jcontent if x["url"] == name][0] - req = requests.delete("{}/api/checks/{}".format(application_url, url_id)) + req = requests.delete(f"{application_url}/api/checks/{url_id}") if not req.ok: - raise CommandExecutionError("request to uptime failed : {}".format(req.reason)) + raise CommandExecutionError(f"request to uptime failed : {req.reason}") log.debug("[uptime] DELETE request successful") return True @@ -106,7 +105,7 @@ def checks_list(): """ application_url = _get_application_url() log.debug("[uptime] get checks") - jcontent = requests.get("{}/api/checks".format(application_url)).json() + jcontent = requests.get(f"{application_url}/api/checks").json() return [x["url"] for x in jcontent] diff --git a/salt/modules/uwsgi.py b/salt/modules/uwsgi.py index 2ede5c17da7..71ced4a4088 100644 --- a/salt/modules/uwsgi.py +++ b/salt/modules/uwsgi.py @@ -40,6 +40,6 @@ def stats(socket): salt '*' uwsgi.stats 127.0.0.1:5050 """ - cmd = ["uwsgi", "--connect-and-read", "{}".format(socket)] + cmd = ["uwsgi", "--connect-and-read", f"{socket}"] out = __salt__["cmd.run"](cmd, python_shell=False) return salt.utils.json.loads(out) diff --git a/salt/modules/vault.py b/salt/modules/vault.py index 3f888a3bc9d..0add87959cb 100644 --- a/salt/modules/vault.py +++ b/salt/modules/vault.py @@ -706,6 +706,7 @@ Minion configuration (optional): .. _vault-setup: """ + import logging import salt.utils.vault as vault diff --git a/salt/modules/vbox_guest.py b/salt/modules/vbox_guest.py index 56c576ed211..e646e4f2b86 100644 --- a/salt/modules/vbox_guest.py +++ b/salt/modules/vbox_guest.py @@ -90,19 +90,17 @@ def _return_mount_error(f): def _additions_install_program_path(mount_point): - return os.path.join( - mount_point, - { - "Linux": "VBoxLinuxAdditions.run", - "Solaris": "VBoxSolarisAdditions.pkg", - "Windows": "VBoxWindowsAdditions.exe", - }[__grains__.get("kernel", "")], - ) + mount_points = { + "Linux": "VBoxLinuxAdditions.run", + "Solaris": "VBoxSolarisAdditions.pkg", + "Windows": "VBoxWindowsAdditions.exe", + } + return os.path.join(mount_point, mount_points[__grains__.get("kernel", "")]) def _additions_install_opensuse(**kwargs): kernel_type = re.sub(r"^(\d|\.|-)*", "", __grains__.get("kernelrelease", "")) - kernel_devel = "kernel-{}-devel".format(kernel_type) + kernel_devel = f"kernel-{kernel_type}-devel" return __states__["pkg.installed"](None, pkgs=["make", "gcc", kernel_devel]) @@ -279,7 +277,7 @@ def additions_version(): except OSError: return False if d and len(os.listdir(d)) > 0: - return re.sub(r"^{}-".format(_additions_dir_prefix), "", os.path.basename(d)) + return re.sub(rf"^{_additions_dir_prefix}-", "", os.path.basename(d)) return False diff --git a/salt/modules/vboxmanage.py b/salt/modules/vboxmanage.py index 635734466a2..290de89dfe3 100644 --- a/salt/modules/vboxmanage.py +++ b/salt/modules/vboxmanage.py @@ -15,7 +15,6 @@ The default for this setting is ``False``. :depends: virtualbox """ - import logging import os.path import re @@ -86,7 +85,7 @@ def list_nodes_min(): salt '*' vboxmanage.list_nodes_min """ ret = {} - cmd = "{} list vms".format(vboxcmd()) + cmd = f"{vboxcmd()} list vms" for line in salt.modules.cmdmod.run(cmd).splitlines(): if not line.strip(): continue @@ -148,7 +147,7 @@ def start(name): salt '*' vboxmanage.start my_vm """ ret = {} - cmd = "{} startvm {}".format(vboxcmd(), name) + cmd = f"{vboxcmd()} startvm {name}" ret = salt.modules.cmdmod.run(cmd).splitlines() return ret @@ -163,7 +162,7 @@ def stop(name): salt '*' vboxmanage.stop my_vm """ - cmd = "{} controlvm {} poweroff".format(vboxcmd(), name) + cmd = f"{vboxcmd()} controlvm {name} poweroff" ret = salt.modules.cmdmod.run(cmd).splitlines() return ret @@ -180,10 +179,10 @@ def register(filename): """ if not os.path.isfile(filename): raise CommandExecutionError( - "The specified filename ({}) does not exist.".format(filename) + f"The specified filename ({filename}) does not exist." ) - cmd = "{} registervm {}".format(vboxcmd(), filename) + cmd = f"{vboxcmd()} registervm {filename}" ret = salt.modules.cmdmod.run_all(cmd) if ret["retcode"] == 0: return True @@ -202,11 +201,9 @@ def unregister(name, delete=False): """ nodes = list_nodes_min() if name not in nodes: - raise CommandExecutionError( - "The specified VM ({}) is not registered.".format(name) - ) + raise CommandExecutionError(f"The specified VM ({name}) is not registered.") - cmd = "{} unregistervm {}".format(vboxcmd(), name) + cmd = f"{vboxcmd()} unregistervm {name}" if delete is True: cmd += " --delete" ret = salt.modules.cmdmod.run_all(cmd) @@ -235,7 +232,7 @@ def create( register=True, basefolder=None, new_uuid=None, - **kwargs + **kwargs, ): """ Create a new VM @@ -248,16 +245,14 @@ def create( """ nodes = list_nodes_min() if name in nodes: - raise CommandExecutionError( - "The specified VM ({}) is already registered.".format(name) - ) + raise CommandExecutionError(f"The specified VM ({name}) is already registered.") params = "" if name: if NAME_RE.search(name): raise CommandExecutionError("New VM name contains invalid characters") - params += " --name {}".format(name) + params += f" --name {name}" if groups: if isinstance(groups, str): @@ -271,9 +266,7 @@ def create( ostypes = list_ostypes() if ostype not in ostypes: - raise CommandExecutionError( - "The specified OS type ({}) is not available.".format(name) - ) + raise CommandExecutionError(f"The specified OS type ({name}) is not available.") else: params += " --ostype " + ostype @@ -282,17 +275,15 @@ def create( if basefolder: if not os.path.exists(basefolder): - raise CommandExecutionError( - "basefolder {} was not found".format(basefolder) - ) - params += " --basefolder {}".format(basefolder) + raise CommandExecutionError(f"basefolder {basefolder} was not found") + params += f" --basefolder {basefolder}" if new_uuid: if NAME_RE.search(new_uuid): raise CommandExecutionError("New UUID contains invalid characters") - params += " --uuid {}".format(new_uuid) + params += f" --uuid {new_uuid}" - cmd = "{} create {}".format(vboxcmd(), params) + cmd = f"{vboxcmd()} create {params}" ret = salt.modules.cmdmod.run_all(cmd) if ret["retcode"] == 0: return True @@ -311,7 +302,7 @@ def clonevm( new_uuid=None, register=False, groups=None, - **kwargs + **kwargs, ): """ Clone a new VM from an existing VM @@ -332,15 +323,11 @@ def clonevm( nodes_uuids = list_items("vms", True, "UUID").keys() if name: if name not in nodes_names: - raise CommandExecutionError( - "The specified VM ({}) is not registered.".format(name) - ) + raise CommandExecutionError(f"The specified VM ({name}) is not registered.") params += " " + name elif uuid: if uuid not in nodes_uuids: - raise CommandExecutionError( - "The specified VM ({}) is not registered.".format(name) - ) + raise CommandExecutionError(f"The specified VM ({name}) is not registered.") params += " " + uuid if snapshot_name and snapshot_uuid: @@ -351,11 +338,11 @@ def clonevm( if snapshot_name: if NAME_RE.search(snapshot_name): raise CommandExecutionError("Snapshot name contains invalid characters") - params += " --snapshot {}".format(snapshot_name) + params += f" --snapshot {snapshot_name}" elif snapshot_uuid: if UUID_RE.search(snapshot_uuid): raise CommandExecutionError("Snapshot name contains invalid characters") - params += " --snapshot {}".format(snapshot_uuid) + params += f" --snapshot {snapshot_uuid}" valid_modes = ("machine", "machineandchildren", "all") if mode and mode not in valid_modes: @@ -376,7 +363,7 @@ def clonevm( if new_name: if NAME_RE.search(new_name): raise CommandExecutionError("New name contains invalid characters") - params += " --name {}".format(new_name) + params += f" --name {new_name}" if groups: if isinstance(groups, str): @@ -390,20 +377,18 @@ def clonevm( if basefolder: if not os.path.exists(basefolder): - raise CommandExecutionError( - "basefolder {} was not found".format(basefolder) - ) - params += " --basefolder {}".format(basefolder) + raise CommandExecutionError(f"basefolder {basefolder} was not found") + params += f" --basefolder {basefolder}" if new_uuid: if NAME_RE.search(new_uuid): raise CommandExecutionError("New UUID contains invalid characters") - params += " --uuid {}".format(new_uuid) + params += f" --uuid {new_uuid}" if register is True: params += " --register" - cmd = "{} clonevm {}".format(vboxcmd(), name) + cmd = f"{vboxcmd()} clonevm {name}" ret = salt.modules.cmdmod.run_all(cmd) if ret["retcode"] == 0: return True @@ -419,7 +404,7 @@ def clonemedium( mformat=None, variant=None, existing=False, - **kwargs + **kwargs, ): """ Clone a new VM from an existing VM @@ -455,11 +440,11 @@ def clonemedium( items = list_items(item) if uuid_in not in items: - raise CommandExecutionError("UUID {} was not found".format(uuid_in)) + raise CommandExecutionError(f"UUID {uuid_in} was not found") params += " " + uuid_in elif file_in: if not os.path.exists(file_in): - raise CommandExecutionError("File {} was not found".format(file_in)) + raise CommandExecutionError(f"File {file_in} was not found") params += " " + file_in if (uuid_out and file_out) or (not uuid_out and not file_out): @@ -477,7 +462,7 @@ def clonemedium( os.unlink(file_out) params += " " + file_out except OSError: - raise CommandExecutionError("{} is not a valid filename".format(file_out)) + raise CommandExecutionError(f"{file_out} is not a valid filename") if mformat: valid_mformat = ("VDI", "VMDK", "VHD", "RAW") @@ -504,7 +489,7 @@ def clonemedium( if existing: params += " --existing" - cmd = "{} clonemedium {}".format(vboxcmd(), params) + cmd = f"{vboxcmd()} clonemedium {params}" ret = salt.modules.cmdmod.run_all(cmd) if ret["retcode"] == 0: return True @@ -587,7 +572,7 @@ def list_items(item, details=False, group_by="UUID"): ret = {} tmp_id = None tmp_dict = {} - cmd = "{} list{} {}".format(vboxcmd(), flag, item) + cmd = f"{vboxcmd()} list{flag} {item}" for line in salt.modules.cmdmod.run(cmd).splitlines(): if not line.strip(): continue diff --git a/salt/modules/victorops.py b/salt/modules/victorops.py index c5288355579..058e0f3ed4a 100644 --- a/salt/modules/victorops.py +++ b/salt/modules/victorops.py @@ -11,7 +11,6 @@ Requires an ``api_key`` in ``/etc/salt/minion``: api_key: '280d4699-a817-4719-ba6f-ca56e573e44f' """ - import datetime import logging import time @@ -49,10 +48,10 @@ def _query( path = "https://alert.victorops.com/integrations/generic/20131114/" if action: - path += "{}/".format(action) + path += f"{action}/" if api_key: - path += "{}/".format(api_key) + path += f"{api_key}/" if routing_key: path += routing_key diff --git a/salt/modules/virt.py b/salt/modules/virt.py index 1e671621c25..d7d7cfe65a6 100644 --- a/salt/modules/virt.py +++ b/salt/modules/virt.py @@ -116,6 +116,7 @@ ZB 10**21 YB 10**24 ====== ======= """ + # Special Thanks to Michael Dehann, many of the concepts, and a few structures # of his in the virt func module have been used @@ -298,9 +299,7 @@ def _get_domain(conn, *vms, **kwargs): if vms: for name in vms: if name not in all_vms: - raise CommandExecutionError( - 'The VM "{name}" is not present'.format(name=name) - ) + raise CommandExecutionError(f'The VM "{name}" is not present') else: lookup_vms.append(name) else: @@ -324,9 +323,9 @@ def _parse_qemu_img_info(info): "file format": disk_infos["format"], "disk size": disk_infos["actual-size"], "virtual size": disk_infos["virtual-size"], - "cluster size": disk_infos["cluster-size"] - if "cluster-size" in disk_infos - else None, + "cluster size": ( + disk_infos["cluster-size"] if "cluster-size" in disk_infos else None + ), } if "full-backing-filename" in disk_infos.keys(): @@ -515,7 +514,7 @@ def _get_disks(conn, dom): disk_type = elem.get("type") def _get_disk_volume_data(pool_name, volume_name): - qemu_target = "{}/{}".format(pool_name, volume_name) + qemu_target = f"{pool_name}/{volume_name}" pool = conn.storagePoolLookupByName(pool_name) extra_properties = {} try: @@ -553,9 +552,9 @@ def _get_disks(conn, dom): "file": backing_path.text } if backing_format is not None: - extra_properties["backing file"][ - "file format" - ] = backing_format.get("type") + extra_properties["backing file"]["file format"] = ( + backing_format.get("type") + ) except libvirt.libvirtError: # The volume won't be found if the pool is not started, just output less infos log.info( @@ -614,7 +613,7 @@ def _get_disks(conn, dom): qemu_target = source.get("protocol") source_name = source.get("name") if source_name: - qemu_target = "{}:{}".format(qemu_target, source_name) + qemu_target = f"{qemu_target}:{source_name}" # Reverse the magic for the rbd and gluster pools if source.get("protocol") in ["rbd", "gluster"]: @@ -622,7 +621,7 @@ def _get_disks(conn, dom): pool_i_xml = ElementTree.fromstring(pool_i.XMLDesc()) name_node = pool_i_xml.find("source/name") if name_node is not None and source_name.startswith( - "{}/".format(name_node.text) + f"{name_node.text}/" ): qemu_target = "{}{}".format( pool_i.name(), source_name[len(name_node.text) :] @@ -638,7 +637,7 @@ def _get_disks(conn, dom): qemu_target = urllib.parse.urlunparse( ( source.get("protocol"), - "{}:{}".format(hostname, port) if port else hostname, + f"{hostname}:{port}" if port else hostname, source_name, "", saxutils.unescape(source.get("query", "")), @@ -743,9 +742,7 @@ def _migrate(dom, dst_uri, **kwargs): try: bandwidth_value = int(max_bandwidth) except ValueError: - raise SaltInvocationError( - "Invalid max_bandwidth value: {}".format(max_bandwidth) - ) + raise SaltInvocationError(f"Invalid max_bandwidth value: {max_bandwidth}") dom.migrateSetMaxSpeed(bandwidth_value) max_downtime = kwargs.get("max_downtime") @@ -753,9 +750,7 @@ def _migrate(dom, dst_uri, **kwargs): try: downtime_value = int(max_downtime) except ValueError: - raise SaltInvocationError( - "Invalid max_downtime value: {}".format(max_downtime) - ) + raise SaltInvocationError(f"Invalid max_downtime value: {max_downtime}") dom.migrateSetMaxDowntime(downtime_value) if kwargs.get("offline") is True: @@ -776,13 +771,13 @@ def _migrate(dom, dst_uri, **kwargs): "comp_xbzrle_cache": libvirt.VIR_MIGRATE_PARAM_COMPRESSION_XBZRLE_CACHE, } - for (comp_option, param_key) in comp_options.items(): + for comp_option, param_key in comp_options.items(): comp_option_value = kwargs.get(comp_option) if comp_option_value: try: params[param_key] = int(comp_option_value) except ValueError: - raise SaltInvocationError("Invalid {} value".format(comp_option)) + raise SaltInvocationError(f"Invalid {comp_option} value") parallel_connections = kwargs.get("parallel_connections") if parallel_connections: @@ -888,7 +883,7 @@ def _disk_from_pool(conn, pool, pool_xml, volume_name): # Gluster and RBD need pool/volume name name_node = pool_xml.find("./source/name") if name_node is not None: - disk_context["volume"] = "{}/{}".format(name_node.text, volume_name) + disk_context["volume"] = f"{name_node.text}/{volume_name}" # Copy the authentication if any for RBD auth_node = pool_xml.find("./source/auth") if auth_node is not None: @@ -947,7 +942,7 @@ def _gen_xml( consoles=None, stop_on_reboot=False, host_devices=None, - **kwargs + **kwargs, ): """ Generate the XML string to define a libvirt VM @@ -1300,9 +1295,11 @@ def _gen_pool_xml( ): source = { "devices": source_devices or [], - "dir": source_dir - if source_format != "cifs" or not source_dir - else source_dir.lstrip("/"), + "dir": ( + source_dir + if source_format != "cifs" or not source_dir + else source_dir.lstrip("/") + ), "adapter": source_adapter, "hosts": [ {"name": host[0], "port": host[1] if len(host) > 1 else None} @@ -1391,7 +1388,7 @@ def _zfs_image_create( ) ) - destination_fs = os.path.join(pool, "{}.{}".format(vm_name, disk_name)) + destination_fs = os.path.join(pool, f"{vm_name}.{disk_name}") log.debug("Image destination will be %s", destination_fs) existing_disk = __salt__["zfs.list"](name=pool) @@ -1423,9 +1420,7 @@ def _zfs_image_create( sparse=sparse_volume, ) - blockdevice_path = os.path.join( - "/dev/zvol", pool, "{}.{}".format(vm_name, disk_name) - ) + blockdevice_path = os.path.join("/dev/zvol", pool, f"{vm_name}.{disk_name}") log.debug("Image path will be %s", blockdevice_path) return blockdevice_path @@ -1458,7 +1453,7 @@ def _qemu_image_create(disk, create_overlay=False, saltenv="base"): qcow2 = False if salt.utils.path.which("qemu-img"): - res = __salt__["cmd.run"]('qemu-img info "{}"'.format(sfn)) + res = __salt__["cmd.run"](f'qemu-img info "{sfn}"') imageinfo = salt.utils.yaml.safe_load(res) qcow2 = imageinfo["file format"] == "qcow2" try: @@ -1477,9 +1472,7 @@ def _qemu_image_create(disk, create_overlay=False, saltenv="base"): if disk_size and qcow2: log.debug("Resize qcow2 image to %sM", disk_size) - __salt__["cmd.run"]( - 'qemu-img resize "{}" {}M'.format(img_dest, disk_size) - ) + __salt__["cmd.run"](f'qemu-img resize "{img_dest}" {disk_size}M') log.debug("Apply umask and remove exec bit") mode = (0o0777 ^ mask) & 0o0666 @@ -1487,7 +1480,7 @@ def _qemu_image_create(disk, create_overlay=False, saltenv="base"): except OSError as err: raise CommandExecutionError( - "Problem while copying image. {} - {}".format(disk_image, err) + f"Problem while copying image. {disk_image} - {err}" ) else: @@ -1514,7 +1507,7 @@ def _qemu_image_create(disk, create_overlay=False, saltenv="base"): except OSError as err: raise CommandExecutionError( - "Problem while creating volume {} - {}".format(img_dest, err) + f"Problem while creating volume {img_dest} - {err}" ) return img_dest @@ -1730,7 +1723,7 @@ def _fill_disk_filename(conn, vm_name, disk, hypervisor, pool_caps): index = min( idx for idx in range(1, max(indexes) + 2) if idx not in indexes ) - disk["filename"] = "{}{}".format(os.path.basename(device), index) + disk["filename"] = f"{os.path.basename(device)}{index}" # Is the user wanting to reuse an existing volume? if disk.get("source_file"): @@ -2006,7 +1999,7 @@ def init( consoles=None, stop_on_reboot=False, host_devices=None, - **kwargs + **kwargs, ): """ Initialize a new vm @@ -2912,7 +2905,7 @@ def init( consoles, stop_on_reboot, host_devices, - **kwargs + **kwargs, ) log.debug("New virtual machine definition: %s", vm_xml) conn.defineXML(vm_xml) @@ -2982,12 +2975,16 @@ def _nics_equal(nic1, nic2): } return { "type": source_type, - "source": source_getters[source_type](source_node) - if source_node is not None - else None, - "model": nic.find("model").attrib["type"] - if nic.find("model") is not None - else None, + "source": ( + source_getters[source_type](source_node) + if source_node is not None + else None + ), + "model": ( + nic.find("model").attrib["type"] + if nic.find("model") is not None + else None + ), } def _get_mac(nic): @@ -3112,7 +3109,7 @@ def _get_disk_target(targets, disks_count, prefix): :param prefix: the prefix of the target name, i.e. "hd" """ for i in range(disks_count): - ret = "{}{}".format(prefix, string.ascii_lowercase[i]) + ret = f"{prefix}{string.ascii_lowercase[i]}" if ret not in targets: return ret return None @@ -3235,12 +3232,16 @@ def _serial_or_concole_equal(old, new): """ return { "type": item.attrib["type"], - "port": item.find("source").get("service") - if item.find("source") is not None - else None, - "protocol": item.find("protocol").get("type") - if item.find("protocol") is not None - else None, + "port": ( + item.find("source").get("service") + if item.find("source") is not None + else None + ), + "protocol": ( + item.find("protocol").get("type") + if item.find("protocol") is not None + else None + ), } return _filter_serial_or_concole(old) == _filter_serial_or_concole(new) @@ -3294,8 +3295,8 @@ def _compute_device_changes(old_xml, new_xml, to_skip): changes[dev_type] = {} if not to_skip[dev_type]: old = devices_node.findall(dev_type) - new = new_xml.findall("devices/{}".format(dev_type)) - changes[dev_type] = globals()["_diff_{}_lists".format(dev_type)](old, new) + new = new_xml.findall(f"devices/{dev_type}") + changes[dev_type] = globals()[f"_diff_{dev_type}_lists"](old, new) return changes @@ -3499,7 +3500,7 @@ def update( stop_on_reboot=False, host_devices=None, autostart=False, - **kwargs + **kwargs, ): """ Update the definition of an existing domain. @@ -3761,7 +3762,7 @@ def update( consoles=consoles, stop_on_reboot=stop_on_reboot, host_devices=host_devices, - **kwargs + **kwargs, ) ) set_autostart(name, "on" if autostart else "off") @@ -3796,7 +3797,7 @@ def update( # _handle_unit treats bytes as invalid unit for the purpose of consistency unit = unit if unit != "bytes" else "b" value = node.get("memory") or node.get("size") or node.text - return _handle_unit("{}{}".format(value, unit)) if value else None + return _handle_unit(f"{value}{unit}") if value else None def _set_vcpu(node, value): node.text = str(value) @@ -4063,32 +4064,32 @@ def update( for timer in timer_names: params_mapping += [ xmlutil.attribute( - "clock:timers:{}:track".format(timer), - "clock/timer[@name='{}']".format(timer), + f"clock:timers:{timer}:track", + f"clock/timer[@name='{timer}']", "track", ["name"], ), xmlutil.attribute( - "clock:timers:{}:tickpolicy".format(timer), - "clock/timer[@name='{}']".format(timer), + f"clock:timers:{timer}:tickpolicy", + f"clock/timer[@name='{timer}']", "tickpolicy", ["name"], ), xmlutil.int_attribute( - "clock:timers:{}:frequency".format(timer), - "clock/timer[@name='{}']".format(timer), + f"clock:timers:{timer}:frequency", + f"clock/timer[@name='{timer}']", "frequency", ["name"], ), xmlutil.attribute( - "clock:timers:{}:mode".format(timer), - "clock/timer[@name='{}']".format(timer), + f"clock:timers:{timer}:mode", + f"clock/timer[@name='{timer}']", "mode", ["name"], ), _yesno_attribute( - "clock:timers:{}:present".format(timer), - "clock/timer[@name='{}']".format(timer), + f"clock:timers:{timer}:present", + f"clock/timer[@name='{timer}']", "present", ["name"], ), @@ -4096,8 +4097,8 @@ def update( for attr in ["slew", "threshold", "limit"]: params_mapping.append( xmlutil.int_attribute( - "clock:timers:{}:{}".format(timer, attr), - "clock/timer[@name='{}']/catchup".format(timer), + f"clock:timers:{timer}:{attr}", + f"clock/timer[@name='{timer}']/catchup", attr, ) ) @@ -5490,7 +5491,7 @@ def migrate(vm_, target, **kwargs): if not urllib.parse.urlparse(target).scheme: proto = "qemu" - dst_uri = "{}://{}/system".format(proto, target) + dst_uri = f"{proto}://{target}/system" else: dst_uri = target @@ -5779,7 +5780,7 @@ def get_hypervisor(): result = [ hyper for hyper in hypervisors - if getattr(sys.modules[__name__], "_is_{}_hyper".format(hyper))() + if getattr(sys.modules[__name__], f"_is_{hyper}_hyper")() ] return result[0] if result else None @@ -5862,7 +5863,7 @@ def vm_cputime(vm_=None, **kwargs): cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { "cputime": int(raw[4]), - "cputime_percent": int("{:.0f}".format(cputime_percent)), + "cputime_percent": int(f"{cputime_percent:.0f}"), } info = {} @@ -6134,7 +6135,7 @@ def snapshot(domain, name=None, suffix=None, **kwargs): ) if suffix: - name = "{name}-{suffix}".format(name=name, suffix=suffix) + name = f"{name}-{suffix}" doc = ElementTree.Element("domainsnapshot") n_name = ElementTree.SubElement(doc, "name") @@ -6258,7 +6259,7 @@ def revert_snapshot(name, vm_snapshot=None, cleanup=False, **kwargs): conn.close() raise CommandExecutionError( snapshot - and 'Snapshot "{}" not found'.format(vm_snapshot) + and f'Snapshot "{vm_snapshot}" not found' or "No more previous snapshots available" ) elif snap.isCurrent(): @@ -6363,7 +6364,7 @@ def _parse_caps_cell(cell): if mem_node is not None: unit = mem_node.get("unit", "KiB") memory = mem_node.text - result["memory"] = "{} {}".format(memory, unit) + result["memory"] = f"{memory} {unit}" pages = [ { @@ -6425,7 +6426,7 @@ def _parse_caps_bank(bank): minimum = control.get("min") if minimum: - result_control["min"] = "{} {}".format(minimum, unit) + result_control["min"] = f"{minimum} {unit}" controls.append(result_control) if controls: result["controls"] = controls @@ -6445,15 +6446,19 @@ def _parse_caps_host(host): elif child.tag == "cpu": cpu = { - "arch": child.find("arch").text - if child.find("arch") is not None - else None, - "model": child.find("model").text - if child.find("model") is not None - else None, - "vendor": child.find("vendor").text - if child.find("vendor") is not None - else None, + "arch": ( + child.find("arch").text if child.find("arch") is not None else None + ), + "model": ( + child.find("model").text + if child.find("model") is not None + else None + ), + "vendor": ( + child.find("vendor").text + if child.find("vendor") is not None + else None + ), "features": [ feature.get("name") for feature in child.findall("feature") ], @@ -6499,12 +6504,14 @@ def _parse_caps_host(host): result["security"] = [ { - "model": secmodel.find("model").text - if secmodel.find("model") is not None - else None, - "doi": secmodel.find("doi").text - if secmodel.find("doi") is not None - else None, + "model": ( + secmodel.find("model").text + if secmodel.find("model") is not None + else None + ), + "doi": ( + secmodel.find("doi").text if secmodel.find("doi") is not None else None + ), "baselabels": [ {"type": label.get("type"), "label": label.text} for label in secmodel.findall("baselabel") @@ -6652,9 +6659,9 @@ def _parse_domain_caps(caps): result = { "emulator": caps.find("path").text if caps.find("path") is not None else None, "domain": caps.find("domain").text if caps.find("domain") is not None else None, - "machine": caps.find("machine").text - if caps.find("machine") is not None - else None, + "machine": ( + caps.find("machine").text if caps.find("machine") is not None else None + ), "arch": caps.find("arch").text if caps.find("arch") is not None else None, } @@ -6848,11 +6855,9 @@ def cpu_baseline(full=False, migratable=False, out="libvirt", **kwargs): ] if not cpu_specs: - raise ValueError("Model {} not found in CPU map".format(cpu_model)) + raise ValueError(f"Model {cpu_model} not found in CPU map") elif len(cpu_specs) > 1: - raise ValueError( - "Multiple models {} found in CPU map".format(cpu_model) - ) + raise ValueError(f"Multiple models {cpu_model} found in CPU map") cpu_specs = cpu_specs[0] @@ -6892,7 +6897,7 @@ def network_define( addresses=None, physical_function=None, dns=None, - **kwargs + **kwargs, ): """ Create libvirt network. @@ -7191,7 +7196,7 @@ def network_update( physical_function=None, dns=None, test=False, - **kwargs + **kwargs, ): """ Update a virtual network if needed. @@ -7658,14 +7663,12 @@ def _parse_pools_caps(doc): } for option_kind in ["pool", "vol"]: options = {} - default_format_node = pool.find( - "{}Options/defaultFormat".format(option_kind) - ) + default_format_node = pool.find(f"{option_kind}Options/defaultFormat") if default_format_node is not None: options["default_format"] = default_format_node.get("type") options_enums = { enum.get("name"): [value.text for value in enum.findall("value")] - for enum in pool.findall("{}Options/enum".format(option_kind)) + for enum in pool.findall(f"{option_kind}Options/enum") } if options_enums: options.update(options_enums) @@ -7888,7 +7891,7 @@ def pool_define( source_format=None, transient=False, start=True, # pylint: disable=redefined-outer-name - **kwargs + **kwargs, ): """ Create libvirt pool. @@ -8076,9 +8079,9 @@ def _pool_set_secret( # Create secret if needed if not secret: - description = "Passphrase for {} pool created by Salt".format(pool_name) + description = f"Passphrase for {pool_name} pool created by Salt" if not usage: - usage = "pool_{}".format(pool_name) + usage = f"pool_{pool_name}" secret_xml = _gen_secret_xml(secret_type, usage, description) if not test: secret = conn.secretDefineXML(secret_xml) @@ -8114,7 +8117,7 @@ def pool_update( source_name=None, source_format=None, test=False, - **kwargs + **kwargs, ): """ Update a libvirt storage pool if needed. @@ -8487,7 +8490,7 @@ def pool_undefine(name, **kwargs): } secret_type = auth_types[auth_node.get("type")] secret_usage = auth_node.find("secret").get("usage") - if secret_type and "pool_{}".format(name) == secret_usage: + if secret_type and f"pool_{name}" == secret_usage: secret = conn.secretLookupByUsage(secret_type, secret_usage) secret.undefine() @@ -8719,9 +8722,11 @@ def volume_infos(pool=None, volume=None, **kwargs): if backing_store_path is not None: backing_store = { "path": backing_store_path.text, - "format": backing_store_format.get("type") - if backing_store_format is not None - else None, + "format": ( + backing_store_format.get("type") + if backing_store_format is not None + else None + ), } format_node = vol_xml.find("./target/format") @@ -8809,7 +8814,7 @@ def volume_define( permissions=None, backing_store=None, nocow=False, - **kwargs + **kwargs, ): """ Create libvirt volume. @@ -8910,7 +8915,7 @@ def _volume_upload(conn, pool, volume, file, offset=0, length=0, sparse=False): inData = False eof = os.lseek(fd, 0, os.SEEK_END) if eof < cur: - raise RuntimeError("Current position in file after EOF: {}".format(cur)) + raise RuntimeError(f"Current position in file after EOF: {cur}") sectionLen = eof - cur else: if data > cur: @@ -8963,16 +8968,14 @@ def _volume_upload(conn, pool, volume, file, offset=0, length=0, sparse=False): if stream: stream.abort() if ret: - raise CommandExecutionError( - "Failed to close file: {}".format(err.strerror) - ) + raise CommandExecutionError(f"Failed to close file: {err.strerror}") if stream: try: stream.finish() except libvirt.libvirtError as err: if ret: raise CommandExecutionError( - "Failed to finish stream: {}".format(err.get_error_message()) + f"Failed to finish stream: {err.get_error_message()}" ) return ret diff --git a/salt/modules/virtualenv_mod.py b/salt/modules/virtualenv_mod.py index 81c270196d2..36fd6c9d93d 100644 --- a/salt/modules/virtualenv_mod.py +++ b/salt/modules/virtualenv_mod.py @@ -4,7 +4,6 @@ Create virtualenv environments. .. versionadded:: 0.17.0 """ - import glob import logging import os @@ -21,7 +20,7 @@ from salt.exceptions import CommandExecutionError, SaltInvocationError KNOWN_BINARY_NAMES = frozenset( [ "virtualenv-{}.{}".format(*sys.version_info[:2]), - "virtualenv{}".format(sys.version_info[0]), + f"virtualenv{sys.version_info[0]}", "virtualenv", ] ) @@ -88,7 +87,7 @@ def create( user=None, use_vt=False, saltenv="base", - **kwargs + **kwargs, ): """ Create a virtualenv @@ -212,15 +211,13 @@ def create( if python is not None and python.strip() != "": if not salt.utils.path.which(python): - raise CommandExecutionError( - "Cannot find requested python ({}).".format(python) - ) - cmd.append("--python={}".format(python)) + raise CommandExecutionError(f"Cannot find requested python ({python}).") + cmd.append(f"--python={python}") if extra_search_dir is not None: if isinstance(extra_search_dir, str) and extra_search_dir.strip() != "": extra_search_dir = [e.strip() for e in extra_search_dir.split(",")] for entry in extra_search_dir: - cmd.append("--extra-search-dir={}".format(entry)) + cmd.append(f"--extra-search-dir={entry}") if never_download is True: if (1, 10) <= virtualenv_version_info < (14, 0, 0): log.info( @@ -231,7 +228,7 @@ def create( else: cmd.append("--never-download") if prompt is not None and prompt.strip() != "": - cmd.append("--prompt='{}'".format(prompt)) + cmd.append(f"--prompt='{prompt}'") else: # venv module from the Python >= 3.3 standard library @@ -500,7 +497,7 @@ def _install_script(source, cwd, python, user, saltenv="base", use_vt=False): def _verify_safe_py_code(*args): for arg in args: if not salt.utils.verify.safe_py_code(arg): - raise SaltInvocationError("Unsafe python code detected in '{}'".format(arg)) + raise SaltInvocationError(f"Unsafe python code detected in '{arg}'") def _verify_virtualenv(venv_path): diff --git a/salt/modules/vmctl.py b/salt/modules/vmctl.py index 6b3d7b8880c..01334383f92 100644 --- a/salt/modules/vmctl.py +++ b/salt/modules/vmctl.py @@ -11,7 +11,6 @@ Manage vms running on the OpenBSD VMM hypervisor using vmctl(8). target machine. """ - import logging import re @@ -60,7 +59,7 @@ def create_disk(name, size): salt '*' vmctl.create_disk /path/to/disk.img size=10G """ ret = False - cmd = "vmctl create {} -s {}".format(name, size) + cmd = f"vmctl create {name} -s {size}" result = __salt__["cmd.run_all"](cmd, output_loglevel="trace", python_shell=False) @@ -89,7 +88,7 @@ def load(path): salt '*' vmctl.load path=/etc/vm.switches.conf """ ret = False - cmd = "vmctl load {}".format(path) + cmd = f"vmctl load {path}" result = __salt__["cmd.run_all"](cmd, output_loglevel="trace", python_shell=False) if result["retcode"] == 0: ret = True @@ -227,7 +226,7 @@ def start( name = _id_to_name(id) if nics > 0: - cmd.append("-i {}".format(nics)) + cmd.append(f"-i {nics}") # Paths cannot be appended as otherwise the inserted whitespace is treated by # vmctl as being part of the path. @@ -235,10 +234,10 @@ def start( cmd.extend(["-b", bootpath]) if memory: - cmd.append("-m {}".format(memory)) + cmd.append(f"-m {memory}") if switch: - cmd.append("-n {}".format(switch)) + cmd.append(f"-n {switch}") if local_iface: cmd.append("-L") diff --git a/salt/modules/vsphere.py b/salt/modules/vsphere.py index d05d22168ce..ff62e1ca3c6 100644 --- a/salt/modules/vsphere.py +++ b/salt/modules/vsphere.py @@ -181,7 +181,6 @@ connection credentials are used instead of vCenter credentials, the ``host_names 6500 """ - import datetime import logging import sys @@ -9640,7 +9639,7 @@ def _create_scsi_devices(scsi_devices): log.trace("Creating SCSI devices %s", devs) # unitNumber for disk attachment, 0:0 1st 0 is the controller busNumber, # 2nd is the unitNumber - for (key, scsi_controller) in zip(keys, scsi_devices): + for key, scsi_controller in zip(keys, scsi_devices): # create the SCSI controller scsi_spec = _apply_scsi_controller( scsi_controller["adapter"], @@ -9688,9 +9687,9 @@ def _create_network_adapters(network_interfaces, parent=None): interface["switch_type"], network_adapter_label=interface["adapter"], operation="add", - connectable=interface["connectable"] - if "connectable" in interface - else None, + connectable=( + interface["connectable"] if "connectable" in interface else None + ), mac=interface["mac"], parent=parent, ) @@ -9758,15 +9757,17 @@ def _create_cd_drives(cd_drives, controllers=None, parent_ref=None): key, drive["device_type"], "add", - client_device=drive["client_device"] - if "client_device" in drive - else None, - datastore_iso_file=drive["datastore_iso_file"] - if "datastore_iso_file" in drive - else None, - connectable=drive["connectable"] - if "connectable" in drive - else None, + client_device=( + drive["client_device"] if "client_device" in drive else None + ), + datastore_iso_file=( + drive["datastore_iso_file"] + if "datastore_iso_file" in drive + else None + ), + connectable=( + drive["connectable"] if "connectable" in drive else None + ), controller_key=controller_key, parent_ref=parent_ref, ) @@ -10056,9 +10057,9 @@ def get_vm_config(name, datacenter=None, objects=True, service_instance=None): if isinstance(device, vim.vm.device.VirtualEthernetCard): interface = {} interface["adapter"] = device.deviceInfo.label - interface[ - "adapter_type" - ] = salt.utils.vmware.get_network_adapter_object_type(device) + interface["adapter_type"] = ( + salt.utils.vmware.get_network_adapter_object_type(device) + ) interface["connectable"] = { "allow_guest_control": device.connectable.allowGuestControl, "connected": device.connectable.connected, @@ -10396,12 +10397,16 @@ def _update_cd_drives(drives_old_new, controllers=None, parent=None): current_drive["key"], new_drive["device_type"], "edit", - client_device=new_drive["client_device"] - if "client_device" in new_drive - else None, - datastore_iso_file=new_drive["datastore_iso_file"] - if "datastore_iso_file" in new_drive - else None, + client_device=( + new_drive["client_device"] + if "client_device" in new_drive + else None + ), + datastore_iso_file=( + new_drive["datastore_iso_file"] + if "datastore_iso_file" in new_drive + else None + ), connectable=new_drive["connectable"], controller_key=controller_key, parent_ref=parent, diff --git a/salt/modules/webutil.py b/salt/modules/webutil.py index 42da8f330d4..bb5109d1c2a 100644 --- a/salt/modules/webutil.py +++ b/salt/modules/webutil.py @@ -7,7 +7,6 @@ The functions here will load inside the webutil module. This allows other functions that don't use htpasswd to use the webutil module name. """ - import logging import os @@ -66,7 +65,7 @@ def useradd(pwfile, user, password, opts="", runas=None): if not os.path.exists(pwfile): opts += "c" - cmd = ["htpasswd", "-b{}".format(opts), pwfile, user, password] + cmd = ["htpasswd", f"-b{opts}", pwfile, user, password] return __salt__["cmd.run_all"](cmd, runas=runas, python_shell=False) @@ -140,7 +139,7 @@ def verify(pwfile, user, password, opts="", runas=None): if not os.path.exists(pwfile): return False - cmd = ["htpasswd", "-bv{}".format(opts), pwfile, user, password] + cmd = ["htpasswd", f"-bv{opts}", pwfile, user, password] ret = __salt__["cmd.run_all"](cmd, runas=runas, python_shell=False) log.debug("Result of verifying htpasswd for user %s: %s", user, ret) diff --git a/salt/modules/win_appx.py b/salt/modules/win_appx.py index 0858f9c8c72..e6057f8fa3b 100644 --- a/salt/modules/win_appx.py +++ b/salt/modules/win_appx.py @@ -42,6 +42,7 @@ Not all packages can be found this way, but it seems like most of them can. Use the ``appx.install`` function to provision the new app. """ + import fnmatch import logging diff --git a/salt/modules/win_autoruns.py b/salt/modules/win_autoruns.py index 14497199e25..940474138c1 100644 --- a/salt/modules/win_autoruns.py +++ b/salt/modules/win_autoruns.py @@ -3,7 +3,6 @@ Module for listing programs that automatically run on startup (very alpha...not tested on anything but my Win 7x64) """ - import os import salt.utils.platform diff --git a/salt/modules/win_certutil.py b/salt/modules/win_certutil.py index efed109e2c0..9a0fd737ff7 100644 --- a/salt/modules/win_certutil.py +++ b/salt/modules/win_certutil.py @@ -48,10 +48,10 @@ def get_cert_serial(cert_file, saltenv="base"): # Since we're allowing a path, let's make sure it exists if not os.path.exists(cert_file): - msg = "cert_file not found: {}".format(cert_file) + msg = f"cert_file not found: {cert_file}" raise CommandExecutionError(msg) - cmd = 'certutil.exe -silent -verify "{}"'.format(cert_file) + cmd = f'certutil.exe -silent -verify "{cert_file}"' out = __salt__["cmd.run"](cmd) # match serial number by paragraph to work with multiple languages matches = re.search(r":\s*(\w*)\r\n\r\n", out) @@ -77,7 +77,7 @@ def get_stored_cert_serials(store): salt '*' certutil.get_stored_cert_serials """ - cmd = 'certutil.exe -store "{}"'.format(store) + cmd = f'certutil.exe -store "{store}"' out = __salt__["cmd.run"](cmd) # match serial numbers by header position to work with multiple languages matches = re.findall(r"={16}\r\n.*:\s*(\w*)\r\n", out) @@ -112,10 +112,10 @@ def add_store(source, store, retcode=False, saltenv="base"): # Since we're allowing a path, let's make sure it exists if not os.path.exists(source): - msg = "cert_file not found: {}".format(source) + msg = f"cert_file not found: {source}" raise CommandExecutionError(msg) - cmd = 'certutil.exe -addstore {} "{}"'.format(store, source) + cmd = f'certutil.exe -addstore {store} "{source}"' if retcode: return __salt__["cmd.retcode"](cmd) else: @@ -150,11 +150,11 @@ def del_store(source, store, retcode=False, saltenv="base"): # Since we're allowing a path, let's make sure it exists if not os.path.exists(source): - msg = "cert_file not found: {}".format(source) + msg = f"cert_file not found: {source}" raise CommandExecutionError(msg) serial = get_cert_serial(source) - cmd = 'certutil.exe -delstore {} "{}"'.format(store, serial) + cmd = f'certutil.exe -delstore {store} "{serial}"' if retcode: return __salt__["cmd.retcode"](cmd) else: diff --git a/salt/modules/win_dacl.py b/salt/modules/win_dacl.py index a084a75684f..b8b5aca3dc3 100644 --- a/salt/modules/win_dacl.py +++ b/salt/modules/win_dacl.py @@ -4,7 +4,6 @@ Manage DACLs on Windows :depends: - winreg Python module """ - import logging import os import re @@ -503,17 +502,17 @@ def add_ace(path, objectType, user, permission, acetype, propagation): ) ret["result"] = True except Exception as e: # pylint: disable=broad-except - ret[ - "comment" - ] = "An error occurred attempting to add the ace. The error was {}".format( - e + ret["comment"] = ( + "An error occurred attempting to add the ace. The error was {}".format( + e + ) ) ret["result"] = False return ret if acesAdded: ret["changes"]["Added ACEs"] = acesAdded else: - ret["comment"] = "Unable to obtain the DACL of {}".format(path) + ret["comment"] = f"Unable to obtain the DACL of {path}" else: ret["comment"] = "An empty value was specified for a required item." ret["result"] = False @@ -604,7 +603,7 @@ def rm_ace(path, objectType, user, permission=None, acetype=None, propagation=No ret["result"] = True except Exception as e: # pylint: disable=broad-except ret["result"] = False - ret["comment"] = "Error removing ACE. The error was {}.".format(e) + ret["comment"] = f"Error removing ACE. The error was {e}." return ret else: ret["comment"] = "The specified ACE was not found on the path." @@ -620,9 +619,9 @@ def _ace_to_text(ace, objectType): try: userSid = win32security.LookupAccountSid("", ace[2]) if userSid[1]: - userSid = "{1}\\{0}".format(userSid[0], userSid[1]) + userSid = f"{userSid[1]}\\{userSid[0]}" else: - userSid = "{}".format(userSid[0]) + userSid = f"{userSid[0]}" except Exception: # pylint: disable=broad-except userSid = win32security.ConvertSidToStringSid(ace[2]) tPerm = ace[1] @@ -644,7 +643,7 @@ def _ace_to_text(ace, objectType): if dc.validPropagations[objectType][x]["BITS"] == tProps: tProps = dc.validPropagations[objectType][x]["TEXT"] break - return "{} {} {} on {} {}".format(userSid, tAceType, tPerm, tProps, tInherited) + return f"{userSid} {tAceType} {tPerm} on {tProps} {tInherited}" def _set_dacl_inheritance(path, objectType, inheritance=True, copy=True, clear=False): @@ -730,9 +729,9 @@ def _set_dacl_inheritance(path, objectType, inheritance=True, copy=True, clear=F ret["result"] = True except Exception as e: # pylint: disable=broad-except ret["result"] = False - ret[ - "comment" - ] = "Error attempting to set the inheritance. The error was {}.".format(e) + ret["comment"] = ( + f"Error attempting to set the inheritance. The error was {e}." + ) return ret @@ -818,9 +817,9 @@ def check_inheritance(path, objectType, user=None): dacls = sd.GetSecurityDescriptorDacl() except Exception as e: # pylint: disable=broad-except ret["result"] = False - ret[ - "comment" - ] = "Error obtaining the Security Descriptor or DACL of the path: {}.".format(e) + ret["comment"] = ( + f"Error obtaining the Security Descriptor or DACL of the path: {e}." + ) return ret for counter in range(0, dacls.GetAceCount()): diff --git a/salt/modules/win_disk.py b/salt/modules/win_disk.py index 155efa5fe3f..92fa81ed59d 100644 --- a/salt/modules/win_disk.py +++ b/salt/modules/win_disk.py @@ -53,19 +53,19 @@ def usage(): available_bytes, total_bytes, total_free_bytes, - ) = win32api.GetDiskFreeSpaceEx("{}:\\".format(drive)) + ) = win32api.GetDiskFreeSpaceEx(f"{drive}:\\") used = total_bytes - total_free_bytes capacity = used / float(total_bytes) * 100 - ret["{}:\\".format(drive)] = { - "filesystem": "{}:\\".format(drive), + ret[f"{drive}:\\"] = { + "filesystem": f"{drive}:\\", "1K-blocks": total_bytes / 1024, "used": used / 1024, "available": total_free_bytes / 1024, - "capacity": "{:.0f}%".format(capacity), + "capacity": f"{capacity:.0f}%", } except Exception: # pylint: disable=broad-except - ret["{}:\\".format(drive)] = { - "filesystem": "{}:\\".format(drive), + ret[f"{drive}:\\"] = { + "filesystem": f"{drive}:\\", "1K-blocks": None, "used": None, "available": None, diff --git a/salt/modules/win_dns_client.py b/salt/modules/win_dns_client.py index 89ba38fffb1..d72e344bbf8 100644 --- a/salt/modules/win_dns_client.py +++ b/salt/modules/win_dns_client.py @@ -118,7 +118,7 @@ def add_dns(ip, interface="Local Area Connection", index=1): "dns", interface, ip, - "index={}".format(index), + f"index={index}", "validate=no", ] diff --git a/salt/modules/win_dsc.py b/salt/modules/win_dsc.py index 9c99efae61b..997a72fd787 100644 --- a/salt/modules/win_dsc.py +++ b/salt/modules/win_dsc.py @@ -60,7 +60,7 @@ def _pshell(cmd, cwd=None, json_depth=2, ignore_retcode=False): CommandExecutionError. """ if "convertto-json" not in cmd.lower(): - cmd = "{} | ConvertTo-Json -Depth {}".format(cmd, json_depth) + cmd = f"{cmd} | ConvertTo-Json -Depth {json_depth}" log.debug("DSC: %s", cmd) results = __salt__["cmd.run_all"]( cmd, @@ -75,9 +75,7 @@ def _pshell(cmd, cwd=None, json_depth=2, ignore_retcode=False): if "retcode" not in results or results["retcode"] != 0: # run_all logs an error to log.error, fail hard back to the user - raise CommandExecutionError( - "Issue executing PowerShell {}".format(cmd), info=results - ) + raise CommandExecutionError(f"Issue executing PowerShell {cmd}", info=results) # Sometimes Powershell returns an empty string, which isn't valid JSON if results["stdout"] == "": @@ -267,7 +265,7 @@ def compile_config( path=source, dest=path, saltenv=salt_env, makedirs=True ) if not cached_files: - error = "Failed to cache {}".format(source) + error = f"Failed to cache {source}" log.error("DSC: %s", error) raise CommandExecutionError(error) @@ -277,13 +275,13 @@ def compile_config( path=config_data_source, dest=config_data, saltenv=salt_env, makedirs=True ) if not cached_files: - error = "Failed to cache {}".format(config_data_source) + error = f"Failed to cache {config_data_source}" log.error("DSC: %s", error) raise CommandExecutionError(error) # Make sure the path exists if not os.path.exists(path): - error = "{} not found".format(path) + error = f"{path} not found" log.error("DSC: %s", error) raise CommandExecutionError(error) @@ -341,8 +339,8 @@ def compile_config( log.info("DSC: Compile Config: %s", ret) return ret - error = "Failed to compile config: {}".format(path) - error += "\nReturned: {}".format(ret) + error = f"Failed to compile config: {path}" + error += f"\nReturned: {ret}" log.error("DSC: %s", error) raise CommandExecutionError(error) @@ -394,7 +392,7 @@ def apply_config(path, source=None, salt_env="base"): source_name = os.path.basename(os.path.normpath(source)) if path_name.lower() != source_name.lower(): # Append the Source name to the Path - path = "{}\\{}".format(path, source_name) + path = f"{path}\\{source_name}" log.debug("DSC: %s appended to the path.", source_name) # Destination path minus the basename @@ -402,7 +400,7 @@ def apply_config(path, source=None, salt_env="base"): log.info("DSC: Caching %s", source) cached_files = __salt__["cp.get_dir"](source, dest_path, salt_env) if not cached_files: - error = "Failed to copy {}".format(source) + error = f"Failed to copy {source}" log.error("DSC: %s", error) raise CommandExecutionError(error) else: @@ -410,13 +408,13 @@ def apply_config(path, source=None, salt_env="base"): # Make sure the path exists if not os.path.exists(config): - error = "{} not found".format(config) + error = f"{config} not found" log.error("DSC: %s", error) raise CommandExecutionError(error) # Run the DSC Configuration # Putting quotes around the parameter protects against command injection - cmd = 'Start-DscConfiguration -Path "{}" -Wait -Force'.format(config) + cmd = f'Start-DscConfiguration -Path "{config}" -Wait -Force' _pshell(cmd) cmd = "$status = Get-DscConfigurationStatus; $status.Status" @@ -541,7 +539,7 @@ def remove_config(reset=False): if os.path.exists(path): log.info("DSC: Removing %s", path) if not __salt__["file.remove"](path): - error = "Failed to remove {}".format(path) + error = f"Failed to remove {path}" log.error("DSC: %s", error) raise CommandExecutionError(error) @@ -550,13 +548,13 @@ def remove_config(reset=False): ) # Remove History - _remove_fs_obj("{}\\DSCStatusHistory.mof".format(dsc_config_dir)) + _remove_fs_obj(f"{dsc_config_dir}\\DSCStatusHistory.mof") # Remove Engine Cache - _remove_fs_obj("{}\\DSCEngineCache.mof".format(dsc_config_dir)) + _remove_fs_obj(f"{dsc_config_dir}\\DSCEngineCache.mof") # Remove Status Directory - _remove_fs_obj("{}\\ConfigurationStatus".format(dsc_config_dir)) + _remove_fs_obj(f"{dsc_config_dir}\\ConfigurationStatus") return True @@ -756,7 +754,7 @@ def set_lcm_config( "or ApplyAndAutoCorrect. Passed {}".format(config_mode) ) raise SaltInvocationError(error) - cmd += ' ConfigurationMode = "{}";'.format(config_mode) + cmd += f' ConfigurationMode = "{config_mode}";' if config_mode_freq: if not isinstance(config_mode_freq, int): error = "config_mode_freq must be an integer. Passed {}".format( @@ -771,11 +769,11 @@ def set_lcm_config( raise SaltInvocationError( "refresh_mode must be one of Disabled, Push, or Pull" ) - cmd += ' RefreshMode = "{}";'.format(refresh_mode) + cmd += f' RefreshMode = "{refresh_mode}";' if refresh_freq: if not isinstance(refresh_freq, int): raise SaltInvocationError("refresh_freq must be an integer") - cmd += " RefreshFrequencyMins = {};".format(refresh_freq) + cmd += f" RefreshFrequencyMins = {refresh_freq};" if reboot_if_needed is not None: if not isinstance(reboot_if_needed, bool): raise SaltInvocationError("reboot_if_needed must be a boolean value") @@ -783,22 +781,22 @@ def set_lcm_config( reboot_if_needed = "$true" else: reboot_if_needed = "$false" - cmd += " RebootNodeIfNeeded = {};".format(reboot_if_needed) + cmd += f" RebootNodeIfNeeded = {reboot_if_needed};" if action_after_reboot: if action_after_reboot not in ("ContinueConfiguration", "StopConfiguration"): raise SaltInvocationError( "action_after_reboot must be one of " "ContinueConfiguration or StopConfiguration" ) - cmd += ' ActionAfterReboot = "{}"'.format(action_after_reboot) + cmd += f' ActionAfterReboot = "{action_after_reboot}"' if certificate_id is not None: if certificate_id == "": certificate_id = None - cmd += ' CertificateID = "{}";'.format(certificate_id) + cmd += f' CertificateID = "{certificate_id}";' if configuration_id is not None: if configuration_id == "": configuration_id = None - cmd += ' ConfigurationID = "{}";'.format(configuration_id) + cmd += f' ConfigurationID = "{configuration_id}";' if allow_module_overwrite is not None: if not isinstance(allow_module_overwrite, bool): raise SaltInvocationError("allow_module_overwrite must be a boolean value") @@ -806,7 +804,7 @@ def set_lcm_config( allow_module_overwrite = "$true" else: allow_module_overwrite = "$false" - cmd += " AllowModuleOverwrite = {};".format(allow_module_overwrite) + cmd += f" AllowModuleOverwrite = {allow_module_overwrite};" if debug_mode is not False: if debug_mode is None: debug_mode = "None" @@ -815,7 +813,7 @@ def set_lcm_config( "debug_mode must be one of None, ForceModuleImport, " "ResourceScriptBreakAll, or All" ) - cmd += ' DebugMode = "{}";'.format(debug_mode) + cmd += f' DebugMode = "{debug_mode}";' if status_retention_days: if not isinstance(status_retention_days, int): raise SaltInvocationError("status_retention_days must be an integer") @@ -823,7 +821,7 @@ def set_lcm_config( status_retention_days ) cmd += " }}};" - cmd += r'SaltConfig -OutputPath "{}\SaltConfig"'.format(temp_dir) + cmd += rf'SaltConfig -OutputPath "{temp_dir}\SaltConfig"' # Execute Config to create the .mof _pshell(cmd) @@ -831,7 +829,7 @@ def set_lcm_config( # Apply the config cmd = r'Set-DscLocalConfigurationManager -Path "{}\SaltConfig"' r"".format(temp_dir) ret = __salt__["cmd.run_all"](cmd, shell="powershell", python_shell=True) - __salt__["file.remove"](r"{}\SaltConfig".format(temp_dir)) + __salt__["file.remove"](rf"{temp_dir}\SaltConfig") if not ret["retcode"]: log.info("DSC: LCM config applied successfully") return True diff --git a/salt/modules/win_event.py b/salt/modules/win_event.py index f813abb329a..71fc1ac4928 100644 --- a/salt/modules/win_event.py +++ b/salt/modules/win_event.py @@ -2,6 +2,7 @@ A module for working with the Windows Event log system. .. versionadded:: 3006.0 """ + # https://docs.microsoft.com/en-us/windows/win32/eventlog/event-logging import collections @@ -174,7 +175,7 @@ def _get_handle(log_name): return win32evtlog.OpenEventLog(None, log_name) except pywintypes.error as exc: raise FileNotFoundError( - "Failed to open log: {}\nError: {}".format(log_name, exc.strerror) + f"Failed to open log: {log_name}\nError: {exc.strerror}" ) @@ -679,7 +680,7 @@ def add( if event_type is None: event_type = event_types["Error"] elif event_type not in event_types: - msg = "Incorrect event type: {}".format(event_type) + msg = f"Incorrect event type: {event_type}" raise CommandExecutionError(msg) else: event_type = event_types[event_type] diff --git a/salt/modules/win_firewall.py b/salt/modules/win_firewall.py index 75dbd3f964e..6d8dd025895 100644 --- a/salt/modules/win_firewall.py +++ b/salt/modules/win_firewall.py @@ -151,7 +151,7 @@ def get_rule(name="all"): salt '*' firewall.get_rule 'MyAppPort' """ - cmd = ["netsh", "advfirewall", "firewall", "show", "rule", "name={}".format(name)] + cmd = ["netsh", "advfirewall", "firewall", "show", "rule", f"name={name}"] ret = __salt__["cmd.run_all"](cmd, python_shell=False, ignore_retcode=True) if ret["retcode"] != 0: raise CommandExecutionError(ret["stdout"]) @@ -228,15 +228,15 @@ def add_rule(name, localport, protocol="tcp", action="allow", dir="in", remoteip "firewall", "add", "rule", - "name={}".format(name), - "protocol={}".format(protocol), - "dir={}".format(dir), - "action={}".format(action), - "remoteip={}".format(remoteip), + f"name={name}", + f"protocol={protocol}", + f"dir={dir}", + f"action={action}", + f"remoteip={remoteip}", ] if protocol is None or ("icmpv4" not in protocol and "icmpv6" not in protocol): - cmd.append("localport={}".format(localport)) + cmd.append(f"localport={localport}") ret = __salt__["cmd.run_all"](cmd, python_shell=False, ignore_retcode=True) if ret["retcode"] != 0: @@ -292,19 +292,19 @@ def delete_rule(name=None, localport=None, protocol=None, dir=None, remoteip=Non """ cmd = ["netsh", "advfirewall", "firewall", "delete", "rule"] if name: - cmd.append("name={}".format(name)) + cmd.append(f"name={name}") if protocol: - cmd.append("protocol={}".format(protocol)) + cmd.append(f"protocol={protocol}") if dir: - cmd.append("dir={}".format(dir)) + cmd.append(f"dir={dir}") if remoteip: - cmd.append("remoteip={}".format(remoteip)) + cmd.append(f"remoteip={remoteip}") if protocol is None or ("icmpv4" not in protocol and "icmpv6" not in protocol): if localport: if not protocol: cmd.append("protocol=tcp") - cmd.append("localport={}".format(localport)) + cmd.append(f"localport={localport}") ret = __salt__["cmd.run_all"](cmd, python_shell=False, ignore_retcode=True) if ret["retcode"] != 0: diff --git a/salt/modules/win_iis.py b/salt/modules/win_iis.py index 42ec335bf32..04d2f35d0ba 100644 --- a/salt/modules/win_iis.py +++ b/salt/modules/win_iis.py @@ -8,6 +8,7 @@ Microsoft IIS site management via WebAdministration powershell module .. versionadded:: 2016.3.0 """ + import decimal import logging import os @@ -83,7 +84,7 @@ def _list_certs(certificate_store="My"): ps_cmd = [ "Get-ChildItem", "-Path", - r"'Cert:\LocalMachine\{}'".format(certificate_store), + rf"'Cert:\LocalMachine\{certificate_store}'", "|", "Select-Object DnsNameList, SerialNumber, Subject, Thumbprint, Version", ] @@ -145,9 +146,9 @@ def _srvmgr(cmd, return_json=False): cmd = " ".join(cmd) if return_json: - cmd = "ConvertTo-Json -Compress -Depth 4 -InputObject @({})".format(cmd) + cmd = f"ConvertTo-Json -Compress -Depth 4 -InputObject @({cmd})" - cmd = "Import-Module WebAdministration; {}".format(cmd) + cmd = f"Import-Module WebAdministration; {cmd}" ret = __salt__["cmd.run_all"](cmd, shell="powershell", python_shell=True) @@ -305,7 +306,7 @@ def create_site( salt '*' win_iis.create_site name='My Test Site' sourcepath='c:\\stage' apppool='TestPool' """ protocol = str(protocol).lower() - site_path = r"IIS:\Sites\{}".format(name) + site_path = rf"IIS:\Sites\{name}" binding_info = _get_binding_info(hostheader, ipaddress, port) current_sites = list_sites() @@ -322,9 +323,9 @@ def create_site( ps_cmd = [ "New-Item", "-Path", - r"'{}'".format(site_path), + rf"'{site_path}'", "-PhysicalPath", - r"'{}'".format(sourcepath), + rf"'{sourcepath}'", "-Bindings", "@{{ protocol='{0}'; bindingInformation='{1}' }};".format( protocol, binding_info @@ -342,11 +343,11 @@ def create_site( [ "Set-ItemProperty", "-Path", - "'{}'".format(site_path), + f"'{site_path}'", "-Name", "ApplicationPool", "-Value", - "'{}'".format(apppool), + f"'{apppool}'", ] ) @@ -385,7 +386,7 @@ def modify_site(name, sourcepath=None, apppool=None): salt '*' win_iis.modify_site name='My Test Site' sourcepath='c:\\new_path' apppool='NewTestPool' """ - site_path = r"IIS:\Sites\{}".format(name) + site_path = rf"IIS:\Sites\{name}" current_sites = list_sites() if name not in current_sites: @@ -399,11 +400,11 @@ def modify_site(name, sourcepath=None, apppool=None): [ "Set-ItemProperty", "-Path", - r"'{}'".format(site_path), + rf"'{site_path}'", "-Name", "PhysicalPath", "-Value", - r"'{}'".format(sourcepath), + rf"'{sourcepath}'", ] ) @@ -423,11 +424,11 @@ def modify_site(name, sourcepath=None, apppool=None): [ "Set-ItemProperty", "-Path", - r"'{}'".format(site_path), + rf"'{site_path}'", "-Name", "ApplicationPool", "-Value", - r"'{}'".format(apppool), + rf"'{apppool}'", ] ) @@ -468,7 +469,7 @@ def remove_site(name): log.debug("Site already absent: %s", name) return True - ps_cmd = ["Remove-WebSite", "-Name", r"'{}'".format(name)] + ps_cmd = ["Remove-WebSite", "-Name", rf"'{name}'"] cmd_ret = _srvmgr(ps_cmd) @@ -498,7 +499,7 @@ def stop_site(name): salt '*' win_iis.stop_site name='My Test Site' """ - ps_cmd = ["Stop-WebSite", r"'{}'".format(name)] + ps_cmd = ["Stop-WebSite", rf"'{name}'"] cmd_ret = _srvmgr(ps_cmd) @@ -523,7 +524,7 @@ def start_site(name): salt '*' win_iis.start_site name='My Test Site' """ - ps_cmd = ["Start-WebSite", r"'{}'".format(name)] + ps_cmd = ["Start-WebSite", rf"'{name}'"] cmd_ret = _srvmgr(ps_cmd) @@ -641,31 +642,31 @@ def create_binding( ps_cmd = [ "New-WebBinding", "-Name", - "'{}'".format(site), + f"'{site}'", "-HostHeader", - "'{}'".format(hostheader), + f"'{hostheader}'", "-IpAddress", - "'{}'".format(ipaddress), + f"'{ipaddress}'", "-Port", - "'{}'".format(port), + f"'{port}'", "-Protocol", - "'{}'".format(protocol), + f"'{protocol}'", "-SslFlags", - "{}".format(sslflags), + f"{sslflags}", ] else: ps_cmd = [ "New-WebBinding", "-Name", - "'{}'".format(site), + f"'{site}'", "-HostHeader", - "'{}'".format(hostheader), + f"'{hostheader}'", "-IpAddress", - "'{}'".format(ipaddress), + f"'{ipaddress}'", "-Port", - "'{}'".format(port), + f"'{port}'", "-Protocol", - "'{}'".format(protocol), + f"'{protocol}'", ] cmd_ret = _srvmgr(ps_cmd) @@ -749,13 +750,13 @@ def modify_binding( ps_cmd = [ "Set-WebBinding", "-Name", - "'{}'".format(site), + f"'{site}'", "-BindingInformation", - "'{}'".format(binding), + f"'{binding}'", "-PropertyName", "BindingInformation", "-Value", - "'{}'".format(new_binding), + f"'{new_binding}'", ] cmd_ret = _srvmgr(ps_cmd) @@ -773,13 +774,13 @@ def modify_binding( ps_cmd = [ "Set-WebBinding", "-Name", - "'{}'".format(site), + f"'{site}'", "-BindingInformation", - "'{}'".format(new_binding), + f"'{new_binding}'", "-PropertyName", "sslflags", "-Value", - "'{}'".format(sslflags), + f"'{sslflags}'", ] cmd_ret = _srvmgr(ps_cmd) @@ -822,11 +823,11 @@ def remove_binding(site, hostheader="", ipaddress="*", port=80): ps_cmd = [ "Remove-WebBinding", "-HostHeader", - "'{}'".format(hostheader), + f"'{hostheader}'", "-IpAddress", - "'{}'".format(ipaddress), + f"'{ipaddress}'", "-Port", - "'{}'".format(port), + f"'{port}'", ] cmd_ret = _srvmgr(ps_cmd) @@ -961,19 +962,19 @@ def create_cert_binding(name, site, hostheader="", ipaddress="*", port=443, sslf ps_cmd = [ "New-Item", "-Path", - "'{}'".format(iis7path), + f"'{iis7path}'", "-Thumbprint", - "'{}'".format(name), + f"'{name}'", ] else: ps_cmd = [ "New-Item", "-Path", - "'{}'".format(binding_path), + f"'{binding_path}'", "-Thumbprint", - "'{}'".format(name), + f"'{name}'", "-SSLFlags", - "{}".format(sslflags), + f"{sslflags}", ] cmd_ret = _srvmgr(ps_cmd) @@ -1037,10 +1038,10 @@ def remove_cert_binding(name, site, hostheader="", ipaddress="*", port=443): r"'IIS:\Sites'", "|", "Where-Object", - r" {{ $_.Name -Eq '{0}' }};".format(site), + rf" {{ $_.Name -Eq '{site}' }};", "$Binding = $Site.Bindings.Collection", r"| Where-Object { $_.bindingInformation", - r"-Eq '{0}' }};".format(binding_info), + rf"-Eq '{binding_info}' }};", "$Binding.RemoveSslCertificate()", ] @@ -1167,13 +1168,13 @@ def create_apppool(name): salt '*' win_iis.create_apppool name='MyTestPool' """ current_apppools = list_apppools() - apppool_path = r"IIS:\AppPools\{}".format(name) + apppool_path = rf"IIS:\AppPools\{name}" if name in current_apppools: log.debug("Application pool '%s' already present.", name) return True - ps_cmd = ["New-Item", "-Path", r"'{}'".format(apppool_path)] + ps_cmd = ["New-Item", "-Path", rf"'{apppool_path}'"] cmd_ret = _srvmgr(ps_cmd) @@ -1204,13 +1205,13 @@ def remove_apppool(name): salt '*' win_iis.remove_apppool name='MyTestPool' """ current_apppools = list_apppools() - apppool_path = r"IIS:\AppPools\{}".format(name) + apppool_path = rf"IIS:\AppPools\{name}" if name not in current_apppools: log.debug("Application pool already absent: %s", name) return True - ps_cmd = ["Remove-Item", "-Path", r"'{}'".format(apppool_path), "-Recurse"] + ps_cmd = ["Remove-Item", "-Path", rf"'{apppool_path}'", "-Recurse"] cmd_ret = _srvmgr(ps_cmd) @@ -1242,7 +1243,7 @@ def stop_apppool(name): salt '*' win_iis.stop_apppool name='MyTestPool' """ - ps_cmd = ["Stop-WebAppPool", r"'{}'".format(name)] + ps_cmd = ["Stop-WebAppPool", rf"'{name}'"] cmd_ret = _srvmgr(ps_cmd) @@ -1267,7 +1268,7 @@ def start_apppool(name): salt '*' win_iis.start_apppool name='MyTestPool' """ - ps_cmd = ["Start-WebAppPool", r"'{}'".format(name)] + ps_cmd = ["Start-WebAppPool", rf"'{name}'"] cmd_ret = _srvmgr(ps_cmd) @@ -1292,7 +1293,7 @@ def restart_apppool(name): salt '*' win_iis.restart_apppool name='MyTestPool' """ - ps_cmd = ["Restart-WebAppPool", r"'{}'".format(name)] + ps_cmd = ["Restart-WebAppPool", rf"'{name}'"] cmd_ret = _srvmgr(ps_cmd) @@ -1324,7 +1325,7 @@ def get_container_setting(name, container, settings): ret = dict() ps_cmd = list() ps_cmd_validate = list() - container_path = r"IIS:\{}\{}".format(container, name) + container_path = rf"IIS:\{container}\{name}" if not settings: log.warning("No settings provided") @@ -1338,9 +1339,9 @@ def get_container_setting(name, container, settings): [ "Get-ItemProperty", "-Path", - "'{}'".format(container_path), + f"'{container_path}'", "-Name", - "'{}'".format(setting), + f"'{setting}'", "-ErrorAction", "Stop", "|", @@ -1351,13 +1352,13 @@ def get_container_setting(name, container, settings): # Some ItemProperties are Strings and others are ConfigurationAttributes. # Since the former doesn't have a Value property, we need to account # for this. - ps_cmd.append("$Property = Get-ItemProperty -Path '{}'".format(container_path)) - ps_cmd.append("-Name '{}' -ErrorAction Stop;".format(setting)) + ps_cmd.append(f"$Property = Get-ItemProperty -Path '{container_path}'") + ps_cmd.append(f"-Name '{setting}' -ErrorAction Stop;") ps_cmd.append(r"if (([String]::IsNullOrEmpty($Property) -eq $False) -and") ps_cmd.append(r"($Property.GetType()).Name -eq 'ConfigurationAttribute') {") ps_cmd.append(r"$Property = $Property | Select-Object") ps_cmd.append(r"-ExpandProperty Value };") - ps_cmd.append("$Settings['{}'] = [String] $Property;".format(setting)) + ps_cmd.append(f"$Settings['{setting}'] = [String] $Property;") ps_cmd.append(r"$Property = $Null;") # Validate the setting names that were passed in. @@ -1425,7 +1426,7 @@ def set_container_setting(name, container, settings): "ApplicationPoolIdentity": "4", } ps_cmd = list() - container_path = r"IIS:\{}\{}".format(container, name) + container_path = rf"IIS:\{container}\{name}" if not settings: log.warning("No settings provided") @@ -1449,7 +1450,7 @@ def set_container_setting(name, container, settings): complex(settings[setting]) value = settings[setting] except ValueError: - value = "'{}'".format(settings[setting]) + value = f"'{settings[setting]}'" # Map to numeric to support server 2008 if ( @@ -1462,18 +1463,18 @@ def set_container_setting(name, container, settings): [ "Set-ItemProperty", "-Path", - "'{}'".format(container_path), + f"'{container_path}'", "-Name", - "'{}'".format(setting), + f"'{setting}'", "-Value", - "{};".format(value), + f"{value};", ] ) cmd_ret = _srvmgr(ps_cmd) if cmd_ret["retcode"] != 0: - msg = "Unable to set settings for {}: {}".format(container, name) + msg = f"Unable to set settings for {container}: {name}" raise CommandExecutionError(msg) # Get the fields post-change so that we can verify tht all values @@ -1520,7 +1521,7 @@ def list_apps(site): """ ret = dict() ps_cmd = list() - ps_cmd.append("Get-WebApplication -Site '{}'".format(site)) + ps_cmd.append(f"Get-WebApplication -Site '{site}'") ps_cmd.append( r"| Select-Object applicationPool, path, PhysicalPath, preloadEnabled," ) @@ -1604,15 +1605,15 @@ def create_app(name, site, sourcepath, apppool=None): ps_cmd = [ "New-WebApplication", "-Name", - "'{}'".format(name), + f"'{name}'", "-Site", - "'{}'".format(site), + f"'{site}'", "-PhysicalPath", - "'{}'".format(sourcepath), + f"'{sourcepath}'", ] if apppool: - ps_cmd.extend(["-ApplicationPool", "'{}'".format(apppool)]) + ps_cmd.extend(["-ApplicationPool", f"'{apppool}'"]) cmd_ret = _srvmgr(ps_cmd) @@ -1658,9 +1659,9 @@ def remove_app(name, site): ps_cmd = [ "Remove-WebApplication", "-Name", - "'{}'".format(name), + f"'{name}'", "-Site", - "'{}'".format(site), + f"'{site}'", ] cmd_ret = _srvmgr(ps_cmd) @@ -1704,9 +1705,9 @@ def list_vdirs(site, app=_DEFAULT_APP): ps_cmd = [ "Get-WebVirtualDirectory", "-Site", - r"'{}'".format(site), + rf"'{site}'", "-Application", - r"'{}'".format(app), + rf"'{app}'", "|", "Select-Object PhysicalPath, @{ Name = 'name';", r"Expression = { $_.path.Trim('/') } }", @@ -1768,15 +1769,15 @@ def create_vdir(name, site, sourcepath, app=_DEFAULT_APP): ps_cmd = [ "New-WebVirtualDirectory", "-Name", - r"'{}'".format(name), + rf"'{name}'", "-Site", - r"'{}'".format(site), + rf"'{site}'", "-PhysicalPath", - r"'{}'".format(sourcepath), + rf"'{sourcepath}'", ] if app != _DEFAULT_APP: - ps_cmd.extend(["-Application", r"'{}'".format(app)]) + ps_cmd.extend(["-Application", rf"'{app}'"]) cmd_ret = _srvmgr(ps_cmd) @@ -1818,8 +1819,8 @@ def remove_vdir(name, site, app=_DEFAULT_APP): app_path = os.path.join(*app.rstrip("/").split("/")) if app_path: - app_path = "{}\\".format(app_path) - vdir_path = r"IIS:\Sites\{}\{}{}".format(site, app_path, name) + app_path = f"{app_path}\\" + vdir_path = rf"IIS:\Sites\{site}\{app_path}{name}" if name not in current_vdirs: log.debug("Virtual directory already absent: %s", name) @@ -1828,7 +1829,7 @@ def remove_vdir(name, site, app=_DEFAULT_APP): # We use Remove-Item here instead of Remove-WebVirtualDirectory, since the # latter has a bug that causes it to always prompt for user input. - ps_cmd = ["Remove-Item", "-Path", r"'{}'".format(vdir_path), "-Recurse"] + ps_cmd = ["Remove-Item", "-Path", rf"'{vdir_path}'", "-Recurse"] cmd_ret = _srvmgr(ps_cmd) @@ -1918,9 +1919,9 @@ def create_backup(name): salt '*' win_iis.create_backup good_config_20170209 """ if name in list_backups(): - raise CommandExecutionError("Backup already present: {}".format(name)) + raise CommandExecutionError(f"Backup already present: {name}") - ps_cmd = ["Backup-WebConfiguration", "-Name", "'{}'".format(name)] + ps_cmd = ["Backup-WebConfiguration", "-Name", f"'{name}'"] cmd_ret = _srvmgr(ps_cmd) @@ -1955,7 +1956,7 @@ def remove_backup(name): log.debug("Backup already removed: %s", name) return True - ps_cmd = ["Remove-WebConfigurationBackup", "-Name", "'{}'".format(name)] + ps_cmd = ["Remove-WebConfigurationBackup", "-Name", f"'{name}'"] cmd_ret = _srvmgr(ps_cmd) @@ -1987,7 +1988,7 @@ def list_worker_processes(apppool): salt '*' win_iis.list_worker_processes 'My App Pool' """ - ps_cmd = ["Get-ChildItem", r"'IIS:\AppPools\{}\WorkerProcesses'".format(apppool)] + ps_cmd = ["Get-ChildItem", rf"'IIS:\AppPools\{apppool}\WorkerProcesses'"] cmd_ret = _srvmgr(cmd=ps_cmd, return_json=True) @@ -2050,20 +2051,16 @@ def get_webapp_settings(name, site, settings): site, name ) ) - pscmd.append( - r' -Name "{}" -ErrorAction Stop | select Value;'.format(setting) - ) + pscmd.append(rf' -Name "{setting}" -ErrorAction Stop | select Value;') pscmd.append( r" $Property = $Property | Select-Object -ExpandProperty Value;" ) - pscmd.append(r" $Settings['{}'] = [String] $Property;".format(setting)) + pscmd.append(rf" $Settings['{setting}'] = [String] $Property;") pscmd.append(r" $Property = $Null;") if setting == "physicalPath" or setting == "applicationPool": - pscmd.append( - r" $Property = (get-webapplication {}).{};".format(name, setting) - ) - pscmd.append(r" $Settings['{}'] = [String] $Property;".format(setting)) + pscmd.append(rf" $Property = (get-webapplication {name}).{setting};") + pscmd.append(rf" $Settings['{setting}'] = [String] $Property;") pscmd.append(r" $Property = $Null;") else: @@ -2171,7 +2168,7 @@ def set_webapp_settings(name, site, settings): complex(settings[setting]) value = settings[setting] except ValueError: - value = "'{}'".format(settings[setting]) + value = f"'{settings[setting]}'" # Append relevant update command per setting key if setting == "userName" or setting == "password": @@ -2181,7 +2178,7 @@ def set_webapp_settings(name, site, settings): site, name ) ) - pscmd.append(' -Name "{}" -Value {};'.format(setting, value)) + pscmd.append(f' -Name "{setting}" -Value {value};') if setting == "physicalPath" or setting == "applicationPool": pscmd.append( @@ -2199,7 +2196,7 @@ def set_webapp_settings(name, site, settings): # Verify commands completed successfully if cmd_ret["retcode"] != 0: - msg = "Unable to set settings for web application {}".format(name) + msg = f"Unable to set settings for web application {name}" raise SaltInvocationError(msg) # verify changes @@ -2252,7 +2249,7 @@ def get_webconfiguration_settings(name, settings): [ "Get-WebConfigurationProperty", "-PSPath", - "'{}'".format(name), + f"'{name}'", "-Filter", "'{}'".format(setting["filter"]), "-Name", @@ -2267,9 +2264,7 @@ def get_webconfiguration_settings(name, settings): # Some ItemProperties are Strings and others are ConfigurationAttributes. # Since the former doesn't have a Value property, we need to account # for this. - ps_cmd.append( - "$Property = Get-WebConfigurationProperty -PSPath '{}'".format(name) - ) + ps_cmd.append(f"$Property = Get-WebConfigurationProperty -PSPath '{name}'") ps_cmd.append( "-Name '{}' -Filter '{}' -ErrorAction Stop;".format( setting["name"], setting["filter"] @@ -2367,7 +2362,7 @@ def set_webconfiguration_settings(name, settings): for value_item in setting["value"]: configelement_construct = [] for key, value in value_item.items(): - configelement_construct.append("{}='{}'".format(key, value)) + configelement_construct.append(f"{key}='{value}'") configelement_list.append( "@{" + ";".join(configelement_construct) + "}" ) @@ -2377,20 +2372,20 @@ def set_webconfiguration_settings(name, settings): [ "Set-WebConfigurationProperty", "-PSPath", - "'{}'".format(name), + f"'{name}'", "-Filter", "'{}'".format(setting["filter"]), "-Name", "'{}'".format(setting["name"]), "-Value", - "{};".format(value), + f"{value};", ] ) cmd_ret = _srvmgr(ps_cmd) if cmd_ret["retcode"] != 0: - msg = "Unable to set settings for {}".format(name) + msg = f"Unable to set settings for {name}" raise CommandExecutionError(msg) # Get the fields post-change so that we can verify tht all values diff --git a/salt/modules/win_ip.py b/salt/modules/win_ip.py index f1c11cfacbc..524a8d887c2 100644 --- a/salt/modules/win_ip.py +++ b/salt/modules/win_ip.py @@ -132,14 +132,14 @@ def is_enabled(iface): salt -G 'os_family:Windows' ip.is_enabled 'Local Area Connection #2' """ - cmd = ["netsh", "interface", "show", "interface", "name={}".format(iface)] + cmd = ["netsh", "interface", "show", "interface", f"name={iface}"] iface_found = False for line in __salt__["cmd.run"](cmd, python_shell=False).splitlines(): if "Connect state:" in line: iface_found = True return line.split()[-1] == "Connected" if not iface_found: - raise CommandExecutionError("Interface '{}' not found".format(iface)) + raise CommandExecutionError(f"Interface '{iface}' not found") return False @@ -173,7 +173,7 @@ def enable(iface): "interface", "set", "interface", - "name={}".format(iface), + f"name={iface}", "admin=ENABLED", ] __salt__["cmd.run"](cmd, python_shell=False) @@ -197,7 +197,7 @@ def disable(iface): "interface", "set", "interface", - "name={}".format(iface), + f"name={iface}", "admin=DISABLED", ] __salt__["cmd.run"](cmd, python_shell=False) @@ -215,7 +215,7 @@ def get_subnet_length(mask): salt -G 'os_family:Windows' ip.get_subnet_length 255.255.255.0 """ if not salt.utils.validate.net.netmask(mask): - raise SaltInvocationError("'{}' is not a valid netmask".format(mask)) + raise SaltInvocationError(f"'{mask}' is not a valid netmask") return salt.utils.network.get_net_size(mask) @@ -258,17 +258,17 @@ def set_static_ip(iface, addr, gateway=None, append=False): return {} if not salt.utils.validate.net.ipv4_addr(addr): - raise SaltInvocationError("Invalid address '{}'".format(addr)) + raise SaltInvocationError(f"Invalid address '{addr}'") if gateway and not salt.utils.validate.net.ipv4_addr(addr): - raise SaltInvocationError("Invalid default gateway '{}'".format(gateway)) + raise SaltInvocationError(f"Invalid default gateway '{gateway}'") if "/" not in addr: addr += "/32" if append and _find_addr(iface, addr): raise CommandExecutionError( - "Address '{}' already exists on interface '{}'".format(addr, iface) + f"Address '{addr}' already exists on interface '{iface}'" ) cmd = ["netsh", "interface", "ip"] @@ -276,12 +276,12 @@ def set_static_ip(iface, addr, gateway=None, append=False): cmd.append("add") else: cmd.append("set") - cmd.extend(["address", "name={}".format(iface)]) + cmd.extend(["address", f"name={iface}"]) if not append: cmd.append("source=static") - cmd.append("address={}".format(addr)) + cmd.append(f"address={addr}") if gateway: - cmd.append("gateway={}".format(gateway)) + cmd.append(f"gateway={gateway}") result = __salt__["cmd.run_all"](cmd, python_shell=False) if result["retcode"] != 0: @@ -348,7 +348,7 @@ def set_static_dns(iface, *addrs): "ip", "set", "dns", - "name={}".format(iface), + f"name={iface}", "source=static", "address=none", ] @@ -363,9 +363,9 @@ def set_static_dns(iface, *addrs): "ip", "set", "dns", - "name={}".format(iface), + f"name={iface}", "source=static", - "address={}".format(addr), + f"address={addr}", "register=primary", ] __salt__["cmd.run"](cmd, python_shell=False) @@ -377,9 +377,9 @@ def set_static_dns(iface, *addrs): "ip", "add", "dns", - "name={}".format(iface), - "address={}".format(addr), - "index={}".format(addr_index), + f"name={iface}", + f"address={addr}", + f"index={addr_index}", ] __salt__["cmd.run"](cmd, python_shell=False) addr_index = addr_index + 1 diff --git a/salt/modules/win_lgpo.py b/salt/modules/win_lgpo.py index 441b549fa50..71a875c5638 100644 --- a/salt/modules/win_lgpo.py +++ b/salt/modules/win_lgpo.py @@ -41,6 +41,7 @@ Current known limitations - struct - salt.utils.win_reg """ + import csv import ctypes import glob @@ -6932,9 +6933,9 @@ def _checkAllAdmxPolicies( TRUE_VALUE_XPATH, policy_file_data, ): - configured_elements[ - this_element_name - ] = True + configured_elements[this_element_name] = ( + True + ) log.trace( "element %s is configured true", child_item.attrib["id"], @@ -6951,9 +6952,9 @@ def _checkAllAdmxPolicies( FALSE_VALUE_XPATH, policy_file_data, ): - configured_elements[ - this_element_name - ] = False + configured_elements[this_element_name] = ( + False + ) policy_disabled_elements = ( policy_disabled_elements + 1 ) @@ -6975,9 +6976,9 @@ def _checkAllAdmxPolicies( TRUE_LIST_XPATH, policy_file_data, ): - configured_elements[ - this_element_name - ] = True + configured_elements[this_element_name] = ( + True + ) log.trace( "element %s is configured true", child_item.attrib["id"], @@ -6994,9 +6995,9 @@ def _checkAllAdmxPolicies( FALSE_LIST_XPATH, policy_file_data, ): - configured_elements[ - this_element_name - ] = False + configured_elements[this_element_name] = ( + False + ) policy_disabled_elements = ( policy_disabled_elements + 1 ) @@ -7096,9 +7097,9 @@ def _checkAllAdmxPolicies( ), policy_file_data, ) - configured_elements[ - this_element_name - ] = configured_value + configured_elements[this_element_name] = ( + configured_value + ) log.trace( "element %s is enabled, value == %s", child_item.attrib["id"], @@ -7218,9 +7219,9 @@ def _checkAllAdmxPolicies( policy_file_data, return_value_name=return_value_name, ) - configured_elements[ - this_element_name - ] = configured_value + configured_elements[this_element_name] = ( + configured_value + ) log.trace( "element %s is enabled values: %s", child_item.attrib["id"], @@ -9396,23 +9397,23 @@ def _get_policy_adm_setting( log.trace( "all valueList items exist in file" ) - configured_elements[ - this_element_name - ] = _getAdmlDisplayName( + configured_elements[this_element_name] = ( + _getAdmlDisplayName( + adml_xml_data=adml_policy_resources, + display_name=enum_item.attrib[ + "displayName" + ], + ) + ) + break + else: + configured_elements[this_element_name] = ( + _getAdmlDisplayName( adml_xml_data=adml_policy_resources, display_name=enum_item.attrib[ "displayName" ], ) - break - else: - configured_elements[ - this_element_name - ] = _getAdmlDisplayName( - adml_xml_data=adml_policy_resources, - display_name=enum_item.attrib[ - "displayName" - ], ) break elif etree.QName(child_item).localname == "list": @@ -9547,12 +9548,12 @@ def _get_policy_adm_setting( this_policy_namespace in policy_vals and this_policy_name in policy_vals[this_policy_namespace] ): - hierarchy.setdefault(this_policy_namespace, {})[ - this_policy_name - ] = _build_parent_list( - policy_definition=admx_policy, - return_full_policy_names=return_full_policy_names, - adml_language=adml_language, + hierarchy.setdefault(this_policy_namespace, {})[this_policy_name] = ( + _build_parent_list( + policy_definition=admx_policy, + return_full_policy_names=return_full_policy_names, + adml_language=adml_language, + ) ) if policy_vals and return_full_policy_names and not hierarchical_return: diff --git a/salt/modules/win_lgpo_reg.py b/salt/modules/win_lgpo_reg.py index 4c88a73c4f4..da0fe393730 100644 --- a/salt/modules/win_lgpo_reg.py +++ b/salt/modules/win_lgpo_reg.py @@ -54,6 +54,7 @@ The same values can also be used to create states for setting these policies. you will have to find the values needed to set them with this module using a different method. """ + import logging import salt.utils.platform diff --git a/salt/modules/win_license.py b/salt/modules/win_license.py index 669521368ef..11851398579 100644 --- a/salt/modules/win_license.py +++ b/salt/modules/win_license.py @@ -6,7 +6,6 @@ This module allows you to manage windows licensing via slmgr.vbs salt '*' license.install XXXXX-XXXXX-XXXXX-XXXXX-XXXXX """ - import logging import re @@ -53,7 +52,7 @@ def install(product_key): salt '*' license.install XXXXX-XXXXX-XXXXX-XXXXX-XXXXX """ - cmd = r"cscript C:\Windows\System32\slmgr.vbs /ipk {}".format(product_key) + cmd = rf"cscript C:\Windows\System32\slmgr.vbs /ipk {product_key}" return __salt__["cmd.run"](cmd) diff --git a/salt/modules/win_network.py b/salt/modules/win_network.py index ad57ca33bc3..d3d9de5681d 100644 --- a/salt/modules/win_network.py +++ b/salt/modules/win_network.py @@ -259,7 +259,7 @@ def get_route(ip): salt '*' network.get_route 10.10.10.10 """ - cmd = "Find-NetRoute -RemoteIPAddress {}".format(ip) + cmd = f"Find-NetRoute -RemoteIPAddress {ip}" out = __salt__["cmd.run"](cmd, shell="powershell", python_shell=True) regexp = re.compile( r"^IPAddress\s+:\s(?P[\d\.:]+)?.*" @@ -492,7 +492,7 @@ def connect(host, port=None, **kwargs): ): address = host else: - address = "{}".format(salt.utils.network.sanitize_host(host)) + address = f"{salt.utils.network.sanitize_host(host)}" # just in case we encounter error on getaddrinfo _address = ("unknown",) diff --git a/salt/modules/win_pkg.py b/salt/modules/win_pkg.py index c2ea64d823a..3b9224c4815 100644 --- a/salt/modules/win_pkg.py +++ b/salt/modules/win_pkg.py @@ -36,7 +36,6 @@ old. """ - import collections import datetime import errno diff --git a/salt/modules/win_pki.py b/salt/modules/win_pki.py index defb92e9d8b..d7129bcf2a1 100644 --- a/salt/modules/win_pki.py +++ b/salt/modules/win_pki.py @@ -90,10 +90,10 @@ def _validate_cert_path(name): """ Ensure that the certificate path, as determind from user input, is valid. """ - cmd = r"Test-Path -Path '{}'".format(name) + cmd = rf"Test-Path -Path '{name}'" if not ast.literal_eval(_cmd_run(cmd=cmd)): - raise SaltInvocationError(r"Invalid path specified: {}".format(name)) + raise SaltInvocationError(rf"Invalid path specified: {name}") def _validate_cert_format(name): @@ -155,11 +155,11 @@ def get_certs(context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE): ret = dict() cmd = list() blacklist_keys = ["DnsNameList"] - store_path = r"Cert:\{}\{}".format(context, store) + store_path = rf"Cert:\{context}\{store}" _validate_cert_path(name=store_path) - cmd.append(r"Get-ChildItem -Path '{}' | Select-Object".format(store_path)) + cmd.append(rf"Get-ChildItem -Path '{store_path}' | Select-Object") cmd.append(" DnsNameList, SerialNumber, Subject, Thumbprint, Version") items = _cmd_run(cmd="".join(cmd), as_json=True) @@ -216,15 +216,15 @@ def get_cert_file(name, cert_format=_DEFAULT_FORMAT, password=""): cmd.append( " System.Security.Cryptography.X509Certificates.X509Certificate2;" ) - cmd.append(r" $CertObject.Import('{}'".format(name)) - cmd.append(",'{}'".format(password)) + cmd.append(rf" $CertObject.Import('{name}'") + cmd.append(f",'{password}'") cmd.append(",'DefaultKeySet') ; $CertObject") cmd.append( " | Select-Object DnsNameList, SerialNumber, Subject, " "Thumbprint, Version" ) else: - cmd.append(r"Get-PfxCertificate -FilePath '{}'".format(name)) + cmd.append(rf"Get-PfxCertificate -FilePath '{name}'") cmd.append( " | Select-Object DnsNameList, SerialNumber, Subject, " "Thumbprint, Version" @@ -232,7 +232,7 @@ def get_cert_file(name, cert_format=_DEFAULT_FORMAT, password=""): else: cmd.append("$CertObject = New-Object") cmd.append(" System.Security.Cryptography.X509Certificates.X509Certificate2;") - cmd.append(r" $CertObject.Import('{}'); $CertObject".format(name)) + cmd.append(rf" $CertObject.Import('{name}'); $CertObject") cmd.append( " | Select-Object DnsNameList, SerialNumber, Subject, Thumbprint, Version" ) @@ -288,7 +288,7 @@ def import_cert( """ cmd = list() thumbprint = None - store_path = r"Cert:\{}\{}".format(context, store) + store_path = rf"Cert:\{context}\{store}" cert_format = cert_format.lower() _validate_cert_format(name=cert_format) @@ -331,14 +331,14 @@ def import_cert( cmd.append( r"Import-PfxCertificate " r"-FilePath '{}'".format(cached_source_path) ) - cmd.append(r" -CertStoreLocation '{}'".format(store_path)) + cmd.append(rf" -CertStoreLocation '{store_path}'") cmd.append(r" -Password $Password") if exportable: cmd.append(" -Exportable") else: cmd.append(r"Import-Certificate " r"-FilePath '{}'".format(cached_source_path)) - cmd.append(r" -CertStoreLocation '{}'".format(store_path)) + cmd.append(rf" -CertStoreLocation '{store_path}'") _cmd_run(cmd="".join(cmd)) @@ -387,7 +387,7 @@ def export_cert( """ cmd = list() thumbprint = thumbprint.upper() - cert_path = r"Cert:\{}\{}\{}".format(context, store, thumbprint) + cert_path = rf"Cert:\{context}\{store}\{thumbprint}" cert_format = cert_format.lower() _validate_cert_path(name=cert_path) @@ -415,7 +415,7 @@ def export_cert( r"Export-Certificate " r"-Cert '{}' -FilePath '{}'".format(cert_path, name) ) - cmd.append(r" | Out-Null; Test-Path -Path '{}'".format(name)) + cmd.append(rf" | Out-Null; Test-Path -Path '{name}'") ret = ast.literal_eval(_cmd_run(cmd="".join(cmd))) @@ -458,17 +458,17 @@ def test_cert( """ cmd = list() thumbprint = thumbprint.upper() - cert_path = r"Cert:\{}\{}\{}".format(context, store, thumbprint) - cmd.append(r"Test-Certificate -Cert '{}'".format(cert_path)) + cert_path = rf"Cert:\{context}\{store}\{thumbprint}" + cmd.append(rf"Test-Certificate -Cert '{cert_path}'") _validate_cert_path(name=cert_path) if untrusted_root: cmd.append(" -AllowUntrustedRoot") if dns_name: - cmd.append(" -DnsName '{}'".format(dns_name)) + cmd.append(f" -DnsName '{dns_name}'") if eku: - cmd.append(" -EKU '{}'".format(eku)) + cmd.append(f" -EKU '{eku}'") cmd.append(" -ErrorAction SilentlyContinue") @@ -493,9 +493,9 @@ def remove_cert(thumbprint, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE): salt '*' win_pki.remove_cert thumbprint='AAA000' """ thumbprint = thumbprint.upper() - store_path = r"Cert:\{}\{}".format(context, store) - cert_path = r"{}\{}".format(store_path, thumbprint) - cmd = r"Remove-Item -Path '{}'".format(cert_path) + store_path = rf"Cert:\{context}\{store}" + cert_path = rf"{store_path}\{thumbprint}" + cmd = rf"Remove-Item -Path '{cert_path}'" current_certs = get_certs(context=context, store=store) diff --git a/salt/modules/win_powercfg.py b/salt/modules/win_powercfg.py index 5a76e98b58b..16428b48ea7 100644 --- a/salt/modules/win_powercfg.py +++ b/salt/modules/win_powercfg.py @@ -47,9 +47,9 @@ def _get_powercfg_minute_values(scheme, guid, subguid, safe_name): scheme = _get_current_scheme() if __grains__["osrelease"] == "7": - cmd = "powercfg /q {} {}".format(scheme, guid) + cmd = f"powercfg /q {scheme} {guid}" else: - cmd = "powercfg /q {} {} {}".format(scheme, guid, subguid) + cmd = f"powercfg /q {scheme} {guid} {subguid}" out = __salt__["cmd.run"](cmd, python_shell=False) split = out.split("\r\n\r\n") diff --git a/salt/modules/win_psget.py b/salt/modules/win_psget.py index 66302b4f91e..af978969a98 100644 --- a/salt/modules/win_psget.py +++ b/salt/modules/win_psget.py @@ -82,7 +82,7 @@ def _pshell(cmd, cwd=None, depth=2): in Xml format and load that into python """ - cmd = '{} | ConvertTo-Xml -Depth {} -As "stream"'.format(cmd, depth) + cmd = f'{cmd} | ConvertTo-Xml -Depth {depth} -As "stream"' log.debug("DSC: %s", cmd) results = __salt__["cmd.run_all"]( @@ -94,9 +94,7 @@ def _pshell(cmd, cwd=None, depth=2): if "retcode" not in results or results["retcode"] != 0: # run_all logs an error to log.error, fail hard back to the user - raise CommandExecutionError( - "Issue executing powershell {}".format(cmd), info=results - ) + raise CommandExecutionError(f"Issue executing powershell {cmd}", info=results) try: ret = _ps_xml_to_dict( @@ -224,8 +222,8 @@ def install( flags.append(("Repository", repository)) params = "" for flag, value in flags: - params += "-{} {} ".format(flag, value) - cmd = "Install-Module {} -Force".format(params) + params += f"-{flag} {value} " + cmd = f"Install-Module {params} -Force" _pshell(cmd) return name in list_modules() @@ -259,8 +257,8 @@ def update(name, maximum_version=None, required_version=None): params = "" for flag, value in flags: - params += "-{} {} ".format(flag, value) - cmd = "Update-Module {} -Force".format(params) + params += f"-{flag} {value} " + cmd = f"Update-Module {params} -Force" _pshell(cmd) return name in list_modules() @@ -279,7 +277,7 @@ def remove(name): salt 'win01' psget.remove PowerPlan """ # Putting quotes around the parameter protects against command injection - cmd = 'Uninstall-Module "{}"'.format(name) + cmd = f'Uninstall-Module "{name}"' no_ret = _pshell(cmd) return name not in list_modules() @@ -313,8 +311,8 @@ def register_repository(name, location, installation_policy=None): params = "" for flag, value in flags: - params += "-{} {} ".format(flag, value) - cmd = "Register-PSRepository {}".format(params) + params += f"-{flag} {value} " + cmd = f"Register-PSRepository {params}" no_ret = _pshell(cmd) return name not in list_modules() @@ -333,6 +331,6 @@ def get_repository(name): salt 'win01' psget.get_repository MyRepo """ # Putting quotes around the parameter protects against command injection - cmd = 'Get-PSRepository "{}"'.format(name) + cmd = f'Get-PSRepository "{name}"' no_ret = _pshell(cmd) return name not in list_modules() diff --git a/salt/modules/win_servermanager.py b/salt/modules/win_servermanager.py index ab714b30e37..15d6c5d64f5 100644 --- a/salt/modules/win_servermanager.py +++ b/salt/modules/win_servermanager.py @@ -7,7 +7,6 @@ available and installed roles/features. Can install and remove roles/features. :depends: PowerShell module ``ServerManager`` """ - import logging import shlex diff --git a/salt/modules/win_service.py b/salt/modules/win_service.py index f788f7559d9..38356e87c69 100644 --- a/salt/modules/win_service.py +++ b/salt/modules/win_service.py @@ -5,6 +5,7 @@ Windows Service module. Rewritten to use PyWin32 """ + import fnmatch import logging import re @@ -112,7 +113,7 @@ def _cmd_quote(cmd): cmd = cmd.strip('"').strip("'") # Ensure the path to the binary is wrapped in double quotes to account for # spaces in the path - cmd = '"{}"'.format(cmd) + cmd = f'"{cmd}"' return cmd @@ -339,9 +340,7 @@ def start(name, timeout=90): win32serviceutil.StartService(name) except pywintypes.error as exc: if exc.winerror != 1056: - raise CommandExecutionError( - "Failed To Start {}: {}".format(name, exc.strerror) - ) + raise CommandExecutionError(f"Failed To Start {name}: {exc.strerror}") log.debug('Service "%s" is running', name) srv_status = _status_wait( @@ -380,9 +379,7 @@ def stop(name, timeout=90): win32serviceutil.StopService(name) except pywintypes.error as exc: if exc.winerror != 1062: - raise CommandExecutionError( - "Failed To Stop {}: {}".format(name, exc.strerror) - ) + raise CommandExecutionError(f"Failed To Stop {name}: {exc.strerror}") log.debug('Service "%s" is not running', name) srv_status = _status_wait( @@ -668,7 +665,7 @@ def modify( win32service.SERVICE_CHANGE_CONFIG | win32service.SERVICE_QUERY_CONFIG, ) except pywintypes.error as exc: - raise CommandExecutionError("Failed To Open {}: {}".format(name, exc.strerror)) + raise CommandExecutionError(f"Failed To Open {name}: {exc.strerror}") config_info = win32service.QueryServiceConfig(handle_svc) @@ -679,7 +676,7 @@ def modify( # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: - bin_path = "{} {}".format(bin_path, exe_args) + bin_path = f"{bin_path} {exe_args}" changes["BinaryPath"] = bin_path if service_type is not None: @@ -688,7 +685,7 @@ def modify( if run_interactive: service_type = service_type | win32service.SERVICE_INTERACTIVE_PROCESS else: - raise CommandExecutionError("Invalid Service Type: {}".format(service_type)) + raise CommandExecutionError(f"Invalid Service Type: {service_type}") else: if run_interactive is True: service_type = config_info[0] | win32service.SERVICE_INTERACTIVE_PROCESS @@ -709,7 +706,7 @@ def modify( if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: - raise CommandExecutionError("Invalid Start Type: {}".format(start_type)) + raise CommandExecutionError(f"Invalid Start Type: {start_type}") changes["StartType"] = SERVICE_START_TYPE[start_type] else: start_type = win32service.SERVICE_NO_CHANGE @@ -718,9 +715,7 @@ def modify( if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: - raise CommandExecutionError( - "Invalid Error Control: {}".format(error_control) - ) + raise CommandExecutionError(f"Invalid Error Control: {error_control}") changes["ErrorControl"] = SERVICE_ERROR_CONTROL[error_control] else: error_control = win32service.SERVICE_NO_CHANGE @@ -897,7 +892,7 @@ def create( account_name=".\\LocalSystem", account_password=None, run_interactive=False, - **kwargs + **kwargs, ): """ Create the named service. @@ -1003,29 +998,29 @@ def create( # Test if the service already exists if name in get_all(): - raise CommandExecutionError("Service Already Exists: {}".format(name)) + raise CommandExecutionError(f"Service Already Exists: {name}") # shlex.quote the path to the binary bin_path = _cmd_quote(bin_path) if exe_args is not None: - bin_path = "{} {}".format(bin_path, exe_args) + bin_path = f"{bin_path} {exe_args}" if service_type.lower() in SERVICE_TYPE: service_type = SERVICE_TYPE[service_type.lower()] if run_interactive: service_type = service_type | win32service.SERVICE_INTERACTIVE_PROCESS else: - raise CommandExecutionError("Invalid Service Type: {}".format(service_type)) + raise CommandExecutionError(f"Invalid Service Type: {service_type}") if start_type.lower() in SERVICE_START_TYPE: start_type = SERVICE_START_TYPE[start_type.lower()] else: - raise CommandExecutionError("Invalid Start Type: {}".format(start_type)) + raise CommandExecutionError(f"Invalid Start Type: {start_type}") if error_control.lower() in SERVICE_ERROR_CONTROL: error_control = SERVICE_ERROR_CONTROL[error_control.lower()] else: - raise CommandExecutionError("Invalid Error Control: {}".format(error_control)) + raise CommandExecutionError(f"Invalid Error Control: {error_control}") if start_delayed: if start_type != 2: @@ -1120,18 +1115,14 @@ def delete(name, timeout=90): except pywintypes.error as exc: win32service.CloseServiceHandle(handle_scm) if exc.winerror != 1060: - raise CommandExecutionError( - "Failed to open {}. {}".format(name, exc.strerror) - ) + raise CommandExecutionError(f"Failed to open {name}. {exc.strerror}") log.debug('Service "%s" is not present', name) return True try: win32service.DeleteService(handle_svc) except pywintypes.error as exc: - raise CommandExecutionError( - "Failed to delete {}. {}".format(name, exc.strerror) - ) + raise CommandExecutionError(f"Failed to delete {name}. {exc.strerror}") finally: log.debug("Cleaning up") win32service.CloseServiceHandle(handle_scm) diff --git a/salt/modules/win_shortcut.py b/salt/modules/win_shortcut.py index c11cc1c64d1..90d1ae52f63 100644 --- a/salt/modules/win_shortcut.py +++ b/salt/modules/win_shortcut.py @@ -6,6 +6,7 @@ url shortcuts. .. versionadded:: 3005 """ + # https://docs.microsoft.com/en-us/troubleshoot/windows-client/admin-development/create-desktop-shortcut-with-wsh # https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/windows-scripting/f5y78918(v=vs.84) import logging @@ -74,11 +75,11 @@ def get(path): salt * shortcut.get path="C:\path\to\shortcut.lnk" """ if not os.path.exists(path): - raise CommandExecutionError("Shortcut not found: {}".format(path)) + raise CommandExecutionError(f"Shortcut not found: {path}") if not path.endswith((".lnk", ".url")): _, ext = os.path.splitext(path) - raise CommandExecutionError("Invalid file extension: {}".format(ext)) + raise CommandExecutionError(f"Invalid file extension: {ext}") # This will load the existing shortcut with salt.utils.winapi.Com(): @@ -101,7 +102,7 @@ def get(path): if target: target = salt.utils.path.expand(target) else: - msg = "Not a valid shortcut: {}".format(path) + msg = f"Not a valid shortcut: {path}" log.debug(msg) raise CommandExecutionError(msg) if shortcut.Arguments: @@ -299,11 +300,11 @@ def modify( salt * shortcut.modify "C:\path\to\shortcut.lnk" "C:\Windows\notepad.exe" """ if not os.path.exists(path): - raise CommandExecutionError("Shortcut not found: {}".format(path)) + raise CommandExecutionError(f"Shortcut not found: {path}") if not path.endswith((".lnk", ".url")): _, ext = os.path.splitext(path) - raise CommandExecutionError("Invalid file extension: {}".format(ext)) + raise CommandExecutionError(f"Invalid file extension: {ext}") return _set_info( path=path, @@ -435,14 +436,14 @@ def create( """ if not path.endswith((".lnk", ".url")): _, ext = os.path.splitext(path) - raise CommandExecutionError("Invalid file extension: {}".format(ext)) + raise CommandExecutionError(f"Invalid file extension: {ext}") if os.path.exists(path): if backup: log.debug("Backing up: %s", path) file, ext = os.path.splitext(path) ext = ext.strip(".") - backup_path = "{}-{}.{}".format(file, time.time_ns(), ext) + backup_path = f"{file}-{time.time_ns()}.{ext}" os.rename(path, backup_path) elif force: log.debug("Removing: %s", path) @@ -471,11 +472,11 @@ def create( __salt__["file.makedirs"](path=path, owner=user) except CommandExecutionError as exc: raise CommandExecutionError( - "Error creating parent directory: {}".format(exc.message) + f"Error creating parent directory: {exc.message}" ) else: raise CommandExecutionError( - "Parent directory not present: {}".format(os.path.dirname(path)) + f"Parent directory not present: {os.path.dirname(path)}" ) return _set_info( diff --git a/salt/modules/win_smtp_server.py b/salt/modules/win_smtp_server.py index ab0e602fe79..44531a569b9 100644 --- a/salt/modules/win_smtp_server.py +++ b/salt/modules/win_smtp_server.py @@ -109,7 +109,7 @@ def _normalize_server_settings(**settings): _LOG.debug("Fixing value: %s", settings[setting]) value_from_key = next(iter(settings[setting].keys())) - ret[setting] = "{{{0}}}".format(value_from_key) + ret[setting] = f"{{{value_from_key}}}" else: ret[setting] = settings[setting] return ret @@ -391,7 +391,7 @@ def get_connection_ip_list(as_wmi_format=False, server=_DEFAULT_SERVER): for unnormalized_address in addresses: ip_address, subnet = re.split(reg_separator, unnormalized_address) if as_wmi_format: - ret.append("{}, {}".format(ip_address, subnet)) + ret.append(f"{ip_address}, {subnet}") else: ret[ip_address] = subnet @@ -431,9 +431,7 @@ def set_connection_ip_list( # Convert addresses to the 'ip_address, subnet' format used by # IIsIPSecuritySetting. for address in addresses: - formatted_addresses.append( - "{}, {}".format(address.strip(), addresses[address].strip()) - ) + formatted_addresses.append(f"{address.strip()}, {addresses[address].strip()}") current_addresses = get_connection_ip_list(as_wmi_format=True, server=server) diff --git a/salt/modules/win_snmp.py b/salt/modules/win_snmp.py index 0fc7775ea6c..a2cff764477 100644 --- a/salt/modules/win_snmp.py +++ b/salt/modules/win_snmp.py @@ -11,11 +11,11 @@ from salt.exceptions import CommandExecutionError, SaltInvocationError _HKEY = "HKLM" _SNMP_KEY = r"SYSTEM\CurrentControlSet\Services\SNMP\Parameters" -_AGENT_KEY = r"{}\RFC1156Agent".format(_SNMP_KEY) -_COMMUNITIES_KEY = r"{}\ValidCommunities".format(_SNMP_KEY) +_AGENT_KEY = rf"{_SNMP_KEY}\RFC1156Agent" +_COMMUNITIES_KEY = rf"{_SNMP_KEY}\ValidCommunities" _SNMP_GPO_KEY = r"SOFTWARE\Policies\SNMP\Parameters" -_COMMUNITIES_GPO_KEY = r"{}\ValidCommunities".format(_SNMP_GPO_KEY) +_COMMUNITIES_GPO_KEY = rf"{_SNMP_GPO_KEY}\ValidCommunities" _PERMISSION_TYPES = { "None": 1, diff --git a/salt/modules/win_status.py b/salt/modules/win_status.py index fad2323a43b..ee789c4363b 100644 --- a/salt/modules/win_status.py +++ b/salt/modules/win_status.py @@ -7,6 +7,7 @@ or for problem solving if your minion is having problems. :depends: - wmi """ + import ctypes import datetime import logging diff --git a/salt/modules/win_task.py b/salt/modules/win_task.py index 8c9f2718dbd..2151b663ba3 100644 --- a/salt/modules/win_task.py +++ b/salt/modules/win_task.py @@ -227,7 +227,7 @@ def _get_date_value(date): :rtype: str """ try: - return "{}".format(date) + return f"{date}" except ValueError: return "Never" @@ -323,11 +323,11 @@ def _save_task_definition( try: failure_code = fc[exc[5]] except KeyError: - failure_code = "Unknown Failure: {}".format(error) + failure_code = f"Unknown Failure: {error}" log.debug("Failed to modify task: %s", failure_code) - return "Failed to modify task: {}".format(failure_code) + return f"Failed to modify task: {failure_code}" def list_tasks(location="\\"): @@ -363,7 +363,7 @@ def list_tasks(location="\\"): try: task_folder = task_service.GetFolder(location) except pywintypes.com_error: - msg = "Unable to load location: {}".format(location) + msg = f"Unable to load location: {location}" log.error(msg) raise CommandExecutionError(msg) @@ -551,7 +551,7 @@ def create_task( # Check for existing task if name in list_tasks(location) and not force: # Connect to an existing task definition - return "{} already exists".format(name) + return f"{name} already exists" # connect to the task scheduler with salt.utils.winapi.Com(): @@ -566,7 +566,7 @@ def create_task( task_definition=task_definition, user_name=user_name, password=password, - **kwargs + **kwargs, ) # Add Action @@ -642,7 +642,7 @@ def create_task_from_xml( # Check for existing task if name in list_tasks(location): # Connect to an existing task definition - return "{} already exists".format(name) + return f"{name} already exists" if not xml_text and not xml_path: raise ArgumentValueError("Must specify either xml_text or xml_path") @@ -731,7 +731,7 @@ def create_task_from_xml( try: failure_code = fc[error_code] except KeyError: - failure_code = "Unknown Failure: {}".format(error_code) + failure_code = f"Unknown Failure: {error_code}" finally: log.debug("Failed to create task: %s", failure_code) raise CommandExecutionError(failure_code) @@ -767,7 +767,7 @@ def create_folder(name, location="\\"): # Check for existing folder if name in list_folders(location): # Connect to an existing task definition - return "{} already exists".format(name) + return f"{name} already exists" # Create the task service object with salt.utils.winapi.Com(): @@ -812,7 +812,7 @@ def edit_task( force_stop=None, delete_after=None, multiple_instances=None, - **kwargs + **kwargs, ): r""" Edit the parameters of a task. Triggers and Actions cannot be edited yet. @@ -1016,7 +1016,7 @@ def edit_task( else: # Not found and create_new not set, return not found - return "{} not found".format(name) + return f"{name} not found" # General Information if save_definition: @@ -1183,7 +1183,7 @@ def delete_task(name, location="\\"): """ # Check for existing task if name not in list_tasks(location): - return "{} not found in {}".format(name, location) + return f"{name} not found in {location}" # connect to the task scheduler with salt.utils.winapi.Com(): @@ -1224,7 +1224,7 @@ def delete_folder(name, location="\\"): """ # Check for existing folder if name not in list_folders(location): - return "{} not found in {}".format(name, location) + return f"{name} not found in {location}" # connect to the task scheduler with salt.utils.winapi.Com(): @@ -1266,7 +1266,7 @@ def run(name, location="\\"): """ # Check for existing folder if name not in list_tasks(location): - return "{} not found in {}".format(name, location) + return f"{name} not found in {location}" # connect to the task scheduler with salt.utils.winapi.Com(): @@ -1309,7 +1309,7 @@ def run_wait(name, location="\\"): """ # Check for existing folder if name not in list_tasks(location): - return "{} not found in {}".format(name, location) + return f"{name} not found in {location}" # connect to the task scheduler with salt.utils.winapi.Com(): @@ -1370,7 +1370,7 @@ def stop(name, location="\\"): """ # Check for existing folder if name not in list_tasks(location): - return "{} not found in {}".format(name, location) + return f"{name} not found in {location}" # connect to the task scheduler with salt.utils.winapi.Com(): @@ -1419,7 +1419,7 @@ def status(name, location="\\"): """ # Check for existing folder if name not in list_tasks(location): - return "{} not found in {}".format(name, location) + return f"{name} not found in {location}" # connect to the task scheduler with salt.utils.winapi.Com(): @@ -1458,7 +1458,7 @@ def info(name, location="\\"): """ # Check for existing folder if name not in list_tasks(location): - return "{} not found in {}".format(name, location) + return f"{name} not found in {location}" # connect to the task scheduler with salt.utils.winapi.Com(): @@ -1582,9 +1582,9 @@ def info(name, location="\\"): trigger["repeat_interval"] = _reverse_lookup( duration, triggerObj.Repetition.Interval ) - trigger[ - "repeat_stop_at_duration_end" - ] = triggerObj.Repetition.StopAtDurationEnd + trigger["repeat_stop_at_duration_end"] = ( + triggerObj.Repetition.StopAtDurationEnd + ) triggers.append(trigger) properties["settings"] = settings @@ -1714,7 +1714,7 @@ def add_action(name=None, location="\\", action_type="Execute", **kwargs): else: # Not found and create_new not set, return not found - return "{} not found".format(name) + return f"{name} not found" # Action Settings task_action = task_definition.Actions.Create(action_types[action_type]) @@ -1808,7 +1808,7 @@ def _clear_actions(name, location="\\"): # TODO: action. # Check for existing task if name not in list_tasks(location): - return "{} not found in {}".format(name, location) + return f"{name} not found in {location}" # Create the task service object with salt.utils.winapi.Com(): @@ -1848,7 +1848,7 @@ def add_trigger( repeat_stop_at_duration_end=False, execution_time_limit=None, delay=None, - **kwargs + **kwargs, ): r""" Add a trigger to a Windows Scheduled task @@ -2303,7 +2303,7 @@ def add_trigger( else: # Not found and create_new not set, return not found - return "{} not found".format(name) + return f"{name} not found" # Create a New Trigger trigger = task_definition.Triggers.Create(trigger_types[trigger_type]) @@ -2481,7 +2481,7 @@ def clear_triggers(name, location="\\"): """ # Check for existing task if name not in list_tasks(location): - return "{} not found in {}".format(name, location) + return f"{name} not found in {location}" # Create the task service object with salt.utils.winapi.Com(): diff --git a/salt/modules/win_timezone.py b/salt/modules/win_timezone.py index d8c3c82bb23..fde63eb7ff8 100644 --- a/salt/modules/win_timezone.py +++ b/salt/modules/win_timezone.py @@ -1,6 +1,7 @@ """ Module for managing timezone on Windows systems. """ + import logging from datetime import datetime @@ -293,14 +294,14 @@ def set_zone(timezone): else: # Raise error because it's neither key nor value - raise CommandExecutionError("Invalid timezone passed: {}".format(timezone)) + raise CommandExecutionError(f"Invalid timezone passed: {timezone}") # Set the value cmd = ["tzutil", "/s", win_zone] res = __salt__["cmd.run_all"](cmd, python_shell=False) if res["retcode"]: raise CommandExecutionError( - "tzutil encountered an error setting timezone: {}".format(timezone), + f"tzutil encountered an error setting timezone: {timezone}", info=res, ) return zone_compare(timezone) @@ -335,7 +336,7 @@ def zone_compare(timezone): else: # Raise error because it's neither key nor value - raise CommandExecutionError("Invalid timezone passed: {}".format(timezone)) + raise CommandExecutionError(f"Invalid timezone passed: {timezone}") return get_zone() == mapper.get_unix(check_zone, "Unknown") diff --git a/salt/modules/win_useradd.py b/salt/modules/win_useradd.py index e557ffd8113..a9e9b2629b6 100644 --- a/salt/modules/win_useradd.py +++ b/salt/modules/win_useradd.py @@ -250,7 +250,7 @@ def update( try: dt_obj = salt.utils.dateutils.date_cast(expiration_date) except (ValueError, RuntimeError): - return "Invalid Date/Time Format: {}".format(expiration_date) + return f"Invalid Date/Time Format: {expiration_date}" user_info["acct_expires"] = time.mktime(dt_obj.timetuple()) if expired is not None: if expired: @@ -467,7 +467,7 @@ def addgroup(name, group): if group in user["groups"]: return True - cmd = 'net localgroup "{}" {} /add'.format(group, name) + cmd = f'net localgroup "{group}" {name} /add' ret = __salt__["cmd.run_all"](cmd, python_shell=True) return ret["retcode"] == 0 @@ -502,7 +502,7 @@ def removegroup(name, group): if group not in user["groups"]: return True - cmd = 'net localgroup "{}" {} /delete'.format(group, name) + cmd = f'net localgroup "{group}" {name} /delete' ret = __salt__["cmd.run_all"](cmd, python_shell=True) return ret["retcode"] == 0 @@ -633,14 +633,14 @@ def chgroups(name, groups, append=True): for group in ugrps: group = shlex.quote(group).lstrip("'").rstrip("'") if group not in groups: - cmd = 'net localgroup "{}" {} /delete'.format(group, name) + cmd = f'net localgroup "{group}" {name} /delete' __salt__["cmd.run_all"](cmd, python_shell=True) for group in groups: if group in ugrps: continue group = shlex.quote(group).lstrip("'").rstrip("'") - cmd = 'net localgroup "{}" {} /add'.format(group, name) + cmd = f'net localgroup "{group}" {name} /add' out = __salt__["cmd.run_all"](cmd, python_shell=True) if out["retcode"] != 0: log.error(out["stdout"]) @@ -774,7 +774,7 @@ def _get_userprofile_from_registry(user, sid): """ profile_dir = __utils__["reg.read_value"]( "HKEY_LOCAL_MACHINE", - "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\{}".format(sid), + f"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\ProfileList\\{sid}", "ProfileImagePath", )["vdata"] log.debug('user %s with sid=%s profile is located at "%s"', user, sid, profile_dir) @@ -901,12 +901,12 @@ def rename(name, new_name): # Load information for the current name current_info = info(name) if not current_info: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") # Look for an existing user with the new name new_info = info(new_name) if new_info: - raise CommandExecutionError("User '{}' already exists".format(new_name)) + raise CommandExecutionError(f"User '{new_name}' already exists") # Rename the user account # Connect to WMI @@ -917,7 +917,7 @@ def rename(name, new_name): try: user = c.Win32_UserAccount(Name=name)[0] except IndexError: - raise CommandExecutionError("User '{}' does not exist".format(name)) + raise CommandExecutionError(f"User '{name}' does not exist") # Rename the user result = user.Rename(new_name)[0] diff --git a/salt/modules/win_wua.py b/salt/modules/win_wua.py index 1393fc6efaf..c7799d5f6be 100644 --- a/salt/modules/win_wua.py +++ b/salt/modules/win_wua.py @@ -54,6 +54,7 @@ Group Policy using the ``lgpo`` module. :depends: salt.utils.win_update """ + import logging import salt.utils.platform @@ -994,7 +995,7 @@ def set_wu_settings( ) = 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]) + ret["Comment"] = f"Failed with failure code: {exc[5]}" ret["Success"] = False else: # msupdate is false, so remove it from the services @@ -1018,7 +1019,7 @@ def set_wu_settings( # -2147024891 (0x80070005) Access Denied # -2145091564 (0x80248014) Service Not Found (shouldn't get # this with the check for _get_msupdate_status above - ret["Comment"] = "Failed with failure code: {}".format(exc[5]) + ret["Comment"] = f"Failed with failure code: {exc[5]}" ret["Success"] = False else: ret["msupdate"] = msupdate diff --git a/salt/modules/win_wusa.py b/salt/modules/win_wusa.py index 1a25fed3fa6..0cb1ef1b21d 100644 --- a/salt/modules/win_wusa.py +++ b/salt/modules/win_wusa.py @@ -8,7 +8,6 @@ Microsoft Update files management via wusa.exe .. versionadded:: 2018.3.4 """ - import logging import os diff --git a/salt/modules/winrepo.py b/salt/modules/winrepo.py index 12d4a0b4c5f..d7d39253eb1 100644 --- a/salt/modules/winrepo.py +++ b/salt/modules/winrepo.py @@ -6,6 +6,7 @@ Module to manage Windows software repo on a Standalone Minion For documentation on Salt's Windows Repo feature, see :ref:`here `. """ + import logging import os @@ -164,15 +165,15 @@ def show_sls(name, saltenv="base"): repo.extend(definition) # Check for the sls file by name - sls_file = "{}.sls".format(os.sep.join(repo)) + sls_file = f"{os.sep.join(repo)}.sls" if not os.path.exists(sls_file): # Maybe it's a directory with an init.sls - sls_file = "{}\\init.sls".format(os.sep.join(repo)) + sls_file = f"{os.sep.join(repo)}\\init.sls" if not os.path.exists(sls_file): # It's neither, return - return "Software definition {} not found".format(name) + return f"Software definition {name} not found" # Load the renderer renderers = salt.loader.render(__opts__, __salt__) @@ -192,7 +193,7 @@ def show_sls(name, saltenv="base"): except SaltRenderError as exc: log.debug("Failed to compile %s.", sls_file) log.debug("Error: %s.", exc) - config["Message"] = "Failed to compile {}".format(sls_file) - config["Error"] = "{}".format(exc) + config["Message"] = f"Failed to compile {sls_file}" + config["Error"] = f"{exc}" return config diff --git a/salt/modules/wordpress.py b/salt/modules/wordpress.py index 792d4f25536..7ce4c6b3cca 100644 --- a/salt/modules/wordpress.py +++ b/salt/modules/wordpress.py @@ -41,7 +41,7 @@ def list_plugins(path, user): salt '*' wordpress.list_plugins /var/www/html apache """ ret = [] - resp = __salt__["cmd.shell"]("wp --path={} plugin list".format(path), runas=user) + resp = __salt__["cmd.shell"](f"wp --path={path} plugin list", runas=user) for line in resp.split("\n")[1:]: ret.append(line.split("\t")) return [plugin.__dict__ for plugin in map(_get_plugins, ret)] @@ -68,7 +68,7 @@ def show_plugin(name, path, user): """ ret = {"name": name} resp = __salt__["cmd.shell"]( - "wp --path={} plugin status {}".format(path, name), runas=user + f"wp --path={path} plugin status {name}", runas=user ).split("\n") for line in resp: if "Status" in line: @@ -101,9 +101,7 @@ def activate(name, path, user): if check["status"] == "active": # already active return None - resp = __salt__["cmd.shell"]( - "wp --path={} plugin activate {}".format(path, name), runas=user - ) + resp = __salt__["cmd.shell"](f"wp --path={path} plugin activate {name}", runas=user) if "Success" in resp: return True elif show_plugin(name, path, user)["status"] == "active": @@ -135,7 +133,7 @@ def deactivate(name, path, user): # already inactive return None resp = __salt__["cmd.shell"]( - "wp --path={} plugin deactivate {}".format(path, name), runas=user + f"wp --path={path} plugin deactivate {name}", runas=user ) if "Success" in resp: return True @@ -160,9 +158,7 @@ def is_installed(path, user=None): salt '*' wordpress.is_installed /var/www/html apache """ - retcode = __salt__["cmd.retcode"]( - "wp --path={} core is-installed".format(path), runas=user - ) + retcode = __salt__["cmd.retcode"](f"wp --path={path} core is-installed", runas=user) if retcode == 0: return True return False diff --git a/salt/modules/x509_v2.py b/salt/modules/x509_v2.py index a8069518c82..1e20c088d59 100644 --- a/salt/modules/x509_v2.py +++ b/salt/modules/x509_v2.py @@ -165,6 +165,7 @@ Note that when a ``ca_server`` is involved, both peers must use the updated modu .. _x509-setup: """ + import base64 import copy import datetime @@ -766,9 +767,11 @@ def encode_certificate( else: cipher = serialization.BestAvailableEncryption(pkcs12_passphrase) crt_bytes = serialization.pkcs12.serialize_key_and_certificates( - name=salt.utils.stringutils.to_bytes(pkcs12_friendlyname) - if pkcs12_friendlyname - else None, + name=( + salt.utils.stringutils.to_bytes(pkcs12_friendlyname) + if pkcs12_friendlyname + else None + ), key=private_key, cert=cert, cas=append_certs, diff --git a/salt/modules/xapi_virt.py b/salt/modules/xapi_virt.py index 489a5b2ed4a..89772a302cd 100644 --- a/salt/modules/xapi_virt.py +++ b/salt/modules/xapi_virt.py @@ -50,7 +50,7 @@ def _check_xenapi(): if os.path.isfile(debian_xen_version): # __salt__ is not available in __virtual__ xenversion = salt.modules.cmdmod._run_quiet(debian_xen_version) - xapipath = "/usr/lib/xen-{}/lib/python".format(xenversion) + xapipath = f"/usr/lib/xen-{xenversion}/lib/python" if os.path.isdir(xapipath): sys.path.append(xapipath) @@ -156,7 +156,7 @@ def _get_metrics_record(xapi, rectype, record): Internal, returns metrics record for a rectype """ metrics_id = record["metrics"] - return getattr(xapi, "{}_metrics".format(rectype)).get_record(metrics_id) + return getattr(xapi, f"{rectype}_metrics").get_record(metrics_id) def _get_val(record, keys): @@ -507,10 +507,10 @@ def vcpu_pin(vm_, vcpu, cpus): if cpus == "all": cpumap = cpu_make_map("0-63") else: - cpumap = cpu_make_map("{}".format(cpus)) + cpumap = cpu_make_map(f"{cpus}") try: - xapi.VM.add_to_VCPUs_params_live(vm_uuid, "cpumap{}".format(vcpu), cpumap) + xapi.VM.add_to_VCPUs_params_live(vm_uuid, f"cpumap{vcpu}", cpumap) return True # VM.add_to_VCPUs_params_live() implementation in xend 4.1+ has # a bug which makes the client call fail. @@ -518,7 +518,7 @@ def vcpu_pin(vm_, vcpu, cpus): # for that particular one, fallback to xm / xl instead. except Exception: # pylint: disable=broad-except return __salt__["cmd.run"]( - "{} vcpu-pin {} {} {}".format(_get_xtool(), vm_, vcpu, cpus), + f"{_get_xtool()} vcpu-pin {vm_} {vcpu} {cpus}", python_shell=False, ) @@ -641,9 +641,7 @@ def start(config_): # This function does NOT use the XenAPI. Instead, it use good old xm / xl. # On Xen Source, creating a virtual machine using XenAPI is really painful. # XCP / XS make it really easy using xapi.Async.VM.start instead. Anyone? - return __salt__["cmd.run"]( - "{} create {}".format(_get_xtool(), config_), python_shell=False - ) + return __salt__["cmd.run"](f"{_get_xtool()} create {config_}", python_shell=False) def reboot(vm_): @@ -816,7 +814,7 @@ def vm_cputime(vm_=None): cputime_percent = (1.0e-7 * cputime / host_cpus) / vcpus return { "cputime": int(cputime), - "cputime_percent": int("{:.0f}".format(cputime_percent)), + "cputime_percent": int(f"{cputime_percent:.0f}"), } info = {} diff --git a/salt/modules/xbpspkg.py b/salt/modules/xbpspkg.py index afcf54fb2f2..65376c7dea1 100644 --- a/salt/modules/xbpspkg.py +++ b/salt/modules/xbpspkg.py @@ -401,7 +401,7 @@ def install(name=None, refresh=False, fromrepo=None, pkgs=None, sources=None, ** if refresh: cmd.append("-S") # update repo db if fromrepo: - cmd.append("--repository={}".format(fromrepo)) + cmd.append(f"--repository={fromrepo}") cmd.append("-y") # assume yes when asked cmd.extend(pkg_params) @@ -578,9 +578,7 @@ def add_repo(repo, conffile="/usr/share/xbps.d/15-saltstack.conf"): if not _locate_repo_files(repo): try: with salt.utils.files.fopen(conffile, "a+") as conf_file: - conf_file.write( - salt.utils.stringutils.to_str("repository={}\n".format(repo)) - ) + conf_file.write(salt.utils.stringutils.to_str(f"repository={repo}\n")) except OSError: return False diff --git a/salt/modules/xfs.py b/salt/modules/xfs.py index 04b104f9967..16c6e85a572 100644 --- a/salt/modules/xfs.py +++ b/salt/modules/xfs.py @@ -111,7 +111,7 @@ def info(device): salt '*' xfs.info /dev/sda1 """ - out = __salt__["cmd.run_all"]("xfs_info {}".format(device)) + out = __salt__["cmd.run_all"](f"xfs_info {device}") if out.get("stderr"): raise CommandExecutionError(out["stderr"].replace("xfs_info:", "").strip()) return _parse_xfs_info(out["stdout"]) @@ -186,16 +186,16 @@ def dump(device, destination, level=0, label=None, noerase=None): label and label or time.strftime( - 'XFS dump for "{}" of %Y.%m.%d, %H:%M'.format(device), time.localtime() + f'XFS dump for "{device}" of %Y.%m.%d, %H:%M', time.localtime() ).replace("'", '"') ) cmd = ["xfsdump"] cmd.append("-F") # Force if not noerase: cmd.append("-E") # pre-erase - cmd.append("-L '{}'".format(label)) # Label - cmd.append("-l {}".format(level)) # Dump level - cmd.append("-f {}".format(destination)) # Media destination + cmd.append(f"-L '{label}'") # Label + cmd.append(f"-l {level}") # Dump level + cmd.append(f"-f {destination}") # Media destination cmd.append(device) # Device cmd = " ".join(cmd) @@ -211,10 +211,10 @@ def _xr_to_keyset(line): """ tkns = [elm for elm in line.strip().split(":", 1) if elm] if len(tkns) == 1: - return "'{}': ".format(tkns[0]) + return f"'{tkns[0]}': " else: key, val = tkns - return "'{}': '{}',".format(key.strip(), val.strip()) + return f"'{key.strip()}': '{val.strip()}'," def _xfs_inventory_output(out): @@ -305,14 +305,14 @@ def prune_dump(sessionid): salt '*' xfs.prune_dump b74a3586-e52e-4a4a-8775-c3334fa8ea2c """ - out = __salt__["cmd.run_all"]("xfsinvutil -s {} -F".format(sessionid)) + out = __salt__["cmd.run_all"](f"xfsinvutil -s {sessionid} -F") _verify_run(out) data = _xfs_prune_output(out["stdout"], sessionid) if data: return data - raise CommandExecutionError('Session UUID "{}" was not found.'.format(sessionid)) + raise CommandExecutionError(f'Session UUID "{sessionid}" was not found.') def _blkid_output(out): @@ -387,9 +387,9 @@ def estimate(path): salt '*' xfs.estimate /path/to/dir/* """ if not os.path.exists(path): - raise CommandExecutionError('Path "{}" was not found.'.format(path)) + raise CommandExecutionError(f'Path "{path}" was not found.') - out = __salt__["cmd.run_all"]("xfs_estimate -v {}".format(path)) + out = __salt__["cmd.run_all"](f"xfs_estimate -v {path}") _verify_run(out) return _xfs_estimate_output(out["stdout"]) @@ -447,7 +447,7 @@ def mkfs( cmd = ["mkfs.xfs"] if label: cmd.append("-L") - cmd.append("'{}'".format(label)) + cmd.append(f"'{label}'") if ssize: cmd.append("-s") @@ -468,7 +468,7 @@ def mkfs( cmd.append(opts) except Exception: # pylint: disable=broad-except raise CommandExecutionError( - 'Wrong parameters "{}" for option "{}"'.format(opts, switch) + f'Wrong parameters "{opts}" for option "{switch}"' ) if not noforce: @@ -496,13 +496,13 @@ def modify(device, label=None, lazy_counting=None, uuid=None): """ if not label and lazy_counting is None and uuid is None: raise CommandExecutionError( - 'Nothing specified for modification for "{}" device'.format(device) + f'Nothing specified for modification for "{device}" device' ) cmd = ["xfs_admin"] if label: cmd.append("-L") - cmd.append("'{}'".format(label)) + cmd.append(f"'{label}'") if lazy_counting is False: cmd.append("-c") @@ -522,7 +522,7 @@ def modify(device, label=None, lazy_counting=None, uuid=None): cmd = " ".join(cmd) _verify_run(__salt__["cmd.run_all"](cmd), cmd=cmd) - out = __salt__["cmd.run_all"]("blkid -o export {}".format(device)) + out = __salt__["cmd.run_all"](f"blkid -o export {device}") _verify_run(out) return _blkid_output(out["stdout"]) @@ -563,9 +563,9 @@ def defragment(device): raise CommandExecutionError("Root is not a device.") if not _get_mounts().get(device): - raise CommandExecutionError('Device "{}" is not mounted'.format(device)) + raise CommandExecutionError(f'Device "{device}" is not mounted') - out = __salt__["cmd.run_all"]("xfs_fsr {}".format(device)) + out = __salt__["cmd.run_all"](f"xfs_fsr {device}") _verify_run(out) return {"log": out["stdout"]} diff --git a/salt/modules/xmpp.py b/salt/modules/xmpp.py index 5e058ff1324..944ef5c92af 100644 --- a/salt/modules/xmpp.py +++ b/salt/modules/xmpp.py @@ -34,7 +34,6 @@ Module for Sending Messages via XMPP (a.k.a. Jabber) """ - import logging HAS_LIBS = False diff --git a/salt/modules/yumpkg.py b/salt/modules/yumpkg.py index 9f3d9d27e6d..0ca3e9dc809 100644 --- a/salt/modules/yumpkg.py +++ b/salt/modules/yumpkg.py @@ -18,6 +18,7 @@ Support for YUM/DNF .. versionadded:: 3007.0 Support for ``dnf5``` on Fedora 39 """ + import configparser import contextlib import datetime diff --git a/salt/modules/zcbuildout.py b/salt/modules/zcbuildout.py index c36f254cd84..c5c32dac2ef 100644 --- a/salt/modules/zcbuildout.py +++ b/salt/modules/zcbuildout.py @@ -22,7 +22,6 @@ You have those following methods: * buildout """ - import copy import logging import os @@ -190,9 +189,9 @@ def _encode_status(status): logs = status["logs_by_level"].get(logger, [])[:] if logs: for i, log in enumerate(logs): - status["logs_by_level"][logger][ - i - ] = salt.utils.stringutils.to_unicode(log) + status["logs_by_level"][logger][i] = ( + salt.utils.stringutils.to_unicode(log) + ) return status diff --git a/salt/modules/zenoss.py b/salt/modules/zenoss.py index 5f2408c486b..50855f2bebb 100644 --- a/salt/modules/zenoss.py +++ b/salt/modules/zenoss.py @@ -203,7 +203,7 @@ def set_prod_state(prod_state, device=None): device_object = find_device(device) if not device_object: - return "Unable to find a device in Zenoss for {}".format(device) + return f"Unable to find a device in Zenoss for {device}" log.info("Setting prodState to %d on %s device", prod_state, device) data = dict( diff --git a/salt/modules/zypperpkg.py b/salt/modules/zypperpkg.py index d5e9203dc26..0b15ca46ff1 100644 --- a/salt/modules/zypperpkg.py +++ b/salt/modules/zypperpkg.py @@ -11,7 +11,6 @@ Package support for openSUSE via the zypper package manager """ - import configparser import datetime import errno @@ -2353,10 +2352,10 @@ def unhold(name=None, pkgs=None, root=None, **kwargs): lock_ver = lock_ver.lstrip("= ") if version and lock_ver != version: ret[target]["result"] = False - ret[target][ - "comment" - ] = "Unable to unhold package {} as it is held with the other version.".format( - target + ret[target]["comment"] = ( + "Unable to unhold package {} as it is held with the other version.".format( + target + ) ) else: removed.append(target if not lock_ver else f"{target}={lock_ver}") @@ -2943,10 +2942,10 @@ def download(*packages, **kwargs): if pkg_ret: failed = [pkg for pkg in packages if pkg not in pkg_ret] if failed: - pkg_ret[ - "_error" - ] = "The following package(s) failed to download: {}".format( - ", ".join(failed) + pkg_ret["_error"] = ( + "The following package(s) failed to download: {}".format( + ", ".join(failed) + ) ) return pkg_ret diff --git a/salt/netapi/__init__.py b/salt/netapi/__init__.py index a89c1a19af0..583a6f158d5 100644 --- a/salt/netapi/__init__.py +++ b/salt/netapi/__init__.py @@ -2,7 +2,6 @@ Make api awesomeness """ - import copy import inspect import logging @@ -54,7 +53,7 @@ def sum_permissions(token, eauth): eauth_groups = {i.rstrip("%") for i in eauth.keys() if i.endswith("%")} for group in user_groups & eauth_groups: - perms.extend(eauth["{}%".format(group)]) + perms.extend(eauth[f"{group}%"]) return perms diff --git a/salt/netapi/rest_cherrypy/app.py b/salt/netapi/rest_cherrypy/app.py index d9dd7e9bcea..56a4859d431 100644 --- a/salt/netapi/rest_cherrypy/app.py +++ b/salt/netapi/rest_cherrypy/app.py @@ -898,9 +898,11 @@ def hypermedia_handler(*args, **kwargs): ret = { "status": cherrypy.response.status, - "return": f"{traceback.format_exc()}" - if cherrypy.config["debug"] - else "An unexpected error occurred", + "return": ( + f"{traceback.format_exc()}" + if cherrypy.config["debug"] + else "An unexpected error occurred" + ), } # Raises 406 if requested content-type is not supported @@ -1740,9 +1742,9 @@ class Keys(LowDataAdapter): tarball.close() headers = cherrypy.response.headers - headers[ - "Content-Disposition" - ] = 'attachment; filename="saltkeys-{}.tar"'.format(lowstate[0]["id_"]) + headers["Content-Disposition"] = ( + 'attachment; filename="saltkeys-{}.tar"'.format(lowstate[0]["id_"]) + ) headers["Content-Type"] = "application/x-tar" headers["Content-Length"] = len(fileobj.getvalue()) headers["Cache-Control"] = "no-cache" diff --git a/salt/netapi/rest_wsgi.py b/salt/netapi/rest_wsgi.py index 4afd3d55ec3..50dfabe23c1 100644 --- a/salt/netapi/rest_wsgi.py +++ b/salt/netapi/rest_wsgi.py @@ -161,7 +161,7 @@ class HTTPError(Exception): def __init__(self, code, message): self.code = code - Exception.__init__(self, "{}: {}".format(code, message)) + Exception.__init__(self, f"{code}: {message}") def mkdir_p(path): diff --git a/salt/output/__init__.py b/salt/output/__init__.py index 32d0560772d..c90932fa8ea 100644 --- a/salt/output/__init__.py +++ b/salt/output/__init__.py @@ -3,7 +3,6 @@ Used to manage the outputter system. This package is the modular system used for managing outputters. """ - import errno import io import logging @@ -54,7 +53,7 @@ def get_progress(opts, out, progress): Get the progress bar from the given outputter """ return salt.loader.raw_mod(opts, out, "rawmodule", mod="output")[ - "{}.progress_iter".format(out) + f"{out}.progress_iter" ](progress) diff --git a/salt/output/highstate.py b/salt/output/highstate.py index 6c852554fc4..dc00885753f 100644 --- a/salt/output/highstate.py +++ b/salt/output/highstate.py @@ -123,7 +123,6 @@ Example output with no special settings in configuration files: Total: 0 """ - import collections import logging import pprint @@ -572,10 +571,10 @@ def _format_host(host, data, indent_level=1): if "data" in ret: if isinstance(ret["data"], list): for item in ret["data"]: - comment = "{} {}".format(comment, item) + comment = f"{comment} {item}" elif isinstance(ret["data"], dict): for key, value in ret["data"].items(): - comment = "{}\n\t\t{}: {}".format(comment, key, value) + comment = f"{comment}\n\t\t{key}: {value}" else: comment = "{} {}".format(comment, ret["data"]) for detail in ["start_time", "duration"]: @@ -635,13 +634,13 @@ def _format_host(host, data, indent_level=1): changestats.append( colorfmt.format( colors["LIGHT_YELLOW"], - "unchanged={}".format(rcounts.get(None, 0)), + f"unchanged={rcounts.get(None, 0)}", colors, ) ) if nchanges > 0: changestats.append( - colorfmt.format(colors["GREEN"], "changed={}".format(nchanges), colors) + colorfmt.format(colors["GREEN"], f"changed={nchanges}", colors) ) if changestats: changestats = " ({})".format(", ".join(changestats)) @@ -733,7 +732,7 @@ def _format_host(host, data, indent_level=1): sum_duration /= 1000 duration_unit = "s" total_duration = "Total run time: {} {}".format( - "{:.3f}".format(sum_duration).rjust(line_max_len - 5), duration_unit + f"{sum_duration:.3f}".rjust(line_max_len - 5), duration_unit ) hstrs.append(colorfmt.format(colors["CYAN"], total_duration, colors)) @@ -763,7 +762,7 @@ def _format_changes(changes, orchestration=False): return True, _nested_changes(changes) if not isinstance(changes, dict): - return True, "Invalid Changes data: {}".format(changes) + return True, f"Invalid Changes data: {changes}" ret = changes.get("ret") if ret is not None and changes.get("out") == "highstate": diff --git a/salt/output/key.py b/salt/output/key.py index 13ee6f0f5fe..f89f95c7f96 100644 --- a/salt/output/key.py +++ b/salt/output/key.py @@ -84,7 +84,7 @@ def output(data, **kwargs): # pylint: disable=unused-argument ret = "" for status in sorted(data): - ret += "{}\n".format(trans[status]) + ret += f"{trans[status]}\n" for key in sorted(data[status]): key = salt.utils.data.decode(key) skey = salt.output.strip_esc_sequence(key) if strip_colors else key diff --git a/salt/output/overstatestage.py b/salt/output/overstatestage.py index 3f80e0871f6..a8facfcb308 100644 --- a/salt/output/overstatestage.py +++ b/salt/output/overstatestage.py @@ -6,7 +6,6 @@ This outputter is used to display :ref:`Orchestrate Runner ` stages, and should not be called directly. """ - import salt.utils.color # [{'group2': {'match': ['fedora17-2', 'fedora17-3'], diff --git a/salt/output/pony.py b/salt/output/pony.py index 908b8b29392..e8cc866cff2 100644 --- a/salt/output/pony.py +++ b/salt/output/pony.py @@ -46,7 +46,6 @@ CLI Example: salt '*' foo.bar --out=pony """ - import subprocess import salt.utils.data diff --git a/salt/output/profile.py b/salt/output/profile.py index d182da565ff..8f54c7017f4 100644 --- a/salt/output/profile.py +++ b/salt/output/profile.py @@ -56,11 +56,11 @@ def _find_durations(data, name_max=60): if len(name) > name_max: name = name[0 : name_max - 3] + "..." - l = len("{:0.4f}".format(dur)) + l = len(f"{dur:0.4f}") if l > ml: ml = l - ret.append([dur, name, "{}.{}".format(mod, fun)]) + ret.append([dur, name, f"{mod}.{fun}"]) for row in ret: row[0] = "{0:{w}.4f}".format(row[0], w=ml) diff --git a/salt/output/progress.py b/salt/output/progress.py index 1d00a379cc4..302ce1f1467 100644 --- a/salt/output/progress.py +++ b/salt/output/progress.py @@ -2,7 +2,6 @@ Display return data as a progress bar """ - try: import progressbar diff --git a/salt/output/raw.py b/salt/output/raw.py index d2e68041180..a3005948e42 100644 --- a/salt/output/raw.py +++ b/salt/output/raw.py @@ -24,7 +24,6 @@ Example output: {'myminion': {'foo': {'list': ['Hello', 'World'], 'bar': 'baz', 'dictionary': {'abc': 123, 'def': 456}}}} """ - import salt.utils.stringutils diff --git a/salt/output/table_out.py b/salt/output/table_out.py index 730e0cb2df8..6b17c901b64 100644 --- a/salt/output/table_out.py +++ b/salt/output/table_out.py @@ -42,7 +42,6 @@ CLI Example: salt '*' foo.bar --out=table """ - import operator from functools import reduce # pylint: disable=redefined-builtin @@ -117,9 +116,9 @@ class TableDisplay: ) def wrap_onspace(self, text): - """ - When the text inside the column is longer then the width, will split by space and continue on the next line.""" + When the text inside the column is longer then the width, will split by space and continue on the next line. + """ def _truncate(line, word): return "{line}{part}{word}".format( @@ -136,7 +135,6 @@ class TableDisplay: return reduce(_truncate, text.split(" ")) def prepare_rows(self, rows, indent, has_header): - """Prepare rows content to be displayed.""" out = [] @@ -198,7 +196,6 @@ class TableDisplay: return out def display_rows(self, rows, labels, indent): - """Prepares row content and displays.""" out = [] @@ -245,7 +242,6 @@ class TableDisplay: return self.prepare_rows(labels_and_rows, indent + 4, has_header) def display(self, ret, indent, out, rows_key=None, labels_key=None): - """Display table(s).""" rows = [] @@ -350,7 +346,7 @@ def output(ret, **kwargs): ) for argk in argks: - argv = kwargs.get(argk) or __opts__.get("out.table.{key}".format(key=argk)) + argv = kwargs.get(argk) or __opts__.get(f"out.table.{argk}") if argv is not None: class_kvargs[argk] = argv diff --git a/salt/output/txt.py b/salt/output/txt.py index 71d694a2333..f5e652cdd14 100644 --- a/salt/output/txt.py +++ b/salt/output/txt.py @@ -26,14 +26,14 @@ def output(data, **kwargs): # pylint: disable=unused-argument # Don't blow up on non-strings try: for line in value.splitlines(): - ret += "{}: {}\n".format(key, line) + ret += f"{key}: {line}\n" except AttributeError: - ret += "{}: {}\n".format(key, value) + ret += f"{key}: {value}\n" else: try: ret += data + "\n" except TypeError: # For non-dictionary, non-string data, just use print - ret += "{}\n".format(pprint.pformat(data)) + ret += f"{pprint.pformat(data)}\n" return ret diff --git a/salt/output/virt_query.py b/salt/output/virt_query.py index d20e6357e60..935b9d213d7 100644 --- a/salt/output/virt_query.py +++ b/salt/output/virt_query.py @@ -13,9 +13,9 @@ def output(data, **kwargs): # pylint: disable=unused-argument """ out = "" for id_ in data["data"]: - out += "{}\n".format(id_) + out += f"{id_}\n" for vm_ in data["data"][id_]["vm_info"]: - out += " {}\n".format(vm_) + out += f" {vm_}\n" vm_data = data[id_]["vm_info"][vm_] if "cpu" in vm_data: out += " CPU: {}\n".format(vm_data["cpu"]) @@ -30,13 +30,13 @@ def output(data, **kwargs): # pylint: disable=unused-argument ) if "disks" in vm_data: for disk, d_data in vm_data["disks"].items(): - out += " Disk - {}:\n".format(disk) + out += f" Disk - {disk}:\n" out += " Size: {}\n".format(d_data["disk size"]) out += " File: {}\n".format(d_data["file"]) out += " File Format: {}\n".format(d_data["file format"]) if "nics" in vm_data: for mac in vm_data["nics"]: - out += " Nic - {}:\n".format(mac) + out += f" Nic - {mac}:\n" out += " Source: {}\n".format( vm_data["nics"][mac]["source"][ next(iter(vm_data["nics"][mac]["source"].keys())) diff --git a/salt/pillar/cmd_yamlex.py b/salt/pillar/cmd_yamlex.py index c014370f1d0..bf6d40a65fa 100644 --- a/salt/pillar/cmd_yamlex.py +++ b/salt/pillar/cmd_yamlex.py @@ -4,7 +4,6 @@ Execute a command and read the output as YAMLEX. The YAMLEX data is then directly overlaid onto the minion's Pillar data """ - import logging from salt.serializers.yamlex import deserialize diff --git a/salt/pillar/cobbler.py b/salt/pillar/cobbler.py index 5103d91f419..74e87d0a91f 100644 --- a/salt/pillar/cobbler.py +++ b/salt/pillar/cobbler.py @@ -25,7 +25,7 @@ Module Documentation """ import logging -import xmlrpc.client +import xmlrpc.client # nosec __opts__ = { "cobbler.url": "http://localhost/cobbler_api", @@ -34,7 +34,6 @@ __opts__ = { } -# Set up logging log = logging.getLogger(__name__) diff --git a/salt/pillar/consul_pillar.py b/salt/pillar/consul_pillar.py index 2b28b297353..3e4ff329329 100644 --- a/salt/pillar/consul_pillar.py +++ b/salt/pillar/consul_pillar.py @@ -315,7 +315,6 @@ def pillar_format(ret, keys, value, expand_keys): def get_conn(opts, profile): - """ Return a client object for accessing consul """ diff --git a/salt/pillar/django_orm.py b/salt/pillar/django_orm.py index 29a5eaaa413..641e6098514 100644 --- a/salt/pillar/django_orm.py +++ b/salt/pillar/django_orm.py @@ -125,7 +125,7 @@ def ext_pillar( env=None, env_file=None, *args, # pylint: disable=W0613 - **kwargs + **kwargs, ): # pylint: disable=W0613 """ Connect to a Django database through the ORM and retrieve model fields @@ -179,7 +179,7 @@ def ext_pillar( (key, _, value) = salt.utils.stringutils.to_str(line).partition("=") base_env[key] = value - command = ["bash", "-c", "source {} && env".format(env_file)] + command = ["bash", "-c", f"source {env_file} && env"] proc = subprocess.Popen(command, stdout=subprocess.PIPE) for line in proc.stdout: @@ -229,7 +229,7 @@ def ext_pillar( # (since we're using it as the key in a dictionary) if name_field not in model: raise salt.exceptions.SaltException( - "Name '{}' not found in returned fields.".format(name_field) + f"Name '{name_field}' not found in returned fields." ) if model[name_field] in pillar_for_model: diff --git a/salt/pillar/ec2_pillar.py b/salt/pillar/ec2_pillar.py index e197940908b..7aa6cb008dd 100644 --- a/salt/pillar/ec2_pillar.py +++ b/salt/pillar/ec2_pillar.py @@ -53,7 +53,6 @@ returns a list of key/value pairs for all of the EC2 tags assigned to the instance. """ - import logging import re @@ -185,9 +184,9 @@ def ext_pillar( find_id = minion_id elif tag_match_key: if tag_match_value == "uqdn": - find_filter = {"tag:{}".format(tag_match_key): minion_id.split(".", 1)[0]} + find_filter = {f"tag:{tag_match_key}": minion_id.split(".", 1)[0]} else: - find_filter = {"tag:{}".format(tag_match_key): minion_id} + find_filter = {f"tag:{tag_match_key}": minion_id} if grain_instance_id: # we have an untrusted grain_instance_id, use it to narrow the search # even more. Combination will be unique even if uqdn is set. diff --git a/salt/pillar/extra_minion_data_in_pillar.py b/salt/pillar/extra_minion_data_in_pillar.py index 170cdb6fa08..457c79462b0 100644 --- a/salt/pillar/extra_minion_data_in_pillar.py +++ b/salt/pillar/extra_minion_data_in_pillar.py @@ -27,6 +27,7 @@ Complete example in etc/salt/master include: """ + import logging # Set up logging diff --git a/salt/pillar/gpg.py b/salt/pillar/gpg.py index 28497a51f2c..8652a18b2a5 100644 --- a/salt/pillar/gpg.py +++ b/salt/pillar/gpg.py @@ -15,7 +15,6 @@ Set ``gpg_keydir`` in your config to adjust the homedir the renderer uses. """ - import salt.loader diff --git a/salt/pillar/hiera.py b/salt/pillar/hiera.py index 19e9c78c034..c799d4f195f 100644 --- a/salt/pillar/hiera.py +++ b/salt/pillar/hiera.py @@ -2,7 +2,6 @@ Use hiera data as a Pillar source """ - import logging import salt.utils.path @@ -25,10 +24,10 @@ def ext_pillar( """ Execute hiera and return the data """ - cmd = "hiera -c {}".format(conf) + cmd = f"hiera -c {conf}" for key, val in __grains__.items(): if isinstance(val, str): - cmd += " {}='{}'".format(key, val) + cmd += f" {key}='{val}'" try: data = salt.utils.yaml.safe_load(__salt__["cmd.run"](cmd)) except Exception: # pylint: disable=broad-except diff --git a/salt/pillar/http_json.py b/salt/pillar/http_json.py index f79f8655020..b07a2573772 100644 --- a/salt/pillar/http_json.py +++ b/salt/pillar/http_json.py @@ -48,7 +48,6 @@ Module Documentation ==================== """ - import logging import re import urllib.parse @@ -102,7 +101,7 @@ def ext_pillar( return {} grain_value = urllib.parse.quote(str(grain_value)) - url = re.sub("<{}>".format(grain_name), grain_value, url) + url = re.sub(f"<{grain_name}>", grain_value, url) log.debug("Getting url: %s", url) data = __salt__["http.query"]( diff --git a/salt/pillar/http_yaml.py b/salt/pillar/http_yaml.py index 434d5b8a892..58df6248ae0 100644 --- a/salt/pillar/http_yaml.py +++ b/salt/pillar/http_yaml.py @@ -43,6 +43,7 @@ in <> brackets) in the url in order to populate pillar data based on the grain v Module Documentation ==================== """ + import logging import re import urllib.parse @@ -94,7 +95,7 @@ def ext_pillar( return {} grain_value = urllib.parse.quote(str(grain_value)) - url = re.sub("<{}>".format(grain_name), grain_value, url) + url = re.sub(f"<{grain_name}>", grain_value, url) log.debug("Getting url: %s", url) data = __salt__["http.query"]( diff --git a/salt/pillar/libvirt.py b/salt/pillar/libvirt.py index 072293df251..cbcba870e4c 100644 --- a/salt/pillar/libvirt.py +++ b/salt/pillar/libvirt.py @@ -4,6 +4,7 @@ generated using the libvirt key runner :depends: certtool """ + import os import subprocess @@ -41,9 +42,7 @@ def ext_pillar(minion_id, pillar, command): continue fn_ = os.path.join(key_dir, key) with salt.utils.files.fopen(fn_, "r") as fp_: - ret["libvirt.{}".format(key)] = salt.utils.stringutils.to_unicode( - fp_.read() - ) + ret[f"libvirt.{key}"] = salt.utils.stringutils.to_unicode(fp_.read()) with salt.utils.files.fopen(cacert, "r") as fp_: ret["libvirt.cacert.pem"] = salt.utils.stringutils.to_unicode(fp_.read()) return ret @@ -74,7 +73,7 @@ def gen_hyper_keys( proc = subprocess.run( ["certtool", "--generate-privkey"], stdout=subprocess.PIPE, - universal_newlines=True, + text=True, check=True, ) with salt.utils.files.fopen(cakey, "w") as wfh: @@ -115,7 +114,7 @@ def gen_hyper_keys( proc = subprocess.run( ["certtool", "--generate-privkey"], stdout=subprocess.PIPE, - universal_newlines=True, + text=True, check=True, ) with salt.utils.files.fopen(priv, "w") as wfh: @@ -152,7 +151,7 @@ def gen_hyper_keys( proc = subprocess.run( ["certtool", "--generate-privkey"], stdout=subprocess.PIPE, - universal_newlines=True, + text=True, check=True, ) with salt.utils.files.fopen(cpriv, "w") as wfh: diff --git a/salt/pillar/makostack.py b/salt/pillar/makostack.py index b689bd5f4cd..f96092f8945 100644 --- a/salt/pillar/makostack.py +++ b/salt/pillar/makostack.py @@ -372,7 +372,6 @@ You can also select a custom merging strategy using a ``__`` object in a list: +----------------+-------------------------+-------------------------+ """ - import functools import logging import os @@ -499,9 +498,7 @@ def _cleanup(obj): def _merge_dict(stack, obj): strategy = obj.pop("__", "merge-last") if strategy not in strategies: - raise Exception( - 'Unknown strategy "{}", should be one of {}'.format(strategy, strategies) - ) + raise Exception(f'Unknown strategy "{strategy}", should be one of {strategies}') if strategy == "overwrite": return _cleanup(obj) else: @@ -538,9 +535,7 @@ def _merge_list(stack, obj): strategy = obj[0]["__"] del obj[0] if strategy not in strategies: - raise Exception( - 'Unknown strategy "{}", should be one of {}'.format(strategy, strategies) - ) + raise Exception(f'Unknown strategy "{strategy}", should be one of {strategies}') if strategy == "overwrite": return obj elif strategy == "remove": diff --git a/salt/pillar/nacl.py b/salt/pillar/nacl.py index 67f8c6fd25a..5e0a03512d7 100644 --- a/salt/pillar/nacl.py +++ b/salt/pillar/nacl.py @@ -18,7 +18,6 @@ Set ``nacl.config`` in your config. """ - import salt __virtualname__ = "nacl" diff --git a/salt/pillar/neutron.py b/salt/pillar/neutron.py index 738305b916b..2999f9a6b7c 100644 --- a/salt/pillar/neutron.py +++ b/salt/pillar/neutron.py @@ -42,7 +42,6 @@ name after the Keystone profile name: - neutron: my_openstack_config neutron_networks """ - import logging try: diff --git a/salt/pillar/pepa.py b/salt/pillar/pepa.py index a35ebb47a09..3be4a4bea62 100644 --- a/salt/pillar/pepa.py +++ b/salt/pillar/pepa.py @@ -615,7 +615,7 @@ if __name__ == "__main__": if not request.ok: raise RuntimeError( - "Failed to authenticate to SaltStack REST API: {}".format(request.text) + f"Failed to authenticate to SaltStack REST API: {request.text}" ) response = request.json() diff --git a/salt/pillar/puppet.py b/salt/pillar/puppet.py index b907ad1f321..792c3ec7738 100644 --- a/salt/pillar/puppet.py +++ b/salt/pillar/puppet.py @@ -19,9 +19,7 @@ def ext_pillar(minion_id, pillar, command): # pylint: disable=W0613 Execute an unmodified puppet_node_classifier and read the output as YAML """ try: - data = salt.utils.yaml.safe_load( - __salt__["cmd.run"]("{} {}".format(command, minion_id)) - ) + data = salt.utils.yaml.safe_load(__salt__["cmd.run"](f"{command} {minion_id}")) return data["parameters"] except Exception: # pylint: disable=broad-except log.critical("YAML data from %s failed to parse", command) diff --git a/salt/pillar/reclass_adapter.py b/salt/pillar/reclass_adapter.py index 2f7e158ce75..ded9d664934 100644 --- a/salt/pillar/reclass_adapter.py +++ b/salt/pillar/reclass_adapter.py @@ -45,7 +45,6 @@ either let the master know via the ``PYTHONPATH`` environment variable, or by setting the configuration option, like in the example above. """ - # This file cannot be called reclass.py, because then the module import would # not work. Thanks to the __virtual__ function, however, the plugin still # responds to the name 'reclass'. @@ -127,4 +126,4 @@ def ext_pillar(minion_id, pillar, **kwargs): raise except ReclassException as e: - raise SaltInvocationError("ext_pillar.reclass: {}".format(e)) + raise SaltInvocationError(f"ext_pillar.reclass: {e}") diff --git a/salt/pillar/s3.py b/salt/pillar/s3.py index 6e97dfd33bd..deb1c9b2a26 100644 --- a/salt/pillar/s3.py +++ b/salt/pillar/s3.py @@ -87,7 +87,6 @@ for each environment rather than specifying multiple_env. This is due to issue #22471 (https://github.com/saltstack/salt/issues/22471) """ - import logging import os import pickle @@ -144,7 +143,6 @@ def ext_pillar( path_style=False, https_enable=True, ): - """ Execute a command and read the output as YAML """ @@ -278,7 +276,7 @@ def _get_buckets_cache_filename(bucket, prefix): if not os.path.exists(cache_dir): os.makedirs(cache_dir) - return os.path.join(cache_dir, "{}-{}-files.cache".format(bucket, prefix)) + return os.path.join(cache_dir, f"{bucket}-{prefix}-files.cache") def _refresh_buckets_cache_file(creds, cache_file, multiple_env, environment, prefix): diff --git a/salt/pillar/saltclass.py b/salt/pillar/saltclass.py index 3354b1ae7ba..badf776eb0d 100644 --- a/salt/pillar/saltclass.py +++ b/salt/pillar/saltclass.py @@ -11,7 +11,6 @@ SaltClass Pillar Module For additional configuration instructions, see the :mod:`saltclass ` module """ - import logging import salt.utils.saltclass as sc diff --git a/salt/pillar/stack.py b/salt/pillar/stack.py index f5e2a07ea44..f8936ad4b4a 100644 --- a/salt/pillar/stack.py +++ b/salt/pillar/stack.py @@ -373,6 +373,7 @@ You can also select a custom merging strategy using a ``__`` object in a list: | - root | - mat | | +----------------+-------------------------+-------------------------+ """ + import functools import glob import logging @@ -475,9 +476,7 @@ def _process_stack_cfg(cfg, stack, minion_id, pillar): try: yaml = jenv.get_template(unix_path).render(stack=stack, ymlpath=path) except Exception as e: - raise Exception( - 'Stack pillar template render error in {}:\n"{}"'.format(path, e) - ) + raise Exception(f'Stack pillar template render error in {path}:\n"{e}"') try: obj = salt.utils.yaml.safe_load(yaml) except Exception as e: @@ -505,9 +504,7 @@ def _cleanup(obj): def _merge_dict(stack, obj): strategy = obj.pop("__", "merge-last") if strategy not in strategies: - raise Exception( - 'Unknown strategy "{}", should be one of {}'.format(strategy, strategies) - ) + raise Exception(f'Unknown strategy "{strategy}", should be one of {strategies}') if strategy == "overwrite": return _cleanup(obj) else: @@ -544,9 +541,7 @@ def _merge_list(stack, obj): strategy = obj[0]["__"] del obj[0] if strategy not in strategies: - raise Exception( - 'Unknown strategy "{}", should be one of {}'.format(strategy, strategies) - ) + raise Exception(f'Unknown strategy "{strategy}", should be one of {strategies}') if strategy == "overwrite": return obj elif strategy == "remove": diff --git a/salt/pillar/varstack_pillar.py b/salt/pillar/varstack_pillar.py index 7f1d707b538..eebb12fda19 100644 --- a/salt/pillar/varstack_pillar.py +++ b/salt/pillar/varstack_pillar.py @@ -18,7 +18,6 @@ data to return as pillar information. From there you can take a look at the varstack on how this file is evaluated. """ - try: import varstack except ImportError: diff --git a/salt/pillar/vault.py b/salt/pillar/vault.py index 1ae0c9c86e0..36ea8bb7b2b 100644 --- a/salt/pillar/vault.py +++ b/salt/pillar/vault.py @@ -151,7 +151,6 @@ You can override the merging behavior per defined ext_pillar: merge_lists: false """ - import logging import salt.utils.dictupdate diff --git a/salt/platform/win.py b/salt/platform/win.py index 694238e4fc0..0483e016d9e 100644 --- a/salt/platform/win.py +++ b/salt/platform/win.py @@ -154,7 +154,7 @@ class NTSTATUS(wintypes.LONG): def __repr__(self): name = self.__class__.__name__ status = wintypes.ULONG.from_buffer(self) - return "{}({})".format(name, status.value) + return f"{name}({status.value})" PNTSTATUS = ctypes.POINTER(NTSTATUS) @@ -163,7 +163,7 @@ PNTSTATUS = ctypes.POINTER(NTSTATUS) class BOOL(wintypes.BOOL): def __repr__(self): name = self.__class__.__name__ - return "{}({})".format(name, bool(self)) + return f"{name}({bool(self)})" class HANDLE(wintypes.HANDLE): @@ -187,7 +187,7 @@ class HANDLE(wintypes.HANDLE): __del__ = Close def __repr__(self): - return "{}({})".format(self.__class__.__name__, int(self)) + return f"{self.__class__.__name__}({int(self)})" class LARGE_INTEGER(wintypes.LARGE_INTEGER): @@ -202,7 +202,7 @@ class LARGE_INTEGER(wintypes.LARGE_INTEGER): def __repr__(self): name = self.__class__.__name__ - return "{}({})".format(name, self.value) + return f"{name}({self.value})" def as_time(self): time100ns = self.value - self._unix_epoch @@ -258,7 +258,7 @@ class LUID(ctypes.Structure): def __repr__(self): name = self.__class__.__name__ - return "{}({})".format(name, int(self)) + return f"{name}({int(self)})" LPLUID = ctypes.POINTER(LUID) @@ -309,7 +309,7 @@ class TOKEN_SOURCE(ctypes.Structure): LPTOKEN_SOURCE = ctypes.POINTER(TOKEN_SOURCE) py_source_context = TOKEN_SOURCE(b"PYTHON ") py_origin_name = __name__.encode() -py_logon_process_name = "{}-{}".format(py_origin_name, os.getpid()) +py_logon_process_name = f"{py_origin_name}-{os.getpid()}" SIZE_T = ctypes.c_size_t @@ -340,7 +340,7 @@ class ContiguousUnicode(ctypes.Structure): def _get_unicode_string(self, name): wchar_size = ctypes.sizeof(WCHAR) - s = getattr(self, "_{}".format(name)) + s = getattr(self, f"_{name}") length = s.Length // wchar_size buf = s.Buffer if buf: @@ -372,7 +372,7 @@ class ContiguousUnicode(ctypes.Structure): addr = ctypes.addressof(self) + ctypes.sizeof(cls) for n, v in zip(self._string_names_, values): ptr = ctypes.cast(addr, PWCHAR) - ustr = getattr(self, "_{}".format(n)) + ustr = getattr(self, f"_{n}") length = ustr.Length = len(v) * wchar_size full_length = length + wchar_size if (n == name and value is None) or ( @@ -404,7 +404,7 @@ class ContiguousUnicode(ctypes.Structure): ctypes.memmove(ctypes.byref(x), address, ctypes.sizeof(x)) delta = ctypes.addressof(x) - address for n in cls._string_names_: - ustr = getattr(x, "_{}".format(n)) + ustr = getattr(x, f"_{n}") addr = ctypes.c_void_p.from_buffer(ustr.Buffer) if addr: addr.value += delta diff --git a/salt/proxy/chronos.py b/salt/proxy/chronos.py index 69b06d63e44..a138f39e78b 100644 --- a/salt/proxy/chronos.py +++ b/salt/proxy/chronos.py @@ -55,7 +55,7 @@ def ping(): """ try: response = salt.utils.http.query( - "{}/scheduler/jobs".format(CONFIG[CONFIG_BASE_URL]), + f"{CONFIG[CONFIG_BASE_URL]}/scheduler/jobs", decode_type="json", decode=True, ) diff --git a/salt/proxy/cisconso.py b/salt/proxy/cisconso.py index aa97f37b1b5..8d9bd56c629 100644 --- a/salt/proxy/cisconso.py +++ b/salt/proxy/cisconso.py @@ -171,7 +171,6 @@ responding: salt test.ping """ - import logging from salt.exceptions import SaltSystemExit diff --git a/salt/proxy/dummy.py b/salt/proxy/dummy.py index d470c1082a7..d1238c9c4eb 100644 --- a/salt/proxy/dummy.py +++ b/salt/proxy/dummy.py @@ -30,7 +30,7 @@ def __virtual__(): def _save_state(opts, details): _id = __context__["dummy_proxy"]["id"] - cachefile = os.path.join(opts["cachedir"], "dummy-proxy-{}.cache".format(_id)) + cachefile = os.path.join(opts["cachedir"], f"dummy-proxy-{_id}.cache") with salt.utils.files.fopen(cachefile, "wb") as pck: pck.write(salt.utils.msgpack.packb(details, use_bin_type=True)) log.warning("Dummy Proxy Saved State(%s):\n%s", cachefile, pprint.pformat(details)) @@ -38,7 +38,7 @@ def _save_state(opts, details): def _load_state(opts): _id = __context__["dummy_proxy"]["id"] - cachefile = os.path.join(opts["cachedir"], "dummy-proxy-{}.cache".format(_id)) + cachefile = os.path.join(opts["cachedir"], f"dummy-proxy-{_id}.cache") try: with salt.utils.files.fopen(cachefile, "rb") as pck: state = salt.utils.msgpack.unpackb(pck.read(), raw=False) diff --git a/salt/proxy/esxcluster.py b/salt/proxy/esxcluster.py index 4448178398a..cbb15e587ff 100644 --- a/salt/proxy/esxcluster.py +++ b/salt/proxy/esxcluster.py @@ -149,6 +149,7 @@ Associated states are documented in Look there to find an example structure for Pillar as well as an example ``.sls`` file for configuring an ESX cluster from scratch. """ + import logging import os diff --git a/salt/proxy/esxdatacenter.py b/salt/proxy/esxdatacenter.py index 98b0be0e1d1..ff100786656 100644 --- a/salt/proxy/esxdatacenter.py +++ b/salt/proxy/esxdatacenter.py @@ -144,7 +144,6 @@ Look there to find an example structure for Pillar as well as an example ``.sls`` file for configuring an ESX datacenter from scratch. """ - import logging import os diff --git a/salt/proxy/esxi.py b/salt/proxy/esxi.py index af58e48185c..a7f6b1e90e4 100644 --- a/salt/proxy/esxi.py +++ b/salt/proxy/esxi.py @@ -277,7 +277,6 @@ for standing up an ESXi host from scratch. """ - import logging import os diff --git a/salt/proxy/esxvm.py b/salt/proxy/esxvm.py index ac46bdf304c..247aa078b47 100644 --- a/salt/proxy/esxvm.py +++ b/salt/proxy/esxvm.py @@ -144,7 +144,6 @@ Look there to find an example structure for Pillar as well as an example ``.sls`` file for configuring an ESX virtual machine from scratch. """ - import logging import os diff --git a/salt/proxy/marathon.py b/salt/proxy/marathon.py index 5347276bbdb..3be5b366333 100644 --- a/salt/proxy/marathon.py +++ b/salt/proxy/marathon.py @@ -55,7 +55,7 @@ def ping(): """ try: response = salt.utils.http.query( - "{}/ping".format(CONFIG[CONFIG_BASE_URL]), + f"{CONFIG[CONFIG_BASE_URL]}/ping", decode_type="plain", decode=True, ) diff --git a/salt/proxy/napalm.py b/salt/proxy/napalm.py index 4b9729635cb..13f2663cf0a 100644 --- a/salt/proxy/napalm.py +++ b/salt/proxy/napalm.py @@ -299,7 +299,7 @@ def shutdown(opts): __context__["napalm_device"]["network_device"].get( "HOSTNAME", "[unknown hostname]" ), - ":{}".format(port) if port else "", + f":{port}" if port else "", error, ) diff --git a/salt/proxy/philips_hue.py b/salt/proxy/philips_hue.py index 9b846baf096..da3ab572430 100644 --- a/salt/proxy/philips_hue.py +++ b/salt/proxy/philips_hue.py @@ -117,9 +117,9 @@ def _query(lamp_id, state, action="", method="GET"): # Because salt.utils.query is that dreadful... :( err = None - url = "{}/lights{}".format( - CONFIG["uri"], lamp_id and "/{}".format(lamp_id) or "" - ) + (action and "/{}".format(action) or "") + url = "{}/lights{}".format(CONFIG["uri"], lamp_id and f"/{lamp_id}" or "") + ( + action and f"/{action}" or "" + ) conn = http.client.HTTPConnection(CONFIG["host"]) if method == "PUT": conn.request(method, url, salt.utils.json.dumps(state)) @@ -130,7 +130,7 @@ def _query(lamp_id, state, action="", method="GET"): if resp.status == http.client.OK: res = salt.utils.json.loads(resp.read()) else: - err = "HTTP error: {}, {}".format(resp.status, resp.reason) + err = f"HTTP error: {resp.status}, {resp.reason}" conn.close() if err: raise CommandExecutionError(err) diff --git a/salt/proxy/rest_sample.py b/salt/proxy/rest_sample.py index 596e91494e3..4e66bbfd67e 100644 --- a/salt/proxy/rest_sample.py +++ b/salt/proxy/rest_sample.py @@ -192,7 +192,6 @@ def fix_outage(): def uptodate(name): - """ Call the REST endpoint to see if the packages on the "server" are up to date. """ @@ -205,7 +204,6 @@ def uptodate(name): def package_remove(name): - """ Remove a "package" on the REST server """ diff --git a/salt/proxy/restconf.py b/salt/proxy/restconf.py index d375894b368..31f214aa7cb 100644 --- a/salt/proxy/restconf.py +++ b/salt/proxy/restconf.py @@ -72,7 +72,6 @@ Proxy Pillar Example verify: false """ - import copy import json import logging diff --git a/salt/queues/pgjsonb_queue.py b/salt/queues/pgjsonb_queue.py index decade54234..f198c580b2b 100644 --- a/salt/queues/pgjsonb_queue.py +++ b/salt/queues/pgjsonb_queue.py @@ -38,7 +38,6 @@ Use the following Pg database schema: salt-run queue.process_queue test all backend=pgjsonb """ - import logging import sys from contextlib import contextmanager @@ -81,15 +80,11 @@ def _conn(commit=False): conn_kwargs = {} for key, value in defaults.items(): - conn_kwargs[key] = __opts__.get( - "queue.{}.{}".format(__virtualname__, key), value - ) + conn_kwargs[key] = __opts__.get(f"queue.{__virtualname__}.{key}", value) try: conn = psycopg2.connect(**conn_kwargs) except psycopg2.OperationalError as exc: - raise SaltMasterError( - "pgjsonb returner could not connect to database: {exc}".format(exc=exc) - ) + raise SaltMasterError(f"pgjsonb returner could not connect to database: {exc}") cursor = conn.cursor() @@ -118,7 +113,7 @@ def _list_tables(cur): def _create_table(cur, queue): - cmd = "CREATE TABLE {}(id SERIAL PRIMARY KEY, data jsonb NOT NULL)".format(queue) + cmd = f"CREATE TABLE {queue}(id SERIAL PRIMARY KEY, data jsonb NOT NULL)" log.debug("SQL Query: %s", cmd) cur.execute(cmd) return True @@ -129,7 +124,7 @@ def _list_items(queue): Private function to list contents of a queue """ with _conn() as cur: - cmd = "SELECT data FROM {}".format(queue) + cmd = f"SELECT data FROM {queue}" log.debug("SQL Query: %s", cmd) cur.execute(cmd) contents = cur.fetchall() @@ -192,7 +187,7 @@ def insert(queue, items): with _conn(commit=True) as cur: if isinstance(items, dict): items = salt.utils.json.dumps(items) - cmd = "INSERT INTO {}(data) VALUES('{}')".format(queue, items) + cmd = f"INSERT INTO {queue}(data) VALUES('{items}')" log.debug("SQL Query: %s", cmd) try: cur.execute(cmd) @@ -202,7 +197,7 @@ def insert(queue, items): ) if isinstance(items, list): items = [(salt.utils.json.dumps(el),) for el in items] - cmd = "INSERT INTO {}(data) VALUES (%s)".format(queue) + cmd = f"INSERT INTO {queue}(data) VALUES (%s)" log.debug("SQL Query: %s", cmd) try: cur.executemany(cmd, items) @@ -228,7 +223,7 @@ def delete(queue, items): return True if isinstance(items, list): items = [(salt.utils.json.dumps(el),) for el in items] - cmd = "DELETE FROM {} WHERE data = %s".format(queue) + cmd = f"DELETE FROM {queue} WHERE data = %s" log.debug("SQL Query: %s", cmd) cur.executemany(cmd, items) return True @@ -238,7 +233,7 @@ def pop(queue, quantity=1, is_runner=False): """ Pop one or more or all items from the queue return them. """ - cmd = "SELECT id, data FROM {}".format(queue) + cmd = f"SELECT id, data FROM {queue}" if quantity != "all": try: quantity = int(quantity) @@ -247,7 +242,7 @@ def pop(queue, quantity=1, is_runner=False): exc ) raise SaltInvocationError(error_txt) - cmd = "".join([cmd, " LIMIT {};".format(quantity)]) + cmd = "".join([cmd, f" LIMIT {quantity};"]) log.debug("SQL Query: %s", cmd) items = [] with _conn(commit=True) as cur: @@ -257,7 +252,7 @@ def pop(queue, quantity=1, is_runner=False): ids = [str(item[0]) for item in result] items = [item[1] for item in result] idlist = "','".join(ids) - del_cmd = "DELETE FROM {} WHERE id IN ('{}');".format(queue, idlist) + del_cmd = f"DELETE FROM {queue} WHERE id IN ('{idlist}');" log.debug("SQL Query: %s", del_cmd) diff --git a/salt/queues/sqlite_queue.py b/salt/queues/sqlite_queue.py index 713bfa09ccd..b81d13ce5ed 100644 --- a/salt/queues/sqlite_queue.py +++ b/salt/queues/sqlite_queue.py @@ -38,7 +38,7 @@ def _conn(queue): Return an sqlite connection """ queue_dir = __opts__["sqlite_queue_dir"] - db = os.path.join(queue_dir, "{}.db".format(queue)) + db = os.path.join(queue_dir, f"{queue}.db") log.debug("Connecting to: %s", db) con = sqlite3.connect(db) @@ -61,7 +61,7 @@ def _list_tables(con): def _create_table(con, queue): with con: cur = con.cursor() - cmd = "CREATE TABLE {}(id INTEGER PRIMARY KEY, name TEXT UNIQUE)".format(queue) + cmd = f"CREATE TABLE {queue}(id INTEGER PRIMARY KEY, name TEXT UNIQUE)" log.debug("SQL Query: %s", cmd) cur.execute(cmd) return True @@ -74,7 +74,7 @@ def _list_items(queue): con = _conn(queue) with con: cur = con.cursor() - cmd = "SELECT name FROM {}".format(queue) + cmd = f"SELECT name FROM {queue}" log.debug("SQL Query: %s", cmd) cur.execute(cmd) contents = cur.fetchall() @@ -138,15 +138,15 @@ def insert(queue, items): cur = con.cursor() if isinstance(items, str): items = _quote_escape(items) - cmd = "INSERT INTO {}(name) VALUES('{}')".format(queue, items) + cmd = f"INSERT INTO {queue}(name) VALUES('{items}')" log.debug("SQL Query: %s", cmd) try: cur.execute(cmd) except sqlite3.IntegrityError as esc: - return "Item already exists in this queue. sqlite error: {}".format(esc) + return f"Item already exists in this queue. sqlite error: {esc}" if isinstance(items, list): items = [_quote_escape(el) for el in items] - cmd = "INSERT INTO {}(name) VALUES(?)".format(queue) + cmd = f"INSERT INTO {queue}(name) VALUES(?)" log.debug("SQL Query: %s", cmd) newitems = [] for item in items: @@ -162,12 +162,12 @@ def insert(queue, items): if isinstance(items, dict): items = salt.utils.json.dumps(items).replace('"', "'") items = _quote_escape(items) - cmd = "INSERT INTO {}(name) VALUES('{}')".format(queue, items) + cmd = f"INSERT INTO {queue}(name) VALUES('{items}')" log.debug("SQL Query: %s", cmd) try: cur.execute(cmd) except sqlite3.IntegrityError as esc: - return "Item already exists in this queue. sqlite error: {}".format(esc) + return f"Item already exists in this queue. sqlite error: {esc}" return True @@ -180,13 +180,13 @@ def delete(queue, items): cur = con.cursor() if isinstance(items, str): items = _quote_escape(items) - cmd = "DELETE FROM {} WHERE name = '{}'".format(queue, items) + cmd = f"DELETE FROM {queue} WHERE name = '{items}'" log.debug("SQL Query: %s", cmd) cur.execute(cmd) return True if isinstance(items, list): items = [_quote_escape(el) for el in items] - cmd = "DELETE FROM {} WHERE name = ?".format(queue) + cmd = f"DELETE FROM {queue} WHERE name = ?" log.debug("SQL Query: %s", cmd) newitems = [] for item in items: @@ -196,7 +196,7 @@ def delete(queue, items): if isinstance(items, dict): items = salt.utils.json.dumps(items).replace('"', "'") items = _quote_escape(items) - cmd = "DELETE FROM {} WHERE name = '{}'".format(queue, items) + cmd = f"DELETE FROM {queue} WHERE name = '{items}'" log.debug("SQL Query: %s", cmd) cur.execute(cmd) return True @@ -207,7 +207,7 @@ def pop(queue, quantity=1, is_runner=False): """ Pop one or more or all items from the queue return them. """ - cmd = "SELECT name FROM {}".format(queue) + cmd = f"SELECT name FROM {queue}" if quantity != "all": try: quantity = int(quantity) @@ -216,7 +216,7 @@ def pop(queue, quantity=1, is_runner=False): exc ) raise SaltInvocationError(error_txt) - cmd = "".join([cmd, " LIMIT {}".format(quantity)]) + cmd = "".join([cmd, f" LIMIT {quantity}"]) log.debug("SQL Query: %s", cmd) con = _conn(queue) items = [] @@ -227,7 +227,7 @@ def pop(queue, quantity=1, is_runner=False): items = [item[0] for item in result] itemlist = '","'.join(items) _quote_escape(itemlist) - del_cmd = 'DELETE FROM {} WHERE name IN ("{}")'.format(queue, itemlist) + del_cmd = f'DELETE FROM {queue} WHERE name IN ("{itemlist}")' log.debug("SQL Query: %s", del_cmd) diff --git a/salt/renderers/cheetah.py b/salt/renderers/cheetah.py index d7351fa6af9..5cb8499e390 100644 --- a/salt/renderers/cheetah.py +++ b/salt/renderers/cheetah.py @@ -2,7 +2,6 @@ Cheetah Renderer for Salt """ - try: from Cheetah.Template import Template diff --git a/salt/renderers/dson.py b/salt/renderers/dson.py index 0a9597aa5f6..45d4f1ab252 100644 --- a/salt/renderers/dson.py +++ b/salt/renderers/dson.py @@ -11,7 +11,6 @@ This renderer requires `Dogeon`__ (installable via pip) .. __: https://github.com/soasme/dogeon """ - import logging try: diff --git a/salt/renderers/genshi.py b/salt/renderers/genshi.py index 206cce5a3fe..62716fc2522 100644 --- a/salt/renderers/genshi.py +++ b/salt/renderers/genshi.py @@ -2,7 +2,6 @@ Genshi Renderer for Salt """ - try: from genshi.template import MarkupTemplate, NewTextTemplate, OldTextTemplate diff --git a/salt/renderers/gpg.py b/salt/renderers/gpg.py index 583d75efd69..8edde999cd9 100644 --- a/salt/renderers/gpg.py +++ b/salt/renderers/gpg.py @@ -335,7 +335,6 @@ In the Chlorine release, the default behavior will be reversed and an error message will be added to ``_errors`` by default. """ - import logging import os import re diff --git a/salt/renderers/hjson.py b/salt/renderers/hjson.py index f76f993dee6..84a7531af94 100644 --- a/salt/renderers/hjson.py +++ b/salt/renderers/hjson.py @@ -6,7 +6,6 @@ See the hjson_ documentation for more information .. _hjson: http://laktak.github.io/hjson/ """ - try: import hjson diff --git a/salt/renderers/jinja.py b/salt/renderers/jinja.py index 3ad9855805f..f238bd281de 100644 --- a/salt/renderers/jinja.py +++ b/salt/renderers/jinja.py @@ -4,7 +4,6 @@ Jinja loading utils to enable a more powerful backend for jinja templates .. include:: ../../../_incl/jinja_security.rst """ - import logging from io import StringIO @@ -47,7 +46,7 @@ def render( argline="", context=None, tmplpath=None, - **kws + **kws, ): """ Render the template_file, passing the functions and grains into the @@ -57,7 +56,7 @@ def render( """ from_str = argline == "-s" if not from_str and argline: - raise SaltRenderError("Unknown renderer option: {opt}".format(opt=argline)) + raise SaltRenderError(f"Unknown renderer option: {argline}") tmp_data = salt.utils.templates.JINJA( template_file, @@ -72,7 +71,7 @@ def render( tmplpath=tmplpath, proxy=__proxy__, from_str=from_str, - **kws + **kws, ) if not tmp_data.get("result", False): raise SaltRenderError( diff --git a/salt/renderers/json.py b/salt/renderers/json.py index 36125685334..79d29fa6b37 100644 --- a/salt/renderers/json.py +++ b/salt/renderers/json.py @@ -2,7 +2,6 @@ JSON Renderer for Salt """ - import salt.utils.json json = salt.utils.json.import_json() diff --git a/salt/renderers/json5.py b/salt/renderers/json5.py index 9d4b345113f..ed8e96e5aa1 100644 --- a/salt/renderers/json5.py +++ b/salt/renderers/json5.py @@ -11,7 +11,6 @@ This renderer requires the `json5 python bindings`__, installable via pip. .. __: https://pypi.python.org/pypi/json5 """ - import logging try: diff --git a/salt/renderers/mako.py b/salt/renderers/mako.py index 01d413140ba..9032542f865 100644 --- a/salt/renderers/mako.py +++ b/salt/renderers/mako.py @@ -10,7 +10,6 @@ To install Mako, do the following: salt-pip install mako """ - import io import salt.utils.templates diff --git a/salt/renderers/nacl.py b/salt/renderers/nacl.py index 9cd2ba0f46b..6fa0351d45c 100644 --- a/salt/renderers/nacl.py +++ b/salt/renderers/nacl.py @@ -50,7 +50,6 @@ data like so: a-secret: "NACL[MRN3cc+fmdxyQbz6WMF+jq1hKdU5X5BBI7OjK+atvHo1ll+w1gZ7XyWtZVfq9gK9rQaMfkDxmidJKwE0Mw==]" """ - import logging import re diff --git a/salt/renderers/pass.py b/salt/renderers/pass.py index ae75bba443b..825810ce68f 100644 --- a/salt/renderers/pass.py +++ b/salt/renderers/pass.py @@ -75,7 +75,6 @@ Salt master configuration options pass_dir: """ - import logging import os from os.path import expanduser diff --git a/salt/renderers/py.py b/salt/renderers/py.py index 3ce58ac405c..46ce1c03902 100644 --- a/salt/renderers/py.py +++ b/salt/renderers/py.py @@ -140,7 +140,7 @@ def render(template, saltenv="base", sls="", tmplpath=None, **kws): """ template = tmplpath if not os.path.isfile(template): - raise SaltRenderError("Template {} is not a file!".format(template)) + raise SaltRenderError(f"Template {template} is not a file!") tmp_data = salt.utils.templates.py( template, @@ -157,7 +157,7 @@ def render(template, saltenv="base", sls="", tmplpath=None, **kws): saltenv=saltenv, __sls__=sls, sls=sls, - **kws + **kws, ) if not tmp_data.get("result", False): raise SaltRenderError( diff --git a/salt/renderers/pydsl.py b/salt/renderers/pydsl.py index 5cd74941bf2..996bbb13848 100644 --- a/salt/renderers/pydsl.py +++ b/salt/renderers/pydsl.py @@ -333,6 +333,7 @@ For example: my_mod = sys.modules['salt.loaded.ext.module.my_mod'] """ + import types import salt.utils.pydsl as pydsl diff --git a/salt/renderers/pyobjects.py b/salt/renderers/pyobjects.py index ad56246396b..a719b34ef5f 100644 --- a/salt/renderers/pyobjects.py +++ b/salt/renderers/pyobjects.py @@ -313,6 +313,7 @@ file ``samba/map.sls``, you could do the following. Service.running("samba", name=Samba.service) """ + # TODO: Interface for working with reactor files @@ -346,7 +347,7 @@ class PyobjectsModule: self.__dict__ = attrs def __repr__(self): - return "".format(self.name) + return f"" def load_states(): @@ -463,9 +464,7 @@ def render(template, saltenv="base", sls="", salt_data=True, **kwargs): with get_file_client(__opts__) as client: state_file = client.cache_file(import_file, saltenv) if not state_file: - raise ImportError( - "Could not find the file '{}'".format(import_file) - ) + raise ImportError(f"Could not find the file '{import_file}'") with salt.utils.files.fopen(state_file) as state_fh: state_contents, state_globals = process_template(state_fh) @@ -490,7 +489,7 @@ def render(template, saltenv="base", sls="", salt_data=True, **kwargs): if name not in state_globals: raise ImportError( - "'{}' was not found in '{}'".format(name, import_file) + f"'{name}' was not found in '{import_file}'" ) template_globals[alias] = state_globals[name] diff --git a/salt/renderers/stateconf.py b/salt/renderers/stateconf.py index 3b0348633af..50b2ebb20c0 100644 --- a/salt/renderers/stateconf.py +++ b/salt/renderers/stateconf.py @@ -5,6 +5,7 @@ A flexible renderer that takes a templating engine and a data format :maturity: new :platform: all """ + # See http://docs.saltstack.org/en/latest/ref/renderers/all/salt.renderers.stateconf.html # for a guide to using this module. # @@ -50,7 +51,7 @@ __opts__ = { # name of the state id for the generated start state. "stateconf_goal_state": ".goal", # name of the state id for the generated goal state. - "stateconf_state_func": "stateconf.set" + "stateconf_state_func": "stateconf.set", # names the state and the state function to be recognized as a special # state from which to gather sls file context variables. It should be # specified in the 'state.func' notation, and both the state module and @@ -115,7 +116,7 @@ def render(input, saltenv="base", sls="", argline="", **kws): sls, context=ctx, argline=rt_argline.strip(), - **kws + **kws, ) high = render_data(tmplout, saltenv, sls, argline=rd_argline.strip()) return process_high_data(high, extract) @@ -201,7 +202,7 @@ def render(input, saltenv="base", sls="", argline="", **kws): name, rt_argline = (args[1] + " ").split(" ", 1) render_template = renderers[name] # e.g., the mako renderer except KeyError as err: - raise SaltRenderError("Renderer: {} is not available!".format(err)) + raise SaltRenderError(f"Renderer: {err} is not available!") except IndexError: raise INVALID_USAGE_ERROR @@ -427,7 +428,7 @@ EXTENDED_REQUIRE_IN = {} # explicit require_in/watch_in/listen_in/onchanges_in/onfail_in can only contain states after it def add_implicit_requires(data): def T(sid, state): # pylint: disable=C0103 - return "{}:{}".format(sid, state_name(state)) + return f"{sid}:{state_name(state)}" states_before = set() states_after = set() diff --git a/salt/renderers/yaml.py b/salt/renderers/yaml.py index eb76a431372..cfc908bce19 100644 --- a/salt/renderers/yaml.py +++ b/salt/renderers/yaml.py @@ -4,7 +4,6 @@ YAML Renderer for Salt For YAML usage information see :ref:`Understanding YAML `. """ - import logging import warnings diff --git a/salt/returners/__init__.py b/salt/returners/__init__.py index 5ad44a7ff65..2f184fa598a 100644 --- a/salt/returners/__init__.py +++ b/salt/returners/__init__.py @@ -120,9 +120,9 @@ def _fetch_option(cfg, ret_config, virtualname, attr_name): if isinstance(cfg, dict): c_cfg = cfg else: - c_cfg = cfg("{}".format(virtualname), {}) + c_cfg = cfg(f"{virtualname}", {}) - default_cfg_key = "{}.{}".format(virtualname, attr_name) + default_cfg_key = f"{virtualname}.{attr_name}" if not ret_config: # Using the default configuration key if isinstance(cfg, dict): @@ -134,7 +134,7 @@ def _fetch_option(cfg, ret_config, virtualname, attr_name): return c_cfg.get(attr_name, cfg(default_cfg_key)) # Using ret_config to override the default configuration key - ret_cfg = cfg("{}.{}".format(ret_config, virtualname), {}) + ret_cfg = cfg(f"{ret_config}.{virtualname}", {}) override_default_cfg_key = "{}.{}.{}".format( ret_config, @@ -209,6 +209,6 @@ def _fetch_profile_opts( return {} return { - pattr: creds.get("{}.{}".format(virtualname, profile_attrs[pattr])) + pattr: creds.get(f"{virtualname}.{profile_attrs[pattr]}") for pattr in profile_attrs } diff --git a/salt/returners/appoptics_return.py b/salt/returners/appoptics_return.py index c49d5e22e28..036112e11fa 100644 --- a/salt/returners/appoptics_return.py +++ b/salt/returners/appoptics_return.py @@ -69,7 +69,6 @@ the name of the state that was invoked, e.g. ``role_salt_master.netapi``. """ - import logging import salt.returners diff --git a/salt/returners/carbon_return.py b/salt/returners/carbon_return.py index 5dd6cd82dbd..91d5ceeb24a 100644 --- a/salt/returners/carbon_return.py +++ b/salt/returners/carbon_return.py @@ -198,10 +198,10 @@ def _walk(path, value, metrics, timestamp, skip): ) if isinstance(value, Mapping): for key, val in value.items(): - _walk("{}.{}".format(path, key), val, metrics, timestamp, skip) + _walk(f"{path}.{key}", val, metrics, timestamp, skip) elif isinstance(value, list): for item in value: - _walk("{}.{}".format(path, item), item, metrics, timestamp, skip) + _walk(f"{path}.{item}", item, metrics, timestamp, skip) else: try: diff --git a/salt/returners/couchdb_return.py b/salt/returners/couchdb_return.py index 1a67a61d275..0e39745c883 100644 --- a/salt/returners/couchdb_return.py +++ b/salt/returners/couchdb_return.py @@ -51,7 +51,6 @@ otherwise multi-minion targeting can lead to losing output: * other minions fail with ``{'error': 'HTTP Error 409: Conflict'}`` """ - import logging import time from urllib.error import HTTPError @@ -123,7 +122,7 @@ def _request(method, url, content_type=None, _data=None): try: handler = opener.open(request) except HTTPError as exc: - return {"error": "{}".format(exc)} + return {"error": f"{exc}"} return salt.utils.json.loads(handler.read()) diff --git a/salt/returners/elasticsearch_return.py b/salt/returners/elasticsearch_return.py index e4c790b64b5..8d329e313e3 100644 --- a/salt/returners/elasticsearch_return.py +++ b/salt/returners/elasticsearch_return.py @@ -93,7 +93,6 @@ Minion configuration: - saltutil.find_job """ - import datetime import logging import uuid @@ -183,8 +182,8 @@ def _ensure_index(index): "number_of_replicas": options["number_of_replicas"], } } - __salt__["elasticsearch.index_create"]("{}-v1".format(index), index_definition) - __salt__["elasticsearch.alias_create"]("{}-v1".format(index), index) + __salt__["elasticsearch.index_create"](f"{index}-v1", index_definition) + __salt__["elasticsearch.alias_create"](f"{index}-v1", index) def _convert_keys(data): @@ -236,9 +235,9 @@ def returner(ret): # Build the index name if options["states_single_index"] and job_fun in STATE_FUNCTIONS: - index = "salt-{}".format(STATE_FUNCTIONS[job_fun]) + index = f"salt-{STATE_FUNCTIONS[job_fun]}" else: - index = "salt-{}".format(job_fun_escaped) + index = f"salt-{job_fun_escaped}" if options["index_date"]: index = "{}-{}".format(index, datetime.date.today().strftime("%Y.%m.%d")) @@ -260,7 +259,7 @@ def returner(ret): # index to be '-ordered' so as not to clash with the unsorted # index data format if options["states_order_output"] and isinstance(ret["return"], dict): - index = "{}-ordered".format(index) + index = f"{index}-ordered" max_chars = len(str(len(ret["return"]))) for uid, data in ret["return"].items(): diff --git a/salt/returners/influxdb_return.py b/salt/returners/influxdb_return.py index 645218242aa..99aa32716c3 100644 --- a/salt/returners/influxdb_return.py +++ b/salt/returners/influxdb_return.py @@ -108,9 +108,7 @@ def _get_version(host, port, user, password): version = None # check the InfluxDB version via the HTTP API try: - result = requests.get( - "http://{}:{}/ping".format(host, port), auth=(user, password) - ) + result = requests.get(f"http://{host}:{port}/ping", auth=(user, password)) if influxDBVersionHeader in result.headers: version = result.headers[influxDBVersionHeader] except Exception as ex: # pylint: disable=broad-except @@ -224,7 +222,7 @@ def get_load(jid): Return the load data that marks a specified jid """ serv = _get_serv(ret=None) - sql = "select load from jids where jid = '{}'".format(jid) + sql = f"select load from jids where jid = '{jid}'" log.debug(">> Now in get_load %s", jid) data = serv.query(sql) @@ -240,7 +238,7 @@ def get_jid(jid): """ serv = _get_serv(ret=None) - sql = "select id, full_ret from returns where jid = '{}'".format(jid) + sql = f"select id, full_ret from returns where jid = '{jid}'" data = serv.query(sql) ret = {} diff --git a/salt/returners/librato_return.py b/salt/returners/librato_return.py index cceaffb6490..890393808e1 100644 --- a/salt/returners/librato_return.py +++ b/salt/returners/librato_return.py @@ -29,7 +29,6 @@ by adding more tags to the submission. """ - import logging import salt.returners diff --git a/salt/returners/local_cache.py b/salt/returners/local_cache.py index 1530d94ddfc..927502358a6 100644 --- a/salt/returners/local_cache.py +++ b/salt/returners/local_cache.py @@ -89,7 +89,7 @@ def prep_jid(nocache=False, passed_jid=None, recurse_count=0): So do what you have to do to make sure that stays the case """ if recurse_count >= 5: - err = "prep_jid could not store a jid after {} tries.".format(recurse_count) + err = f"prep_jid could not store a jid after {recurse_count} tries." log.error(err) raise salt.exceptions.SaltCacheError(err) if passed_jid is None: # this can be a None or an empty string. @@ -237,7 +237,7 @@ def save_minions(jid, minions, syndic_id=None): log.debug( "Adding minions for job %s%s: %s", jid, - " from syndic master '{}'".format(syndic_id) if syndic_id else "", + f" from syndic master '{syndic_id}'" if syndic_id else "", minions, ) diff --git a/salt/returners/mattermost_returner.py b/salt/returners/mattermost_returner.py index fae03a0259b..d41841aa4a1 100644 --- a/salt/returners/mattermost_returner.py +++ b/salt/returners/mattermost_returner.py @@ -128,7 +128,7 @@ def event_return(events): log.debug("Event data: %s", event["data"]) message = "tag: {}\r\n".format(event["tag"]) for key, value in event["data"].items(): - message += "{}: {}\r\n".format(key, value) + message += f"{key}: {value}\r\n" result = post_message(channel, message, username, api_url, hook) if not result: is_ok = False @@ -157,7 +157,7 @@ def post_message(channel, message, username, api_url, hook): result = salt.utils.mattermost.query( api_url=api_url, hook=hook, - data="payload={}".format(salt.utils.json.dumps(parameters)), + data=f"payload={salt.utils.json.dumps(parameters)}", ) log.debug("result %s", result) diff --git a/salt/returners/memcache_return.py b/salt/returners/memcache_return.py index a5d80802757..455f0a4adc9 100644 --- a/salt/returners/memcache_return.py +++ b/salt/returners/memcache_return.py @@ -121,9 +121,9 @@ def _get_list(serv, key): def _append_list(serv, key, value): if value in _get_list(serv, key): return - r = serv.append(key, "{},".format(value)) + r = serv.append(key, f"{value},") if not r: - serv.add(key, "{},".format(value)) + serv.add(key, f"{value},") def prep_jid(nocache=False, passed_jid=None): # pylint: disable=unused-argument @@ -142,8 +142,8 @@ def returner(ret): jid = ret["jid"] fun = ret["fun"] rets = salt.utils.json.dumps(ret) - serv.set("{}:{}".format(jid, minion), rets) # cache for get_jid - serv.set("{}:{}".format(fun, minion), rets) # cache for get_fun + serv.set(f"{jid}:{minion}", rets) # cache for get_jid + serv.set(f"{fun}:{minion}", rets) # cache for get_fun # The following operations are neither efficient nor atomic. # If there is a way to make them so, this should be updated. @@ -183,7 +183,7 @@ def get_jid(jid): """ serv = _get_serv(ret=None) minions = _get_list(serv, "minions") - returns = serv.get_multi(minions, key_prefix="{}:".format(jid)) + returns = serv.get_multi(minions, key_prefix=f"{jid}:") # returns = {minion: return, minion: return, ...} ret = {} for minion, data in returns.items(): @@ -197,7 +197,7 @@ def get_fun(fun): """ serv = _get_serv(ret=None) minions = _get_list(serv, "minions") - returns = serv.get_multi(minions, key_prefix="{}:".format(fun)) + returns = serv.get_multi(minions, key_prefix=f"{fun}:") # returns = {minion: return, minion: return, ...} ret = {} for minion, data in returns.items(): diff --git a/salt/returners/multi_returner.py b/salt/returners/multi_returner.py index 550a6c1e43e..0017f6e7a2f 100644 --- a/salt/returners/multi_returner.py +++ b/salt/returners/multi_returner.py @@ -3,7 +3,6 @@ Read/Write multiple returners """ - import logging import salt.minion @@ -42,11 +41,9 @@ def prep_jid(nocache=False, passed_jid=None): jid = passed_jid for returner_ in __opts__[CONFIG_KEY]: if jid is None: - jid = _mminion().returners["{}.prep_jid".format(returner_)](nocache=nocache) + jid = _mminion().returners[f"{returner_}.prep_jid"](nocache=nocache) else: - r_jid = _mminion().returners["{}.prep_jid".format(returner_)]( - nocache=nocache - ) + r_jid = _mminion().returners[f"{returner_}.prep_jid"](nocache=nocache) if r_jid != jid: log.debug("Uhh.... crud the jids do not match") return jid @@ -57,7 +54,7 @@ def returner(load): Write return to all returners in multi_returner """ for returner_ in __opts__[CONFIG_KEY]: - _mminion().returners["{}.returner".format(returner_)](load) + _mminion().returners[f"{returner_}.returner"](load) def save_load(jid, clear_load, minions=None): @@ -65,7 +62,7 @@ def save_load(jid, clear_load, minions=None): Write load to all returners in multi_returner """ for returner_ in __opts__[CONFIG_KEY]: - _mminion().returners["{}.save_load".format(returner_)](jid, clear_load) + _mminion().returners[f"{returner_}.save_load"](jid, clear_load) def save_minions(jid, minions, syndic_id=None): # pylint: disable=unused-argument @@ -80,7 +77,7 @@ def get_load(jid): """ ret = {} for returner_ in __opts__[CONFIG_KEY]: - ret.update(_mminion().returners["{}.get_load".format(returner_)](jid)) + ret.update(_mminion().returners[f"{returner_}.get_load"](jid)) return ret @@ -91,7 +88,7 @@ def get_jid(jid): """ ret = {} for returner_ in __opts__[CONFIG_KEY]: - ret.update(_mminion().returners["{}.get_jid".format(returner_)](jid)) + ret.update(_mminion().returners[f"{returner_}.get_jid"](jid)) return ret @@ -102,7 +99,7 @@ def get_jids(): """ ret = {} for returner_ in __opts__[CONFIG_KEY]: - ret.update(_mminion().returners["{}.get_jids".format(returner_)]()) + ret.update(_mminion().returners[f"{returner_}.get_jids"]()) return ret @@ -112,6 +109,6 @@ def clean_old_jobs(): Clean out the old jobs from all returners (if you have it) """ for returner_ in __opts__[CONFIG_KEY]: - fstr = "{}.clean_old_jobs".format(returner_) + fstr = f"{returner_}.clean_old_jobs" if fstr in _mminion().returners: _mminion().returners[fstr]() diff --git a/salt/returners/mysql.py b/salt/returners/mysql.py index 67b44004acf..87f5e37fa46 100644 --- a/salt/returners/mysql.py +++ b/salt/returners/mysql.py @@ -274,7 +274,7 @@ def _get_serv(ret=None, commit=False): pass except OperationalError as exc: raise salt.exceptions.SaltMasterError( - "MySQL returner could not connect to database: {exc}".format(exc=exc) + f"MySQL returner could not connect to database: {exc}" ) cursor = conn.cursor() diff --git a/salt/returners/odbc.py b/salt/returners/odbc.py index f7393876739..da98baf18c4 100644 --- a/salt/returners/odbc.py +++ b/salt/returners/odbc.py @@ -153,7 +153,7 @@ def _get_options(ret=None): attrs = {"dsn": "dsn", "user": "user", "passwd": "passwd"} _options = salt.returners.get_returner_options( - "returner.{}".format(__virtualname__), + f"returner.{__virtualname__}", ret, attrs, __salt__=__salt__, @@ -171,7 +171,7 @@ def _get_conn(ret=None): user = _options.get("user") passwd = _options.get("passwd") - return pyodbc.connect("DSN={};UID={};PWD={}".format(dsn, user, passwd)) + return pyodbc.connect(f"DSN={dsn};UID={user};PWD={passwd}") def _close_conn(conn): diff --git a/salt/returners/pgjsonb.py b/salt/returners/pgjsonb.py index d47e9cce8d6..5cfd1150172 100644 --- a/salt/returners/pgjsonb.py +++ b/salt/returners/pgjsonb.py @@ -225,7 +225,7 @@ def _get_options(ret=None): } _options = salt.returners.get_returner_options( - "returner.{}".format(__virtualname__), + f"returner.{__virtualname__}", ret, attrs, __salt__=__salt__, @@ -258,11 +258,11 @@ def _get_serv(ret=None, commit=False): dbname=_options.get("db"), user=_options.get("user"), password=_options.get("pass"), - **ssl_options + **ssl_options, ) except psycopg2.OperationalError as exc: raise salt.exceptions.SaltMasterError( - "pgjsonb returner could not connect to database: {exc}".format(exc=exc) + f"pgjsonb returner could not connect to database: {exc}" ) if conn.server_version is not None and conn.server_version >= 90500: diff --git a/salt/returners/postgres.py b/salt/returners/postgres.py index a30ac590056..de7d436c83c 100644 --- a/salt/returners/postgres.py +++ b/salt/returners/postgres.py @@ -174,7 +174,7 @@ def _get_options(ret=None): } _options = salt.returners.get_returner_options( - "returner.{}".format(__virtualname__), + f"returner.{__virtualname__}", ret, attrs, __salt__=__salt__, @@ -204,7 +204,7 @@ def _get_serv(ret=None, commit=False): except psycopg2.OperationalError as exc: raise salt.exceptions.SaltMasterError( - "postgres returner could not connect to database: {exc}".format(exc=exc) + f"postgres returner could not connect to database: {exc}" ) cursor = conn.cursor() diff --git a/salt/returners/postgres_local_cache.py b/salt/returners/postgres_local_cache.py index 58d2a19766e..4a8c6d4262e 100644 --- a/salt/returners/postgres_local_cache.py +++ b/salt/returners/postgres_local_cache.py @@ -106,7 +106,6 @@ and then: Required python modules: psycopg2 """ - import logging import re import sys diff --git a/salt/returners/rawfile_json.py b/salt/returners/rawfile_json.py index e06347180d5..a4687611813 100644 --- a/salt/returners/rawfile_json.py +++ b/salt/returners/rawfile_json.py @@ -16,7 +16,6 @@ noise, so you may wish to configure batch processing and/or configure the to restrict the events that are written. """ - import logging import salt.returners diff --git a/salt/returners/sentry_return.py b/salt/returners/sentry_return.py index 0b660392ef0..6f477dc1c99 100644 --- a/salt/returners/sentry_return.py +++ b/salt/returners/sentry_return.py @@ -111,11 +111,7 @@ def _get_message(ret): kwargs = ret["fun_args"][-1] if isinstance(kwargs, dict): kwarg_string = " ".join( - sorted( - "{}={}".format(k, v) - for k, v in kwargs.items() - if not k.startswith("_") - ) + sorted(f"{k}={v}" for k, v in kwargs.items() if not k.startswith("_")) ) return "salt func: {fun} {argstr} {kwargstr}".format( fun=ret["fun"], argstr=arg_string, kwargstr=kwarg_string diff --git a/salt/returners/slack_webhook_return.py b/salt/returners/slack_webhook_return.py index 43357f53d23..5df1a1d641c 100644 --- a/salt/returners/slack_webhook_return.py +++ b/salt/returners/slack_webhook_return.py @@ -170,10 +170,10 @@ def _generate_payload(author_icon, title, report, **kwargs): text += "JID: {}\n".format(report.get("jid")) if TOTAL_KEY in report: - text += "Total: {}\n".format(report[TOTAL_KEY]) + text += f"Total: {report[TOTAL_KEY]}\n" if DURATION_KEY in report: - text += "Duration: {:.2f} secs".format(float(report[DURATION_KEY])) + text += f"Duration: {float(report[DURATION_KEY]):.2f} secs" attachments = [ { @@ -201,7 +201,7 @@ def _generate_payload(author_icon, title, report, **kwargs): # Changed changed = { "color": "warning", - "title": "Changed: {}".format(report[CHANGED_KEY].get(COUNTER_KEY, 0)), + "title": f"Changed: {report[CHANGED_KEY].get(COUNTER_KEY, 0)}", } if len(report[CHANGED_KEY].get(TASKS_KEY, [])) > 0: @@ -212,7 +212,7 @@ def _generate_payload(author_icon, title, report, **kwargs): # Failed failed = { "color": "danger", - "title": "Failed: {}".format(report[FAILED_KEY].get(COUNTER_KEY, None)), + "title": f"Failed: {report[FAILED_KEY].get(COUNTER_KEY, None)}", } if len(report[FAILED_KEY].get(TASKS_KEY, [])) > 0: @@ -319,9 +319,7 @@ def _generate_report(ret, show_tasks): del ret_return[CHANGED_KEY][TASKS_KEY] del ret_return[FAILED_KEY][TASKS_KEY] elif isinstance(ret_return, dict): - ret_return = { - "return": "\n{}".format(salt.utils.yaml.safe_dump(ret_return, indent=2)) - } + ret_return = {"return": f"\n{salt.utils.yaml.safe_dump(ret_return, indent=2)}"} else: ret_return = {"return": ret_return} diff --git a/salt/returners/smtp_return.py b/salt/returners/smtp_return.py index 7e3787d46e8..6c6394861d9 100644 --- a/salt/returners/smtp_return.py +++ b/salt/returners/smtp_return.py @@ -104,7 +104,6 @@ Also you need to create additional file ``/srv/salt/templates/email.j2`` with em This configuration enables Salt Master to send an email when accepting or rejecting minions keys. """ - import io import logging import os @@ -186,7 +185,7 @@ def returner(ret): for field in fields: if field in ret: - subject += " {}".format(ret[field]) + subject += f" {ret[field]}" subject = compile_template( ":string:", rend, renderer, blacklist, whitelist, input_data=subject, **ret ) @@ -214,7 +213,7 @@ def returner(ret): if gpgowner: if HAS_GNUPG: gpg = gnupg.GPG( - gnupghome=os.path.expanduser("~{}/.gnupg".format(gpgowner)), + gnupghome=os.path.expanduser(f"~{gpgowner}/.gnupg"), options=["--trust-model always"], ) encrypted_data = gpg.encrypt(content, to_addrs) diff --git a/salt/returners/zabbix_return.py b/salt/returners/zabbix_return.py index a762c67badf..ac49150f0cd 100644 --- a/salt/returners/zabbix_return.py +++ b/salt/returners/zabbix_return.py @@ -16,7 +16,6 @@ To use the Zabbix returner, append '--return zabbix' to the salt command. ex: salt '*' test.ping --return zabbix """ - import os # Define the module's virtual name diff --git a/salt/roster/__init__.py b/salt/roster/__init__.py index fc7339d785b..a6b8bb2475d 100644 --- a/salt/roster/__init__.py +++ b/salt/roster/__init__.py @@ -45,10 +45,10 @@ def get_roster_file(options): template = os.path.join(salt.syspaths.CONFIG_DIR, "roster") if not os.path.isfile(template): - raise OSError('Roster file "{}" not found'.format(template)) + raise OSError(f'Roster file "{template}" not found') if not os.access(template, os.R_OK): - raise OSError('Access denied to roster "{}"'.format(template)) + raise OSError(f'Access denied to roster "{template}"') return template @@ -80,7 +80,7 @@ class Roster: back = set() if self.backends: for backend in self.backends: - fun = "{}.targets".format(backend) + fun = f"{backend}.targets" if fun in self.rosters: back.add(backend) return back @@ -93,7 +93,7 @@ class Roster: """ targets = {} for back in self._gen_back(): - f_str = "{}.targets".format(back) + f_str = f"{back}.targets" if f_str not in self.rosters: continue try: diff --git a/salt/roster/cache.py b/salt/roster/cache.py index a6a117d2d8e..57f096dde6b 100644 --- a/salt/roster/cache.py +++ b/salt/roster/cache.py @@ -177,7 +177,7 @@ def _load_minion(minion_id, cache): 6: sorted(ipaddress.IPv6Address(addr) for addr in grains.get("ipv6", [])), } - mine = cache.fetch("minions/{}".format(minion_id), "mine") + mine = cache.fetch(f"minions/{minion_id}", "mine") return grains, pillar, addrs, mine @@ -205,9 +205,9 @@ def _minion_lookup(minion_id, key, minion): elif isinstance(key, dict): # Lookup the key in the dict for data_id, lookup in key.items(): - ref = {"pillar": pillar, "grain": grains, "mine": mine}[data_id] + ref = {"pillar": pillar, "grain": grains, "mine": mine} - for k in _data_lookup(ref, lookup): + for k in _data_lookup(ref[data_id], lookup): if k: return k @@ -229,9 +229,9 @@ def _minion_lookup(minion_id, key, minion): else: # Take the addresses from the grains and filter them filters = { - "global": lambda addr: addr.is_global - if addr.version == 6 - else not addr.is_private, + "global": lambda addr: ( + addr.is_global if addr.version == 6 else not addr.is_private + ), "public": lambda addr: not addr.is_private, "private": lambda addr: addr.is_private and not addr.is_loopback @@ -250,6 +250,4 @@ def _minion_lookup(minion_id, key, minion): if filters[key](addr): return str(addr) except KeyError: - raise KeyError( - "Invalid filter {} specified in roster_order".format(key) - ) + raise KeyError(f"Invalid filter {key} specified in roster_order") diff --git a/salt/roster/cloud.py b/salt/roster/cloud.py index 7b9305fbd0c..096329f569d 100644 --- a/salt/roster/cloud.py +++ b/salt/roster/cloud.py @@ -17,7 +17,6 @@ usually located at /etc/salt/cloud. For example, add the following: sudo: True """ - import copy import os diff --git a/salt/roster/clustershell.py b/salt/roster/clustershell.py index 1d07bf4adc4..ea3250117ef 100644 --- a/salt/roster/clustershell.py +++ b/salt/roster/clustershell.py @@ -11,7 +11,6 @@ When you want to use host globs for target matching, use ``--roster clustershell """ - import copy import socket diff --git a/salt/roster/dir.py b/salt/roster/dir.py index b194f192fd0..8ac42a3350b 100644 --- a/salt/roster/dir.py +++ b/salt/roster/dir.py @@ -46,7 +46,6 @@ This makes it possible to avoid having to specify the hostnames when you always their minion id plus some domain. """ - import logging import os @@ -72,7 +71,7 @@ def targets(tgt, tgt_type="glob", **kwargs): for minion_id in matched_raw: target_file = salt.utils.verify.clean_path(roster_dir, minion_id) if not os.path.exists(target_file): - raise CommandExecutionError("{} does not exist".format(target_file)) + raise CommandExecutionError(f"{target_file} does not exist") rendered[minion_id] = _render(target_file, **kwargs) pruned_rendered = {id_: data for id_, data in rendered.items() if data} log.debug( @@ -100,9 +99,9 @@ def _render(roster_file, **kwargs): __opts__["renderer_blacklist"], __opts__["renderer_whitelist"], mask_value="*passw*", - **kwargs + **kwargs, ) - result.setdefault("host", "{}.{}".format(os.path.basename(roster_file), domain)) + result.setdefault("host", f"{os.path.basename(roster_file)}.{domain}") return result except: # pylint: disable=W0702 log.warning('Unable to render roster file "%s".', roster_file, exc_info=True) diff --git a/salt/roster/sshconfig.py b/salt/roster/sshconfig.py index a499fff5860..c4b3bdcb7ae 100644 --- a/salt/roster/sshconfig.py +++ b/salt/roster/sshconfig.py @@ -33,7 +33,7 @@ def _get_ssh_config_file(opts): if not os.path.isfile(ssh_config_file): raise OSError("Cannot find SSH config file") if not os.access(ssh_config_file, os.R_OK): - raise OSError("Cannot access SSH config file: {}".format(ssh_config_file)) + raise OSError(f"Cannot access SSH config file: {ssh_config_file}") return ssh_config_file @@ -117,7 +117,7 @@ class RosterMatcher: Execute the correct tgt_type routine and return """ try: - return getattr(self, "ret_{}_minions".format(self.tgt_type))() + return getattr(self, f"ret_{self.tgt_type}_minions")() except AttributeError: return {} diff --git a/salt/roster/sshknownhosts.py b/salt/roster/sshknownhosts.py index 33ecea925a1..6f895e2e7fa 100644 --- a/salt/roster/sshknownhosts.py +++ b/salt/roster/sshknownhosts.py @@ -36,7 +36,6 @@ Or with a Saltfile """ - import logging import os @@ -98,9 +97,7 @@ def targets(tgt, tgt_type="glob"): raise OSError("Cannot find SSH known_hosts file") if not os.access(ssh_known_hosts_file, os.R_OK): log.error("Cannot access SSH known_hosts file: %s", ssh_known_hosts_file) - raise OSError( - "Cannot access SSH known_hosts file: {}".format(ssh_known_hosts_file) - ) + raise OSError(f"Cannot access SSH known_hosts file: {ssh_known_hosts_file}") with salt.utils.files.fopen(ssh_known_hosts_file, "r") as hostfile: raw = _parse_ssh_known_hosts([line.rstrip() for line in hostfile]) diff --git a/salt/runners/asam.py b/salt/runners/asam.py index 81e547b784b..ca80dcfdf78 100644 --- a/salt/runners/asam.py +++ b/salt/runners/asam.py @@ -226,7 +226,7 @@ def remove_platform(name, server_url): try: html_content = _make_post_request(url, data, auth, verify=config["verify_ssl"]) except Exception as exc: # pylint: disable=broad-except - err_msg = "Failed to look up existing platforms on {}".format(server_url) + err_msg = f"Failed to look up existing platforms on {server_url}" log.error("%s:\n%s", err_msg, exc) return {name: err_msg} @@ -244,18 +244,18 @@ def remove_platform(name, server_url): url, data, auth, verify=config["verify_ssl"] ) except Exception as exc: # pylint: disable=broad-except - err_msg = "Failed to delete platform from {}".format(server_url) + err_msg = f"Failed to delete platform from {server_url}" log.error("%s:\n%s", err_msg, exc) return {name: err_msg} parser = _parse_html_content(html_content) platformset_name = _get_platformset_name(parser.data, name) if platformset_name: - return {name: "Failed to delete platform from {}".format(server_url)} + return {name: f"Failed to delete platform from {server_url}"} else: - return {name: "Successfully deleted platform from {}".format(server_url)} + return {name: f"Successfully deleted platform from {server_url}"} else: - return {name: "Specified platform name does not exist on {}".format(server_url)} + return {name: f"Specified platform name does not exist on {server_url}"} def list_platforms(server_url): @@ -351,11 +351,11 @@ def add_platform(name, platform_set, server_url): platforms = list_platforms(server_url) if name in platforms[server_url]: - return {name: "Specified platform already exists on {}".format(server_url)} + return {name: f"Specified platform already exists on {server_url}"} platform_sets = list_platform_sets(server_url) if platform_set not in platform_sets[server_url]: - return {name: "Specified platform set does not exist on {}".format(server_url)} + return {name: f"Specified platform set does not exist on {server_url}"} url = config["platform_edit_url"] @@ -373,12 +373,12 @@ def add_platform(name, platform_set, server_url): try: html_content = _make_post_request(url, data, auth, verify=config["verify_ssl"]) except Exception as exc: # pylint: disable=broad-except - err_msg = "Failed to add platform on {}".format(server_url) + err_msg = f"Failed to add platform on {server_url}" log.error("%s:\n%s", err_msg, exc) return {name: err_msg} platforms = list_platforms(server_url) if name in platforms[server_url]: - return {name: "Successfully added platform on {}".format(server_url)} + return {name: f"Successfully added platform on {server_url}"} else: - return {name: "Failed to add platform on {}".format(server_url)} + return {name: f"Failed to add platform on {server_url}"} diff --git a/salt/runners/auth.py b/salt/runners/auth.py index 7485ef55a44..91f20c52e38 100644 --- a/salt/runners/auth.py +++ b/salt/runners/auth.py @@ -5,7 +5,6 @@ Authentication runner for creating, deleting, and managing eauth tokens. """ - import os import salt.auth diff --git a/salt/runners/bgp.py b/salt/runners/bgp.py index 4603de029af..bee6d4698ea 100644 --- a/salt/runners/bgp.py +++ b/salt/runners/bgp.py @@ -331,9 +331,7 @@ def neighbors(*asns, **kwargs): ) ) if ipnet: - title_parts.append( - "Selecting neighbors within the IP network: {ipnet}".format(ipnet=ipnet) - ) + title_parts.append(f"Selecting neighbors within the IP network: {ipnet}") if kwargs: title_parts.append( "Searching for BGP neighbors having the attributes: {attrmap}".format( diff --git a/salt/runners/cache.py b/salt/runners/cache.py index 88a5c6be0db..89309af690f 100644 --- a/salt/runners/cache.py +++ b/salt/runners/cache.py @@ -327,7 +327,7 @@ def clear_git_lock(role, remote=None, **kwargs): ) git_objects.append(obj) else: - raise SaltInvocationError("Invalid role '{}'".format(role)) + raise SaltInvocationError(f"Invalid role '{role}'") ret = {} for obj in git_objects: diff --git a/salt/runners/ddns.py b/salt/runners/ddns.py index 9e4d5c64971..831f5211627 100644 --- a/salt/runners/ddns.py +++ b/salt/runners/ddns.py @@ -75,7 +75,7 @@ def create( """ if zone in name: name = name.replace(zone, "").rstrip(".") - fqdn = "{}.{}".format(name, zone) + fqdn = f"{name}.{zone}" request = dns.message.make_query(fqdn, rdtype) answer = dns.query.udp(request, nameserver, timeout, port) @@ -99,9 +99,9 @@ def create( answer = dns.query.udp(dns_update, nameserver, timeout, port) if answer.rcode() > 0: - return {fqdn: "Failed to create record of type '{}'".format(rdtype)} + return {fqdn: f"Failed to create record of type '{rdtype}'"} - return {fqdn: "Created record of type '{}': {} -> {}".format(rdtype, fqdn, data)} + return {fqdn: f"Created record of type '{rdtype}': {fqdn} -> {data}"} def update( @@ -135,7 +135,7 @@ def update( """ if zone in name: name = name.replace(zone, "").rstrip(".") - fqdn = "{}.{}".format(name, zone) + fqdn = f"{name}.{zone}" request = dns.message.make_query(fqdn, rdtype) answer = dns.query.udp(request, nameserver, timeout, port) if not answer.answer: @@ -166,9 +166,9 @@ def update( answer = dns.query.udp(dns_update, nameserver, timeout, port) if answer.rcode() > 0: - return {fqdn: "Failed to update record of type '{}'".format(rdtype)} + return {fqdn: f"Failed to update record of type '{rdtype}'"} - return {fqdn: "Updated record of type '{}'".format(rdtype)} + return {fqdn: f"Updated record of type '{rdtype}'"} def delete( @@ -194,7 +194,7 @@ def delete( """ if zone in name: name = name.replace(zone, "").rstrip(".") - fqdn = "{}.{}".format(name, zone) + fqdn = f"{name}.{zone}" request = dns.message.make_query(fqdn, (rdtype or "ANY")) answer = dns.query.udp(request, nameserver, timeout, port) @@ -248,7 +248,7 @@ def add_host( res = [] if zone in name: name = name.replace(zone, "").rstrip(".") - fqdn = "{}.{}".format(name, zone) + fqdn = f"{name}.{zone}" ret = create( zone, @@ -277,13 +277,13 @@ def add_host( zone = "{}.{}".format(".".join(parts), "in-addr.arpa.") name = ".".join(popped) - rev_fqdn = "{}.{}".format(name, zone) + rev_fqdn = f"{name}.{zone}" ret = create( zone, name, ttl, "PTR", - "{}.".format(fqdn), + f"{fqdn}.", keyname, keyfile, nameserver, @@ -317,7 +317,7 @@ def delete_host( res = [] if zone in name: name = name.replace(zone, "").rstrip(".") - fqdn = "{}.{}".format(name, zone) + fqdn = f"{name}.{zone}" request = dns.message.make_query(fqdn, "A") answer = dns.query.udp(request, nameserver, timeout, port) @@ -336,7 +336,7 @@ def delete_host( port=port, keyalgorithm=keyalgorithm, ) - res.append("{} of type 'A'".format(ret[fqdn])) + res.append(f"{ret[fqdn]} of type 'A'") for ip in ips: parts = ip.split(".")[::-1] @@ -350,7 +350,7 @@ def delete_host( popped.append(p) zone = "{}.{}".format(".".join(parts), "in-addr.arpa.") name = ".".join(popped) - rev_fqdn = "{}.{}".format(name, zone) + rev_fqdn = f"{name}.{zone}" ret = delete( zone, name, @@ -359,13 +359,13 @@ def delete_host( nameserver, timeout, "PTR", - "{}.".format(fqdn), + f"{fqdn}.", port, keyalgorithm, ) if "Deleted" in ret[rev_fqdn]: - res.append("{} of type 'PTR'".format(ret[rev_fqdn])) + res.append(f"{ret[rev_fqdn]} of type 'PTR'") return {fqdn: res} res.append(ret[rev_fqdn]) diff --git a/salt/runners/digicertapi.py b/salt/runners/digicertapi.py index 76db62ed61f..a7450d7b8ad 100644 --- a/salt/runners/digicertapi.py +++ b/salt/runners/digicertapi.py @@ -34,6 +34,7 @@ This API currently only supports RSA key types. Support for other key types wil if interest warrants. """ + import logging import os import re @@ -112,7 +113,7 @@ def _paginate(url, topkey, *args, **kwargs): aggregate_ret = ret["dict"][topkey] url = args[0] for p in range(2, numpages): - param_url = url + "?offset={}".format(lim * (p - 1)) + param_url = url + f"?offset={lim * (p - 1)}" next_ret = salt.utils.http.query(param_url, kwargs) aggregate_ret[topkey].extend(next_ret["dict"][topkey]) @@ -131,9 +132,9 @@ def list_domains(container_id=None): salt-run digicert.list_domains """ if container_id: - url = "{}/domain?{}".format(_base_url(), container_id) + url = f"{_base_url()}/domain?{container_id}" else: - url = "{}/domain".format(_base_url()) + url = f"{_base_url()}/domain" orgs = _paginate( url, @@ -160,9 +161,9 @@ def list_requests(status=None): salt-run digicert.list_requests pending """ if status: - url = "{}/request?status={}".format(_base_url(), status) + url = f"{_base_url()}/request?status={status}" else: - url = "{}/request".format(_base_url()) + url = f"{_base_url()}/request" reqs = _paginate( url, @@ -188,7 +189,7 @@ def list_orders(status=None): salt-run digicert.list_orders """ - url = "{}/order/certificate".format(_base_url()) + url = f"{_base_url()}/order/certificate" reqs = _paginate( url, @@ -238,7 +239,7 @@ def get_certificate( if order_id: order_cert = salt.utils.http.query( - "{}/order/certificate/{}".format(_base_url(), order_id), + f"{_base_url()}/order/certificate/{order_id}", method="GET", raise_error=False, decode=True, @@ -372,7 +373,7 @@ def list_organizations(container_id=None, include_validation=True): """ orgs = _paginate( - "{}/organization".format(_base_url()), + f"{_base_url()}/organization", "organizations", method="GET", decode=True, @@ -495,7 +496,7 @@ def order_certificate( encoded_body = salt.utils.json.dumps(body) qdata = salt.utils.http.query( - "{}/order/certificate/ssl".format(_base_url()), + f"{_base_url()}/order/certificate/ssl", method="POST", data=encoded_body, decode=True, @@ -571,7 +572,7 @@ def get_org_details(organization_id): """ qdata = salt.utils.http.query( - "{}/organization/{}".format(_base_url(), organization_id), + f"{_base_url()}/organization/{organization_id}", method="GET", decode=True, decode_type="json", @@ -623,8 +624,8 @@ def gen_csr( if "private_key" not in data: data["private_key"] = gen_key(minion_id, dns_name, password, key_len=key_len) - tmppriv = "{}/priv".format(tmpdir) - tmpcsr = "{}/csr".format(tmpdir) + tmppriv = f"{tmpdir}/priv" + tmpcsr = f"{tmpdir}/csr" with salt.utils.files.fopen(tmppriv, "w") as if_: if_.write(salt.utils.stringutils.to_str(data["private_key"])) @@ -636,9 +637,9 @@ def gen_csr( ) if ou_name: - subject = subject + "/OU={}".format(ou_name) + subject = subject + f"/OU={ou_name}" - subject = subject + "/CN={}".format(dns_name) + subject = subject + f"/CN={dns_name}" cmd = "openssl req -new -{} -key {} -out {} -subj '{}'".format( shatype, tmppriv, tmpcsr, subject @@ -689,7 +690,7 @@ def show_organization(domain): salt-run digicert.show_company example.com """ data = salt.utils.http.query( - "{}/companies/domain/{}".format(_base_url(), domain), + f"{_base_url()}/companies/domain/{domain}", status=True, decode=True, decode_type="json", @@ -712,7 +713,7 @@ def show_csrs(): salt-run digicert.show_csrs """ data = salt.utils.http.query( - "{}/certificaterequests".format(_base_url()), + f"{_base_url()}/certificaterequests", status=True, decode=True, decode_type="json", diff --git a/salt/runners/drac.py b/salt/runners/drac.py index f5e9d39ed7d..0a377c6d808 100644 --- a/salt/runners/drac.py +++ b/salt/runners/drac.py @@ -12,7 +12,6 @@ configuration file. """ - import logging try: @@ -58,7 +57,7 @@ def __connect(hostname, timeout=20, username=None, password=None): password = drac_cred.get("password", None) client = paramiko.SSHClient() - client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) + client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # nosec try: client.connect(hostname, username=username, password=password, timeout=timeout) diff --git a/salt/runners/f5.py b/salt/runners/f5.py index bac50c00cd9..13f33f31a1d 100644 --- a/salt/runners/f5.py +++ b/salt/runners/f5.py @@ -53,7 +53,7 @@ class F5Mgmt: wsdls=["LocalLB.VirtualServer", "LocalLB.Pool"], ) except Exception: # pylint: disable=broad-except - raise Exception("Unable to connect to {}".format(self.lb)) + raise Exception(f"Unable to connect to {self.lb}") return True @@ -123,9 +123,7 @@ class F5Mgmt: profiles=[vs_profile_seq], ) except Exception as e: # pylint: disable=broad-except - raise Exception( - "Unable to create `{}` virtual server\n\n{}".format(name, e) - ) + raise Exception(f"Unable to create `{name}` virtual server\n\n{e}") return True def create_pool(self, name, method="ROUND_ROBIN"): @@ -144,7 +142,7 @@ class F5Mgmt: pool_names=[name], lb_methods=[supported_method], members=[[]] ) except Exception as e: # pylint: disable=broad-except - raise Exception("Unable to create `{}` pool\n\n{}".format(name, e)) + raise Exception(f"Unable to create `{name}` pool\n\n{e}") else: raise Exception("Unsupported method") return True @@ -154,7 +152,7 @@ class F5Mgmt: Add a node to a pool """ if not self.check_pool(pool_name): - raise CommandExecutionError("{} pool does not exists".format(pool_name)) + raise CommandExecutionError(f"{pool_name} pool does not exists") members_seq = self.bigIP.LocalLB.Pool.typefactory.create( "Common.IPPortDefinitionSequence" @@ -173,9 +171,7 @@ class F5Mgmt: pool_names=[pool_name], members=[members_seq] ) except Exception as e: # pylint: disable=broad-except - raise Exception( - "Unable to add `{}` to `{}`\n\n{}".format(name, pool_name, e) - ) + raise Exception(f"Unable to add `{name}` to `{pool_name}`\n\n{e}") return True def check_pool(self, name): @@ -229,7 +225,7 @@ def create_vs(lb, name, ip, port, protocol, profile, pool_name): if __opts__["load_balancers"].get(lb, None): (username, password) = list(__opts__["load_balancers"][lb].values()) else: - raise Exception("Unable to find `{}` load balancer".format(lb)) + raise Exception(f"Unable to find `{lb}` load balancer") F5 = F5Mgmt(lb, username, password) F5.create_vs(name, ip, port, protocol, profile, pool_name) @@ -250,7 +246,7 @@ def create_pool(lb, name, method="ROUND_ROBIN"): if __opts__["load_balancers"].get(lb, None): (username, password) = list(__opts__["load_balancers"][lb].values()) else: - raise Exception("Unable to find `{}` load balancer".format(lb)) + raise Exception(f"Unable to find `{lb}` load balancer") F5 = F5Mgmt(lb, username, password) F5.create_pool(name, method) return True @@ -269,7 +265,7 @@ def add_pool_member(lb, name, port, pool_name): if __opts__["load_balancers"].get(lb, None): (username, password) = list(__opts__["load_balancers"][lb].values()) else: - raise Exception("Unable to find `{}` load balancer".format(lb)) + raise Exception(f"Unable to find `{lb}` load balancer") F5 = F5Mgmt(lb, username, password) F5.add_pool_member(name, port, pool_name) return True @@ -288,7 +284,7 @@ def check_pool(lb, name): if __opts__["load_balancers"].get(lb, None): (username, password) = list(__opts__["load_balancers"][lb].values()) else: - raise Exception("Unable to find `{}` load balancer".format(lb)) + raise Exception(f"Unable to find `{lb}` load balancer") F5 = F5Mgmt(lb, username, password) return F5.check_pool(name) @@ -306,7 +302,7 @@ def check_virtualserver(lb, name): if __opts__["load_balancers"].get(lb, None): (username, password) = list(__opts__["load_balancers"][lb].values()) else: - raise Exception("Unable to find `{}` load balancer".format(lb)) + raise Exception(f"Unable to find `{lb}` load balancer") F5 = F5Mgmt(lb, username, password) return F5.check_virtualserver(name) @@ -324,6 +320,6 @@ def check_member_pool(lb, member, pool_name): if __opts__["load_balancers"].get(lb, None): (username, password) = list(__opts__["load_balancers"][lb].values()) else: - raise Exception("Unable to find `{}` load balancer".format(lb)) + raise Exception(f"Unable to find `{lb}` load balancer") F5 = F5Mgmt(lb, username, password) return F5.check_member_pool(member, pool_name) diff --git a/salt/runners/jobs.py b/salt/runners/jobs.py index 1d958b87a9b..f1ff0f8b492 100644 --- a/salt/runners/jobs.py +++ b/salt/runners/jobs.py @@ -70,7 +70,7 @@ def active(display_progress=False): for minion, data in active_.items(): if display_progress: __jid_event__.fire_event( - {"message": "Received reply from minion {}".format(minion)}, "progress" + {"message": f"Received reply from minion {minion}"}, "progress" ) if not isinstance(data, list): continue @@ -88,7 +88,7 @@ def active(display_progress=False): returner = _get_returner( (__opts__["ext_job_cache"], __opts__["master_job_cache"]) ) - data = mminion.returners["{}.get_jid".format(returner)](jid) + data = mminion.returners[f"{returner}.get_jid"](jid) if data: for minion in data: if minion not in ret[jid]["Returned"]: @@ -199,12 +199,12 @@ def list_job(jid, ext_source=None, display_progress=False): ) if display_progress: __jid_event__.fire_event( - {"message": "Querying returner: {}".format(returner)}, "progress" + {"message": f"Querying returner: {returner}"}, "progress" ) - job = mminion.returners["{}.get_load".format(returner)](jid) + job = mminion.returners[f"{returner}.get_load"](jid) ret.update(_format_jid_instance(jid, job)) - ret["Result"] = mminion.returners["{}.get_jid".format(returner)](jid) + ret["Result"] = mminion.returners[f"{returner}.get_jid"](jid) fstr = "{}.get_endtime".format(__opts__["master_job_cache"]) if __opts__.get("job_cache_store_endtime") and fstr in mminion.returners: @@ -306,11 +306,11 @@ def list_jobs( ) if display_progress: __jid_event__.fire_event( - {"message": "Querying returner {} for jobs.".format(returner)}, "progress" + {"message": f"Querying returner {returner} for jobs."}, "progress" ) mminion = salt.minion.MasterMinion(__opts__) - ret = mminion.returners["{}.get_jids".format(returner)]() + ret = mminion.returners[f"{returner}.get_jids"]() mret = {} for item in ret: @@ -401,15 +401,13 @@ def list_jobs_filter( ) if display_progress: __jid_event__.fire_event( - {"message": "Querying returner {} for jobs.".format(returner)}, "progress" + {"message": f"Querying returner {returner} for jobs."}, "progress" ) mminion = salt.minion.MasterMinion(__opts__) - fun = "{}.get_jids_filter".format(returner) + fun = f"{returner}.get_jids_filter" if fun not in mminion.returners: - raise NotImplementedError( - "'{}' returner function not implemented yet.".format(fun) - ) + raise NotImplementedError(f"'{fun}' returner function not implemented yet.") ret = mminion.returners[fun](count, filter_find_job) if outputter: @@ -436,7 +434,7 @@ def print_job(jid, ext_source=None): mminion = salt.minion.MasterMinion(__opts__) try: - job = mminion.returners["{}.get_load".format(returner)](jid) + job = mminion.returners[f"{returner}.get_load"](jid) ret[jid] = _format_jid_instance(jid, job) except TypeError: ret[jid]["Result"] = ( @@ -444,7 +442,7 @@ def print_job(jid, ext_source=None): "retrieved. Check master log for details.".format(returner) ) return ret - ret[jid]["Result"] = mminion.returners["{}.get_jid".format(returner)](jid) + ret[jid]["Result"] = mminion.returners[f"{returner}.get_jid"](jid) fstr = "{}.get_endtime".format(__opts__["master_job_cache"]) if __opts__.get("job_cache_store_endtime") and fstr in mminion.returners: @@ -598,7 +596,5 @@ def _walk_through(job_dir, display_progress=False): job = salt.payload.load(rfh) jid = job["jid"] if display_progress: - __jid_event__.fire_event( - {"message": "Found JID {}".format(jid)}, "progress" - ) + __jid_event__.fire_event({"message": f"Found JID {jid}"}, "progress") yield jid, job, t_path, final diff --git a/salt/runners/launchd.py b/salt/runners/launchd.py index ce9be4e3a9c..cbbd22ae6ec 100644 --- a/salt/runners/launchd.py +++ b/salt/runners/launchd.py @@ -48,7 +48,7 @@ def write_launchd_plist(program): supported_programs = ["salt-master", "salt-minion"] if program not in supported_programs: - sys.stderr.write("Supported programs: '{}'\n".format(supported_programs)) + sys.stderr.write(f"Supported programs: '{supported_programs}'\n") sys.exit(-1) return plist_sample_text.format( diff --git a/salt/runners/lxc.py b/salt/runners/lxc.py index 0ded584f427..c12826f4162 100644 --- a/salt/runners/lxc.py +++ b/salt/runners/lxc.py @@ -4,7 +4,6 @@ Control Linux Containers via Salt :depends: lxc execution module """ - import copy import logging import os @@ -41,7 +40,7 @@ def _do(name, fun, path=None): with salt.client.get_local_client(__opts__["conf_file"]) as client: cmd_ret = client.cmd_iter( - host, "lxc.{}".format(fun), [name], kwarg={"path": path}, timeout=60 + host, f"lxc.{fun}", [name], kwarg={"path": path}, timeout=60 ) data = next(cmd_ret) data = data.get(host, {}).get("ret", None) @@ -72,7 +71,7 @@ def _do_names(names, fun, path=None): cmds.append( client.cmd_iter( host, - "lxc.{}".format(fun), + f"lxc.{fun}", [name], kwarg={"path": path}, timeout=60, @@ -248,7 +247,7 @@ def init(names, host=None, saltcloud_mode=False, quiet=False, **kwargs): except (TypeError, KeyError): pass if not alive: - ret["comment"] = "Host {} is not reachable".format(host) + ret["comment"] = f"Host {host} is not reachable" ret["result"] = False return ret @@ -264,7 +263,7 @@ def init(names, host=None, saltcloud_mode=False, quiet=False, **kwargs): host, ) if host not in data: - ret["comment"] = "Host '{}' was not found".format(host) + ret["comment"] = f"Host '{host}' was not found" ret["result"] = False return ret @@ -391,7 +390,7 @@ def init(names, host=None, saltcloud_mode=False, quiet=False, **kwargs): time.sleep(1) if ping: return "OK" - raise Exception("Unresponsive {}".format(mid_)) + raise Exception(f"Unresponsive {mid_}") ping = salt.utils.cloud.wait_for_fun(testping, timeout=21, mid=mid) if ping != "OK": diff --git a/salt/runners/manage.py b/salt/runners/manage.py index b15573ed168..43f76e1d529 100644 --- a/salt/runners/manage.py +++ b/salt/runners/manage.py @@ -3,7 +3,6 @@ General management functions for salt, tools like seeing what hosts are up and what hosts are down """ - import logging import operator import os @@ -134,7 +133,7 @@ def key_regen(): path = os.path.join(root, fn_) try: os.remove(path) - except os.error: + except OSError: pass msg = ( "The minion and master keys have been deleted. Restart the Salt\n" @@ -540,10 +539,10 @@ def safe_accept(target, tgt_type="glob"): elif minion not in pending: failures[minion] = f"Minion key {minion} not found by salt-key" 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/match.py b/salt/runners/match.py index 0133d3a2343..1dea4186560 100644 --- a/salt/runners/match.py +++ b/salt/runners/match.py @@ -3,6 +3,7 @@ Run matchers from the master context. .. versionadded:: 3007.0 """ + import logging import salt.utils.minions diff --git a/salt/runners/mattermost.py b/salt/runners/mattermost.py index 40309f62160..828ff857939 100644 --- a/salt/runners/mattermost.py +++ b/salt/runners/mattermost.py @@ -14,7 +14,6 @@ Module for sending messages to Mattermost api_url: https://example.com """ - import logging import salt.utils.json @@ -130,7 +129,7 @@ def post_message(message, channel=None, username=None, api_url=None, hook=None): log.debug("Parameters: %s", parameters) data = salt.utils.json.dumps(parameters) result = salt.utils.mattermost.query( - api_url=api_url, hook=hook, data="payload={}".format(data) + api_url=api_url, hook=hook, data=f"payload={data}" ) if result: @@ -168,7 +167,7 @@ def post_event(event, channel=None, username=None, api_url=None, hook=None): log.debug("Event data: %s", event["data"]) message = "tag: {}\r\n".format(event["tag"]) for key, value in event["data"].items(): - message += "{}: {}\r\n".format(key, value) + message += f"{key}: {value}\r\n" result = post_message( message, channel=channel, username=username, api_url=api_url, hook=hook ) diff --git a/salt/runners/nacl.py b/salt/runners/nacl.py index 3c097604bad..62b89444723 100644 --- a/salt/runners/nacl.py +++ b/salt/runners/nacl.py @@ -111,7 +111,6 @@ Larger files like certificates can be encrypted with: """ - import salt.utils.nacl __virtualname__ = "nacl" diff --git a/salt/runners/net.py b/salt/runners/net.py index a7865219b62..f330c0ba924 100644 --- a/salt/runners/net.py +++ b/salt/runners/net.py @@ -347,13 +347,13 @@ def interfaces( if not title: title = "Details" if interface: - title += " for interface {}".format(interface) + title += f" for interface {interface}" else: title += " for all interfaces" if device: - title += " on device {}".format(device) + title += f" on device {device}" if ipnet: - title += " that include network {net}".format(net=str(ipnet)) + title += f" that include network {str(ipnet)}" if best: title += " - only best match returned" @@ -511,13 +511,13 @@ def findarp( title = "ARP Entries" if device: - title += " on device {device}".format(device=device) + title += f" on device {device}" if interface: - title += " on interface {interf}".format(interf=interface) + title += f" on interface {interface}" if ip: - title += " for IP {ip}".format(ip=ip) + title += f" for IP {ip}" if mac: - title += " for MAC {mac}".format(mac=mac) + title += f" for MAC {mac}" if device: all_arp = {device: all_arp.get(device)} @@ -615,11 +615,11 @@ def findmac(device=None, mac=None, interface=None, vlan=None, display=_DEFAULT_D title = "MAC Address(es)" if device: - title += " on device {device}".format(device=device) + title += f" on device {device}" if interface: - title += " on interface {interf}".format(interf=interface) + title += f" on interface {interface}" if vlan: - title += " on VLAN {vlan}".format(vlan=vlan) + title += f" on VLAN {vlan}" if device: all_mac = {device: all_mac.get(device)} @@ -752,13 +752,13 @@ def lldp( if not title: title = "LLDP Neighbors" if interface: - title += " for interface {}".format(interface) + title += f" for interface {interface}" else: title += " for all interfaces" if device: - title += " on device {}".format(device) + title += f" on device {device}" if chassis: - title += " having Chassis ID {}".format(chassis) + title += f" having Chassis ID {chassis}" if device: all_lldp = {device: all_lldp.get(device)} diff --git a/salt/runners/network.py b/salt/runners/network.py index 1a56da20f17..2bf46e80a98 100644 --- a/salt/runners/network.py +++ b/salt/runners/network.py @@ -2,7 +2,6 @@ Network tools to run from the Master """ - import logging import socket @@ -32,11 +31,11 @@ def wollist(maclist, bcast="255.255.255.255", destport=9): for mac in ifile: mac = salt.utils.stringutils.to_unicode(mac).strip() wol(mac, bcast, destport) - print("Waking up {}".format(mac)) + print(f"Waking up {mac}") ret.append(mac) except Exception as err: # pylint: disable=broad-except __jid_event__.fire_event( - {"error": "Failed to open the MAC file. Error: {}".format(err)}, "progress" + {"error": f"Failed to open the MAC file. Error: {err}"}, "progress" ) return [] return ret diff --git a/salt/runners/pkg.py b/salt/runners/pkg.py index 6a4a06e6109..7d36caf2998 100644 --- a/salt/runners/pkg.py +++ b/salt/runners/pkg.py @@ -4,7 +4,6 @@ Package helper functions using ``salt.modules.pkg`` .. versionadded:: 2015.8.0 """ - import salt.minion import salt.output @@ -33,7 +32,7 @@ def list_upgrades(jid, style="group", outputter="nested", ext_source=None): (__opts__["ext_job_cache"], ext_source, __opts__["master_job_cache"]) ) - data = mminion.returners["{}.get_jid".format(returner)](jid) + data = mminion.returners[f"{returner}.get_jid"](jid) pkgs = {} if style == "group": diff --git a/salt/runners/queue.py b/salt/runners/queue.py index 286ebebcbff..d91418355c3 100644 --- a/salt/runners/queue.py +++ b/salt/runners/queue.py @@ -61,7 +61,6 @@ run them. And it will do this every minute, unless there are any jobs that are still running from the last time the process_runner task was executed. """ - import salt.loader from salt.exceptions import SaltInvocationError from salt.utils.event import get_event, tagify @@ -81,9 +80,9 @@ def insert(queue, items, backend="sqlite"): salt-run queue.insert myqueue "['item1', 'item2', 'item3']" backend=sqlite """ queue_funcs = salt.loader.queues(__opts__) - cmd = "{}.insert".format(backend) + cmd = f"{backend}.insert" if cmd not in queue_funcs: - raise SaltInvocationError('Function "{}" is not available'.format(cmd)) + raise SaltInvocationError(f'Function "{cmd}" is not available') ret = queue_funcs[cmd](items=items, queue=queue) return ret @@ -101,9 +100,9 @@ def delete(queue, items, backend="sqlite"): salt-run queue.delete myqueue "['item1', 'item2', 'item3']" """ queue_funcs = salt.loader.queues(__opts__) - cmd = "{}.delete".format(backend) + cmd = f"{backend}.delete" if cmd not in queue_funcs: - raise SaltInvocationError('Function "{}" is not available'.format(cmd)) + raise SaltInvocationError(f'Function "{cmd}" is not available') ret = queue_funcs[cmd](items=items, queue=queue) return ret @@ -120,9 +119,9 @@ def list_queues(backend="sqlite"): salt-run queue.list_queues backend=sqlite """ queue_funcs = salt.loader.queues(__opts__) - cmd = "{}.list_queues".format(backend) + cmd = f"{backend}.list_queues" if cmd not in queue_funcs: - raise SaltInvocationError('Function "{}" is not available'.format(cmd)) + raise SaltInvocationError(f'Function "{cmd}" is not available') ret = queue_funcs[cmd]() return ret @@ -139,9 +138,9 @@ def list_length(queue, backend="sqlite"): salt-run queue.list_length myqueue backend=sqlite """ queue_funcs = salt.loader.queues(__opts__) - cmd = "{}.list_length".format(backend) + cmd = f"{backend}.list_length" if cmd not in queue_funcs: - raise SaltInvocationError('Function "{}" is not available'.format(cmd)) + raise SaltInvocationError(f'Function "{cmd}" is not available') ret = queue_funcs[cmd](queue=queue) return ret @@ -158,9 +157,9 @@ def list_items(queue, backend="sqlite"): salt-run queue.list_items myqueue backend=sqlite """ queue_funcs = salt.loader.queues(__opts__) - cmd = "{}.list_items".format(backend) + cmd = f"{backend}.list_items" if cmd not in queue_funcs: - raise SaltInvocationError('Function "{}" is not available'.format(cmd)) + raise SaltInvocationError(f'Function "{cmd}" is not available') ret = queue_funcs[cmd](queue=queue) return ret @@ -180,9 +179,9 @@ def pop(queue, quantity=1, backend="sqlite", is_runner=False): salt-run queue.pop myqueue all backend=sqlite """ queue_funcs = salt.loader.queues(__opts__) - cmd = "{}.pop".format(backend) + cmd = f"{backend}.pop" if cmd not in queue_funcs: - raise SaltInvocationError('Function "{}" is not available'.format(cmd)) + raise SaltInvocationError(f'Function "{cmd}" is not available') ret = queue_funcs[cmd](quantity=quantity, queue=queue, is_runner=is_runner) return ret @@ -212,7 +211,7 @@ def process_queue(queue, quantity=1, backend="sqlite", is_runner=False): queue=queue, quantity=quantity, backend=backend, is_runner=is_runner ) except SaltInvocationError as exc: - error_txt = "{}".format(exc) + error_txt = f"{exc}" __jid_event__.fire_event({"errors": error_txt}, "progress") return False diff --git a/salt/runners/salt.py b/salt/runners/salt.py index 50fac6ab4a7..3ac499ae579 100644 --- a/salt/runners/salt.py +++ b/salt/runners/salt.py @@ -102,7 +102,7 @@ def cmd(fun, *args, **kwargs): return ( functions[fun](*args, **kwargs) if fun in functions - else "'{}' is not available.".format(fun) + else f"'{fun}' is not available." ) @@ -115,7 +115,7 @@ def execute( ret="", jid="", kwarg=None, - **kwargs + **kwargs, ): """ .. versionadded:: 2017.7.0 @@ -159,7 +159,7 @@ def execute( ret=ret, jid=jid, kwarg=kwarg, - **kwargs + **kwargs, ) except SaltClientError as client_error: log.error("Error while executing %s on %s (%s)", fun, tgt, tgt_type) diff --git a/salt/runners/spacewalk.py b/salt/runners/spacewalk.py index 638e338b496..4936859b16b 100644 --- a/salt/runners/spacewalk.py +++ b/salt/runners/spacewalk.py @@ -31,7 +31,7 @@ master configuration at ``/etc/salt/master`` or ``/etc/salt/master.d/spacewalk.c import atexit import logging -import xmlrpc.client +import xmlrpc.client # nosec log = logging.getLogger(__name__) @@ -71,7 +71,7 @@ def _get_spacewalk_configuration(spacewalk_url=""): return False ret = { - "api_url": "{}://{}/rpc/api".format(protocol, spacewalk_server), + "api_url": f"{protocol}://{spacewalk_server}/rpc/api", "username": username, "password": password, } @@ -120,7 +120,7 @@ def _get_session(server): config = _get_spacewalk_configuration(server) if not config: - raise Exception("No config for '{}' found on master".format(server)) + raise Exception(f"No config for '{server}' found on master") session = _get_client_and_key( config["api_url"], config["username"], config["password"] @@ -163,7 +163,7 @@ def api(server, command, *args, **kwargs): else: arguments = args - call = "{} {}".format(command, arguments) + call = f"{command} {arguments}" try: client, key = _get_session(server) except Exception as exc: # pylint: disable=broad-except @@ -185,7 +185,7 @@ def api(server, command, *args, **kwargs): try: output = endpoint(key, *arguments) except Exception as e: # pylint: disable=broad-except - output = "API call failed: {}".format(e) + output = f"API call failed: {e}" return {call: output} @@ -360,10 +360,8 @@ def unregister(name, server_url): for system in systems_list: out = client.system.deleteSystem(key, system["id"]) if out == 1: - return {name: "Successfully unregistered from {}".format(server_url)} + return {name: f"Successfully unregistered from {server_url}"} else: - return {name: "Failed to unregister from {}".format(server_url)} + return {name: f"Failed to unregister from {server_url}"} else: - return { - name: "System does not exist in spacewalk server ({})".format(server_url) - } + return {name: f"System does not exist in spacewalk server ({server_url})"} diff --git a/salt/runners/ssh.py b/salt/runners/ssh.py index 90ac4cfc02d..6a6086d21c1 100644 --- a/salt/runners/ssh.py +++ b/salt/runners/ssh.py @@ -4,7 +4,6 @@ A Runner module interface on top of the salt-ssh Python API. This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. """ - import salt.client.ssh.client diff --git a/salt/runners/test.py b/salt/runners/test.py index 98df7fd4e11..b20e27c847c 100644 --- a/salt/runners/test.py +++ b/salt/runners/test.py @@ -116,9 +116,7 @@ def stream(): """ ret = True for i in range(1, 100): - __jid_event__.fire_event( - {"message": "Runner is {}% done".format(i)}, "progress" - ) + __jid_event__.fire_event({"message": f"Runner is {i}% done"}, "progress") time.sleep(0.1) return ret diff --git a/salt/runners/thin.py b/salt/runners/thin.py index 83698cf6eb2..346c9ce68b0 100644 --- a/salt/runners/thin.py +++ b/salt/runners/thin.py @@ -6,7 +6,6 @@ in a standalone way. This runner has tools which generate the standalone salt system for easy consumption. """ - import salt.utils.thin diff --git a/salt/runners/venafiapi.py b/salt/runners/venafiapi.py index 23118ee8f7a..e5794f906dd 100644 --- a/salt/runners/venafiapi.py +++ b/salt/runners/venafiapi.py @@ -138,9 +138,7 @@ def request( csr = csr_file.read() request = CertificateRequest(csr=csr, common_name=dns_name) except Exception as e: - raise Exception( - "Unable to open file {file}: {excp}".format(file=csr_path, excp=e) - ) + raise Exception(f"Unable to open file {csr_path}: {e}") conn.request_cert(request, zone) # TODO: add timeout parameter here @@ -160,9 +158,7 @@ def request( with salt.utils.files.fopen(pkey_path) as pkey_file: private_key = pkey_file.read() except Exception as e: - raise Exception( - "Unable to open file {file}: {excp}".format(file=pkey_path, excp=e) - ) + raise Exception(f"Unable to open file {pkey_path}: {e}") else: private_key = None diff --git a/salt/runners/virt.py b/salt/runners/virt.py index 71e665b4c50..669ded40137 100644 --- a/salt/runners/virt.py +++ b/salt/runners/virt.py @@ -2,7 +2,6 @@ Control virtual machines via Salt """ - import logging import os.path @@ -247,7 +246,7 @@ def init( if "vm_info" in data[node]: if name in data[node]["vm_info"]: __jid_event__.fire_event( - {"message": "Virtual machine {} is already deployed".format(name)}, + {"message": f"Virtual machine {name} is already deployed"}, "progress", ) return "fail" @@ -256,9 +255,7 @@ def init( host = _determine_host(data) if host not in data or not host: - __jid_event__.fire_event( - {"message": "Host {} was not found".format(host)}, "progress" - ) + __jid_event__.fire_event({"message": f"Host {host} was not found"}, "progress") return "fail" pub_key = None @@ -273,7 +270,7 @@ def init( with salt.client.get_local_client(__opts__["conf_file"]) as client: __jid_event__.fire_event( - {"message": "Creating VM {} on host {}".format(name, host)}, "progress" + {"message": f"Creating VM {name} on host {host}"}, "progress" ) try: cmd_ret = client.cmd_iter( @@ -305,7 +302,7 @@ def init( ret = next(cmd_ret) if not ret: __jid_event__.fire_event( - {"message": "VM {} was not initialized.".format(name)}, "progress" + {"message": f"VM {name} was not initialized."}, "progress" ) return "fail" for minion_id in ret: @@ -318,7 +315,7 @@ def init( return "fail" __jid_event__.fire_event( - {"message": "VM {} initialized on host {}".format(name, host)}, "progress" + {"message": f"VM {name} initialized on host {host}"}, "progress" ) return "good" @@ -340,7 +337,7 @@ def reset(name): data = vm_info(name, quiet=True) if not data: __jid_event__.fire_event( - {"message": "Failed to find VM {} to reset".format(name)}, "progress" + {"message": f"Failed to find VM {name} to reset"}, "progress" ) return "fail" host = next(iter(data.keys())) @@ -348,9 +345,7 @@ def reset(name): cmd_ret = client.cmd_iter(host, "virt.reset", [name], timeout=600) for comp in cmd_ret: ret.update(comp) - __jid_event__.fire_event( - {"message": "Reset VM {}".format(name)}, "progress" - ) + __jid_event__.fire_event({"message": f"Reset VM {name}"}, "progress") except SaltClientError as client_error: print(client_error) return ret @@ -365,20 +360,20 @@ def start(name): data = vm_info(name, quiet=True) if not data: __jid_event__.fire_event( - {"message": "Failed to find VM {} to start".format(name)}, "progress" + {"message": f"Failed to find VM {name} to start"}, "progress" ) return "fail" host = next(iter(data.keys())) if data[host][name]["state"] == "running": - print("VM {} is already running".format(name)) + print(f"VM {name} is already running") return "bad state" try: cmd_ret = client.cmd_iter(host, "virt.start", [name], timeout=600) except SaltClientError as client_error: - return "Virtual machine {} not started: {}".format(name, client_error) + return f"Virtual machine {name} not started: {client_error}" for comp in cmd_ret: ret.update(comp) - __jid_event__.fire_event({"message": "Started VM {}".format(name)}, "progress") + __jid_event__.fire_event({"message": f"Started VM {name}"}, "progress") return "good" @@ -390,11 +385,11 @@ def force_off(name): with salt.client.get_local_client(__opts__["conf_file"]) as client: data = vm_info(name, quiet=True) if not data: - print("Failed to find VM {} to destroy".format(name)) + print(f"Failed to find VM {name} to destroy") return "fail" host = next(iter(data.keys())) if data[host][name]["state"] == "shutdown": - print("VM {} is already shutdown".format(name)) + print(f"VM {name} is already shutdown") return "bad state" try: cmd_ret = client.cmd_iter(host, "virt.stop", [name], timeout=600) @@ -404,9 +399,7 @@ def force_off(name): ) for comp in cmd_ret: ret.update(comp) - __jid_event__.fire_event( - {"message": "Powered off VM {}".format(name)}, "progress" - ) + __jid_event__.fire_event({"message": f"Powered off VM {name}"}, "progress") return "good" @@ -419,7 +412,7 @@ def purge(name, delete_key=True): data = vm_info(name, quiet=True) if not data: __jid_event__.fire_event( - {"error": "Failed to find VM {} to purge".format(name)}, "progress" + {"error": f"Failed to find VM {name} to purge"}, "progress" ) return "fail" host = next(iter(data.keys())) @@ -437,7 +430,7 @@ def purge(name, delete_key=True): log.debug("Deleting key %s", name) with salt.key.Key(__opts__) as skey: skey.delete_key(name) - __jid_event__.fire_event({"message": "Purged VM {}".format(name)}, "progress") + __jid_event__.fire_event({"message": f"Purged VM {name}"}, "progress") return "good" @@ -451,13 +444,13 @@ def pause(name): data = vm_info(name, quiet=True) if not data: __jid_event__.fire_event( - {"error": "Failed to find VM {} to pause".format(name)}, "progress" + {"error": f"Failed to find VM {name} to pause"}, "progress" ) return "fail" host = next(iter(data.keys())) if data[host][name]["state"] == "paused": __jid_event__.fire_event( - {"error": "VM {} is already paused".format(name)}, "progress" + {"error": f"VM {name} is already paused"}, "progress" ) return "bad state" try: @@ -468,7 +461,7 @@ def pause(name): ) for comp in cmd_ret: ret.update(comp) - __jid_event__.fire_event({"message": "Paused VM {}".format(name)}, "progress") + __jid_event__.fire_event({"message": f"Paused VM {name}"}, "progress") return "good" @@ -481,14 +474,12 @@ def resume(name): data = vm_info(name, quiet=True) if not data: __jid_event__.fire_event( - {"error": "Failed to find VM {} to pause".format(name)}, "progress" + {"error": f"Failed to find VM {name} to pause"}, "progress" ) return "not found" host = next(iter(data.keys())) if data[host][name]["state"] != "paused": - __jid_event__.fire_event( - {"error": "VM {} is not paused".format(name)}, "progress" - ) + __jid_event__.fire_event({"error": f"VM {name} is not paused"}, "progress") return "bad state" try: cmd_ret = client.cmd_iter(host, "virt.resume", [name], timeout=600) @@ -498,7 +489,7 @@ def resume(name): ) for comp in cmd_ret: ret.update(comp) - __jid_event__.fire_event({"message": "Resumed VM {}".format(name)}, "progress") + __jid_event__.fire_event({"message": f"Resumed VM {name}"}, "progress") return "good" @@ -514,14 +505,14 @@ def migrate(name, target=""): origin_host = next(iter(origin_data)) except StopIteration: __jid_event__.fire_event( - {"error": "Named VM {} was not found to migrate".format(name)}, + {"error": f"Named VM {name} was not found to migrate"}, "progress", ) return "" disks = origin_data[origin_host][name]["disks"] if not origin_data: __jid_event__.fire_event( - {"error": "Named VM {} was not found to migrate".format(name)}, + {"error": f"Named VM {name} was not found to migrate"}, "progress", ) return "" @@ -529,7 +520,7 @@ def migrate(name, target=""): target = _determine_host(data, origin_host) if target not in data: __jid_event__.fire_event( - {"error": "Target host {} not found".format(origin_data)}, "progress" + {"error": f"Target host {origin_data} not found"}, "progress" ) return "" try: diff --git a/salt/runners/vistara.py b/salt/runners/vistara.py index ea2d708e354..bd594764919 100644 --- a/salt/runners/vistara.py +++ b/salt/runners/vistara.py @@ -94,7 +94,7 @@ def delete_device(name, safety_on=True): if not access_token: return "Vistara access token not available" - query_string = "dnsName:{}".format(name) + query_string = f"dnsName:{name}" devices = _search_devices(query_string, config["client_id"], access_token) @@ -123,7 +123,7 @@ def delete_device(name, safety_on=True): def _search_devices(query_string, client_id, access_token): - authstring = "Bearer {}".format(access_token) + authstring = f"Bearer {access_token}" headers = { "Authorization": authstring, @@ -134,7 +134,7 @@ def _search_devices(query_string, client_id, access_token): params = {"queryString": query_string} method = "GET" - url = "https://api.vistara.io/api/v2/tenants/{}/devices/search".format(client_id) + url = f"https://api.vistara.io/api/v2/tenants/{client_id}/devices/search" resp = salt.utils.http.query( url=url, method=method, header_dict=headers, params=params, opts=__opts__ @@ -152,7 +152,7 @@ def _search_devices(query_string, client_id, access_token): def _delete_resource(device_id, client_id, access_token): - authstring = "Bearer {}".format(access_token) + authstring = f"Bearer {access_token}" headers = { "Authorization": authstring, diff --git a/salt/runners/winrepo.py b/salt/runners/winrepo.py index 9e31040884c..856115d6642 100644 --- a/salt/runners/winrepo.py +++ b/salt/runners/winrepo.py @@ -241,7 +241,7 @@ def update_git_repos(opts=None, clean=False, masterless=False): winrepo.clear_old_remotes() winrepo.checkout() except Exception as exc: # pylint: disable=broad-except - msg = "Failed to update winrepo_remotes: {}".format(exc) + msg = f"Failed to update winrepo_remotes: {exc}" log.error(msg, exc_info_on_loglevel=logging.DEBUG) return msg ret.update(winrepo.winrepo_dirs) diff --git a/salt/scripts.py b/salt/scripts.py index cc960f07854..f322490f659 100644 --- a/salt/scripts.py +++ b/salt/scripts.py @@ -1,6 +1,7 @@ """ This module contains the function calls to execute command line scripts """ + import contextlib import functools import logging @@ -18,9 +19,6 @@ from salt.exceptions import SaltClientError, SaltReqTimeoutError, SaltSystemExit log = logging.getLogger(__name__) -if sys.version_info < (3,): - raise SystemExit(salt.defaults.exitcodes.EX_GENERIC) - def _handle_signals(client, signum, sigframe): try: diff --git a/salt/sdb/cache.py b/salt/sdb/cache.py index 837fcba8ff1..96503b3bbc3 100644 --- a/salt/sdb/cache.py +++ b/salt/sdb/cache.py @@ -44,7 +44,6 @@ it must be specified in the URI: master_ip: sdb://mastercloudcache/public_ips?bank=cloud/active/ec2/my-ec2-conf/saltmaster """ - import salt.cache __func_alias__ = {"set_": "set"} diff --git a/salt/sdb/couchdb.py b/salt/sdb/couchdb.py index 978385f9788..5e7012798a1 100644 --- a/salt/sdb/couchdb.py +++ b/salt/sdb/couchdb.py @@ -35,7 +35,6 @@ Additional contributions to build true map-reduce functionality into this module would be welcome. """ - # Import Python libraries import logging from uuid import uuid4 diff --git a/salt/sdb/etcd_db.py b/salt/sdb/etcd_db.py index bf31fc74eb3..aa2858307c7 100644 --- a/salt/sdb/etcd_db.py +++ b/salt/sdb/etcd_db.py @@ -39,7 +39,6 @@ defaults to true, meaning you will use v2 unless you specify otherwise. """ - import logging try: diff --git a/salt/sdb/rest.py b/salt/sdb/rest.py index f436fc5802b..dfcb980331b 100644 --- a/salt/sdb/rest.py +++ b/salt/sdb/rest.py @@ -64,7 +64,6 @@ For instance: user: myuser """ - import logging import salt.loader diff --git a/salt/sdb/sqlite3.py b/salt/sdb/sqlite3.py index 28419060789..3aba762fe78 100644 --- a/salt/sdb/sqlite3.py +++ b/salt/sdb/sqlite3.py @@ -106,8 +106,8 @@ def _connect(profile): for sql in stmts: cur.execute(sql) elif profile.get("create_table", True): - cur.execute("CREATE TABLE {} (key text, value blob)".format(table)) - cur.execute("CREATE UNIQUE INDEX {} ON {} (key)".format(idx, table)) + cur.execute(f"CREATE TABLE {table} (key text, value blob)") + cur.execute(f"CREATE UNIQUE INDEX {idx} ON {table} (key)") except sqlite3.OperationalError: pass @@ -124,7 +124,7 @@ def set_(key, value, profile=None): value = memoryview(salt.utils.msgpack.packb(value)) q = profile.get( "set_query", - "INSERT OR REPLACE INTO {} VALUES (:key, :value)".format(table), + f"INSERT OR REPLACE INTO {table} VALUES (:key, :value)", ) conn.execute(q, {"key": key, "value": value}) conn.commit() @@ -138,7 +138,7 @@ def get(key, profile=None): if not profile: return None _, cur, table = _connect(profile) - q = profile.get("get_query", "SELECT value FROM {} WHERE key=:key".format(table)) + q = profile.get("get_query", f"SELECT value FROM {table} WHERE key=:key") res = cur.execute(q, {"key": key}) res = res.fetchone() if not res: diff --git a/salt/sdb/tism.py b/salt/sdb/tism.py index 08b05b08b4a..50c72b85317 100644 --- a/salt/sdb/tism.py +++ b/salt/sdb/tism.py @@ -27,7 +27,6 @@ configuration. token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZG1pbiI6MSwiZXhwIjoxNTg1MTExNDYwLCJqdGkiOiI3NnA5cWNiMWdtdmw4Iiwia2V5cyI6WyJBTEwiXX0.RtAhG6Uorf5xnSf4Ya_GwJnoHkCsql4r1_hiOeDSLzo """ - import logging import salt.utils.http as http diff --git a/salt/sdb/vault.py b/salt/sdb/vault.py index 907714942ff..ba2fbb002f8 100644 --- a/salt/sdb/vault.py +++ b/salt/sdb/vault.py @@ -52,7 +52,6 @@ patch .. versionadded:: 3007.0 """ - import logging import salt.exceptions diff --git a/salt/sdb/yaml.py b/salt/sdb/yaml.py index 1411e6c2899..e899382eff5 100644 --- a/salt/sdb/yaml.py +++ b/salt/sdb/yaml.py @@ -41,7 +41,6 @@ embedded GPG-encrypted data using the :py:mod:`GPG renderer `. """ - import logging import salt.exceptions diff --git a/salt/serializers/__init__.py b/salt/serializers/__init__.py index 2d0b5dc10db..afa7ff49cb3 100644 --- a/salt/serializers/__init__.py +++ b/salt/serializers/__init__.py @@ -14,7 +14,6 @@ """ - from salt.exceptions import SaltException, SaltRenderError diff --git a/salt/serializers/configparser.py b/salt/serializers/configparser.py index cb9c820758c..96fdbcde282 100644 --- a/salt/serializers/configparser.py +++ b/salt/serializers/configparser.py @@ -54,7 +54,7 @@ def serialize(obj, **options): try: if not isinstance(obj, dict): raise TypeError( - "configparser can only serialize dictionaries, not {}".format(type(obj)) + f"configparser can only serialize dictionaries, not {type(obj)}" ) fp = options.pop("fp", None) cp = configparser.ConfigParser(**options) diff --git a/salt/serializers/json.py b/salt/serializers/json.py index 8ee1085452c..cea79944b42 100644 --- a/salt/serializers/json.py +++ b/salt/serializers/json.py @@ -7,7 +7,6 @@ It's just a wrapper around json (or simplejson if available). """ - import salt.utils.json from salt.serializers import DeserializationError, SerializationError diff --git a/salt/serializers/msgpack.py b/salt/serializers/msgpack.py index 93a3fddeb3a..ac9eebb1e49 100644 --- a/salt/serializers/msgpack.py +++ b/salt/serializers/msgpack.py @@ -5,7 +5,6 @@ Implements MsgPack serializer. """ - import copy import logging diff --git a/salt/serializers/plist.py b/salt/serializers/plist.py index a833b4e7897..d205d68ea1d 100644 --- a/salt/serializers/plist.py +++ b/salt/serializers/plist.py @@ -7,6 +7,7 @@ Wrapper around plistlib. """ + import logging import plistlib diff --git a/salt/serializers/yaml.py b/salt/serializers/yaml.py index e8a5e85e4b5..bc6391618df 100644 --- a/salt/serializers/yaml.py +++ b/salt/serializers/yaml.py @@ -8,7 +8,6 @@ It also use C bindings if they are available. """ - import datetime import logging diff --git a/salt/serializers/yamlex.py b/salt/serializers/yamlex.py index d67ff7a60b2..c1f68f1c07a 100644 --- a/salt/serializers/yamlex.py +++ b/salt/serializers/yamlex.py @@ -98,6 +98,7 @@ Document is defacto an aggregate mapping. """ + # pylint: disable=invalid-name,no-member,missing-docstring,no-self-use # pylint: disable=too-few-public-methods,too-many-public-methods @@ -208,7 +209,7 @@ class Loader(BaseLoader): # pylint: disable=W0232 raise ConstructorError( None, None, - "expected a mapping node, but found {}".format(node.id), + f"expected a mapping node, but found {node.id}", node.start_mark, ) diff --git a/salt/spm/__init__.py b/salt/spm/__init__.py index fa8f366702c..34649f6d087 100644 --- a/salt/spm/__init__.py +++ b/salt/spm/__init__.py @@ -136,7 +136,7 @@ class SPMClient: elif command == "close": self._close() else: - raise SPMInvocationError("Invalid command '{}'".format(command)) + raise SPMInvocationError(f"Invalid command '{command}'") except SPMException as exc: self.ui.error(str(exc)) @@ -144,7 +144,7 @@ class SPMClient: try: return getattr(getattr(self.pkgdb, self.db_prov), func)(*args, **kwargs) except AttributeError: - return self.pkgdb["{}.{}".format(self.db_prov, func)](*args, **kwargs) + return self.pkgdb[f"{self.db_prov}.{func}"](*args, **kwargs) def _pkgfiles_fun(self, func, *args, **kwargs): try: @@ -152,7 +152,7 @@ class SPMClient: *args, **kwargs ) except AttributeError: - return self.pkgfiles["{}.{}".format(self.files_prov, func)](*args, **kwargs) + return self.pkgfiles[f"{self.files_prov}.{func}"](*args, **kwargs) def _list(self, args): """ @@ -167,7 +167,7 @@ class SPMClient: elif command == "repos": self._repo_list(args) else: - raise SPMInvocationError("Invalid list command '{}'".format(command)) + raise SPMInvocationError(f"Invalid list command '{command}'") def _local(self, args): """ @@ -182,7 +182,7 @@ class SPMClient: elif command == "info": self._local_info(args) else: - raise SPMInvocationError("Invalid local command '{}'".format(command)) + raise SPMInvocationError(f"Invalid local command '{command}'") def _repo(self, args): """ @@ -201,7 +201,7 @@ class SPMClient: elif command == "create": self._create_repo(args) else: - raise SPMInvocationError("Invalid repo command '{}'".format(command)) + raise SPMInvocationError(f"Invalid repo command '{command}'") def _repo_packages(self, args, search=False): """ @@ -216,7 +216,7 @@ class SPMClient: release = repo_metadata[repo]["packages"][pkg]["info"]["release"] packages.append((pkg, version, release, repo)) for pkg in sorted(packages): - self.ui.status("{}\t{}-{}\t{}".format(pkg[0], pkg[1], pkg[2], pkg[3])) + self.ui.status(f"{pkg[0]}\t{pkg[1]}-{pkg[2]}\t{pkg[3]}") return packages def _repo_list(self, args): @@ -255,7 +255,7 @@ class SPMClient: pkg_name = comps[-1] formula_tar = tarfile.open(pkg, "r:bz2") - formula_ref = formula_tar.extractfile("{}/FORMULA".format(pkg_name)) + formula_ref = formula_tar.extractfile(f"{pkg_name}/FORMULA") formula_def = salt.utils.yaml.safe_load(formula_ref) file_map[pkg_name] = pkg @@ -267,7 +267,7 @@ class SPMClient: recommended.extend(re_) formula_tar.close() else: - raise SPMInvocationError("Package file {} not found".format(pkg)) + raise SPMInvocationError(f"Package file {pkg} not found") else: to_, op_, re_ = self._check_all_deps(pkg_name=pkg) to_install.extend(to_) @@ -385,7 +385,7 @@ class SPMClient: Starting with one package, check all packages for dependencies """ if pkg_file and not os.path.exists(pkg_file): - raise SPMInvocationError("Package file {} not found".format(pkg_file)) + raise SPMInvocationError(f"Package file {pkg_file} not found") self.repo_metadata = self._get_repo_metadata() if not formula_def: @@ -396,7 +396,7 @@ class SPMClient: formula_def = self.repo_metadata[repo]["packages"][pkg_name]["info"] if not formula_def: - raise SPMInvocationError("Unable to read formula for {}".format(pkg_name)) + raise SPMInvocationError(f"Unable to read formula for {pkg_name}") # Check to see if the package is already installed pkg_info = self._pkgdb_fun("info", pkg_name, self.db_conn) @@ -439,7 +439,7 @@ class SPMClient: pkg_info = self._pkgdb_fun("info", formula_def["name"]) msg = dep_pkg if isinstance(pkg_info, dict): - msg = "{} [Installed]".format(dep_pkg) + msg = f"{dep_pkg} [Installed]" optional_install.append(msg) if recommended: @@ -448,7 +448,7 @@ class SPMClient: pkg_info = self._pkgdb_fun("info", formula_def["name"]) msg = dep_pkg if isinstance(pkg_info, dict): - msg = "{} [Installed]".format(dep_pkg) + msg = f"{dep_pkg} [Installed]" recommended_install.append(msg) if needs: @@ -457,7 +457,7 @@ class SPMClient: pkg_info = self._pkgdb_fun("info", formula_def["name"]) msg = dep_pkg if isinstance(pkg_info, dict): - msg = "{} [Installed]".format(dep_pkg) + msg = f"{dep_pkg} [Installed]" return pkgs_to_install, optional_install, recommended_install @@ -465,16 +465,14 @@ class SPMClient: """ Install one individual package """ - self.ui.status("... installing {}".format(pkg_name)) + self.ui.status(f"... installing {pkg_name}") formula_tar = tarfile.open(pkg_file, "r:bz2") - formula_ref = formula_tar.extractfile("{}/FORMULA".format(pkg_name)) + formula_ref = formula_tar.extractfile(f"{pkg_name}/FORMULA") formula_def = salt.utils.yaml.safe_load(formula_ref) for field in ("version", "release", "summary", "description"): if field not in formula_def: - raise SPMPackageError( - "Invalid package: the {} was not found".format(field) - ) + raise SPMPackageError(f"Invalid package: the {field} was not found") pkg_files = formula_tar.getmembers() @@ -542,7 +540,7 @@ class SPMClient: digest = "" else: self._verbose( - "Installing file {} to {}".format(member.name, out_path), + f"Installing file {member.name} to {out_path}", log.trace, ) file_hash = hashlib.sha1() @@ -580,7 +578,7 @@ class SPMClient: Return a list of packages which need to be installed, to resolve all dependencies """ - pkg_info = self.pkgdb["{}.info".format(self.db_prov)](formula_def["name"]) + pkg_info = self.pkgdb[f"{self.db_prov}.info"](formula_def["name"]) if not isinstance(pkg_info, dict): pkg_info = {} @@ -592,7 +590,7 @@ class SPMClient: dep = dep.strip() if not dep: continue - if self.pkgdb["{}.info".format(self.db_prov)](dep): + if self.pkgdb[f"{self.db_prov}.info"](dep): continue if dep in self.avail_pkgs: @@ -635,7 +633,7 @@ class SPMClient: if os.path.exists(self.opts["spm_repos_config"]): repo_files.append(self.opts["spm_repos_config"]) - for (dirpath, dirnames, filenames) in salt.utils.path.os_walk( + for dirpath, dirnames, filenames in salt.utils.path.os_walk( "{}.d".format(self.opts["spm_repos_config"]) ): for repo_file in filenames: @@ -753,17 +751,17 @@ class SPMClient: old_files = [] repo_metadata = {} - for (dirpath, dirnames, filenames) in salt.utils.path.os_walk(repo_path): + for dirpath, dirnames, filenames in salt.utils.path.os_walk(repo_path): for spm_file in filenames: if not spm_file.endswith(".spm"): continue - spm_path = "{}/{}".format(repo_path, spm_file) + spm_path = f"{repo_path}/{spm_file}" if not tarfile.is_tarfile(spm_path): continue comps = spm_file.split("-") spm_name = "-".join(comps[:-2]) spm_fh = tarfile.open(spm_path, "r:bz2") - formula_handle = spm_fh.extractfile("{}/FORMULA".format(spm_name)) + formula_handle = spm_fh.extractfile(f"{spm_name}/FORMULA") formula_conf = salt.utils.yaml.safe_load(formula_handle.read()) use_formula = True @@ -815,7 +813,7 @@ class SPMClient: } repo_metadata[spm_name]["filename"] = spm_file - metadata_filename = "{}/SPM-METADATA".format(repo_path) + metadata_filename = f"{repo_path}/SPM-METADATA" with salt.utils.files.fopen(metadata_filename, "w") as mfh: salt.utils.yaml.safe_dump( repo_metadata, @@ -868,7 +866,7 @@ class SPMClient: self.ui.confirm(msg) for package in packages: - self.ui.status("... removing {}".format(package)) + self.ui.status(f"... removing {package}") if not self._pkgdb_fun("db_exists", self.opts["spm_db"]): raise SPMDatabaseError( @@ -880,7 +878,7 @@ class SPMClient: # Look at local repo index pkg_info = self._pkgdb_fun("info", package, self.db_conn) if pkg_info is None: - raise SPMInvocationError("Package {} not installed".format(package)) + raise SPMInvocationError(f"Package {package} not installed") # Find files that have not changed and remove them files = self._pkgdb_fun("list_files", package, self.db_conn) @@ -894,22 +892,22 @@ class SPMClient: "hash_file", filerow[0], file_hash, self.files_conn ) if filerow[1] == digest: - self._verbose("Removing file {}".format(filerow[0]), log.trace) + self._verbose(f"Removing file {filerow[0]}", log.trace) self._pkgfiles_fun("remove_file", filerow[0], self.files_conn) else: - self._verbose("Not removing file {}".format(filerow[0]), log.trace) + self._verbose(f"Not removing file {filerow[0]}", log.trace) self._pkgdb_fun("unregister_file", filerow[0], package, self.db_conn) # Clean up directories for dir_ in sorted(dirs, reverse=True): self._pkgdb_fun("unregister_file", dir_, package, self.db_conn) try: - self._verbose("Removing directory {}".format(dir_), log.trace) + self._verbose(f"Removing directory {dir_}", log.trace) os.rmdir(dir_) except OSError: # Leave directories in place that still have files in them self._verbose( - "Cannot remove directory {}, probably not empty".format(dir_), + f"Cannot remove directory {dir_}, probably not empty", log.trace, ) @@ -933,14 +931,14 @@ class SPMClient: pkg_file = args[1] if not os.path.exists(pkg_file): - raise SPMInvocationError("Package file {} not found".format(pkg_file)) + raise SPMInvocationError(f"Package file {pkg_file} not found") comps = pkg_file.split("-") comps = "-".join(comps[:-2]).split("/") name = comps[-1] formula_tar = tarfile.open(pkg_file, "r:bz2") - formula_ref = formula_tar.extractfile("{}/FORMULA".format(name)) + formula_ref = formula_tar.extractfile(f"{name}/FORMULA") formula_def = salt.utils.yaml.safe_load(formula_ref) self.ui.status(self._get_info(formula_def)) @@ -957,7 +955,7 @@ class SPMClient: pkg_info = self._pkgdb_fun("info", package, self.db_conn) if pkg_info is None: - raise SPMPackageError("package {} not installed".format(package)) + raise SPMPackageError(f"package {package} not installed") self.ui.status(self._get_info(pkg_info)) def _get_info(self, formula_def): @@ -1007,7 +1005,7 @@ class SPMClient: pkg_file = args[1] if not os.path.exists(pkg_file): - raise SPMPackageError("Package file {} not found".format(pkg_file)) + raise SPMPackageError(f"Package file {pkg_file} not found") formula_tar = tarfile.open(pkg_file, "r:bz2") pkg_files = formula_tar.getmembers() @@ -1037,7 +1035,7 @@ class SPMClient: files = self._pkgdb_fun("list_files", package, self.db_conn) if files is None: - raise SPMPackageError("package {} not installed".format(package)) + raise SPMPackageError(f"package {package} not installed") else: for file_ in files: if self.opts["verbose"]: @@ -1057,17 +1055,15 @@ class SPMClient: comps = self.abspath.split("/") self.relpath = comps[-1] - formula_path = "{}/FORMULA".format(self.abspath) + formula_path = f"{self.abspath}/FORMULA" if not os.path.exists(formula_path): - raise SPMPackageError("Formula file {} not found".format(formula_path)) + raise SPMPackageError(f"Formula file {formula_path} not found") with salt.utils.files.fopen(formula_path) as fp_: formula_conf = salt.utils.yaml.safe_load(fp_) for field in ("name", "version", "release", "summary", "description"): if field not in formula_conf: - raise SPMPackageError( - "Invalid package: a {} must be defined".format(field) - ) + raise SPMPackageError(f"Invalid package: a {field} must be defined") out_path = "{}/{}-{}-{}.spm".format( self.opts["spm_build_dir"], @@ -1094,8 +1090,8 @@ class SPMClient: formula_tar.addfile(formula_dir) for file_ in formula_conf["files"]: for ftype in FILE_TYPES: - if file_.startswith("{}|".format(ftype)): - file_ = file_.lstrip("{}|".format(ftype)) + if file_.startswith(f"{ftype}|"): + file_ = file_.lstrip(f"{ftype}|") formula_tar.add( os.path.join(os.getcwd(), file_), os.path.join(formula_conf["name"], file_), @@ -1118,7 +1114,7 @@ class SPMClient: ) formula_tar.close() - self.ui.status("Built package {}".format(out_path)) + self.ui.status(f"Built package {out_path}") def _exclude(self, member): """ @@ -1130,7 +1126,7 @@ class SPMClient: for item in self.opts["spm_build_exclude"]: if member.name.startswith("{}/{}".format(self.formula_conf["name"], item)): return None - elif member.name.startswith("{}/{}".format(self.abspath, item)): + elif member.name.startswith(f"{self.abspath}/{item}"): return None return member @@ -1152,7 +1148,7 @@ class SPMClient: blacklist, whitelist, input_data=data, - **template_vars + **template_vars, ) diff --git a/salt/spm/pkgdb/sqlite3.py b/salt/spm/pkgdb/sqlite3.py index 48a23e0109a..c6c0fb1384f 100644 --- a/salt/spm/pkgdb/sqlite3.py +++ b/salt/spm/pkgdb/sqlite3.py @@ -4,7 +4,6 @@ This module allows SPM to use sqlite3 as the backend for SPM's package database. .. versionadded:: 2015.8.0 """ - import datetime import logging import os @@ -194,7 +193,7 @@ def register_file(name, member, path, digest="", conn=None): "INSERT INTO files VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", ( name, - "{}/{}".format(path, member.path), + f"{path}/{member.path}", member.size, member.mode, digest, diff --git a/salt/spm/pkgfiles/local.py b/salt/spm/pkgfiles/local.py index b75a1457448..2b826a5d393 100644 --- a/salt/spm/pkgfiles/local.py +++ b/salt/spm/pkgfiles/local.py @@ -4,7 +4,6 @@ This module allows SPM to use the local filesystem to install files for SPM. .. versionadded:: 2015.8.0 """ - import logging import os import os.path @@ -57,11 +56,11 @@ def check_existing(package, pkg_files, formula_def, conn=None): continue tld = formula_def.get("top_level_dir", package) - new_name = member.name.replace("{}/".format(package), "") + new_name = member.name.replace(f"{package}/", "") if not new_name.startswith(tld): continue - if member.name.startswith("{}/_".format(package)): + if member.name.startswith(f"{package}/_"): if node_type in ("master", "minion"): # Module files are distributed via extmods directory out_file = os.path.join( @@ -73,9 +72,9 @@ def check_existing(package, pkg_files, formula_def, conn=None): else: # Module files are distributed via _modules, _states, etc out_file = os.path.join(conn["formula_path"], new_name) - elif member.name == "{}/pillar.example".format(package): + elif member.name == f"{package}/pillar.example": # Pillars are automatically put in the pillar_path - new_name = "{}.sls.orig".format(package) + new_name = f"{package}.sls.orig" out_file = os.path.join(conn["pillar_path"], new_name) elif package.endswith("-conf"): # Configuration files go into /etc/salt/ @@ -109,7 +108,7 @@ def install_file(package, formula_tar, member, formula_def, conn=None): out_path = conn["formula_path"] tld = formula_def.get("top_level_dir", package) - new_name = member.name.replace("{}/".format(package), "", 1) + new_name = member.name.replace(f"{package}/", "", 1) if ( not new_name.startswith(tld) and not new_name.startswith("_") @@ -122,7 +121,7 @@ def install_file(package, formula_tar, member, formula_def, conn=None): for line in formula_def.get("files", []): tag = "" for ftype in FILE_TYPES: - if line.startswith("{}|".format(ftype)): + if line.startswith(f"{ftype}|"): tag = line.split("|", 1)[0] line = line.split("|", 1)[1] if tag and new_name == line: @@ -131,10 +130,10 @@ def install_file(package, formula_tar, member, formula_def, conn=None): elif tag in ("s", "m"): pass - if member.name.startswith("{}{}_".format(package, os.sep)): + if member.name.startswith(f"{package}{os.sep}_"): if node_type in ("master", "minion"): # Module files are distributed via extmods directory - member.name = new_name.replace("{}{}_".format(package, os.sep), "") + member.name = new_name.replace(f"{package}{os.sep}_", "") out_path = os.path.join( salt.syspaths.CACHE_DIR, node_type, @@ -142,14 +141,14 @@ def install_file(package, formula_tar, member, formula_def, conn=None): ) else: # Module files are distributed via _modules, _states, etc - member.name = new_name.replace("{}{}".format(package, os.sep), "") - elif member.name == "{}/pillar.example".format(package): + member.name = new_name.replace(f"{package}{os.sep}", "") + elif member.name == f"{package}/pillar.example": # Pillars are automatically put in the pillar_path - member.name = "{}.sls.orig".format(package) + member.name = f"{package}.sls.orig" out_path = conn["pillar_path"] elif package.endswith("-conf"): # Configuration files go into /etc/salt/ - member.name = member.name.replace("{}/".format(package), "") + member.name = member.name.replace(f"{package}/", "") out_path = salt.syspaths.CONFIG_DIR elif package.endswith("-reactor"): # Reactor files go into /srv/reactor/ diff --git a/salt/state.py b/salt/state.py index ed37dfb1034..92e6cbca385 100644 --- a/salt/state.py +++ b/salt/state.py @@ -4518,9 +4518,11 @@ class BaseHighState: " on the salt master in saltenv(s): {} ".format( env_key, inc_sls, - ", ".join(matches) - if env_key == xenv_key - else env_key, + ( + ", ".join(matches) + if env_key == xenv_key + else env_key + ), ) ) elif len(resolved_envs) > 1: @@ -4720,10 +4722,10 @@ class BaseHighState: # match SLS foobar in environment this_sls = f"SLS {sls_match} in saltenv" if this_sls in error: - errors[ - i - ] = "No matching sls found for '{}' in env '{}'".format( - sls_match, saltenv + errors[i] = ( + "No matching sls found for '{}' in env '{}'".format( + sls_match, saltenv + ) ) all_errors.extend(errors) diff --git a/salt/states/alias.py b/salt/states/alias.py index 6c2eb8959e1..48b153b5f6e 100644 --- a/salt/states/alias.py +++ b/salt/states/alias.py @@ -43,20 +43,20 @@ def present(name, target): ret = {"name": name, "changes": {}, "result": False, "comment": ""} if __salt__["aliases.has_target"](name, target): ret["result"] = True - ret["comment"] = "Alias {} already present".format(name) + ret["comment"] = f"Alias {name} already present" return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Alias {} -> {} is set to be added".format(name, target) + ret["comment"] = f"Alias {name} -> {target} is set to be added" return ret if __salt__["aliases.set_target"](name, target): ret["changes"] = {"alias": name} ret["result"] = True - ret["comment"] = "Set email alias {} -> {}".format(name, target) + ret["comment"] = f"Set email alias {name} -> {target}" return ret else: ret["result"] = False - ret["comment"] = "Failed to set alias {} -> {}".format(name, target) + ret["comment"] = f"Failed to set alias {name} -> {target}" return ret @@ -70,18 +70,18 @@ def absent(name): ret = {"name": name, "changes": {}, "result": False, "comment": ""} if not __salt__["aliases.get_target"](name): ret["result"] = True - ret["comment"] = "Alias {} already absent".format(name) + ret["comment"] = f"Alias {name} already absent" return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Alias {} is set to be removed".format(name) + ret["comment"] = f"Alias {name} is set to be removed" return ret if __salt__["aliases.rm_alias"](name): ret["changes"] = {"alias": name} ret["result"] = True - ret["comment"] = "Removed alias {}".format(name) + ret["comment"] = f"Removed alias {name}" return ret else: ret["result"] = False - ret["comment"] = "Failed to remove alias {}".format(name) + ret["comment"] = f"Failed to remove alias {name}" return ret diff --git a/salt/states/alternatives.py b/salt/states/alternatives.py index f69b5f70351..2f89516acbc 100644 --- a/salt/states/alternatives.py +++ b/salt/states/alternatives.py @@ -76,10 +76,10 @@ def install(name, link, path, priority): ) else: if __opts__["test"]: - ret[ - "comment" - ] = "Alternative will be set for {} to {} with priority {}".format( - name, path, priority + ret["comment"] = ( + "Alternative will be set for {} to {} with priority {}".format( + name, path, priority + ) ) ret["result"] = None return ret @@ -87,10 +87,10 @@ def install(name, link, path, priority): out = __salt__["alternatives.install"](name, link, path, priority) if __salt__["alternatives.check_exists"](name, path): if __salt__["alternatives.check_installed"](name, path): - ret[ - "comment" - ] = "Alternative for {} set to path {} with priority {}".format( - name, path, priority + ret["comment"] = ( + "Alternative for {} set to path {} with priority {}".format( + name, path, priority + ) ) else: ret["comment"] = ( @@ -105,7 +105,7 @@ def install(name, link, path, priority): } else: ret["result"] = False - ret["comment"] = "Alternative for {} not installed: {}".format(name, out) + ret["comment"] = f"Alternative for {name} not installed: {out}" return ret @@ -128,22 +128,22 @@ def remove(name, path): isinstalled = __salt__["alternatives.check_exists"](name, path) if isinstalled: if __opts__["test"]: - ret["comment"] = "Alternative for {} will be removed".format(name) + ret["comment"] = f"Alternative for {name} will be removed" ret["result"] = None return ret __salt__["alternatives.remove"](name, path) current = __salt__["alternatives.show_current"](name) if current: ret["result"] = True - ret[ - "comment" - ] = "Alternative for {} removed. Falling back to path {}".format( - name, current + ret["comment"] = ( + "Alternative for {} removed. Falling back to path {}".format( + name, current + ) ) ret["changes"] = {"path": current} return ret - ret["comment"] = "Alternative for {} removed".format(name) + ret["comment"] = f"Alternative for {name} removed" ret["changes"] = {} return ret @@ -156,7 +156,7 @@ def remove(name, path): return ret ret["result"] = False - ret["comment"] = "Alternative for {} doesn't exist".format(name) + ret["comment"] = f"Alternative for {name} doesn't exist" return ret @@ -178,11 +178,11 @@ def auto(name): display = __salt__["alternatives.display"](name) line = display.splitlines()[0] if line.endswith(" auto mode"): - ret["comment"] = "{} already in auto mode".format(name) + ret["comment"] = f"{name} already in auto mode" return ret if __opts__["test"]: - ret["comment"] = "{} will be put in auto mode".format(name) + ret["comment"] = f"{name} will be put in auto mode" ret["result"] = None return ret ret["changes"]["result"] = __salt__["alternatives.auto"](name) @@ -214,7 +214,7 @@ def set_(name, path): current = __salt__["alternatives.show_current"](name) if current == path: - ret["comment"] = "Alternative for {} already set to {}".format(name, path) + ret["comment"] = f"Alternative for {name} already set to {path}" return ret display = __salt__["alternatives.display"](name) @@ -234,15 +234,15 @@ def set_(name, path): __salt__["alternatives.set"](name, path) current = __salt__["alternatives.show_current"](name) if current == path: - ret["comment"] = "Alternative for {} set to path {}".format(name, current) + ret["comment"] = f"Alternative for {name} set to path {current}" ret["changes"] = {"path": current} else: - ret["comment"] = "Alternative for {} not updated".format(name) + ret["comment"] = f"Alternative for {name} not updated" return ret else: ret["result"] = False - ret["comment"] = "Alternative {} for {} doesn't exist".format(path, name) + ret["comment"] = f"Alternative {path} for {name} doesn't exist" return ret diff --git a/salt/states/apache.py b/salt/states/apache.py index 9bd7779e9fc..598b429fca0 100644 --- a/salt/states/apache.py +++ b/salt/states/apache.py @@ -84,7 +84,6 @@ it still needs keyword ``this`` with empty string (or "\b" if nicer output is re do: another thing """ - import os import salt.utils.files diff --git a/salt/states/aptpkg.py b/salt/states/aptpkg.py index 62b83f37b26..0b196e3503e 100644 --- a/salt/states/aptpkg.py +++ b/salt/states/aptpkg.py @@ -3,7 +3,6 @@ Package management operations specific to APT- and DEB-based systems ==================================================================== """ - import logging import salt.utils.data @@ -36,18 +35,18 @@ def held(name): pattern=name, ) if not state: - ret.update(comment="Package {} does not have a state".format(name)) + ret.update(comment=f"Package {name} does not have a state") elif not salt.utils.data.is_true(state.get("hold", False)): if not __opts__["test"]: result = __salt__["pkg.set_selections"](selection={"hold": [name]}) ret.update( changes=result[name], result=True, - comment="Package {} is now being held".format(name), + comment=f"Package {name} is now being held", ) else: - ret.update(result=None, comment="Package {} is set to be held".format(name)) + ret.update(result=None, comment=f"Package {name} is set to be held") else: - ret.update(result=True, comment="Package {} is already held".format(name)) + ret.update(result=True, comment=f"Package {name} is already held") return ret diff --git a/salt/states/archive.py b/salt/states/archive.py index 25ca6549dbf..03dd9bdb441 100644 --- a/salt/states/archive.py +++ b/salt/states/archive.py @@ -826,9 +826,9 @@ def extracted( kwargs = salt.utils.args.clean_kwargs(**kwargs) if skip_files_list_verify and skip_verify: - ret[ - "comment" - ] = 'Only one of "skip_files_list_verify" and "skip_verify" can be set to True' + ret["comment"] = ( + 'Only one of "skip_files_list_verify" and "skip_verify" can be set to True' + ) return ret if "keep_source" in kwargs and "keep" in kwargs: @@ -890,9 +890,9 @@ def extracted( # from making this state blow up with a traceback. not_rel = True if not_rel: - ret[ - "comment" - ] = f"Value for 'enforce_ownership_on' must be within {name}" + ret["comment"] = ( + f"Value for 'enforce_ownership_on' must be within {name}" + ) return ret if if_missing is not None and os.path.exists(if_missing): @@ -902,9 +902,9 @@ def extracted( if user or group: if salt.utils.platform.is_windows(): - ret[ - "comment" - ] = "User/group ownership cannot be enforced on Windows minions" + ret["comment"] = ( + "User/group ownership cannot be enforced on Windows minions" + ) return ret if user: @@ -939,9 +939,9 @@ def extracted( try: __salt__["gpg.verify"] except KeyError: - ret[ - "comment" - ] = "Cannot verify signatures because the gpg module was not loaded" + ret["comment"] = ( + "Cannot verify signatures because the gpg module was not loaded" + ) return ret try: @@ -1061,9 +1061,9 @@ def extracted( ) else: if password: - ret[ - "comment" - ] = "The 'password' argument is only supported for zip archives" + ret["comment"] = ( + "The 'password' argument is only supported for zip archives" + ) return ret if archive_format == "rar": @@ -1091,9 +1091,9 @@ def extracted( # string-ified integer. trim_output = int(trim_output) except TypeError: - ret[ - "comment" - ] = "Invalid value for trim_output, must be True/False or an integer" + ret["comment"] = ( + "Invalid value for trim_output, must be True/False or an integer" + ) return ret if source_hash: @@ -1173,10 +1173,10 @@ def extracted( # salt/states/file.py from being processed through the loader. If # that is the case, we have much more important problems as _all_ # file states would be unavailable. - ret[ - "comment" - ] = "Unable to cache {}, file.cached state not available".format( - salt.utils.url.redact_http_basic_auth(source_match) + ret["comment"] = ( + "Unable to cache {}, file.cached state not available".format( + salt.utils.url.redact_http_basic_auth(source_match) + ) ) return ret @@ -1565,7 +1565,7 @@ def extracted( if options is None: try: with closing(tarfile.open(cached, "r")) as tar: - tar.extractall(salt.utils.stringutils.to_str(name)) + tar.extractall(salt.utils.stringutils.to_str(name)) # nosec files = tar.getnames() if trim_output: files = files[:trim_output] diff --git a/salt/states/artifactory.py b/salt/states/artifactory.py index 2395fe7d6c4..23fa8d8dd59 100644 --- a/salt/states/artifactory.py +++ b/salt/states/artifactory.py @@ -3,7 +3,6 @@ This state downloads artifacts from artifactory. """ - import logging log = logging.getLogger(__name__) diff --git a/salt/states/at.py b/salt/states/at.py index 59a44555bf4..5d211f7f7d3 100644 --- a/salt/states/at.py +++ b/salt/states/at.py @@ -209,10 +209,10 @@ def absent(name, jobid=None, **kwargs): return ret else: ret["result"] = False - ret[ - "comment" - ] = "more than one job was return for job with id {jobid}".format( - jobid=jobid + ret["comment"] = ( + "more than one job was return for job with id {jobid}".format( + jobid=jobid + ) ) return ret diff --git a/salt/states/aws_sqs.py b/salt/states/aws_sqs.py index 42b8a5eb996..68370410ef2 100644 --- a/salt/states/aws_sqs.py +++ b/salt/states/aws_sqs.py @@ -48,7 +48,7 @@ def exists(name, region, user=None, opts=False): if not does_exist: if __opts__["test"]: ret["result"] = None - ret["comment"] = "AWS SQS queue {} is set to be created".format(name) + ret["comment"] = f"AWS SQS queue {name} is set to be created" return ret created = __salt__["aws_sqs.create_queue"](name, region, opts, user) if created["retcode"] == 0: @@ -58,7 +58,7 @@ def exists(name, region, user=None, opts=False): ret["comment"] = created["stderr"] else: - ret["comment"] = "{} exists in {}".format(name, region) + ret["comment"] = f"{name} exists in {region}" return ret @@ -86,7 +86,7 @@ def absent(name, region, user=None, opts=False): if does_exist: if __opts__["test"]: ret["result"] = None - ret["comment"] = "AWS SQS queue {} is set to be removed".format(name) + ret["comment"] = f"AWS SQS queue {name} is set to be removed" return ret removed = __salt__["aws_sqs.delete_queue"](name, region, opts, user) if removed["retcode"] == 0: @@ -95,6 +95,6 @@ def absent(name, region, user=None, opts=False): ret["result"] = False ret["comment"] = removed["stderr"] else: - ret["comment"] = "{} does not exist in {}".format(name, region) + ret["comment"] = f"{name} does not exist in {region}" return ret diff --git a/salt/states/beacon.py b/salt/states/beacon.py index 088c8d308ec..b83717ae2bd 100644 --- a/salt/states/beacon.py +++ b/salt/states/beacon.py @@ -104,7 +104,7 @@ def present(name, save=False, **kwargs): if name in current_beacons: if beacon_data == current_beacons[name]: - ret["comment"].append("Job {} in correct state".format(name)) + ret["comment"].append(f"Job {name} in correct state") else: if __opts__.get("test"): kwargs["test"] = True @@ -119,7 +119,7 @@ def present(name, save=False, **kwargs): return ret else: if "changes" in result: - ret["comment"].append("Modifying {} in beacons".format(name)) + ret["comment"].append(f"Modifying {name} in beacons") ret["changes"] = result["changes"] else: ret["comment"].append(result["comment"]) @@ -136,14 +136,14 @@ def present(name, save=False, **kwargs): ret["comment"] = result["comment"] return ret else: - ret["comment"].append("Adding {} to beacons".format(name)) + ret["comment"].append(f"Adding {name} to beacons") if save: if __opts__.get("test"): - ret["comment"].append("Beacon {} would be saved".format(name)) + ret["comment"].append(f"Beacon {name} would be saved") else: __salt__["beacons.save"]() - ret["comment"].append("Beacon {} saved".format(name)) + ret["comment"].append(f"Beacon {name} saved") ret["comment"] = "\n".join(ret["comment"]) return ret @@ -184,16 +184,16 @@ def absent(name, save=False, **kwargs): ret["comment"] = result["comment"] return ret else: - ret["comment"].append("Removed {} from beacons".format(name)) + ret["comment"].append(f"Removed {name} from beacons") else: - ret["comment"].append("{} not configured in beacons".format(name)) + ret["comment"].append(f"{name} not configured in beacons") if save: if __opts__.get("test"): - ret["comment"].append("Beacon {} would be saved".format(name)) + ret["comment"].append(f"Beacon {name} would be saved") else: __salt__["beacons.save"]() - ret["comment"].append("Beacon {} saved".format(name)) + ret["comment"].append(f"Beacon {name} saved") ret["comment"] = "\n".join(ret["comment"]) return ret @@ -231,9 +231,9 @@ def enabled(name, **kwargs): ret["comment"] = result["comment"] return ret else: - ret["comment"].append("Enabled {} from beacons".format(name)) + ret["comment"].append(f"Enabled {name} from beacons") else: - ret["comment"].append("{} not a configured beacon".format(name)) + ret["comment"].append(f"{name} not a configured beacon") ret["comment"] = "\n".join(ret["comment"]) return ret @@ -271,9 +271,9 @@ def disabled(name, **kwargs): ret["comment"] = result["comment"] return ret else: - ret["comment"].append("Disabled beacon {}.".format(name)) + ret["comment"].append(f"Disabled beacon {name}.") else: - ret["comment"].append("Job {} is not configured.".format(name)) + ret["comment"].append(f"Job {name} is not configured.") ret["comment"] = "\n".join(ret["comment"]) return ret diff --git a/salt/states/bigip.py b/salt/states/bigip.py index 58b525435c6..9f494ac20c5 100644 --- a/salt/states/bigip.py +++ b/salt/states/bigip.py @@ -4,7 +4,6 @@ A state module designed to enforce load-balancing configurations for F5 Big-IP e :platform: f5_bigip_11.6 """ - import salt.utils.json @@ -331,9 +330,9 @@ def manage_node( # we think we are managing if existing["content"]["address"] != address: ret["result"] = False - ret[ - "comment" - ] = "A node with this name exists but the address does not match." + ret["comment"] = ( + "A node with this name exists but the address does not match." + ) modified = __salt__["bigip.modify_node"]( hostname=hostname, @@ -1443,10 +1442,10 @@ def add_pool_member(hostname, username, password, name, member): if exists: ret["result"] = True - ret[ - "comment" - ] = "Member: {name} already exists within this pool. No changes made.".format( - name=member["name"] + ret["comment"] = ( + "Member: {name} already exists within this pool. No changes made.".format( + name=member["name"] + ) ) ret["changes"]["old"] = {} ret["changes"]["new"] = {} @@ -1457,10 +1456,10 @@ def add_pool_member(hostname, username, password, name, member): if new_member["code"] == 200: ret["result"] = True - ret[ - "comment" - ] = "Member: {name} has been successfully added to the pool.".format( - name=member["name"] + ret["comment"] = ( + "Member: {name} has been successfully added to the pool.".format( + name=member["name"] + ) ) ret["changes"]["old"] = {} @@ -1629,17 +1628,15 @@ def modify_pool_member( # check for changes old = {"content": existing_member} new = {"content": modified_member} - ret = _check_for_changes( - "Pool Member: {member}".format(member=member), ret, old, new - ) + ret = _check_for_changes(f"Pool Member: {member}", ret, old, new) else: ret = _load_result(modified, ret) else: - ret[ - "comment" - ] = "Member: {name} does not exists within this pool. No changes made.".format( - name=member["name"] + ret["comment"] = ( + "Member: {name} does not exists within this pool. No changes made.".format( + name=member["name"] + ) ) # pool does not exists @@ -1706,10 +1703,10 @@ def delete_pool_member(hostname, username, password, name, member): # did we get rid of it? if deleted["code"] == 200: ret["result"] = True - ret[ - "comment" - ] = "Pool Member: {member} was successfully deleted.".format( - member=member + ret["comment"] = ( + "Pool Member: {member} was successfully deleted.".format( + member=member + ) ) ret["changes"]["old"] = existing_member ret["changes"]["new"] = {} @@ -2353,9 +2350,9 @@ def manage_virtual( ret["result"] = True ret["changes"]["old"] = {} ret["changes"]["new"] = virtual["content"] - ret[ - "comment" - ] = "Virtual was successfully created and enforced to the desired state." + ret["comment"] = ( + "Virtual was successfully created and enforced to the desired state." + ) else: ret = _load_result(virtual, ret) diff --git a/salt/states/blockdev.py b/salt/states/blockdev.py index c8218e68b3d..0f85f3485e5 100644 --- a/salt/states/blockdev.py +++ b/salt/states/blockdev.py @@ -82,7 +82,7 @@ def tuned(name, **kwargs): name ) elif __opts__["test"]: - ret["comment"] = "Changes to {} will be applied ".format(name) + ret["comment"] = f"Changes to {name} will be applied " ret["result"] = None return ret else: @@ -102,15 +102,15 @@ def tuned(name, **kwargs): if key == "read-write": old = not old new = not new - changeset[key] = "Changed from {} to {}".format(old, new) + changeset[key] = f"Changed from {old} to {new}" if changes: if changeset: - ret["comment"] = "Block device {} successfully modified ".format(name) + ret["comment"] = f"Block device {name} successfully modified " ret["changes"] = changeset else: - ret["comment"] = "Block device {} already in correct state".format(name) + ret["comment"] = f"Block device {name} already in correct state" else: - ret["comment"] = "Failed to modify block device {}".format(name) + ret["comment"] = f"Failed to modify block device {name}" ret["result"] = False return ret @@ -136,13 +136,13 @@ def formatted(name, fs_type="ext4", force=False, **kwargs): """ ret = { "changes": {}, - "comment": "{} already formatted with {}".format(name, fs_type), + "comment": f"{name} already formatted with {fs_type}", "name": name, "result": False, } if not os.path.exists(name): - ret["comment"] = "{} does not exist".format(name) + ret["comment"] = f"{name} does not exist" return ret current_fs = _checkblk(name) @@ -150,12 +150,12 @@ def formatted(name, fs_type="ext4", force=False, **kwargs): if current_fs == fs_type: ret["result"] = True return ret - elif not salt.utils.path.which("mkfs.{}".format(fs_type)): - ret["comment"] = "Invalid fs_type: {}".format(fs_type) + elif not salt.utils.path.which(f"mkfs.{fs_type}"): + ret["comment"] = f"Invalid fs_type: {fs_type}" ret["result"] = False return ret elif __opts__["test"]: - ret["comment"] = "Changes to {} will be applied ".format(name) + ret["comment"] = f"Changes to {name} will be applied " ret["result"] = None return ret @@ -171,7 +171,7 @@ def formatted(name, fs_type="ext4", force=False, **kwargs): current_fs = _checkblk(name) if current_fs == fs_type: - ret["comment"] = "{} has been formatted with {}".format(name, fs_type) + ret["comment"] = f"{name} has been formatted with {fs_type}" ret["changes"] = {"new": fs_type, "old": current_fs} ret["result"] = True return ret @@ -182,7 +182,7 @@ def formatted(name, fs_type="ext4", force=False, **kwargs): else: break - ret["comment"] = "Failed to format {}".format(name) + ret["comment"] = f"Failed to format {name}" ret["result"] = False return ret diff --git a/salt/states/boto3_elasticache.py b/salt/states/boto3_elasticache.py index 0cf1a867851..d2d5774a4b5 100644 --- a/salt/states/boto3_elasticache.py +++ b/salt/states/boto3_elasticache.py @@ -173,7 +173,7 @@ def cache_cluster_present( key=None, keyid=None, profile=None, - **args + **args, ): """ Ensure a given cache cluster exists. @@ -444,7 +444,7 @@ def cache_cluster_present( else: create_args[k] = v if __opts__["test"]: - ret["comment"] = "Cache cluster {} would be created.".format(name) + ret["comment"] = f"Cache cluster {name} would be created." ret["result"] = None return ret created = __salt__["boto3_elasticache.create_cache_cluster"]( @@ -455,18 +455,18 @@ def cache_cluster_present( key=key, keyid=keyid, profile=profile, - **create_args + **create_args, ) if created: new = __salt__["boto3_elasticache.describe_cache_clusters"]( name, region=region, key=key, keyid=keyid, profile=profile ) - ret["comment"] = "Cache cluster {} was created.".format(name) + ret["comment"] = f"Cache cluster {name} was created." ret["changes"]["old"] = None ret["changes"]["new"] = new[0] else: ret["result"] = False - ret["comment"] = "Failed to create {} cache cluster.".format(name) + ret["comment"] = f"Failed to create {name} cache cluster." if check_update: # Refresh this in case we're updating from 'only_on_modify' above... @@ -476,7 +476,7 @@ def cache_cluster_present( need_update = _diff_cache_cluster(updated["CacheClusters"][0], args) if need_update: if __opts__["test"]: - ret["comment"] = "Cache cluster {} would be modified.".format(name) + ret["comment"] = f"Cache cluster {name} would be modified." ret["result"] = None return ret modified = __salt__["boto3_elasticache.modify_cache_cluster"]( @@ -487,7 +487,7 @@ def cache_cluster_present( key=key, keyid=keyid, profile=profile, - **need_update + **need_update, ) if modified: new = __salt__["boto3_elasticache.describe_cache_clusters"]( @@ -496,14 +496,14 @@ def cache_cluster_present( if ret["comment"]: # 'create' just ran... ret["comment"] += " ... and then immediately modified." else: - ret["comment"] = "Cache cluster {} was modified.".format(name) + ret["comment"] = f"Cache cluster {name} was modified." ret["changes"]["old"] = current ret["changes"]["new"] = new[0] else: ret["result"] = False - ret["comment"] = "Failed to modify cache cluster {}.".format(name) + ret["comment"] = f"Failed to modify cache cluster {name}." else: - ret["comment"] = "Cache cluster {} is in the desired state.".format(name) + ret["comment"] = f"Cache cluster {name} is in the desired state." return ret @@ -552,7 +552,7 @@ def cache_cluster_absent( ) if exists: if __opts__["test"]: - ret["comment"] = "Cache cluster {} would be removed.".format(name) + ret["comment"] = f"Cache cluster {name} would be removed." ret["result"] = None return ret deleted = __salt__["boto3_elasticache.delete_cache_cluster"]( @@ -562,16 +562,16 @@ def cache_cluster_absent( key=key, keyid=keyid, profile=profile, - **args + **args, ) if deleted: ret["changes"]["old"] = name ret["changes"]["new"] = None else: ret["result"] = False - ret["comment"] = "Failed to delete {} cache cluster.".format(name) + ret["comment"] = f"Failed to delete {name} cache cluster." else: - ret["comment"] = "Cache cluster {} already absent.".format(name) + ret["comment"] = f"Cache cluster {name} already absent." return ret @@ -637,7 +637,7 @@ def replication_group_present( key=None, keyid=None, profile=None, - **args + **args, ): """ Ensure a replication group exists and is in the given state. @@ -896,7 +896,7 @@ def replication_group_present( else: create_args[k] = v if __opts__["test"]: - ret["comment"] = "Replication group {} would be created.".format(name) + ret["comment"] = f"Replication group {name} would be created." ret["result"] = None return ret created = __salt__["boto3_elasticache.create_replication_group"]( @@ -907,18 +907,18 @@ def replication_group_present( key=key, keyid=keyid, profile=profile, - **create_args + **create_args, ) if created: new = __salt__["boto3_elasticache.describe_replication_groups"]( name, region=region, key=key, keyid=keyid, profile=profile ) - ret["comment"] = "Replication group {} was created.".format(name) + ret["comment"] = f"Replication group {name} was created." ret["changes"]["old"] = None ret["changes"]["new"] = new[0] else: ret["result"] = False - ret["comment"] = "Failed to create {} replication group.".format(name) + ret["comment"] = f"Failed to create {name} replication group." if check_update: # Refresh this in case we're updating from 'only_on_modify' above... @@ -928,7 +928,7 @@ def replication_group_present( need_update = _diff_replication_group(updated, args) if need_update: if __opts__["test"]: - ret["comment"] = "Replication group {} would be modified.".format(name) + ret["comment"] = f"Replication group {name} would be modified." ret["result"] = None return ret modified = __salt__["boto3_elasticache.modify_replication_group"]( @@ -939,7 +939,7 @@ def replication_group_present( key=key, keyid=keyid, profile=profile, - **need_update + **need_update, ) if modified: new = __salt__["boto3_elasticache.describe_replication_groups"]( @@ -948,12 +948,12 @@ def replication_group_present( if ret["comment"]: # 'create' just ran... ret["comment"] += " ... and then immediately modified." else: - ret["comment"] = "Replication group {} was modified.".format(name) + ret["comment"] = f"Replication group {name} was modified." ret["changes"]["old"] = current[0] if current else None ret["changes"]["new"] = new[0] else: ret["result"] = False - ret["comment"] = "Failed to modify replication group {}.".format(name) + ret["comment"] = f"Failed to modify replication group {name}." else: ret["comment"] = "Replication group {} is in the desired state.".format( name @@ -1010,7 +1010,7 @@ def replication_group_absent( ) if exists: if __opts__["test"]: - ret["comment"] = "Replication group {} would be removed.".format(name) + ret["comment"] = f"Replication group {name} would be removed." ret["result"] = None return ret deleted = __salt__["boto3_elasticache.delete_replication_group"]( @@ -1020,16 +1020,16 @@ def replication_group_absent( key=key, keyid=keyid, profile=profile, - **args + **args, ) if deleted: ret["changes"]["old"] = name ret["changes"]["new"] = None else: ret["result"] = False - ret["comment"] = "Failed to delete {} replication group.".format(name) + ret["comment"] = f"Failed to delete {name} replication group." else: - ret["comment"] = "Replication group {} already absent.".format(name) + ret["comment"] = f"Replication group {name} already absent." return ret @@ -1113,7 +1113,7 @@ def cache_subnet_group_present( else: check_update = False if __opts__["test"]: - ret["comment"] = "Cache subnet group {} would be created.".format(name) + ret["comment"] = f"Cache subnet group {name} would be created." ret["result"] = None return ret created = __salt__["boto3_elasticache.create_cache_subnet_group"]( @@ -1123,24 +1123,24 @@ def cache_subnet_group_present( key=key, keyid=keyid, profile=profile, - **args + **args, ) if created: new = __salt__["boto3_elasticache.describe_cache_subnet_groups"]( name, region=region, key=key, keyid=keyid, profile=profile ) - ret["comment"] = "Cache subnet group {} was created.".format(name) + ret["comment"] = f"Cache subnet group {name} was created." ret["changes"]["old"] = None ret["changes"]["new"] = new[0] else: ret["result"] = False - ret["comment"] = "Failed to create {} cache subnet group.".format(name) + ret["comment"] = f"Failed to create {name} cache subnet group." if check_update: need_update = _diff_cache_subnet_group(current, args) if need_update: if __opts__["test"]: - ret["comment"] = "Cache subnet group {} would be modified.".format(name) + ret["comment"] = f"Cache subnet group {name} would be modified." ret["result"] = None return ret modified = __salt__["boto3_elasticache.modify_cache_subnet_group"]( @@ -1150,18 +1150,18 @@ def cache_subnet_group_present( key=key, keyid=keyid, profile=profile, - **need_update + **need_update, ) if modified: new = __salt__["boto3_elasticache.describe_cache_subnet_groups"]( name, region=region, key=key, keyid=keyid, profile=profile ) - ret["comment"] = "Cache subnet group {} was modified.".format(name) + ret["comment"] = f"Cache subnet group {name} was modified." ret["changes"]["old"] = current["CacheSubetGroups"][0] ret["changes"]["new"] = new[0] else: ret["result"] = False - ret["comment"] = "Failed to modify cache subnet group {}.".format(name) + ret["comment"] = f"Failed to modify cache subnet group {name}." else: ret["comment"] = "Cache subnet group {} is in the desired state.".format( name @@ -1202,7 +1202,7 @@ def cache_subnet_group_absent( ) if exists: if __opts__["test"]: - ret["comment"] = "Cache subnet group {} would be removed.".format(name) + ret["comment"] = f"Cache subnet group {name} would be removed." ret["result"] = None return ret deleted = __salt__["boto3_elasticache.delete_cache_subnet_group"]( @@ -1213,7 +1213,7 @@ def cache_subnet_group_absent( ret["changes"]["new"] = None else: ret["result"] = False - ret["comment"] = "Failed to delete {} cache_subnet group.".format(name) + ret["comment"] = f"Failed to delete {name} cache_subnet group." else: - ret["comment"] = "Cache subnet group {} already absent.".format(name) + ret["comment"] = f"Cache subnet group {name} already absent." return ret diff --git a/salt/states/boto3_elasticsearch.py b/salt/states/boto3_elasticsearch.py index ff0dae55457..9a908f33ae7 100644 --- a/salt/states/boto3_elasticsearch.py +++ b/salt/states/boto3_elasticsearch.py @@ -43,7 +43,6 @@ Manage Elasticsearch Service :depends: boto3 """ - import logging import salt.utils.json @@ -73,7 +72,7 @@ def __virtual__(): if req not in __salt__: return ( False, - "A required function was not found in __salt__: {}".format(req), + f"A required function was not found in __salt__: {req}", ) return __virtualname__ @@ -378,7 +377,7 @@ def present( else: ret["result"] = True ret["comment"].append( - 'Elasticsearch Domain "{}" has been {}d.'.format(name, action) + f'Elasticsearch Domain "{name}" has been {action}d.' ) ret["changes"] = config_diff elif action == "upgrade": @@ -455,7 +454,7 @@ def absent(name, blocking=True, region=None, keyid=None, key=None, profile=None) if __opts__["test"]: ret["result"] = None ret["comment"].append( - 'Elasticsearch domain "{}" would have been removed.'.format(name) + f'Elasticsearch domain "{name}" would have been removed.' ) ret["changes"] = {"old": name, "new": None} else: @@ -477,14 +476,12 @@ def absent(name, blocking=True, region=None, keyid=None, key=None, profile=None) else: ret["result"] = True ret["comment"].append( - 'Elasticsearch domain "{}" has been deleted.'.format(name) + f'Elasticsearch domain "{name}" has been deleted.' ) ret["changes"] = {"old": name, "new": None} else: ret["result"] = True - ret["comment"].append( - 'Elasticsearch domain "{}" is already absent.'.format(name) - ) + ret["comment"].append(f'Elasticsearch domain "{name}" is already absent.') ret = _check_return_value(ret) return ret @@ -529,9 +526,7 @@ def upgraded( if not res["result"]: ret["result"] = False if "ResourceNotFoundException" in res["error"]: - ret["comment"].append( - 'The Elasticsearch domain "{}" does not exist.'.format(name) - ) + ret["comment"].append(f'The Elasticsearch domain "{name}" does not exist.') else: ret["comment"].append(res["error"]) else: @@ -727,9 +722,7 @@ def latest(name, minor_only=True, region=None, keyid=None, key=None, profile=Non pass if not current_version: ret["result"] = True - ret["comment"].append( - 'The Elasticsearch domain "{}" can not be upgraded.'.format(name) - ) + ret["comment"].append(f'The Elasticsearch domain "{name}" can not be upgraded.') elif not latest_version: ret["result"] = True ret["comment"].append( @@ -819,7 +812,7 @@ def tagged( current_tags = res["response"] or {} else: ret["result"] = False - ret["comment"].append('Elasticsearch domain "{}" does not exist.'.format(name)) + ret["comment"].append(f'Elasticsearch domain "{name}" does not exist.') if isinstance(ret["result"], bool): return ret @@ -827,7 +820,7 @@ def tagged( if not diff_tags: ret["result"] = True ret["comment"].append( - 'Elasticsearch domain "{}" already has the specified tags.'.format(name) + f'Elasticsearch domain "{name}" already has the specified tags.' ) else: if replace: diff --git a/salt/states/boto3_route53.py b/salt/states/boto3_route53.py index 3edbc57a870..8494ecb4b12 100644 --- a/salt/states/boto3_route53.py +++ b/salt/states/boto3_route53.py @@ -59,6 +59,7 @@ passed in as a dict, or as a string to pull from pillars or minion config: - key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs """ + # keep lint from choking # pylint: disable=W0106 # pylint: disable=E1320 @@ -241,7 +242,7 @@ def hosted_zone_present( update_comment = True if not (create or add_vpcs or del_vpcs or update_comment): - ret["comment"] = "Hostd Zone {} already in desired state".format(Name) + ret["comment"] = f"Hostd Zone {Name} already in desired state" return ret if create: @@ -282,10 +283,10 @@ def hosted_zone_present( if update_comment: if __opts__["test"]: - ret[ - "comment" - ] = "Route 53 {} hosted zone {} comment would be updated.".format( - "private" if PrivateZone else "public", Name + ret["comment"] = ( + "Route 53 {} hosted zone {} comment would be updated.".format( + "private" if PrivateZone else "public", Name + ) ) ret["result"] = None return ret @@ -310,10 +311,10 @@ def hosted_zone_present( ret["changes"].get("new", {}), r ) else: - ret[ - "comment" - ] = "Update of Route 53 {} hosted zone {} comment failed".format( - "private" if PrivateZone else "public", Name + ret["comment"] = ( + "Update of Route 53 {} hosted zone {} comment failed".format( + "private" if PrivateZone else "public", Name + ) ) log.error(ret["comment"]) ret["result"] = False @@ -321,10 +322,10 @@ def hosted_zone_present( if add_vpcs or del_vpcs: if __opts__["test"]: - ret[ - "comment" - ] = "Route 53 {} hosted zone {} associated VPCs would be updated.".format( - "private" if PrivateZone else "public", Name + ret["comment"] = ( + "Route 53 {} hosted zone {} associated VPCs would be updated.".format( + "private" if PrivateZone else "public", Name + ) ) ret["result"] = None return ret @@ -366,10 +367,10 @@ def hosted_zone_present( log.info(msg) ret["comment"] = " ".join([ret["comment"], msg]) else: - ret[ - "comment" - ] = "Update of Route 53 {} hosted zone {} associated VPCs failed".format( - "private" if PrivateZone else "public", Name + ret["comment"] = ( + "Update of Route 53 {} hosted zone {} associated VPCs failed".format( + "private" if PrivateZone else "public", Name + ) ) log.error(ret["comment"]) ret["result"] = False @@ -697,19 +698,19 @@ def rr_present( profile=profile, ) if len(r) < 1: - ret[ - "comment" - ] = "No EC2 instance with tag {} == {} found".format( - tag_name, tag_value + ret["comment"] = ( + "No EC2 instance with tag {} == {} found".format( + tag_name, tag_value + ) ) log.error(ret["comment"]) ret["result"] = False return ret if len(r) > 1: - ret[ - "comment" - ] = "Multiple EC2 instances with tag {} == {} found".format( - tag_name, tag_value + ret["comment"] = ( + "Multiple EC2 instances with tag {} == {} found".format( + tag_name, tag_value + ) ) log.error(ret["comment"]) ret["result"] = False @@ -745,7 +746,7 @@ def rr_present( # this appears to be incredibly difficult with the jinja templating engine # so inject the quotations here to make a viable ChangeBatch if Type == "TXT": - rr = '"{}"'.format(rr) + rr = f'"{rr}"' fixed_rrs += [rr] ResourceRecords = [{"Value": rr} for rr in sorted(fixed_rrs)] @@ -782,10 +783,10 @@ def rr_present( if not recordsets: create = True if __opts__["test"]: - ret[ - "comment" - ] = "Route 53 resource record {} with type {} would be added.".format( - Name, Type + ret["comment"] = ( + "Route 53 resource record {} with type {} would be added.".format( + Name, Type + ) ) ret["result"] = None return ret @@ -818,10 +819,10 @@ def rr_present( return ret else: if __opts__["test"]: - ret[ - "comment" - ] = "Route 53 resource record {} with type {} would be updated.".format( - Name, Type + ret["comment"] = ( + "Route 53 resource record {} with type {} would be updated.".format( + Name, Type + ) ) ret["result"] = None return ret @@ -859,10 +860,10 @@ def rr_present( ret["changes"]["old"] = rrset ret["changes"]["new"] = ResourceRecordSet else: - ret[ - "comment" - ] = "Failed to {} Route 53 resource record {} with type {}.".format( - "create" if create else "update", Name, Type + ret["comment"] = ( + "Failed to {} Route 53 resource record {} with type {}.".format( + "create" if create else "update", Name, Type + ) ) log.error(ret["comment"]) ret["result"] = False @@ -967,10 +968,10 @@ def rr_absent( recordsets = [r for r in recordsets if r.get("SetIdentifier") == SetIdentifier] log.debug("Resulted in recordsets %s.", recordsets) if not recordsets: - ret[ - "comment" - ] = "Route 53 resource record {} with type {} already absent.".format( - Name, Type + ret["comment"] = ( + "Route 53 resource record {} with type {} already absent.".format( + Name, Type + ) ) return ret elif len(recordsets) > 1: @@ -980,10 +981,10 @@ def rr_absent( return ret ResourceRecordSet = recordsets[0] if __opts__["test"]: - ret[ - "comment" - ] = "Route 53 resource record {} with type {} would be deleted.".format( - Name, Type + ret["comment"] = ( + "Route 53 resource record {} with type {} would be deleted.".format( + Name, Type + ) ) ret["result"] = None return ret @@ -1007,10 +1008,10 @@ def rr_absent( ret["changes"]["old"] = ResourceRecordSet ret["changes"]["new"] = None else: - ret[ - "comment" - ] = "Failed to delete Route 53 resource record {} with type {}.".format( - Name, Type + ret["comment"] = ( + "Failed to delete Route 53 resource record {} with type {}.".format( + Name, Type + ) ) log.error(ret["comment"]) ret["result"] = False diff --git a/salt/states/boto3_sns.py b/salt/states/boto3_sns.py index 30509176e70..feeca5602c1 100644 --- a/salt/states/boto3_sns.py +++ b/salt/states/boto3_sns.py @@ -135,11 +135,11 @@ def topic_present( something_changed = False current = __salt__["boto3_sns.describe_topic"](name, region, key, keyid, profile) if current: - ret["comment"] = "AWS SNS topic {} present.".format(name) + ret["comment"] = f"AWS SNS topic {name} present." TopicArn = current["TopicArn"] else: if __opts__["test"]: - ret["comment"] = "AWS SNS topic {} would be created.".format(name) + ret["comment"] = f"AWS SNS topic {name} would be created." ret["result"] = None return ret else: @@ -152,7 +152,7 @@ def topic_present( ) something_changed = True else: - ret["comment"] = "Failed to create AWS SNS topic {}".format(name) + ret["comment"] = f"Failed to create AWS SNS topic {name}" log.error(ret["comment"]) ret["result"] = False return ret @@ -246,7 +246,7 @@ def topic_present( TopicArn, prot, endp, region=region, key=key, keyid=keyid, profile=profile ) if subbed: - msg = " Subscription {}:{} set on topic {}.".format(prot, endp, TopicArn) + msg = f" Subscription {prot}:{endp} set on topic {TopicArn}." ret["comment"] += msg something_changed = True else: @@ -318,11 +318,11 @@ def topic_absent( something_changed = False current = __salt__["boto3_sns.describe_topic"](name, region, key, keyid, profile) if not current: - ret["comment"] = "AWS SNS topic {} absent.".format(name) + ret["comment"] = f"AWS SNS topic {name} absent." else: TopicArn = current["TopicArn"] if __opts__["test"]: - ret["comment"] = "AWS SNS topic {} would be removed.".format(TopicArn) + ret["comment"] = f"AWS SNS topic {TopicArn} would be removed." if unsubscribe: ret["comment"] += " {} subscription(s) would be removed.".format( len(current["Subscriptions"]) @@ -350,27 +350,24 @@ def topic_absent( log.debug("Deleted subscription %s for SNS topic %s", sub, TopicArn) something_changed = True else: - ret[ - "comment" - ] = "Failed to delete subscription {} for SNS topic {}".format( - sub, TopicArn + ret["comment"] = ( + "Failed to delete subscription {} for SNS topic {}".format( + sub, TopicArn + ) ) ret["result"] = False return ret if not __salt__["boto3_sns.delete_topic"]( TopicArn, region=region, key=key, keyid=keyid, profile=profile ): - ret["comment"] = "Failed to delete SNS topic {}".format(TopicArn) + ret["comment"] = f"Failed to delete SNS topic {TopicArn}" log.error(ret["comment"]) ret["result"] = False else: - ret["comment"] = "AWS SNS topic {} deleted.".format(TopicArn) + ret["comment"] = f"AWS SNS topic {TopicArn} deleted." if unsubscribe: ret["comment"] += " ".join( - [ - "Subscription {} deleted".format(s) - for s in current["Subscriptions"] - ] + [f"Subscription {s} deleted" for s in current["Subscriptions"]] ) something_changed = True diff --git a/salt/states/boto_apigateway.py b/salt/states/boto_apigateway.py index f70edf470f1..554f574c8a3 100644 --- a/salt/states/boto_apigateway.py +++ b/salt/states/boto_apigateway.py @@ -50,7 +50,6 @@ config: """ - import hashlib import logging import os @@ -350,7 +349,7 @@ def present( except (ValueError, OSError) as e: ret["result"] = False - ret["comment"] = "{}".format(e.args) + ret["comment"] = f"{e.args}" return ret @@ -435,7 +434,7 @@ def absent( swagger = _Swagger(api_name, stage_name, "", None, None, None, common_args) if not swagger.restApiId: - ret["comment"] = "[Rest API: {}] does not exist.".format(api_name) + ret["comment"] = f"[Rest API: {api_name}] does not exist." return ret if __opts__["test"]: @@ -446,7 +445,7 @@ def absent( "deleted.".format(stage_name, api_name) ) else: - ret["comment"] = "[stage: {}] will be deleted.".format(stage_name) + ret["comment"] = f"[stage: {stage_name}] will be deleted." ret["result"] = None return ret @@ -460,7 +459,7 @@ def absent( except (ValueError, OSError) as e: ret["result"] = False - ret["comment"] = "{}".format(e.args) + ret["comment"] = f"{e.args}" return ret @@ -725,11 +724,11 @@ class _Swagger: _name = self._paramdict.get("name") if _name: if self.location == "header": - return "method.request.header.{}".format(_name) + return f"method.request.header.{_name}" elif self.location == "query": - return "method.request.querystring.{}".format(_name) + return f"method.request.querystring.{_name}" elif self.location == "path": - return "method.request.path.{}".format(_name) + return f"method.request.path.{_name}" return None raise ValueError( "Parameter must have a name: {}".format( @@ -754,9 +753,7 @@ class _Swagger: self.name ) ) - raise ValueError( - "Body parameter must have a schema: {}".format(self.name) - ) + raise ValueError(f"Body parameter must have a schema: {self.name}") return None class SwaggerMethodResponse: @@ -819,7 +816,7 @@ class _Swagger: self._cfg = salt.utils.yaml.safe_load(sf) self._swagger_version = "" else: - raise OSError("Invalid swagger file path, {}".format(swagger_file_path)) + raise OSError(f"Invalid swagger file path, {swagger_file_path}") self._validate_swagger_file() @@ -877,7 +874,7 @@ class _Swagger: if model.get("type") != "object": raise ValueError( - "model schema {} must be type object".format(modelname) + f"model schema {modelname} must be type object" ) if "properties" not in model: raise ValueError( @@ -928,12 +925,12 @@ class _Swagger: field not in _Swagger.SWAGGER_OBJ_V2_FIELDS and not _Swagger.VENDOR_EXT_PATTERN.match(field) ): - raise ValueError("Invalid Swagger Object Field: {}".format(field)) + raise ValueError(f"Invalid Swagger Object Field: {field}") # check for Required Swagger fields by Saltstack boto apigateway state for field in _Swagger.SWAGGER_OBJ_V2_FIELDS_REQUIRED: if field not in self._cfg: - raise ValueError("Missing Swagger Object Field: {}".format(field)) + raise ValueError(f"Missing Swagger Object Field: {field}") # check for Swagger Version self._swagger_version = self._cfg.get("swagger") @@ -1027,7 +1024,7 @@ class _Swagger: for path in paths: if not path.startswith("/"): raise ValueError( - "Path object {} should start with /. Please fix it".format(path) + f"Path object {path} should start with /. Please fix it" ) return paths.items() @@ -1100,7 +1097,7 @@ class _Swagger: stages = __salt__["boto_apigateway.describe_api_stages"]( restApiId=self.restApiId, deploymentId=deploymentId, - **self._common_aws_args + **self._common_aws_args, ).get("stages") if stages: no_more_deployments = False @@ -1116,7 +1113,7 @@ class _Swagger: stage = __salt__["boto_apigateway.describe_api_stage"]( restApiId=self.restApiId, stageName=self._stage_name, - **self._common_aws_args + **self._common_aws_args, ).get("stage") if stage: deploymentId = stage.get("deploymentId") @@ -1156,7 +1153,7 @@ class _Swagger: restApiId=self.restApiId, stageName=self._stage_name, variables=stage_variables, - **self._common_aws_args + **self._common_aws_args, ) if not res.get("overwrite"): @@ -1174,7 +1171,7 @@ class _Swagger: stage = __salt__["boto_apigateway.describe_api_stage"]( restApiId=self.restApiId, stageName=self._stage_name, - **self._common_aws_args + **self._common_aws_args, ).get("stage") if not stage: stage = __salt__["boto_apigateway.create_api_stage"]( @@ -1183,7 +1180,7 @@ class _Swagger: deploymentId=self._deploymentId, description=stage_desc_json, variables=stage_variables, - **self._common_aws_args + **self._common_aws_args, ) if not stage.get("stage"): return {"set": False, "error": stage.get("error")} @@ -1193,7 +1190,7 @@ class _Swagger: restApiId=self.restApiId, stageName=self._stage_name, variables=stage_variables, - **self._common_aws_args + **self._common_aws_args, ) if not overwrite.get("stage"): return {"set": False, "error": overwrite.get("error")} @@ -1202,7 +1199,7 @@ class _Swagger: restApiId=self.restApiId, stageName=self._stage_name, deploymentId=self._deploymentId, - **self._common_aws_args + **self._common_aws_args, ) def _resolve_api_id(self): @@ -1213,7 +1210,7 @@ class _Swagger: apis = __salt__["boto_apigateway.describe_apis"]( name=self.rest_api_name, description=_Swagger.AWS_API_DESCRIPTION, - **self._common_aws_args + **self._common_aws_args, ).get("restapi") if apis: if len(apis) == 1: @@ -1236,7 +1233,7 @@ class _Swagger: result = __salt__["boto_apigateway.delete_api_stage"]( restApiId=self.restApiId, stageName=self._stage_name, - **self._common_aws_args + **self._common_aws_args, ) if not result.get("deleted"): ret["abort"] = True @@ -1250,15 +1247,15 @@ class _Swagger: result = __salt__["boto_apigateway.delete_api_deployment"]( restApiId=self.restApiId, deploymentId=deploymentId, - **self._common_aws_args + **self._common_aws_args, ) if not result.get("deleted"): ret["abort"] = True ret["result"] = False - ret[ - "comment" - ] = "delete_stage delete_api_deployment, {}".format( - result.get("error") + ret["comment"] = ( + "delete_stage delete_api_deployment, {}".format( + result.get("error") + ) ) else: ret["comment"] = "stage {} has been deleted.\n".format( @@ -1266,7 +1263,7 @@ class _Swagger: ) else: # no matching stage_name/deployment found - ret["comment"] = "stage {} does not exist".format(self._stage_name) + ret["comment"] = f"stage {self._stage_name} does not exist" return ret @@ -1327,7 +1324,7 @@ class _Swagger: stageDescription=stage_desc_json, description=self.deployment_label_json, variables=stage_variables, - **self._common_aws_args + **self._common_aws_args, ) if not res.get("created"): ret["abort"] = True @@ -1354,7 +1351,7 @@ class _Swagger: delres = __salt__["boto_apigateway.delete_api_resources"]( restApiId=self.restApiId, path=resource.get("path"), - **self._common_aws_args + **self._common_aws_args, ) if not delres.get("deleted"): return delres @@ -1367,7 +1364,7 @@ class _Swagger: delres = __salt__["boto_apigateway.delete_api_model"]( restApiId=self.restApiId, modelName=model.get("name"), - **self._common_aws_args + **self._common_aws_args, ) if not delres.get("deleted"): return delres @@ -1381,7 +1378,7 @@ class _Swagger: if self.restApiId: res = self._cleanup_api() if not res.get("deleted"): - ret["comment"] = "Failed to cleanup restAreId {}".format(self.restApiId) + ret["comment"] = f"Failed to cleanup restAreId {self.restApiId}" ret["abort"] = True ret["result"] = False return ret @@ -1390,7 +1387,7 @@ class _Swagger: response = __salt__["boto_apigateway.create_api"]( name=self.rest_api_name, description=_Swagger.AWS_API_DESCRIPTION, - **self._common_aws_args + **self._common_aws_args, ) if not response.get("created"): @@ -1417,7 +1414,7 @@ class _Swagger: exists_response = __salt__["boto_apigateway.api_exists"]( name=self.rest_api_name, description=_Swagger.AWS_API_DESCRIPTION, - **self._common_aws_args + **self._common_aws_args, ) if exists_response.get("exists"): if __opts__["test"]: @@ -1431,7 +1428,7 @@ class _Swagger: delete_api_response = __salt__["boto_apigateway.delete_api"]( name=self.rest_api_name, description=_Swagger.AWS_API_DESCRIPTION, - **self._common_aws_args + **self._common_aws_args, ) if not delete_api_response.get("deleted"): ret["result"] = False @@ -1553,7 +1550,7 @@ class _Swagger: _schema.update( { "$schema": _Swagger.JSON_SCHEMA_DRAFT_4, - "title": "{} Schema".format(model), + "title": f"{model} Schema", } ) @@ -1570,7 +1567,7 @@ class _Swagger: restApiId=self.restApiId, modelName=model, schema=_dict_to_json_pretty(_schema), - **self._common_aws_args + **self._common_aws_args, ) if not update_model_schema_response.get("updated"): ret["result"] = False @@ -1594,19 +1591,19 @@ class _Swagger: modelDescription=model, schema=_dict_to_json_pretty(_schema), contentType="application/json", - **self._common_aws_args + **self._common_aws_args, ) if not create_model_response.get("created"): 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 @@ -1745,7 +1742,7 @@ class _Swagger: method_response_params = {} method_integration_response_params = {} for header in method_response.headers: - response_header = "method.response.header.{}".format(header) + response_header = f"method.response.header.{header}" method_response_params[response_header] = False header_data = method_response.headers.get(header) method_integration_response_params[response_header] = ( @@ -1822,7 +1819,7 @@ class _Swagger: apiKeyRequired=api_key_required, requestParameters=method.get("params"), requestModels=method.get("models"), - **self._common_aws_args + **self._common_aws_args, ) if not m.get("created"): ret = _log_error_and_abort(ret, m) @@ -1848,7 +1845,7 @@ class _Swagger: uri=lambda_uri, credentials=lambda_integration_role, requestTemplates=method.get("request_templates"), - **self._common_aws_args + **self._common_aws_args, ) if not integration.get("created"): ret = _log_error_and_abort(ret, integration) @@ -1871,7 +1868,7 @@ class _Swagger: statusCode=httpStatus, responseParameters=method_response.get("params"), responseModels=method_response.get("models"), - **self._common_aws_args + **self._common_aws_args, ) if not mr.get("created"): ret = _log_error_and_abort(ret, mr) @@ -1886,7 +1883,7 @@ class _Swagger: selectionPattern=method_response.get("pattern"), responseParameters=method_response.get("integration_params"), responseTemplates=method_response.get("response_templates"), - **self._common_aws_args + **self._common_aws_args, ) if not mir.get("created"): ret = _log_error_and_abort(ret, mir) @@ -1896,7 +1893,7 @@ class _Swagger: ) else: raise ValueError( - "No responses specified for {} {}".format(resource_path, method_name) + f"No responses specified for {resource_path} {method_name}" ) return ret @@ -2043,7 +2040,7 @@ def usage_plan_present( description=description, throttle=throttle, quota=quota, - **common_args + **common_args, ) if "error" in result: ret["result"] = False @@ -2053,7 +2050,7 @@ def usage_plan_present( return ret ret["changes"]["old"] = {"plan": None} - ret["comment"] = "A new usage plan {} has been created".format(plan_name) + ret["comment"] = f"A new usage plan {plan_name} has been created" else: # need an existing plan modified to match given value @@ -2098,7 +2095,7 @@ def usage_plan_present( return ret ret["changes"]["old"] = {"plan": plan} - ret["comment"] = "usage plan {} has been updated".format(plan_name) + ret["comment"] = f"usage plan {plan_name} has been updated" newstate = __salt__["boto_apigateway.describe_usage_plans"]( name=plan_name, **common_args @@ -2112,7 +2109,7 @@ def usage_plan_present( except (ValueError, OSError) as e: ret["result"] = False - ret["comment"] = "{}".format(e.args) + ret["comment"] = f"{e.args}" return ret @@ -2153,7 +2150,7 @@ def usage_plan_absent(name, plan_name, region=None, key=None, keyid=None, profil return ret if not existing["plans"]: - ret["comment"] = "Usage plan {} does not exist already".format(plan_name) + ret["comment"] = f"Usage plan {plan_name} does not exist already" return ret if __opts__["test"]: @@ -2173,13 +2170,13 @@ def usage_plan_absent(name, plan_name, region=None, key=None, keyid=None, profil ) return ret - ret["comment"] = "Usage plan {} has been deleted".format(plan_name) + ret["comment"] = f"Usage plan {plan_name} has been deleted" ret["changes"]["old"] = {"plan": existing["plans"][0]} ret["changes"]["new"] = {"plan": None} except (ValueError, OSError) as e: ret["result"] = False - ret["comment"] = "{}".format(e.args) + ret["comment"] = f"{e.args}" return ret @@ -2235,7 +2232,7 @@ def usage_plan_association_present( return ret if not existing["plans"]: - ret["comment"] = "Usage plan {} does not exist".format(plan_name) + ret["comment"] = f"Usage plan {plan_name} does not exist" ret["result"] = False return ret @@ -2264,10 +2261,10 @@ def usage_plan_association_present( plan_id, stages_to_add, **common_args ) if "error" in result: - ret[ - "comment" - ] = "Failed to associate a usage plan {} to the apis {}, {}".format( - plan_name, stages_to_add, result["error"] + ret["comment"] = ( + "Failed to associate a usage plan {} to the apis {}, {}".format( + plan_name, stages_to_add, result["error"] + ) ) ret["result"] = False return ret @@ -2278,7 +2275,7 @@ def usage_plan_association_present( except (ValueError, OSError) as e: ret["result"] = False - ret["comment"] = "{}".format(e.args) + ret["comment"] = f"{e.args}" return ret @@ -2336,7 +2333,7 @@ def usage_plan_association_absent( return ret if not existing["plans"]: - ret["comment"] = "Usage plan {} does not exist".format(plan_name) + ret["comment"] = f"Usage plan {plan_name} does not exist" ret["result"] = False return ret @@ -2371,10 +2368,10 @@ def usage_plan_association_absent( plan_id, stages_to_remove, **common_args ) if "error" in result: - ret[ - "comment" - ] = "Failed to disassociate a usage plan {} from the apis {}, {}".format( - plan_name, stages_to_remove, result["error"] + ret["comment"] = ( + "Failed to disassociate a usage plan {} from the apis {}, {}".format( + plan_name, stages_to_remove, result["error"] + ) ) ret["result"] = False return ret @@ -2385,6 +2382,6 @@ def usage_plan_association_absent( except (ValueError, OSError) as e: ret["result"] = False - ret["comment"] = "{}".format(e.args) + ret["comment"] = f"{e.args}" return ret diff --git a/salt/states/boto_asg.py b/salt/states/boto_asg.py index 58a5baed2ca..64d44574773 100644 --- a/salt/states/boto_asg.py +++ b/salt/states/boto_asg.py @@ -191,7 +191,6 @@ Overriding the alarm values on the resource: threshold: 50.0 """ - import copy import hashlib import logging @@ -450,7 +449,7 @@ def present( ret["result"] = False return ret if "id" not in r: - ret["comment"] = "Subnet {} does not exist.".format(i) + ret["comment"] = f"Subnet {i} does not exist." ret["result"] = False return ret vpc_zone_identifier.append(r["id"]) @@ -830,7 +829,7 @@ def _alarms_present( if "scaling_policy" not in action: scaling_policy_actions_only = False if ":self:" in action: - action = action.replace(":self:", ":{}:".format(name)) + action = action.replace(":self:", f":{name}:") new_actions.append(action) info["attributes"][action_type] = new_actions # skip alarms that only have actions for scaling policy, if min_size == max_size for this ASG diff --git a/salt/states/boto_cfn.py b/salt/states/boto_cfn.py index 971514a3b6b..bd748eb410f 100644 --- a/salt/states/boto_cfn.py +++ b/salt/states/boto_cfn.py @@ -56,7 +56,7 @@ def __virtual__(): else: return ( False, - "Cannot load {} state: boto_cfn module unavailable".format(__virtualname__), + f"Cannot load {__virtualname__} state: boto_cfn module unavailable", ) @@ -177,7 +177,7 @@ def present( log.debug("Templates are not the same. Compare value is %s", compare) # At this point we should be able to run update safely since we already validated the template if __opts__["test"]: - ret["comment"] = "Stack {} is set to be updated.".format(name) + ret["comment"] = f"Stack {name} is set to be updated." ret["result"] = None return ret updated = __salt__["boto_cfn.update_stack"]( @@ -213,11 +213,11 @@ def present( ) ret["changes"]["new"] = updated return ret - ret["comment"] = "Stack {} exists.".format(name) + ret["comment"] = f"Stack {name} exists." ret["changes"] = {} return ret if __opts__["test"]: - ret["comment"] = "Stack {} is set to be created.".format(name) + ret["comment"] = f"Stack {name} is set to be created." ret["result"] = None return ret created = __salt__["boto_cfn.create"]( @@ -239,7 +239,7 @@ def present( profile, ) if created: - ret["comment"] = "Stack {} was created.".format(name) + ret["comment"] = f"Stack {name} was created." ret["changes"]["new"] = created return ret ret["result"] = False @@ -263,11 +263,11 @@ def absent(name, region=None, key=None, keyid=None, profile=None): """ ret = {"name": name, "result": True, "comment": "", "changes": {}} if not __salt__["boto_cfn.exists"](name, region, key, keyid, profile): - ret["comment"] = "Stack {} does not exist.".format(name) + ret["comment"] = f"Stack {name} does not exist." ret["changes"] = {} return ret if __opts__["test"]: - ret["comment"] = "Stack {} is set to be deleted.".format(name) + ret["comment"] = f"Stack {name} is set to be deleted." ret["result"] = None return ret deleted = __salt__["boto_cfn.delete"](name, region, key, keyid, profile) @@ -280,7 +280,7 @@ def absent(name, region=None, key=None, keyid=None, profile=None): ret["changes"] = {} return ret if deleted: - ret["comment"] = "Stack {} was deleted.".format(name) + ret["comment"] = f"Stack {name} was deleted." ret["changes"]["deleted"] = name return ret @@ -293,7 +293,7 @@ def _get_template(template, name): return __salt__["cp.get_file_str"](template) except OSError as e: log.debug(e) - ret["comment"] = "File {} not found.".format(template) + ret["comment"] = f"File {template} not found." ret["result"] = False return ret return template diff --git a/salt/states/boto_cloudfront.py b/salt/states/boto_cloudfront.py index db83cc10b80..0bdd44d13bb 100644 --- a/salt/states/boto_cloudfront.py +++ b/salt/states/boto_cloudfront.py @@ -43,7 +43,6 @@ either passed in as a dict, or a string to pull from pillars or minion config: :depends: boto3 """ - import difflib import logging @@ -132,7 +131,7 @@ def present( if old is None: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Distribution {} set for creation.".format(name) + ret["comment"] = f"Distribution {name} set for creation." ret["changes"] = {"old": None, "new": name} return ret @@ -154,7 +153,7 @@ def present( return ret ret["result"] = True - ret["comment"] = "Created distribution {}.".format(name) + ret["comment"] = f"Created distribution {name}." ret["changes"] = {"old": None, "new": name} return ret else: @@ -199,7 +198,7 @@ def present( if __opts__["test"]: ret["result"] = None ret["comment"] = "\n".join( - ["Distribution {} set for new config:".format(name), changes_diff] + [f"Distribution {name} set for new config:", changes_diff] ) ret["changes"] = {"diff": changes_diff} return ret @@ -222,6 +221,6 @@ def present( return ret ret["result"] = True - ret["comment"] = "Updated distribution {}.".format(name) + ret["comment"] = f"Updated distribution {name}." ret["changes"] = {"diff": changes_diff} return ret diff --git a/salt/states/boto_cloudtrail.py b/salt/states/boto_cloudtrail.py index 5699ef2033d..d4cf62f5be3 100644 --- a/salt/states/boto_cloudtrail.py +++ b/salt/states/boto_cloudtrail.py @@ -51,7 +51,6 @@ config: """ - import logging import os import os.path @@ -165,7 +164,7 @@ def present( if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "CloudTrail {} is set to be created.".format(Name) + ret["comment"] = f"CloudTrail {Name} is set to be created." ret["result"] = None return ret r = __salt__["boto_cloudtrail.create"]( @@ -193,7 +192,7 @@ def present( ) ret["changes"]["old"] = {"trail": None} ret["changes"]["new"] = _describe - ret["comment"] = "CloudTrail {} created.".format(Name) + ret["comment"] = f"CloudTrail {Name} created." if LoggingEnabled: r = __salt__["boto_cloudtrail.start_logging"]( @@ -224,9 +223,7 @@ def present( ret["changes"]["new"]["trail"]["Tags"] = Tags return ret - ret["comment"] = os.linesep.join( - [ret["comment"], "CloudTrail {} is present.".format(Name)] - ) + ret["comment"] = os.linesep.join([ret["comment"], f"CloudTrail {Name} is present."]) ret["changes"] = {} # trail exists, ensure config matches _describe = __salt__["boto_cloudtrail.describe"]( @@ -278,7 +275,7 @@ def present( if need_update: if __opts__["test"]: - msg = "CloudTrail {} set to be modified.".format(Name) + msg = f"CloudTrail {Name} set to be modified." ret["comment"] = msg ret["result"] = None return ret @@ -345,7 +342,7 @@ def present( key=key, keyid=keyid, profile=profile, - **adds + **adds, ) if bool(removes): r = __salt__["boto_cloudtrail.remove_tags"]( @@ -354,7 +351,7 @@ def present( key=key, keyid=keyid, profile=profile, - **removes + **removes, ) return ret @@ -395,11 +392,11 @@ def absent(name, Name, region=None, key=None, keyid=None, profile=None): return ret if r and not r["exists"]: - ret["comment"] = "CloudTrail {} does not exist.".format(Name) + ret["comment"] = f"CloudTrail {Name} does not exist." return ret if __opts__["test"]: - ret["comment"] = "CloudTrail {} is set to be removed.".format(Name) + ret["comment"] = f"CloudTrail {Name} is set to be removed." ret["result"] = None return ret r = __salt__["boto_cloudtrail.delete"]( @@ -411,5 +408,5 @@ def absent(name, Name, region=None, key=None, keyid=None, profile=None): return ret ret["changes"]["old"] = {"trail": Name} ret["changes"]["new"] = {"trail": None} - ret["comment"] = "CloudTrail {} deleted.".format(Name) + ret["comment"] = f"CloudTrail {Name} deleted." return ret diff --git a/salt/states/boto_cloudwatch_alarm.py b/salt/states/boto_cloudwatch_alarm.py index a3737765dff..5a931ef2ae2 100644 --- a/salt/states/boto_cloudwatch_alarm.py +++ b/salt/states/boto_cloudwatch_alarm.py @@ -52,7 +52,6 @@ as a passed in dict, or as a string to pull from pillars or minion config: - arn:aws:sns:us-east-1:1111111:myalerting-action """ - import salt.utils.data @@ -106,7 +105,7 @@ def present(name, attributes, region=None, key=None, keyid=None, profile=None): if alarm_details: for k, v in attributes.items(): if k not in alarm_details: - difference.append("{}={} (new)".format(k, v)) + difference.append(f"{k}={v} (new)") continue v = salt.utils.data.decode(v) v2 = salt.utils.data.decode(alarm_details[k]) @@ -120,7 +119,7 @@ def present(name, attributes, region=None, key=None, keyid=None, profile=None): continue if isinstance(v, list) and sorted(v) == sorted(v2): continue - difference.append("{}='{}' was: '{}'".format(k, v, v2)) + difference.append(f"{k}='{v}' was: '{v2}'") else: difference.append("new alarm") create_or_update_alarm_args = { @@ -134,10 +133,10 @@ def present(name, attributes, region=None, key=None, keyid=None, profile=None): if alarm_details: # alarm is present. update, or do nothing # check to see if attributes matches is_present. If so, do nothing. if len(difference) == 0: - ret["comment"] = "alarm {} present and matching".format(name) + ret["comment"] = f"alarm {name} present and matching" return ret if __opts__["test"]: - msg = "alarm {} is to be created/updated.".format(name) + msg = f"alarm {name} is to be created/updated." ret["comment"] = msg ret["result"] = None return ret @@ -148,10 +147,10 @@ def present(name, attributes, region=None, key=None, keyid=None, profile=None): ret["changes"]["diff"] = difference else: ret["result"] = False - ret["comment"] = "Failed to create {} alarm".format(name) + ret["comment"] = f"Failed to create {name} alarm" else: # alarm is absent. create it. if __opts__["test"]: - msg = "alarm {} is to be created/updated.".format(name) + msg = f"alarm {name} is to be created/updated." ret["comment"] = msg ret["result"] = None return ret @@ -162,7 +161,7 @@ def present(name, attributes, region=None, key=None, keyid=None, profile=None): ret["changes"]["new"] = attributes else: ret["result"] = False - ret["comment"] = "Failed to create {} alarm".format(name) + ret["comment"] = f"Failed to create {name} alarm" return ret @@ -194,7 +193,7 @@ def absent(name, region=None, key=None, keyid=None, profile=None): if is_present: if __opts__["test"]: - ret["comment"] = "alarm {} is set to be removed.".format(name) + ret["comment"] = f"alarm {name} is set to be removed." ret["result"] = None return ret deleted = __salt__["boto_cloudwatch.delete_alarm"]( @@ -205,8 +204,8 @@ def absent(name, region=None, key=None, keyid=None, profile=None): ret["changes"]["new"] = None else: ret["result"] = False - ret["comment"] = "Failed to delete {} alarm.".format(name) + ret["comment"] = f"Failed to delete {name} alarm." else: - ret["comment"] = "{} does not exist in {}.".format(name, region) + ret["comment"] = f"{name} does not exist in {region}." return ret diff --git a/salt/states/boto_cloudwatch_event.py b/salt/states/boto_cloudwatch_event.py index 4a421549bfc..1e718b374cc 100644 --- a/salt/states/boto_cloudwatch_event.py +++ b/salt/states/boto_cloudwatch_event.py @@ -51,7 +51,6 @@ config: """ - import logging import os @@ -183,7 +182,7 @@ def present( return ret ret["changes"]["old"] = {"rule": None} ret["changes"]["new"] = _describe - ret["comment"] = "CloudTrail {} created.".format(Name) + ret["comment"] = f"CloudTrail {Name} created." if bool(Targets): r = __salt__["boto_cloudwatch_event.put_targets"]( @@ -205,7 +204,7 @@ def present( return ret ret["comment"] = os.linesep.join( - [ret["comment"], "CloudWatch event rule {} is present.".format(Name)] + [ret["comment"], f"CloudWatch event rule {Name} is present."] ) ret["changes"] = {} # trail exists, ensure config matches @@ -250,7 +249,7 @@ def present( if need_update: if __opts__["test"]: - msg = "CloudWatch event rule {} set to be modified.".format(Name) + msg = f"CloudWatch event rule {Name} set to be modified." ret["comment"] = msg ret["result"] = None return ret @@ -361,11 +360,11 @@ def absent(name, Name=None, region=None, key=None, keyid=None, profile=None): return ret if r and not r["exists"]: - ret["comment"] = "CloudWatch event rule {} does not exist.".format(Name) + ret["comment"] = f"CloudWatch event rule {Name} does not exist." return ret if __opts__["test"]: - ret["comment"] = "CloudWatch event rule {} is set to be removed.".format(Name) + ret["comment"] = f"CloudWatch event rule {Name} is set to be removed." ret["result"] = None return ret @@ -406,5 +405,5 @@ def absent(name, Name=None, region=None, key=None, keyid=None, profile=None): return ret ret["changes"]["old"] = {"rule": Name} ret["changes"]["new"] = {"rule": None} - ret["comment"] = "CloudWatch event rule {} deleted.".format(Name) + ret["comment"] = f"CloudWatch event rule {Name} deleted." return ret diff --git a/salt/states/boto_cognitoidentity.py b/salt/states/boto_cognitoidentity.py index cb6905a2781..a6115f9f49a 100644 --- a/salt/states/boto_cognitoidentity.py +++ b/salt/states/boto_cognitoidentity.py @@ -45,7 +45,6 @@ config: """ - import logging log = logging.getLogger(__name__) @@ -109,7 +108,7 @@ def _role_present( IdentityPoolId=IdentityPoolId, AuthenticatedRole=AuthenticatedRole, UnauthenticatedRole=UnauthenticatedRole, - **conn_params + **conn_params, ) if not r.get("set"): ret["result"] = False @@ -234,10 +233,10 @@ def pool_present( IdentityPoolName ) else: - ret[ - "comment" - ] = "An existing identity pool named {} with id {} will be updated.".format( - IdentityPoolName, IdentityPoolId + ret["comment"] = ( + "An existing identity pool named {} with id {} will be updated.".format( + IdentityPoolName, IdentityPoolId + ) ) ret["result"] = None return ret @@ -261,10 +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 @@ -280,26 +279,26 @@ 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 if existing_identity_pool != updated_identity_pool: ret["changes"]["old"] = dict() ret["changes"]["new"] = dict() - change_key = "Identity Pool Name {}".format(IdentityPoolName) + change_key = f"Identity Pool Name {IdentityPoolName}" ret["changes"]["old"][change_key] = existing_identity_pool ret["changes"]["new"][change_key] = updated_identity_pool else: @@ -388,10 +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 @@ -413,12 +412,10 @@ def pool_absent( if not ret["changes"]: ret["changes"]["old"] = dict() ret["changes"]["new"] = dict() - change_key = "Identity Pool Id {}".format(IdentityPoolId) + change_key = f"Identity Pool Id {IdentityPoolId}" ret["changes"]["old"][change_key] = IdentityPoolName ret["changes"]["new"][change_key] = None - ret["comment"] = "{}\n{}".format( - ret["comment"], "{} deleted".format(change_key) - ) + ret["comment"] = "{}\n{}".format(ret["comment"], f"{change_key} deleted") else: ret["result"] = False failure_comment = ( diff --git a/salt/states/boto_datapipeline.py b/salt/states/boto_datapipeline.py index e42e328791e..0ed8ab42257 100644 --- a/salt/states/boto_datapipeline.py +++ b/salt/states/boto_datapipeline.py @@ -48,7 +48,6 @@ config: myDDBTableName: my-dynamo-table """ - import copy import datetime import difflib @@ -133,11 +132,11 @@ def present( profile=profile, ) if present: - ret["comment"] = "AWS data pipeline {} present".format(name) + ret["comment"] = f"AWS data pipeline {name} present" return ret if __opts__["test"]: - ret["comment"] = "Data pipeline {} is set to be created or updated".format(name) + ret["comment"] = f"Data pipeline {name} is set to be created or updated" ret["result"] = None return ret @@ -260,10 +259,10 @@ def present( if not old_pipeline_definition: ret["changes"]["new"] = "Pipeline created." - ret["comment"] = "Data pipeline {} created".format(name) + ret["comment"] = f"Data pipeline {name} created" else: ret["changes"]["diff"] = _diff(old_pipeline_definition, new_pipeline_definition) - ret["comment"] = "Data pipeline {} updated".format(name) + ret["comment"] = f"Data pipeline {name} updated" return ret @@ -596,7 +595,7 @@ def absent(name, region=None, key=None, keyid=None, profile=None): if "error" not in result_pipeline_id: pipeline_id = result_pipeline_id["result"] if __opts__["test"]: - ret["comment"] = "Data pipeline {} set to be deleted.".format(name) + ret["comment"] = f"Data pipeline {name} set to be deleted." ret["result"] = None return ret else: @@ -610,6 +609,6 @@ def absent(name, region=None, key=None, keyid=None, profile=None): ret["changes"]["old"] = {"pipeline_id": pipeline_id} ret["changes"]["new"] = None else: - ret["comment"] = "AWS data pipeline {} absent.".format(name) + ret["comment"] = f"AWS data pipeline {name} absent." return ret diff --git a/salt/states/boto_dynamodb.py b/salt/states/boto_dynamodb.py index 8e563ba0574..505f0f11a63 100644 --- a/salt/states/boto_dynamodb.py +++ b/salt/states/boto_dynamodb.py @@ -284,7 +284,7 @@ def present( if not table_exists: if __opts__["test"]: ret["result"] = None - ret["comment"] = "DynamoDB table {} would be created.".format(name) + ret["comment"] = f"DynamoDB table {name} would be created." return ret else: is_created = __salt__["boto_dynamodb.create_table"]( @@ -304,11 +304,11 @@ def present( ) if not is_created: ret["result"] = False - ret["comment"] = "Failed to create table {}".format(name) + ret["comment"] = f"Failed to create table {name}" _add_changes(ret, changes_old, changes_new) return ret - comments.append("DynamoDB table {} was successfully created".format(name)) + comments.append(f"DynamoDB table {name} was successfully created") changes_new["table"] = name changes_new["read_capacity_units"] = read_capacity_units changes_new["write_capacity_units"] = write_capacity_units @@ -319,7 +319,7 @@ def present( changes_new["local_indexes"] = local_indexes changes_new["global_indexes"] = global_indexes else: - comments.append("DynamoDB table {} exists".format(name)) + comments.append(f"DynamoDB table {name} exists") # Ensure DynamoDB table provisioned throughput matches description = __salt__["boto_dynamodb.describe"](name, region, key, keyid, profile) @@ -335,7 +335,7 @@ def present( if not throughput_matches: if __opts__["test"]: ret["result"] = None - comments.append("DynamoDB table {} is set to be updated.".format(name)) + comments.append(f"DynamoDB table {name} is set to be updated.") else: is_updated = __salt__["boto_dynamodb.update"]( name, @@ -350,17 +350,17 @@ def present( ) if not is_updated: ret["result"] = False - ret["comment"] = "Failed to update table {}".format(name) + ret["comment"] = f"Failed to update table {name}" _add_changes(ret, changes_old, changes_new) return ret - comments.append("DynamoDB table {} was successfully updated".format(name)) + comments.append(f"DynamoDB table {name} was successfully updated") changes_old["read_capacity_units"] = (current_read_capacity_units,) changes_old["write_capacity_units"] = (current_write_capacity_units,) changes_new["read_capacity_units"] = (read_capacity_units,) changes_new["write_capacity_units"] = (write_capacity_units,) else: - comments.append("DynamoDB table {} throughput matches".format(name)) + comments.append(f"DynamoDB table {name} throughput matches") provisioned_indexes = description.get("Table", {}).get("GlobalSecondaryIndexes", []) @@ -478,7 +478,7 @@ def _global_indexes_present( index_name = next(iter(entry.values())) if not index_name: ret["result"] = False - ret["comment"] = "Index name not found for table {}".format(name) + ret["comment"] = f"Index name not found for table {name}" return ret gsi_config[index_name] = index @@ -591,11 +591,11 @@ def _add_global_secondary_index( ) if success: - comments.append("Created GSI {}".format(index_name)) + comments.append(f"Created GSI {index_name}") changes_new["global_indexes"][index_name] = gsi_config[index_name] else: ret["result"] = False - ret["comment"] = "Failed to create GSI {}".format(index_name) + ret["comment"] = f"Failed to create GSI {index_name}" def _update_global_secondary_indexes( @@ -641,9 +641,7 @@ def _update_global_secondary_indexes( ) if success: - comments.append( - "Updated GSIs with new throughputs {}".format(index_updates) - ) + comments.append(f"Updated GSIs with new throughputs {index_updates}") for index_name in index_updates: changes_old["global_indexes"][index_name] = provisioned_throughputs[ index_name @@ -651,7 +649,7 @@ def _update_global_secondary_indexes( changes_new["global_indexes"][index_name] = index_updates[index_name] else: ret["result"] = False - ret["comment"] = "Failed to update GSI throughputs {}".format(index_updates) + ret["comment"] = f"Failed to update GSI throughputs {index_updates}" def _determine_gsi_updates(existing_index_names, provisioned_gsi_config, gsi_config): @@ -779,7 +777,7 @@ def _ensure_backup_datapipeline_present( ): kwargs = { - "name": "{}-{}-backup".format(name, schedule_name), + "name": f"{name}-{schedule_name}-backup", "pipeline_objects": { "DefaultSchedule": { "name": schedule_name, @@ -794,7 +792,7 @@ def _ensure_backup_datapipeline_present( }, "parameter_values": { "myDDBTableName": name, - "myOutputS3Loc": "{}/{}/".format(s3_base_location, name), + "myOutputS3Loc": f"{s3_base_location}/{name}/", }, } return __states__["boto_datapipeline.present"](**kwargs) @@ -860,20 +858,20 @@ def absent(name, region=None, key=None, keyid=None, profile=None): ret = {"name": name, "result": True, "comment": "", "changes": {}} exists = __salt__["boto_dynamodb.exists"](name, region, key, keyid, profile) if not exists: - ret["comment"] = "DynamoDB table {} does not exist".format(name) + ret["comment"] = f"DynamoDB table {name} does not exist" return ret if __opts__["test"]: - ret["comment"] = "DynamoDB table {} is set to be deleted".format(name) + ret["comment"] = f"DynamoDB table {name} is set to be deleted" ret["result"] = None return ret is_deleted = __salt__["boto_dynamodb.delete"](name, region, key, keyid, profile) if is_deleted: - ret["comment"] = "Deleted DynamoDB table {}".format(name) - ret["changes"].setdefault("old", "Table {} exists".format(name)) - ret["changes"].setdefault("new", "Table {} deleted".format(name)) + ret["comment"] = f"Deleted DynamoDB table {name}" + ret["changes"].setdefault("old", f"Table {name} exists") + ret["changes"].setdefault("new", f"Table {name} deleted") else: - ret["comment"] = "Failed to delete DynamoDB table {}".format(name) + ret["comment"] = f"Failed to delete DynamoDB table {name}" ret["result"] = False return ret diff --git a/salt/states/boto_ec2.py b/salt/states/boto_ec2.py index 773016b48a7..6e7b1d3ea06 100644 --- a/salt/states/boto_ec2.py +++ b/salt/states/boto_ec2.py @@ -50,7 +50,6 @@ The below code deletes a key pair: - key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs """ - import logging from time import sleep, time @@ -90,12 +89,12 @@ def key_present( upload_public = __salt__["cp.get_file_str"](upload_public) except OSError as e: log.debug(e) - ret["comment"] = "File {} not found.".format(upload_public) + ret["comment"] = f"File {upload_public} not found." ret["result"] = False return ret if not exists: if __opts__["test"]: - ret["comment"] = "The key {} is set to be created.".format(name) + ret["comment"] = f"The key {name} is set to be created." ret["result"] = None return ret if save_private and not upload_public: @@ -104,29 +103,29 @@ def key_present( ) if created: ret["result"] = True - ret["comment"] = "The key {} is created.".format(name) + ret["comment"] = f"The key {name} is created." ret["changes"]["new"] = created else: ret["result"] = False - ret["comment"] = "Could not create key {} ".format(name) + ret["comment"] = f"Could not create key {name} " elif not save_private and upload_public: imported = __salt__["boto_ec2.import_key"]( name, upload_public, region, key, keyid, profile ) if imported: ret["result"] = True - ret["comment"] = "The key {} is created.".format(name) + ret["comment"] = f"The key {name} is created." ret["changes"]["old"] = None ret["changes"]["new"] = imported else: ret["result"] = False - ret["comment"] = "Could not create key {} ".format(name) + ret["comment"] = f"Could not create key {name} " else: ret["result"] = False ret["comment"] = "You can either upload or download a private key " else: ret["result"] = True - ret["comment"] = "The key name {} already exists".format(name) + ret["comment"] = f"The key name {name} already exists" return ret @@ -138,21 +137,21 @@ def key_absent(name, region=None, key=None, keyid=None, profile=None): exists = __salt__["boto_ec2.get_key"](name, region, key, keyid, profile) if exists: if __opts__["test"]: - ret["comment"] = "The key {} is set to be deleted.".format(name) + ret["comment"] = f"The key {name} is set to be deleted." ret["result"] = None return ret deleted = __salt__["boto_ec2.delete_key"](name, region, key, keyid, profile) log.debug("exists is %s", deleted) if deleted: ret["result"] = True - ret["comment"] = "The key {} is deleted.".format(name) + ret["comment"] = f"The key {name} is deleted." ret["changes"]["old"] = name else: ret["result"] = False - ret["comment"] = "Could not delete key {} ".format(name) + ret["comment"] = f"Could not delete key {name} " else: ret["result"] = True - ret["comment"] = "The key name {} does not exist".format(name) + ret["comment"] = f"The key name {name} does not exist" return ret @@ -284,7 +283,7 @@ def eni_present( ) return ret r["result"] = result_create["result"] - ret["comment"] = "Created ENI {}".format(name) + ret["comment"] = f"Created ENI {name}" ret["changes"]["id"] = r["result"]["id"] else: _ret = _eni_attribute( @@ -422,7 +421,7 @@ def _eni_attribute(metadata, attr, value, region, key, keyid, profile): if metadata[attr] == value: return ret if __opts__["test"]: - ret["comment"] = "ENI set to have {} updated.".format(attr) + ret["comment"] = f"ENI set to have {attr} updated." ret["result"] = None return ret result_update = __salt__["boto_ec2.modify_network_interface_attribute"]( @@ -439,7 +438,7 @@ def _eni_attribute(metadata, attr, value, region, key, keyid, profile): ret["result"] = False ret["comment"] = msg.format(attr, result_update["error"]["message"]) else: - ret["comment"] = "Updated ENI {}.".format(attr) + ret["comment"] = f"Updated ENI {attr}." ret["changes"][attr] = {"old": metadata[attr], "new": value} return ret @@ -561,7 +560,7 @@ def eni_absent( result_delete["error"]["message"] ) return ret - ret["comment"] = "Deleted ENI {}".format(name) + ret["comment"] = f"Deleted ENI {name}" ret["changes"]["id"] = None if release_eip and "allocationId" in r["result"]: _ret = __salt__["boto_ec2.release_eip_address"]( @@ -590,7 +589,7 @@ def snapshot_created( instance_name, wait_until_available=True, wait_timeout_seconds=300, - **kwargs + **kwargs, ): """ Create a snapshot from the given instance @@ -602,11 +601,11 @@ def snapshot_created( if not __salt__["boto_ec2.create_image"]( ami_name=ami_name, instance_name=instance_name, **kwargs ): - ret["comment"] = "Failed to create new AMI {ami_name}".format(ami_name=ami_name) + ret["comment"] = f"Failed to create new AMI {ami_name}" ret["result"] = False return ret - ret["comment"] = "Created new AMI {ami_name}".format(ami_name=ami_name) + ret["comment"] = f"Created new AMI {ami_name}" ret["changes"]["new"] = {ami_name: ami_name} if not wait_until_available: return ret @@ -624,10 +623,10 @@ def snapshot_created( state=images[0].state ) else: - ret[ - "comment" - ] = "AMI with name {ami_name} not found after timeout.".format( - ami_name=ami_name + ret["comment"] = ( + "AMI with name {ami_name} not found after timeout.".format( + ami_name=ami_name + ) ) ret["result"] = False return ret @@ -888,7 +887,7 @@ def instance_present( if _create: if __opts__["test"]: - ret["comment"] = "The instance {} is set to be created.".format(name) + ret["comment"] = f"The instance {name} is set to be created." ret["result"] = None return ret if image_name: @@ -1007,15 +1006,15 @@ 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: if __opts__["test"]: - ret["comment"] = "Instance {} to be updated.".format(name) + ret["comment"] = f"Instance {name} to be updated." ret["result"] = None return ret r = __salt__["boto_ec2.associate_eip_address"]( @@ -1070,10 +1069,10 @@ def instance_present( ) except SaltInvocationError as e: ret["result"] = False - ret[ - "comment" - ] = "Failed to set attribute {} to {} on instance {}.".format( - k, v, instance_name + ret["comment"] = ( + "Failed to set attribute {} to {} on instance {}.".format( + k, v, instance_name + ) ) return ret ret["changes"] = ( @@ -1248,7 +1247,7 @@ def instance_absent( ) if not instances: ret["result"] = True - ret["comment"] = "Instance {} is already gone.".format(instance_id) + ret["comment"] = f"Instance {instance_id} is already gone." return ret instance = instances[0] @@ -1269,7 +1268,7 @@ def instance_absent( return ret if __opts__["test"]: - ret["comment"] = "The instance {} is set to be deleted.".format(name) + ret["comment"] = f"The instance {name} is set to be deleted." ret["result"] = None return ret @@ -1283,7 +1282,7 @@ def instance_absent( ) if not r: ret["result"] = False - ret["comment"] = "Failed to terminate instance {}.".format(instance_id) + ret["comment"] = f"Failed to terminate instance {instance_id}." return ret ret["changes"]["old"] = {"instance_id": instance_id} @@ -1309,9 +1308,7 @@ def instance_absent( else: # I /believe/ this situation is impossible but let's hedge our bets... ret["result"] = False - ret[ - "comment" - ] = "Can't determine AllocationId for address {}.".format(ip) + ret["comment"] = f"Can't determine AllocationId for address {ip}." return ret else: public_ip = instance.ip_address @@ -1330,7 +1327,7 @@ def instance_absent( ret["changes"]["old"]["public_ip"] = public_ip or r[0]["public_ip"] else: ret["result"] = False - ret["comment"] = "Failed to release EIP {}.".format(ip) + ret["comment"] = f"Failed to release EIP {ip}." return ret return ret @@ -1450,14 +1447,14 @@ def volume_absent( log.info("Matched Volume ID %s", vol) if __opts__["test"]: - ret["comment"] = "The volume {} is set to be deleted.".format(vol) + ret["comment"] = f"The volume {vol} is set to be deleted." ret["result"] = None return ret if __salt__["boto_ec2.delete_volume"](volume_id=vol, force=True, **args): - ret["comment"] = "Volume {} deleted.".format(vol) + ret["comment"] = f"Volume {vol} deleted." ret["changes"] = {"old": {"volume_id": vol}, "new": {"volume_id": None}} else: - ret["comment"] = "Error deleting volume {}.".format(vol) + ret["comment"] = f"Error deleting volume {vol}." ret["result"] = False return ret @@ -1665,9 +1662,7 @@ def volume_present( name=instance_name, in_states=running_states, **args ) if not instance_id: - raise SaltInvocationError( - "Instance with Name {} not found.".format(instance_name) - ) + raise SaltInvocationError(f"Instance with Name {instance_name} not found.") instances = __salt__["boto_ec2.find_instances"]( instance_id=instance_id, return_objs=True, **args @@ -1700,13 +1695,13 @@ def volume_present( encrypted=encrypted, kms_key_id=kms_key_id, wait_for_creation=True, - **args + **args, ) if "result" in _rt: volume_id = _rt["result"] else: raise SaltInvocationError( - "Error creating volume with name {}.".format(volume_name) + f"Error creating volume with name {volume_name}." ) _rt = __salt__["boto_ec2.set_volumes_tags"]( tag_maps=[ @@ -1715,7 +1710,7 @@ def volume_present( "tags": {"Name": volume_name}, } ], - **args + **args, ) if _rt["success"] is False: raise SaltInvocationError( @@ -1731,7 +1726,7 @@ def volume_present( volume_ids=[volume_id], return_objs=True, **args ) if len(vols) < 1: - raise SaltInvocationError("Volume {} do not exist".format(volume_id)) + raise SaltInvocationError(f"Volume {volume_id} do not exist") vol = vols[0] if vol.zone != instance.placement: raise SaltInvocationError( @@ -1748,14 +1743,14 @@ def volume_present( return ret else: if __opts__["test"]: - ret[ - "comment" - ] = "The volume {} is set to be detached from {}({} and attached on {}({}).".format( - attach_data.instance_id, - attach_data.devic, - volume_id, - instance_id, - device, + ret["comment"] = ( + "The volume {} is set to be detached from {}({} and attached on {}({}).".format( + attach_data.instance_id, + attach_data.devic, + volume_id, + instance_id, + device, + ) ) ret["result"] = None return ret @@ -1956,7 +1951,6 @@ def private_ips_absent( keyid=None, profile=None, ): - """ Ensure an ENI does not have secondary private ip addresses associated with it diff --git a/salt/states/boto_elasticache.py b/salt/states/boto_elasticache.py index f46b2f7a1b4..b5520bfc7da 100644 --- a/salt/states/boto_elasticache.py +++ b/salt/states/boto_elasticache.py @@ -75,7 +75,6 @@ passed in as a dict, or as a string to pull from pillars or minion config: key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs """ - import logging log = logging.getLogger(__name__) @@ -227,7 +226,7 @@ def present( return ret elif not config: if __opts__["test"]: - msg = "Cache cluster {} is set to be created.".format(name) + msg = f"Cache cluster {name} is set to be created." ret["comment"] = msg ret["result"] = None return ret @@ -261,11 +260,11 @@ def present( ret["changes"]["new"] = config else: ret["result"] = False - ret["comment"] = "Failed to create {} cache cluster.".format(name) + ret["comment"] = f"Failed to create {name} cache cluster." return ret # TODO: support modification of existing elasticache clusters else: - ret["comment"] = "Cache cluster {} is present.".format(name) + ret["comment"] = f"Cache cluster {name} is present." return ret @@ -320,7 +319,7 @@ def subnet_group_present( ) if not exists: if __opts__["test"]: - ret["comment"] = "Subnet group {} is set to be created.".format(name) + ret["comment"] = f"Subnet group {name} is set to be created." ret["result"] = None return ret created = __salt__["boto_elasticache.create_subnet_group"]( @@ -336,11 +335,11 @@ def subnet_group_present( ) if not created: ret["result"] = False - ret["comment"] = "Failed to create {} subnet group.".format(name) + ret["comment"] = f"Failed to create {name} subnet group." return ret ret["changes"]["old"] = None ret["changes"]["new"] = name - ret["comment"] = "Subnet group {} created.".format(name) + ret["comment"] = f"Subnet group {name} created." return ret ret["comment"] = "Subnet group present." return ret @@ -380,7 +379,7 @@ def absent(name, wait=True, region=None, key=None, keyid=None, profile=None): if is_present: if __opts__["test"]: - ret["comment"] = "Cache cluster {} is set to be removed.".format(name) + ret["comment"] = f"Cache cluster {name} is set to be removed." ret["result"] = None return ret deleted = __salt__["boto_elasticache.delete"]( @@ -391,9 +390,9 @@ def absent(name, wait=True, region=None, key=None, keyid=None, profile=None): ret["changes"]["new"] = None else: ret["result"] = False - ret["comment"] = "Failed to delete {} cache cluster.".format(name) + ret["comment"] = f"Failed to delete {name} cache cluster." else: - ret["comment"] = "{} does not exist in {}.".format(name, region) + ret["comment"] = f"{name} does not exist in {region}." return ret @@ -445,7 +444,7 @@ def creategroup( ) if not is_present: if __opts__["test"]: - ret["comment"] = "Replication {} is set to be created.".format(name) + ret["comment"] = f"Replication {name} is set to be created." ret["result"] = None created = __salt__["boto_elasticache.create_replication_group"]( name, @@ -466,9 +465,9 @@ def creategroup( ret["result"] = True else: ret["result"] = False - ret["comment"] = "Failed to create {} replication group.".format(name) + ret["comment"] = f"Failed to create {name} replication group." else: - ret["comment"] = "{} replication group exists .".format(name) + ret["comment"] = f"{name} replication group exists ." ret["result"] = True return ret @@ -483,7 +482,7 @@ def subnet_group_absent( ) if not exists: ret["result"] = True - ret["comment"] = "{} ElastiCache subnet group does not exist.".format(name) + ret["comment"] = f"{name} ElastiCache subnet group does not exist." return ret if __opts__["test"]: @@ -497,11 +496,11 @@ def subnet_group_absent( ) if not deleted: ret["result"] = False - ret["comment"] = "Failed to delete {} ElastiCache subnet group.".format(name) + ret["comment"] = f"Failed to delete {name} ElastiCache subnet group." return ret ret["changes"]["old"] = name ret["changes"]["new"] = None - ret["comment"] = "ElastiCache subnet group {} deleted.".format(name) + ret["comment"] = f"ElastiCache subnet group {name} deleted." return ret @@ -515,14 +514,12 @@ def replication_group_absent( ) if not exists: ret["result"] = True - ret["comment"] = "{} ElastiCache replication group does not exist.".format(name) + ret["comment"] = f"{name} ElastiCache replication group does not exist." log.info(ret["comment"]) return ret if __opts__["test"]: - ret[ - "comment" - ] = "ElastiCache replication group {} is set to be removed.".format(name) + ret["comment"] = f"ElastiCache replication group {name} is set to be removed." ret["result"] = True return ret deleted = __salt__["boto_elasticache.delete_replication_group"]( @@ -537,6 +534,6 @@ def replication_group_absent( return ret ret["changes"]["old"] = name ret["changes"]["new"] = None - ret["comment"] = "ElastiCache replication group {} deleted.".format(name) + ret["comment"] = f"ElastiCache replication group {name} deleted." log.info(ret["comment"]) return ret diff --git a/salt/states/boto_elasticsearch_domain.py b/salt/states/boto_elasticsearch_domain.py index 4c47222b560..e682c463257 100644 --- a/salt/states/boto_elasticsearch_domain.py +++ b/salt/states/boto_elasticsearch_domain.py @@ -77,7 +77,6 @@ config: """ - import logging import os @@ -222,7 +221,7 @@ def present( AccessPolicies = salt.utils.json.loads(AccessPolicies) except ValueError as e: ret["result"] = False - ret["comment"] = "Failed to create domain: {}.".format(e.message) + ret["comment"] = f"Failed to create domain: {e.message}." return ret r = __salt__["boto_elasticsearch_domain.exists"]( DomainName=DomainName, region=region, key=key, keyid=keyid, profile=profile @@ -235,7 +234,7 @@ def present( if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "Domain {} is set to be created.".format(DomainName) + ret["comment"] = f"Domain {DomainName} is set to be created." ret["result"] = None return ret r = __salt__["boto_elasticsearch_domain.create"]( @@ -262,11 +261,11 @@ def present( ) ret["changes"]["old"] = {"domain": None} ret["changes"]["new"] = _describe - ret["comment"] = "Domain {} created.".format(DomainName) + ret["comment"] = f"Domain {DomainName} created." return ret ret["comment"] = os.linesep.join( - [ret["comment"], "Domain {} is present.".format(DomainName)] + [ret["comment"], f"Domain {DomainName} is present."] ) ret["changes"] = {} # domain exists, ensure config matches @@ -275,11 +274,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"]( @@ -311,7 +310,7 @@ def present( ret["changes"].setdefault("old", {})[k] = _describe[k] if need_update: if __opts__["test"]: - msg = "Domain {} set to be modified.".format(DomainName) + msg = f"Domain {DomainName} set to be modified." ret["comment"] = msg ret["result"] = None return ret @@ -324,7 +323,7 @@ def present( key=key, keyid=keyid, profile=profile, - **comm_args + **comm_args, ) if not r.get("updated"): ret["result"] = False @@ -369,11 +368,11 @@ def absent(name, DomainName, region=None, key=None, keyid=None, profile=None): return ret if r and not r["exists"]: - ret["comment"] = "Domain {} does not exist.".format(DomainName) + ret["comment"] = f"Domain {DomainName} does not exist." return ret if __opts__["test"]: - ret["comment"] = "Domain {} is set to be removed.".format(DomainName) + ret["comment"] = f"Domain {DomainName} is set to be removed." ret["result"] = None return ret @@ -386,5 +385,5 @@ def absent(name, DomainName, region=None, key=None, keyid=None, profile=None): return ret ret["changes"]["old"] = {"domain": DomainName} ret["changes"]["new"] = {"domain": None} - ret["comment"] = "Domain {} deleted.".format(DomainName) + ret["comment"] = f"Domain {DomainName} deleted." return ret diff --git a/salt/states/boto_elb.py b/salt/states/boto_elb.py index 0fd59a31088..7499f9c1008 100644 --- a/salt/states/boto_elb.py +++ b/salt/states/boto_elb.py @@ -234,7 +234,6 @@ Tags can also be set: OtherTag: 'My Other Value' """ - import hashlib import logging import re @@ -549,7 +548,7 @@ def present( if __salt__["boto_elb.set_instances"]( name, instance_ids, True, region, key, keyid, profile ): - ret["comment"] += " ELB {} instances would be updated.".format(name) + ret["comment"] += f" ELB {name} instances would be updated." ret["result"] = None else: success = __salt__["boto_elb.set_instances"]( @@ -592,7 +591,7 @@ def register_instances( ret = {"name": name, "result": True, "comment": "", "changes": {}} lb = __salt__["boto_elb.exists"](name, region, key, keyid, profile) if not lb: - msg = "Could not find lb {}".format(name) + msg = f"Could not find lb {name}" log.error(msg) ret.update({"comment": msg, "result": False}) return ret @@ -611,7 +610,7 @@ def register_instances( return ret if __opts__["test"]: - ret["comment"] = "ELB {} is set to register : {}.".format(name, new) + ret["comment"] = f"ELB {name} is set to register : {new}." ret["result"] = None return ret @@ -619,7 +618,7 @@ def register_instances( name, instances, region, key, keyid, profile ) if state: - msg = "Load Balancer {} has been changed".format(name) + msg = f"Load Balancer {name} has been changed" log.info(msg) new = set().union(nodes, instances) ret.update( @@ -629,7 +628,7 @@ def register_instances( } ) else: - msg = "Load balancer {} failed to add instances".format(name) + msg = f"Load balancer {name} failed to add instances" log.error(msg) ret.update({"comment": msg, "result": False}) return ret @@ -706,7 +705,7 @@ def _elb_present( ret["result"] = False return ret if "id" not in r: - ret["comment"] = "Subnet {} does not exist.".format(i) + ret["comment"] = f"Subnet {i} does not exist." ret["result"] = False return ret subnets.append(r["id"]) @@ -718,7 +717,7 @@ def _elb_present( ) vpc_id = vpc_id.get("vpc_id") if not vpc_id: - ret["comment"] = "Subnets {} do not map to a valid vpc id.".format(subnets) + ret["comment"] = f"Subnets {subnets} do not map to a valid vpc id." ret["result"] = False return ret _security_groups = __salt__["boto_secgroup.convert_to_group_ids"]( @@ -730,17 +729,17 @@ def _elb_present( profile=profile, ) if not _security_groups: - ret[ - "comment" - ] = "Security groups {} do not map to valid security group ids.".format( - security_groups + ret["comment"] = ( + "Security groups {} do not map to valid security group ids.".format( + security_groups + ) ) ret["result"] = False return ret exists = __salt__["boto_elb.exists"](name, region, key, keyid, profile) if not exists: if __opts__["test"]: - ret["comment"] = "ELB {} is set to be created.".format(name) + ret["comment"] = f"ELB {name} is set to be created." ret["result"] = None return ret created = __salt__["boto_elb.create"]( @@ -758,12 +757,12 @@ def _elb_present( if created: ret["changes"]["old"] = {"elb": None} ret["changes"]["new"] = {"elb": name} - ret["comment"] = "ELB {} created.".format(name) + ret["comment"] = f"ELB {name} created." else: ret["result"] = False - ret["comment"] = "Failed to create {} ELB.".format(name) + ret["comment"] = f"Failed to create {name} ELB." else: - ret["comment"] = "ELB {} present.".format(name) + ret["comment"] = f"ELB {name} present." _ret = _security_groups_present( name, _security_groups, region, key, keyid, profile ) @@ -805,7 +804,7 @@ def _listeners_present(name, listeners, region, key, keyid, profile): ret = {"result": True, "comment": "", "changes": {}} lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile) if not lb: - ret["comment"] = "{} ELB configuration could not be retrieved.".format(name) + ret["comment"] = f"{name} ELB configuration could not be retrieved." ret["result"] = False return ret if not listeners: @@ -833,7 +832,7 @@ def _listeners_present(name, listeners, region, key, keyid, profile): if __opts__["test"]: msg = [] if to_create or to_delete: - msg.append("ELB {} set to have listeners modified:".format(name)) + msg.append(f"ELB {name} set to have listeners modified:") for listener in to_create: msg.append( "Listener {} added.".format( @@ -848,7 +847,7 @@ def _listeners_present(name, listeners, region, key, keyid, profile): ) ret["result"] = None else: - msg.append("Listeners already set on ELB {}.".format(name)) + msg.append(f"Listeners already set on ELB {name}.") ret["comment"] = " ".join(msg) return ret @@ -858,9 +857,9 @@ def _listeners_present(name, listeners, region, key, keyid, profile): name, ports, region, key, keyid, profile ) if deleted: - ret["comment"] = "Deleted listeners on {} ELB.".format(name) + ret["comment"] = f"Deleted listeners on {name} ELB." else: - ret["comment"] = "Failed to delete listeners on {} ELB.".format(name) + ret["comment"] = f"Failed to delete listeners on {name} ELB." ret["result"] = False if to_create: @@ -881,7 +880,7 @@ def _listeners_present(name, listeners, region, key, keyid, profile): lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile) ret["changes"]["listeners"]["new"] = lb["listeners"] else: - ret["comment"] = "Listeners already set on ELB {}.".format(name) + ret["comment"] = f"Listeners already set on ELB {name}." return ret @@ -890,7 +889,7 @@ def _security_groups_present(name, security_groups, region, key, keyid, profile) ret = {"result": True, "comment": "", "changes": {}} lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile) if not lb: - ret["comment"] = "{} ELB configuration could not be retrieved.".format(name) + ret["comment"] = f"{name} ELB configuration could not be retrieved." ret["result"] = False return ret if not security_groups: @@ -900,21 +899,21 @@ def _security_groups_present(name, security_groups, region, key, keyid, profile) change_needed = True if change_needed: if __opts__["test"]: - ret["comment"] = "ELB {} set to have security groups modified.".format(name) + ret["comment"] = f"ELB {name} set to have security groups modified." ret["result"] = None return ret changed = __salt__["boto_elb.apply_security_groups"]( name, security_groups, region, key, keyid, profile ) if changed: - ret["comment"] = "Modified security_groups on {} ELB.".format(name) + ret["comment"] = f"Modified security_groups on {name} ELB." else: - ret["comment"] = "Failed to modify security_groups on {} ELB.".format(name) + ret["comment"] = f"Failed to modify security_groups on {name} ELB." ret["result"] = False ret["changes"]["old"] = {"security_groups": lb["security_groups"]} ret["changes"]["new"] = {"security_groups": security_groups} else: - ret["comment"] = "security_groups already set on ELB {}.".format(name) + ret["comment"] = f"security_groups already set on ELB {name}." return ret @@ -923,7 +922,7 @@ def _attributes_present(name, attributes, region, key, keyid, profile): _attributes = __salt__["boto_elb.get_attributes"](name, region, key, keyid, profile) if not _attributes: ret["result"] = False - ret["comment"] = "Failed to retrieve attributes for ELB {}.".format(name) + ret["comment"] = f"Failed to retrieve attributes for ELB {name}." return ret attrs_to_set = [] if "cross_zone_load_balancing" in attributes: @@ -955,7 +954,7 @@ def _attributes_present(name, attributes, region, key, keyid, profile): ) if attrs_to_set: if __opts__["test"]: - ret["comment"] = "ELB {} set to have attributes set.".format(name) + ret["comment"] = f"ELB {name} set to have attributes set." ret["result"] = None return ret was_set = __salt__["boto_elb.set_attributes"]( @@ -964,12 +963,12 @@ def _attributes_present(name, attributes, region, key, keyid, profile): if was_set: ret["changes"]["old"] = {"attributes": _attributes} ret["changes"]["new"] = {"attributes": attributes} - ret["comment"] = "Set attributes on ELB {}.".format(name) + ret["comment"] = f"Set attributes on ELB {name}." else: ret["result"] = False - ret["comment"] = "Failed to set attributes on ELB {}.".format(name) + ret["comment"] = f"Failed to set attributes on ELB {name}." else: - ret["comment"] = "Attributes already set on ELB {}.".format(name) + ret["comment"] = f"Attributes already set on ELB {name}." return ret @@ -982,7 +981,7 @@ def _health_check_present(name, health_check, region, key, keyid, profile): ) if not _health_check: ret["result"] = False - ret["comment"] = "Failed to retrieve health_check for ELB {}.".format(name) + ret["comment"] = f"Failed to retrieve health_check for ELB {name}." return ret need_to_set = False for attr, val in health_check.items(): @@ -990,7 +989,7 @@ def _health_check_present(name, health_check, region, key, keyid, profile): need_to_set = True if need_to_set: if __opts__["test"]: - ret["comment"] = "ELB {} set to have health check set.".format(name) + ret["comment"] = f"ELB {name} set to have health check set." ret["result"] = None return ret was_set = __salt__["boto_elb.set_health_check"]( @@ -1002,12 +1001,12 @@ def _health_check_present(name, health_check, region, key, keyid, profile): name, region, key, keyid, profile ) ret["changes"]["new"] = {"health_check": _health_check} - ret["comment"] = "Set health check on ELB {}.".format(name) + ret["comment"] = f"Set health check on ELB {name}." else: ret["result"] = False - ret["comment"] = "Failed to set health check on ELB {}.".format(name) + ret["comment"] = f"Failed to set health check on ELB {name}." else: - ret["comment"] = "Health check already set on ELB {}.".format(name) + ret["comment"] = f"Health check already set on ELB {name}." return ret @@ -1016,7 +1015,7 @@ def _zones_present(name, availability_zones, region, key, keyid, profile): lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile) if not lb: ret["result"] = False - ret["comment"] = "Failed to retrieve ELB {}.".format(name) + ret["comment"] = f"Failed to retrieve ELB {name}." return ret to_enable = [] to_disable = [] @@ -1029,7 +1028,7 @@ def _zones_present(name, availability_zones, region, key, keyid, profile): to_disable.append(zone) if to_enable or to_disable: if __opts__["test"]: - ret["comment"] = "ELB {} to have availability zones set.".format(name) + ret["comment"] = f"ELB {name} to have availability zones set." ret["result"] = None return ret if to_enable: @@ -1037,11 +1036,9 @@ def _zones_present(name, availability_zones, region, key, keyid, profile): name, to_enable, region, key, keyid, profile ) if enabled: - ret["comment"] = "Enabled availability zones on {} ELB.".format(name) + ret["comment"] = f"Enabled availability zones on {name} ELB." else: - ret[ - "comment" - ] = "Failed to enable availability zones on {} ELB.".format(name) + ret["comment"] = f"Failed to enable availability zones on {name} ELB." ret["result"] = False if to_disable: disabled = __salt__["boto_elb.disable_availability_zones"]( @@ -1058,7 +1055,7 @@ def _zones_present(name, availability_zones, region, key, keyid, profile): lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile) ret["changes"]["new"] = {"availability_zones": lb["availability_zones"]} else: - ret["comment"] = "Availability zones already set on ELB {}.".format(name) + ret["comment"] = f"Availability zones already set on ELB {name}." return ret @@ -1069,7 +1066,7 @@ def _subnets_present(name, subnets, region, key, keyid, profile): lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile) if not lb: ret["result"] = False - ret["comment"] = "Failed to retrieve ELB {}.".format(name) + ret["comment"] = f"Failed to retrieve ELB {name}." return ret to_enable = [] to_disable = [] @@ -1082,7 +1079,7 @@ def _subnets_present(name, subnets, region, key, keyid, profile): to_disable.append(subnet) if to_enable or to_disable: if __opts__["test"]: - ret["comment"] = "ELB {} to have subnets set.".format(name) + ret["comment"] = f"ELB {name} to have subnets set." ret["result"] = None return ret if to_enable: @@ -1090,9 +1087,9 @@ def _subnets_present(name, subnets, region, key, keyid, profile): name, to_enable, region, key, keyid, profile ) if attached: - ret["comment"] = "Attached subnets on {} ELB.".format(name) + ret["comment"] = f"Attached subnets on {name} ELB." else: - ret["comment"] = "Failed to attach subnets on {} ELB.".format(name) + ret["comment"] = f"Failed to attach subnets on {name} ELB." ret["result"] = False if to_disable: detached = __salt__["boto_elb.detach_subnets"]( @@ -1100,13 +1097,13 @@ def _subnets_present(name, subnets, region, key, keyid, profile): ) if detached: ret["comment"] = " ".join( - [ret["comment"], "Detached subnets on {} ELB.".format(name)] + [ret["comment"], f"Detached subnets on {name} ELB."] ) else: ret["comment"] = " ".join( [ ret["comment"], - "Failed to detach subnets on {} ELB.".format(name), + f"Failed to detach subnets on {name} ELB.", ] ) ret["result"] = False @@ -1114,7 +1111,7 @@ def _subnets_present(name, subnets, region, key, keyid, profile): lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile) ret["changes"]["new"] = {"subnets": lb["subnets"]} else: - ret["comment"] = "Subnets already set on ELB {}.".format(name) + ret["comment"] = f"Subnets already set on ELB {name}." return ret @@ -1210,7 +1207,7 @@ def _policies_present( lb = __salt__["boto_elb.get_elb_config"](name, region, key, keyid, profile) if not lb: - ret["comment"] = "{} ELB configuration could not be retrieved.".format(name) + ret["comment"] = f"{name} ELB configuration could not be retrieved." ret["result"] = False return ret @@ -1296,18 +1293,18 @@ def _policies_present( if __opts__["test"]: msg = [] if to_create or to_delete: - msg.append("ELB {} set to have policies modified:".format(name)) + msg.append(f"ELB {name} set to have policies modified:") for policy in to_create: - msg.append("Policy {} added.".format(policy)) + msg.append(f"Policy {policy} added.") for policy in to_delete: - msg.append("Policy {} deleted.".format(policy)) + msg.append(f"Policy {policy} deleted.") ret["result"] = None else: - msg.append("Policies already set on ELB {}.".format(name)) + msg.append(f"Policies already set on ELB {name}.") for listener in listeners_to_update: - msg.append("Listener {} policies updated.".format(listener)) + msg.append(f"Listener {listener} policies updated.") for backend in backends_to_update: - msg.append("Backend {} policies updated.".format(backend)) + msg.append(f"Backend {backend} policies updated.") ret["comment"] = " ".join(msg) return ret @@ -1325,7 +1322,7 @@ def _policies_present( ) if created: ret["changes"].setdefault(policy_name, {})["new"] = policy_name - comment = "Policy {} was created on ELB {}".format(policy_name, name) + comment = f"Policy {policy_name} was created on ELB {name}" ret["comment"] = " ".join([ret["comment"], comment]) ret["result"] = True else: @@ -1343,7 +1340,7 @@ def _policies_present( profile=profile, ) if policy_set: - policy_key = "listener_{}_policy".format(port) + policy_key = f"listener_{port}_policy" ret["changes"][policy_key] = { "old": list(actual_policies_by_listener.get(port, [])), "new": list(expected_policies_by_listener.get(port, [])), @@ -1368,7 +1365,7 @@ def _policies_present( profile=profile, ) if policy_set: - policy_key = "backend_{}_policy".format(port) + policy_key = f"backend_{port}_policy" ret["changes"][policy_key] = { "old": list(actual_policies_by_backend.get(port, [])), "new": list(expected_policies_by_backend.get(port, [])), @@ -1394,7 +1391,7 @@ def _policies_present( ) if deleted: ret["changes"].setdefault(policy_name, {})["old"] = policy_name - comment = "Policy {} was deleted from ELB {}".format(policy_name, name) + comment = f"Policy {policy_name} was deleted from ELB {name}" ret["comment"] = " ".join([ret["comment"], comment]) ret["result"] = True else: @@ -1413,7 +1410,7 @@ def _policy_cname(policy_dict): ).hexdigest() if policy_type.endswith("Type"): policy_type = policy_type[:-4] - return "{}-{}-{}".format(policy_type, policy_name, policy_hash) + return f"{policy_type}-{policy_name}-{policy_hash}" def absent(name, region=None, key=None, keyid=None, profile=None): @@ -1428,19 +1425,19 @@ def absent(name, region=None, key=None, keyid=None, profile=None): exists = __salt__["boto_elb.exists"](name, region, key, keyid, profile) if exists: if __opts__["test"]: - ret["comment"] = "ELB {} is set to be removed.".format(name) + ret["comment"] = f"ELB {name} is set to be removed." ret["result"] = None return ret deleted = __salt__["boto_elb.delete"](name, region, key, keyid, profile) if deleted: ret["changes"]["old"] = {"elb": name} ret["changes"]["new"] = {"elb": None} - ret["comment"] = "ELB {} deleted.".format(name) + ret["comment"] = f"ELB {name} deleted." else: ret["result"] = False - ret["comment"] = "Failed to delete {} ELB.".format(name) + ret["comment"] = f"Failed to delete {name} ELB." else: - ret["comment"] = "{} ELB does not exist.".format(name) + ret["comment"] = f"{name} ELB does not exist." return ret @@ -1478,7 +1475,7 @@ def _tags_present(name, tags, region, key, keyid, profile): ) if not _ret: ret["result"] = False - msg = "Error attempting to delete tag {}.".format(tags_to_remove) + msg = f"Error attempting to delete tag {tags_to_remove}." ret["comment"] = " ".join([ret["comment"], msg]) return ret if "old" not in ret["changes"]: diff --git a/salt/states/boto_elbv2.py b/salt/states/boto_elbv2.py index b3c2fe2a2e0..480d5b3b04a 100644 --- a/salt/states/boto_elbv2.py +++ b/salt/states/boto_elbv2.py @@ -64,9 +64,8 @@ def create_target_group( health_check_timeout_seconds=5, healthy_threshold_count=5, unhealthy_threshold_count=2, - **kwargs + **kwargs, ): - """ .. versionadded:: 2017.11.0 @@ -122,11 +121,11 @@ def create_target_group( if __salt__["boto_elbv2.target_group_exists"](name, region, key, keyid, profile): ret["result"] = True - ret["comment"] = "Target Group {} already exists".format(name) + ret["comment"] = f"Target Group {name} already exists" return ret if __opts__["test"]: - ret["comment"] = "Target Group {} will be created".format(name) + ret["comment"] = f"Target Group {name} will be created" return ret state = __salt__["boto_elbv2.create_target_group"]( @@ -145,16 +144,16 @@ def create_target_group( health_check_timeout_seconds=health_check_timeout_seconds, healthy_threshold_count=healthy_threshold_count, unhealthy_threshold_count=unhealthy_threshold_count, - **kwargs + **kwargs, ) if state: ret["changes"]["target_group"] = name ret["result"] = True - ret["comment"] = "Target Group {} created".format(name) + ret["comment"] = f"Target Group {name} created" else: ret["result"] = False - ret["comment"] = "Target Group {} creation failed".format(name) + ret["comment"] = f"Target Group {name} creation failed" return ret @@ -185,11 +184,11 @@ def delete_target_group(name, region=None, key=None, keyid=None, profile=None): name, region, key, keyid, profile ): ret["result"] = True - ret["comment"] = "Target Group {} does not exists".format(name) + ret["comment"] = f"Target Group {name} does not exists" return ret if __opts__["test"]: - ret["comment"] = "Target Group {} will be deleted".format(name) + ret["comment"] = f"Target Group {name} will be deleted" return ret state = __salt__["boto_elbv2.delete_target_group"]( @@ -199,10 +198,10 @@ def delete_target_group(name, region=None, key=None, keyid=None, profile=None): if state: ret["result"] = True ret["changes"]["target_group"] = name - ret["comment"] = "Target Group {} deleted".format(name) + ret["comment"] = f"Target Group {name} deleted" else: ret["result"] = False - ret["comment"] = "Target Group {} deletion failed".format(name) + ret["comment"] = f"Target Group {name} deletion failed" return ret @@ -277,18 +276,18 @@ def targets_registered( if changes: ret["changes"]["old"] = health if __opts__["test"]: - ret["comment"] = "Target Group {} would be changed".format(name) + ret["comment"] = f"Target Group {name} would be changed" ret["result"] = None ret["changes"]["new"] = newhealth_mock else: - ret["comment"] = "Target Group {} has been changed".format(name) + ret["comment"] = f"Target Group {name} has been changed" newhealth = __salt__["boto_elbv2.describe_target_health"]( name, region=region, key=key, keyid=keyid, profile=profile ) ret["changes"]["new"] = newhealth return ret else: - ret["comment"] = "Could not find target group {}".format(name) + ret["comment"] = f"Could not find target group {name}" return ret @@ -327,9 +326,9 @@ def targets_deregistered( targets = [targets] for target in targets: if target not in health or health.get(target) == "draining": - ret["comment"] = ret[ - "comment" - ] + "Target/s {} already deregistered\n".format(target) + ret["comment"] = ( + ret["comment"] + f"Target/s {target} already deregistered\n" + ) ret["result"] = True else: if __opts__["test"]: @@ -348,25 +347,23 @@ def targets_deregistered( changes = True ret["result"] = True else: - ret[ - "comment" - ] = "Target Group {} failed to remove targets".format(name) + ret["comment"] = f"Target Group {name} failed to remove targets" failure = True if failure: ret["result"] = False if changes: ret["changes"]["old"] = health if __opts__["test"]: - ret["comment"] = "Target Group {} would be changed".format(name) + ret["comment"] = f"Target Group {name} would be changed" ret["result"] = None ret["changes"]["new"] = newhealth_mock else: - ret["comment"] = "Target Group {} has been changed".format(name) + ret["comment"] = f"Target Group {name} has been changed" newhealth = __salt__["boto_elbv2.describe_target_health"]( name, region=region, key=key, keyid=keyid, profile=profile ) ret["changes"]["new"] = newhealth return ret else: - ret["comment"] = "Could not find target group {}".format(name) + ret["comment"] = f"Could not find target group {name}" return ret diff --git a/salt/states/boto_iam.py b/salt/states/boto_iam.py index 93400521fce..d89573cf5ae 100644 --- a/salt/states/boto_iam.py +++ b/salt/states/boto_iam.py @@ -155,7 +155,7 @@ def __virtual__(): else: return ( False, - "Cannot load {} state: boto_iam module unavailable".format(__virtualname__), + f"Cannot load {__virtualname__} state: boto_iam module unavailable", ) @@ -207,7 +207,7 @@ def user_absent( ret = {"name": name, "result": True, "comment": "", "changes": {}} if not __salt__["boto_iam.get_user"](name, region, key, keyid, profile): ret["result"] = True - ret["comment"] = "IAM User {} does not exist.".format(name) + ret["comment"] = f"IAM User {name} does not exist." return ret # delete the user's access keys if delete_keys: @@ -297,7 +297,7 @@ def user_absent( ret["comment"] = " ".join( [ ret["comment"], - "Virtual MFA device {} is deleted.".format(serial), + f"Virtual MFA device {serial} is deleted.", ] ) # delete the user's login profile @@ -306,7 +306,7 @@ def user_absent( ret["comment"] = " ".join( [ ret["comment"], - "IAM user {} login profile is set to be deleted.".format(name), + f"IAM user {name} login profile is set to be deleted.", ] ) ret["result"] = None @@ -318,14 +318,14 @@ def user_absent( ret["comment"] = " ".join( [ ret["comment"], - "IAM user {} login profile is deleted.".format(name), + f"IAM user {name} login profile is deleted.", ] ) if __opts__["test"]: ret["comment"] = " ".join( [ ret["comment"], - "IAM user {} managed policies are set to be detached.".format(name), + f"IAM user {name} managed policies are set to be detached.", ] ) ret["result"] = None @@ -340,7 +340,7 @@ def user_absent( ret["comment"] = " ".join( [ ret["comment"], - "IAM user {} inline policies are set to be deleted.".format(name), + f"IAM user {name} inline policies are set to be deleted.", ] ) ret["result"] = None @@ -354,19 +354,17 @@ def user_absent( # finally, actually delete the user if __opts__["test"]: ret["comment"] = " ".join( - [ret["comment"], "IAM user {} is set to be deleted.".format(name)] + [ret["comment"], f"IAM user {name} is set to be deleted."] ) ret["result"] = None return ret deleted = __salt__["boto_iam.delete_user"](name, region, key, keyid, profile) if deleted is True: - ret["comment"] = " ".join( - [ret["comment"], "IAM user {} is deleted.".format(name)] - ) + ret["comment"] = " ".join([ret["comment"], f"IAM user {name} is deleted."]) ret["result"] = True ret["changes"]["deleted"] = name return ret - ret["comment"] = "IAM user {} could not be deleted.\n {}".format(name, deleted) + ret["comment"] = f"IAM user {name} could not be deleted.\n {deleted}" ret["result"] = False return ret @@ -418,14 +416,14 @@ def keys_present( ret = {"name": name, "result": True, "comment": "", "changes": {}} if not __salt__["boto_iam.get_user"](name, region, key, keyid, profile): ret["result"] = False - ret["comment"] = "IAM User {} does not exist.".format(name) + ret["comment"] = f"IAM User {name} does not exist." return ret if not isinstance(number, int): ret["comment"] = "The number of keys must be an integer." ret["result"] = False return ret if not os.path.isdir(save_dir): - ret["comment"] = "The directory {} does not exist.".format(save_dir) + ret["comment"] = f"The directory {save_dir} does not exist." ret["result"] = False return ret keys = __salt__["boto_iam.get_all_access_keys"]( @@ -434,7 +432,7 @@ def keys_present( if isinstance(keys, str): log.debug("keys are : false %s", keys) error, message = _get_error(keys) - ret["comment"] = "Could not get keys.\n{}\n{}".format(error, message) + ret["comment"] = f"Could not get keys.\n{error}\n{message}" ret["result"] = False return ret keys = keys["list_access_keys_response"]["list_access_keys_result"][ @@ -442,11 +440,11 @@ def keys_present( ] log.debug("Keys are : %s.", keys) if len(keys) >= number: - ret["comment"] = "The number of keys exist for user {}".format(name) + ret["comment"] = f"The number of keys exist for user {name}" ret["result"] = True return ret if __opts__["test"]: - ret["comment"] = "Access key is set to be created for {}.".format(name) + ret["comment"] = f"Access key is set to be created for {name}." ret["result"] = None return ret new_keys = {} @@ -456,7 +454,7 @@ def keys_present( ) if isinstance(created, str): error, message = _get_error(created) - ret["comment"] = "Could not create keys.\n{}\n{}".format(error, message) + ret["comment"] = f"Could not create keys.\n{error}\n{message}" ret["result"] = False return ret log.debug("Created is : %s", created) @@ -470,7 +468,7 @@ def keys_present( "secret_access_key" ] try: - with salt.utils.files.fopen("{}/{}".format(save_dir, name), "a") as _wrf: + with salt.utils.files.fopen(f"{save_dir}/{name}", "a") as _wrf: for key_num, key in new_keys.items(): key_id = key["key_id"] secret_key = key["secret_key"] @@ -479,17 +477,17 @@ def keys_present( save_format.format( key_id, secret_key, - "key_id-{}".format(key_num), - "key-{}".format(key_num), + f"key_id-{key_num}", + f"key-{key_num}", ) ) ) - ret["comment"] = "Keys have been written to file {}/{}.".format(save_dir, name) + ret["comment"] = f"Keys have been written to file {save_dir}/{name}." ret["result"] = True ret["changes"] = new_keys return ret except OSError: - ret["comment"] = "Could not write to file {}/{}.".format(save_dir, name) + ret["comment"] = f"Could not write to file {save_dir}/{name}." ret["result"] = False return ret @@ -525,7 +523,7 @@ def keys_absent( ret = {"name": access_keys, "result": True, "comment": "", "changes": {}} if not __salt__["boto_iam.get_user"](user_name, region, key, keyid, profile): ret["result"] = False - ret["comment"] = "IAM User {} does not exist.".format(user_name) + ret["comment"] = f"IAM User {user_name} does not exist." return ret for k in access_keys: ret = _delete_key(ret, k, user_name, region, key, keyid, profile) @@ -542,7 +540,7 @@ def _delete_key( if isinstance(keys, str): log.debug("Keys %s are a string. Something went wrong.", keys) ret["comment"] = " ".join( - [ret["comment"], "Key {} could not be deleted.".format(access_key_id)] + [ret["comment"], f"Key {access_key_id} could not be deleted."] ) return ret keys = keys["list_access_keys_response"]["list_access_keys_result"][ @@ -564,15 +562,15 @@ def _delete_key( ) if deleted: ret["comment"] = " ".join( - [ret["comment"], "Key {} has been deleted.".format(access_key_id)] + [ret["comment"], f"Key {access_key_id} has been deleted."] ) ret["changes"][access_key_id] = "deleted" return ret ret["comment"] = " ".join( - [ret["comment"], "Key {} could not be deleted.".format(access_key_id)] + [ret["comment"], f"Key {access_key_id} could not be deleted."] ) return ret - ret["comment"] = " ".join([ret["comment"], "Key {} does not exist.".format(k)]) + ret["comment"] = " ".join([ret["comment"], f"Key {k} does not exist."]) return ret @@ -649,7 +647,7 @@ def user_present( exists = __salt__["boto_iam.get_user"](name, region, key, keyid, profile) if not exists: if __opts__["test"]: - ret["comment"] = "IAM user {} is set to be created.".format(name) + ret["comment"] = f"IAM user {name} is set to be created." ret["result"] = None return ret created = __salt__["boto_iam.create_user"]( @@ -658,7 +656,7 @@ def user_present( if created: ret["changes"]["user"] = created ret["comment"] = " ".join( - [ret["comment"], "User {} has been created.".format(name)] + [ret["comment"], f"User {name} has been created."] ) if password: ret = _case_password(ret, name, password, region, key, keyid, profile) @@ -666,7 +664,7 @@ def user_present( ret["changes"] = dictupdate.update(ret["changes"], _ret["changes"]) ret["comment"] = " ".join([ret["comment"], _ret["comment"]]) else: - ret["comment"] = " ".join([ret["comment"], "User {} is present.".format(name)]) + ret["comment"] = " ".join([ret["comment"], f"User {name} is present."]) if password: ret = _case_password(ret, name, password, region, key, keyid, profile) _ret = _user_policies_present(name, _policies, region, key, keyid, profile) @@ -845,7 +843,7 @@ def _user_policies_detached(name, region=None, key=None, keyid=None, profile=Non ) oldpolicies = [x.get("policy_arn") for x in _list] if not _list: - ret["comment"] = "No attached policies in user {}.".format(name) + ret["comment"] = f"No attached policies in user {name}." return ret if __opts__["test"]: ret["comment"] = "{} policies to be detached from user {}.".format( @@ -865,7 +863,7 @@ def _user_policies_detached(name, region=None, key=None, keyid=None, profile=Non newpolicies = [x.get("policy_arn") for x in _list] ret["changes"]["new"] = {"managed_policies": newpolicies} ret["result"] = False - ret["comment"] = "Failed to detach {} from user {}".format(policy_arn, name) + ret["comment"] = f"Failed to detach {policy_arn} from user {name}" return ret _list = __salt__["boto_iam.list_attached_user_policies"]( name, region=region, key=key, keyid=keyid, profile=profile @@ -884,7 +882,7 @@ def _user_policies_deleted(name, region=None, key=None, keyid=None, profile=None user_name=name, region=region, key=key, keyid=keyid, profile=profile ) if not oldpolicies: - ret["comment"] = "No inline policies in user {}.".format(name) + ret["comment"] = f"No inline policies in user {name}." return ret if __opts__["test"]: ret["comment"] = "{} policies to be deleted from user {}.".format( @@ -921,7 +919,7 @@ def _case_password( ret, name, password, region=None, key=None, keyid=None, profile=None ): if __opts__["test"]: - ret["comment"] = "Login policy for {} is set to be changed.".format(name) + ret["comment"] = f"Login policy for {name} is set to be changed." ret["result"] = None return ret login = __salt__["boto_iam.create_login_profile"]( @@ -931,11 +929,11 @@ def _case_password( if login: if "Conflict" in login: ret["comment"] = " ".join( - [ret["comment"], "Login profile for user {} exists.".format(name)] + [ret["comment"], f"Login profile for user {name} exists."] ) else: ret["comment"] = " ".join( - [ret["comment"], "Password has been added to User {}.".format(name)] + [ret["comment"], f"Password has been added to User {name}."] ) ret["changes"]["password"] = "REDACTED" else: @@ -976,13 +974,13 @@ def group_absent(name, region=None, key=None, keyid=None, profile=None): ret = {"name": name, "result": True, "comment": "", "changes": {}} if not __salt__["boto_iam.get_group"](name, region, key, keyid, profile): ret["result"] = True - ret["comment"] = "IAM Group {} does not exist.".format(name) + ret["comment"] = f"IAM Group {name} does not exist." return ret if __opts__["test"]: ret["comment"] = " ".join( [ ret["comment"], - "IAM group {} managed policies are set to be detached.".format(name), + f"IAM group {name} managed policies are set to be detached.", ] ) ret["result"] = None @@ -997,7 +995,7 @@ def group_absent(name, region=None, key=None, keyid=None, profile=None): ret["comment"] = " ".join( [ ret["comment"], - "IAM group {} inline policies are set to be deleted.".format(name), + f"IAM group {name} inline policies are set to be deleted.", ] ) ret["result"] = None @@ -1009,7 +1007,7 @@ def group_absent(name, region=None, key=None, keyid=None, profile=None): if ret["result"] is False: return ret ret["comment"] = " ".join( - [ret["comment"], "IAM group {} users are set to be removed.".format(name)] + [ret["comment"], f"IAM group {name} users are set to be removed."] ) existing_users = __salt__["boto_iam.get_group_members"]( group_name=name, region=region, key=key, keyid=keyid, profile=profile @@ -1023,19 +1021,17 @@ def group_absent(name, region=None, key=None, keyid=None, profile=None): # finally, actually delete the group if __opts__["test"]: ret["comment"] = " ".join( - [ret["comment"], "IAM group {} is set to be deleted.".format(name)] + [ret["comment"], f"IAM group {name} is set to be deleted."] ) ret["result"] = None return ret deleted = __salt__["boto_iam.delete_group"](name, region, key, keyid, profile) if deleted is True: - ret["comment"] = " ".join( - [ret["comment"], "IAM group {} is deleted.".format(name)] - ) + ret["comment"] = " ".join([ret["comment"], f"IAM group {name} is deleted."]) ret["result"] = True ret["changes"]["deleted"] = name return ret - ret["comment"] = "IAM group {} could not be deleted.\n {}".format(name, deleted) + ret["comment"] = f"IAM group {name} could not be deleted.\n {deleted}" ret["result"] = False return ret @@ -1119,7 +1115,7 @@ def group_present( ) if not exists: if __opts__["test"]: - ret["comment"] = "IAM group {} is set to be created.".format(name) + ret["comment"] = f"IAM group {name} is set to be created." ret["result"] = None return ret created = __salt__["boto_iam.create_group"]( @@ -1131,15 +1127,13 @@ def group_present( profile=profile, ) if not created: - ret["comment"] = "Failed to create IAM group {}.".format(name) + ret["comment"] = f"Failed to create IAM group {name}." ret["result"] = False return ret ret["changes"]["group"] = created - ret["comment"] = " ".join( - [ret["comment"], "Group {} has been created.".format(name)] - ) + ret["comment"] = " ".join([ret["comment"], f"Group {name} has been created."]) else: - ret["comment"] = " ".join([ret["comment"], "Group {} is present.".format(name)]) + ret["comment"] = " ".join([ret["comment"], f"Group {name} is present."]) # Group exists, ensure group policies and users are set. _ret = _group_policies_present( name, _policies, region, key, keyid, profile, delete_policies @@ -1178,7 +1172,7 @@ def _case_group(ret, users, group_name, existing_users, region, key, keyid, prof ret["comment"] = " ".join( [ ret["comment"], - "User {} is already a member of group {}.".format(user, group_name), + f"User {user} is already a member of group {group_name}.", ] ) continue @@ -1196,7 +1190,7 @@ def _case_group(ret, users, group_name, existing_users, region, key, keyid, prof ret["comment"] = " ".join( [ ret["comment"], - "User {} has been added to group {}.".format(user, group_name), + f"User {user} has been added to group {group_name}.", ] ) ret["changes"][user] = group_name @@ -1229,7 +1223,7 @@ def _case_group(ret, users, group_name, existing_users, region, key, keyid, prof ), ] ) - ret["changes"][user] = "Removed from group {}.".format(group_name) + ret["changes"][user] = f"Removed from group {group_name}." return ret @@ -1410,7 +1404,7 @@ def _group_policies_detached(name, region=None, key=None, keyid=None, profile=No ) oldpolicies = [x.get("policy_arn") for x in _list] if not _list: - ret["comment"] = "No attached policies in group {}.".format(name) + ret["comment"] = f"No attached policies in group {name}." return ret if __opts__["test"]: ret["comment"] = "{} policies to be detached from group {}.".format( @@ -1451,7 +1445,7 @@ def _group_policies_deleted(name, region=None, key=None, keyid=None, profile=Non group_name=name, region=region, key=key, keyid=keyid, profile=profile ) if not oldpolicies: - ret["comment"] = "No inline policies in group {}.".format(name) + ret["comment"] = f"No inline policies in group {name}." return ret if __opts__["test"]: ret["comment"] = "{} policies to be deleted from group {}.".format( @@ -1568,7 +1562,7 @@ def account_policy( ret["comment"] = " ".join( [ ret["comment"], - "Policy value {} has been set to {}.".format(value, info[key]), + f"Policy value {value} has been set to {info[key]}.", ] ) ret["changes"][key] = str(value).lower() @@ -1627,18 +1621,18 @@ def server_cert_absent(name, region=None, key=None, keyid=None, profile=None): name, region, key, keyid, profile ) if not exists: - ret["comment"] = "Certificate {} does not exist.".format(name) + ret["comment"] = f"Certificate {name} does not exist." return ret if __opts__["test"]: - ret["comment"] = "Server certificate {} is set to be deleted.".format(name) + ret["comment"] = f"Server certificate {name} is set to be deleted." ret["result"] = None return ret deleted = __salt__["boto_iam.delete_server_cert"](name, region, key, keyid, profile) if not deleted: ret["result"] = False - ret["comment"] = "Certificate {} failed to be deleted.".format(name) + ret["comment"] = f"Certificate {name} failed to be deleted." return ret - ret["comment"] = "Certificate {} was deleted.".format(name) + ret["comment"] = f"Certificate {name} was deleted." ret["changes"] = deleted return ret @@ -1693,14 +1687,14 @@ def server_cert_present( ) log.debug("Variables are : %s.", locals()) if exists: - ret["comment"] = "Certificate {} exists.".format(name) + ret["comment"] = f"Certificate {name} exists." return ret if "salt://" in public_key: try: public_key = __salt__["cp.get_file_str"](public_key) except OSError as e: log.debug(e) - ret["comment"] = "File {} not found.".format(public_key) + ret["comment"] = f"File {public_key} not found." ret["result"] = False return ret if "salt://" in private_key: @@ -1708,7 +1702,7 @@ def server_cert_present( private_key = __salt__["cp.get_file_str"](private_key) except OSError as e: log.debug(e) - ret["comment"] = "File {} not found.".format(private_key) + ret["comment"] = f"File {private_key} not found." ret["result"] = False return ret if cert_chain is not None and "salt://" in cert_chain: @@ -1716,22 +1710,22 @@ def server_cert_present( cert_chain = __salt__["cp.get_file_str"](cert_chain) except OSError as e: log.debug(e) - ret["comment"] = "File {} not found.".format(cert_chain) + ret["comment"] = f"File {cert_chain} not found." ret["result"] = False return ret if __opts__["test"]: - ret["comment"] = "Server certificate {} is set to be created.".format(name) + ret["comment"] = f"Server certificate {name} is set to be created." ret["result"] = None return ret created = __salt__["boto_iam.upload_server_cert"]( name, public_key, private_key, cert_chain, path, region, key, keyid, profile ) if created is not False: - ret["comment"] = "Certificate {} was created.".format(name) + ret["comment"] = f"Certificate {name} was created." ret["changes"] = created return ret ret["result"] = False - ret["comment"] = "Certificate {} failed to be created.".format(name) + ret["comment"] = f"Certificate {name} failed to be created." return ret @@ -1780,7 +1774,7 @@ def policy_present( policy = __salt__["boto_iam.get_policy"](name, region, key, keyid, profile) if not policy: if __opts__["test"]: - ret["comment"] = "IAM policy {} is set to be created.".format(name) + ret["comment"] = f"IAM policy {name} is set to be created." ret["result"] = None return ret created = __salt__["boto_iam.create_policy"]( @@ -1789,7 +1783,7 @@ def policy_present( if created: ret["changes"]["policy"] = created ret["comment"] = " ".join( - [ret["comment"], "Policy {} has been created.".format(name)] + [ret["comment"], f"Policy {name} has been created."] ) else: ret["result"] = False @@ -1798,9 +1792,7 @@ def policy_present( return ret else: policy = policy.get("policy", {}) - ret["comment"] = " ".join( - [ret["comment"], "Policy {} is present.".format(name)] - ) + ret["comment"] = " ".join([ret["comment"], f"Policy {name} is present."]) _describe = __salt__["boto_iam.get_policy_version"]( name, policy.get("default_version_id"), region, key, keyid, profile ).get("policy_version", {}) @@ -1816,7 +1808,7 @@ def policy_present( if bool(r): if __opts__["test"]: - ret["comment"] = "Policy {} set to be modified.".format(name) + ret["comment"] = f"Policy {name} set to be modified." ret["result"] = None return ret @@ -1883,11 +1875,11 @@ def policy_absent(name, region=None, key=None, keyid=None, profile=None): name, region=region, key=key, keyid=keyid, profile=profile ) if not r: - ret["comment"] = "Policy {} does not exist.".format(name) + ret["comment"] = f"Policy {name} does not exist." return ret if __opts__["test"]: - ret["comment"] = "Policy {} is set to be removed.".format(name) + ret["comment"] = f"Policy {name} is set to be removed." ret["result"] = None return ret # delete non-default versions @@ -1908,18 +1900,18 @@ def policy_absent(name, region=None, key=None, keyid=None, profile=None): ) if not r: ret["result"] = False - ret["comment"] = "Failed to delete policy {}.".format(name) + ret["comment"] = f"Failed to delete policy {name}." return ret r = __salt__["boto_iam.delete_policy"]( name, region=region, key=key, keyid=keyid, profile=profile ) if not r: ret["result"] = False - ret["comment"] = "Failed to delete policy {}.".format(name) + ret["comment"] = f"Failed to delete policy {name}." return ret ret["changes"]["old"] = {"policy": name} ret["changes"]["new"] = {"policy": None} - ret["comment"] = "Policy {} deleted.".format(name) + ret["comment"] = f"Policy {name} deleted." return ret @@ -1957,19 +1949,19 @@ def saml_provider_present( ET.fromstring(saml_metadata_document) except OSError as e: log.debug(e) - ret[ - "comment" - ] = "SAML document file {} not found or could not be loaded".format(name) + ret["comment"] = ( + f"SAML document file {name} not found or could not be loaded" + ) ret["result"] = False return ret for provider in __salt__["boto_iam.list_saml_providers"]( region=region, key=key, keyid=keyid, profile=profile ): if provider == name: - ret["comment"] = "SAML provider {} is present.".format(name) + ret["comment"] = f"SAML provider {name} is present." return ret if __opts__["test"]: - ret["comment"] = "SAML provider {} is set to be create.".format(name) + ret["comment"] = f"SAML provider {name} is set to be create." ret["result"] = None return ret created = __salt__["boto_iam.create_saml_provider"]( @@ -1981,11 +1973,11 @@ def saml_provider_present( profile=profile, ) if created: - ret["comment"] = "SAML provider {} was created.".format(name) + ret["comment"] = f"SAML provider {name} was created." ret["changes"]["new"] = name return ret ret["result"] = False - ret["comment"] = "SAML provider {} failed to be created.".format(name) + ret["comment"] = f"SAML provider {name} failed to be created." return ret @@ -2019,21 +2011,21 @@ def saml_provider_absent(name, region=None, key=None, keyid=None, profile=None): region=region, key=key, keyid=keyid, profile=profile ) if len(provider) == 0: - ret["comment"] = "SAML provider {} is absent.".format(name) + ret["comment"] = f"SAML provider {name} is absent." return ret if __opts__["test"]: - ret["comment"] = "SAML provider {} is set to be removed.".format(name) + ret["comment"] = f"SAML provider {name} is set to be removed." ret["result"] = None return ret deleted = __salt__["boto_iam.delete_saml_provider"]( name, region=region, key=key, keyid=keyid, profile=profile ) if deleted is not False: - ret["comment"] = "SAML provider {} was deleted.".format(name) + ret["comment"] = f"SAML provider {name} was deleted." ret["changes"]["old"] = name return ret ret["result"] = False - ret["comment"] = "SAML provider {} failed to be deleted.".format(name) + ret["comment"] = f"SAML provider {name} failed to be deleted." return ret diff --git a/salt/states/boto_iam_role.py b/salt/states/boto_iam_role.py index 67c41f760a0..9ddcdfdee39 100644 --- a/salt/states/boto_iam_role.py +++ b/salt/states/boto_iam_role.py @@ -255,7 +255,7 @@ def _role_present( role = __salt__["boto_iam.describe_role"](name, region, key, keyid, profile) if not role: if __opts__["test"]: - ret["comment"] = "IAM role {} is set to be created.".format(name) + ret["comment"] = f"IAM role {name} is set to be created." ret["result"] = None return ret created = __salt__["boto_iam.create_role"]( @@ -264,12 +264,12 @@ def _role_present( if created: ret["changes"]["old"] = {"role": None} ret["changes"]["new"] = {"role": name} - ret["comment"] = "IAM role {} created.".format(name) + ret["comment"] = f"IAM role {name} created." else: ret["result"] = False - ret["comment"] = "Failed to create {} IAM role.".format(name) + ret["comment"] = f"Failed to create {name} IAM role." else: - ret["comment"] = "{} role present.".format(name) + ret["comment"] = f"{name} role present." if not policy_document: _policy_document = __salt__["boto_iam.build_policy"]( region, key, keyid, profile @@ -309,7 +309,7 @@ def _instance_profile_present(name, region=None, key=None, keyid=None, profile=N ) if not exists: if __opts__["test"]: - ret["comment"] = "Instance profile {} is set to be created.".format(name) + ret["comment"] = f"Instance profile {name} is set to be created." ret["result"] = None return ret created = __salt__["boto_iam.create_instance_profile"]( @@ -318,10 +318,10 @@ def _instance_profile_present(name, region=None, key=None, keyid=None, profile=N if created: ret["changes"]["old"] = {"instance_profile": None} ret["changes"]["new"] = {"instance_profile": name} - ret["comment"] = "Instance profile {} created.".format(name) + ret["comment"] = f"Instance profile {name} created." else: ret["result"] = False - ret["comment"] = "Failed to create {} instance profile.".format(name) + ret["comment"] = f"Failed to create {name} instance profile." return ret @@ -332,7 +332,7 @@ def _instance_profile_associated(name, region=None, key=None, keyid=None, profil ) if not is_associated: if __opts__["test"]: - ret["comment"] = "Instance profile {} is set to be associated.".format(name) + ret["comment"] = f"Instance profile {name} is set to be associated." ret["result"] = None return ret associated = __salt__["boto_iam.associate_profile_to_role"]( @@ -341,12 +341,12 @@ def _instance_profile_associated(name, region=None, key=None, keyid=None, profil if associated: ret["changes"]["old"] = {"profile_associated": None} ret["changes"]["new"] = {"profile_associated": True} - ret["comment"] = "Instance profile {} associated.".format(name) + ret["comment"] = f"Instance profile {name} associated." else: ret["result"] = False - ret[ - "comment" - ] = "Failed to associate {0} instance profile with {0} role.".format(name) + ret["comment"] = ( + "Failed to associate {0} instance profile with {0} role.".format(name) + ) return ret @@ -591,19 +591,19 @@ def _role_absent(name, region=None, key=None, keyid=None, profile=None): exists = __salt__["boto_iam.role_exists"](name, region, key, keyid, profile) if exists: if __opts__["test"]: - ret["comment"] = "IAM role {} is set to be removed.".format(name) + ret["comment"] = f"IAM role {name} is set to be removed." ret["result"] = None return ret deleted = __salt__["boto_iam.delete_role"](name, region, key, keyid, profile) if deleted: ret["changes"]["old"] = {"role": name} ret["changes"]["new"] = {"role": None} - ret["comment"] = "IAM role {} removed.".format(name) + ret["comment"] = f"IAM role {name} removed." else: ret["result"] = False - ret["comment"] = "Failed to delete {} iam role.".format(name) + ret["comment"] = f"Failed to delete {name} iam role." else: - ret["comment"] = "{} role does not exist.".format(name) + ret["comment"] = f"{name} role does not exist." return ret @@ -615,7 +615,7 @@ def _instance_profile_absent(name, region=None, key=None, keyid=None, profile=No ) if exists: if __opts__["test"]: - ret["comment"] = "Instance profile {} is set to be removed.".format(name) + ret["comment"] = f"Instance profile {name} is set to be removed." ret["result"] = None return ret deleted = __salt__["boto_iam.delete_instance_profile"]( @@ -624,12 +624,12 @@ def _instance_profile_absent(name, region=None, key=None, keyid=None, profile=No if deleted: ret["changes"]["old"] = {"instance_profile": name} ret["changes"]["new"] = {"instance_profile": None} - ret["comment"] = "Instance profile {} removed.".format(name) + ret["comment"] = f"Instance profile {name} removed." else: ret["result"] = False - ret["comment"] = "Failed to delete {} instance profile.".format(name) + ret["comment"] = f"Failed to delete {name} instance profile." else: - ret["comment"] = "{} instance profile does not exist.".format(name) + ret["comment"] = f"{name} instance profile does not exist." return ret @@ -637,7 +637,7 @@ def _policies_absent(name, region=None, key=None, keyid=None, profile=None): ret = {"result": True, "comment": "", "changes": {}} _list = __salt__["boto_iam.list_role_policies"](name, region, key, keyid, profile) if not _list: - ret["comment"] = "No policies in role {}.".format(name) + ret["comment"] = f"No policies in role {name}." return ret if __opts__["test"]: ret["comment"] = "{} policies to be removed from role {}.".format( @@ -673,7 +673,7 @@ def _policies_detached(name, region=None, key=None, keyid=None, profile=None): ) oldpolicies = [x.get("policy_arn") for x in _list] if not _list: - ret["comment"] = "No attached policies in role {}.".format(name) + ret["comment"] = f"No attached policies in role {name}." return ret if __opts__["test"]: ret["comment"] = "{} policies to be detached from role {}.".format( @@ -693,7 +693,7 @@ def _policies_detached(name, region=None, key=None, keyid=None, profile=None): newpolicies = [x.get("policy_arn") for x in _list] ret["changes"]["new"] = {"managed_policies": newpolicies} ret["result"] = False - ret["comment"] = "Failed to detach {} from role {}".format(policy_arn, name) + ret["comment"] = f"Failed to detach {policy_arn} from role {name}" return ret _list = __salt__["boto_iam.list_attached_role_policies"]( name, region=region, key=key, keyid=keyid, profile=profile @@ -726,12 +726,12 @@ def _instance_profile_disassociated( if associated: ret["changes"]["old"] = {"profile_associated": True} ret["changes"]["new"] = {"profile_associated": False} - ret["comment"] = "Instance profile {} disassociated.".format(name) + ret["comment"] = f"Instance profile {name} disassociated." else: ret["result"] = False - ret[ - "comment" - ] = "Failed to disassociate {0} instance profile from {0} role.".format( - name + ret["comment"] = ( + "Failed to disassociate {0} instance profile from {0} role.".format( + name + ) ) return ret diff --git a/salt/states/boto_iot.py b/salt/states/boto_iot.py index e14d1541949..bea8f9481f5 100644 --- a/salt/states/boto_iot.py +++ b/salt/states/boto_iot.py @@ -157,7 +157,7 @@ def thing_type_present( return ret if __opts__["test"]: - ret["comment"] = "Thing type {} is set to be created.".format(thingTypeName) + ret["comment"] = f"Thing type {thingTypeName} is set to be created." ret["result"] = None return ret @@ -187,7 +187,7 @@ def thing_type_present( ) ret["changes"]["old"] = {"thing_type": None} ret["changes"]["new"] = _describe - ret["comment"] = "Thing Type {} created.".format(thingTypeName) + ret["comment"] = f"Thing Type {thingTypeName} created." return ret @@ -237,7 +237,7 @@ def thing_type_absent( return ret if _describe and not _describe["thing_type"]: - ret["comment"] = "Thing Type {} does not exist.".format(thingTypeName) + ret["comment"] = f"Thing Type {thingTypeName} does not exist." return ret _existing_thing_type = _describe["thing_type"] @@ -319,7 +319,7 @@ def thing_type_absent( return ret ret["changes"]["old"] = _describe ret["changes"]["new"] = {"thing_type": None} - ret["comment"] = "Thing Type {} deleted.".format(thingTypeName) + ret["comment"] = f"Thing Type {thingTypeName} deleted." return ret @@ -366,7 +366,7 @@ def policy_present( if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "Policy {} is set to be created.".format(policyName) + ret["comment"] = f"Policy {policyName} is set to be created." ret["result"] = None return ret r = __salt__["boto_iot.create_policy"]( @@ -388,11 +388,11 @@ def policy_present( ) ret["changes"]["old"] = {"policy": None} ret["changes"]["new"] = _describe - ret["comment"] = "Policy {} created.".format(policyName) + ret["comment"] = f"Policy {policyName} created." return ret ret["comment"] = os.linesep.join( - [ret["comment"], "Policy {} is present.".format(policyName)] + [ret["comment"], f"Policy {policyName} is present."] ) ret["changes"] = {} # policy exists, ensure config matches @@ -411,7 +411,7 @@ def policy_present( r = salt.utils.data.compare_dicts(describeDict, policyDocument) if bool(r): if __opts__["test"]: - msg = "Policy {} set to be modified.".format(policyName) + msg = f"Policy {policyName} set to be modified." ret["comment"] = msg ret["result"] = None return ret @@ -487,11 +487,11 @@ def policy_absent(name, policyName, region=None, key=None, keyid=None, profile=N return ret if r and not r["exists"]: - ret["comment"] = "Policy {} does not exist.".format(policyName) + ret["comment"] = f"Policy {policyName} does not exist." return ret if __opts__["test"]: - ret["comment"] = "Policy {} is set to be removed.".format(policyName) + ret["comment"] = f"Policy {policyName} is set to be removed." ret["result"] = None return ret # delete non-default versions @@ -532,7 +532,7 @@ def policy_absent(name, policyName, region=None, key=None, keyid=None, profile=N return ret ret["changes"]["old"] = {"policy": policyName} ret["changes"]["new"] = {"policy": None} - ret["comment"] = "Policy {} deleted.".format(policyName) + ret["comment"] = f"Policy {policyName} deleted." return ret @@ -603,11 +603,11 @@ def policy_attached( return ret ret["changes"]["old"] = {"attached": False} ret["changes"]["new"] = {"attached": True} - ret["comment"] = "Policy {} attached to {}.".format(policyName, principal) + ret["comment"] = f"Policy {policyName} attached to {principal}." return ret ret["comment"] = os.linesep.join( - [ret["comment"], "Policy {} is attached.".format(policyName)] + [ret["comment"], f"Policy {policyName} is attached."] ) ret["changes"] = {} @@ -682,11 +682,11 @@ def policy_detached( return ret ret["changes"]["old"] = {"attached": True} ret["changes"]["new"] = {"attached": False} - ret["comment"] = "Policy {} detached from {}.".format(policyName, principal) + ret["comment"] = f"Policy {policyName} detached from {principal}." return ret ret["comment"] = os.linesep.join( - [ret["comment"], "Policy {} is detached.".format(policyName)] + [ret["comment"], f"Policy {policyName} is detached."] ) ret["changes"] = {} @@ -752,7 +752,7 @@ def topic_rule_present( if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "Rule {} is set to be created.".format(ruleName) + ret["comment"] = f"Rule {ruleName} is set to be created." ret["result"] = None return ret r = __salt__["boto_iot.create_topic_rule"]( @@ -775,12 +775,10 @@ def topic_rule_present( ) ret["changes"]["old"] = {"rule": None} ret["changes"]["new"] = _describe - ret["comment"] = "Rule {} created.".format(ruleName) + ret["comment"] = f"Rule {ruleName} created." return ret - ret["comment"] = os.linesep.join( - [ret["comment"], "Rule {} is present.".format(ruleName)] - ) + ret["comment"] = os.linesep.join([ret["comment"], f"Rule {ruleName} is present."]) ret["changes"] = {} # policy exists, ensure config matches _describe = __salt__["boto_iot.describe_topic_rule"]( @@ -805,7 +803,7 @@ def topic_rule_present( ret["changes"].setdefault("old", {})[var] = _describe[var] if need_update: if __opts__["test"]: - msg = "Rule {} set to be modified.".format(ruleName) + msg = f"Rule {ruleName} set to be modified." ret["changes"] = {} ret["comment"] = msg ret["result"] = None @@ -864,11 +862,11 @@ def topic_rule_absent(name, ruleName, region=None, key=None, keyid=None, profile return ret if r and not r["exists"]: - ret["comment"] = "Rule {} does not exist.".format(ruleName) + ret["comment"] = f"Rule {ruleName} does not exist." return ret if __opts__["test"]: - ret["comment"] = "Rule {} is set to be removed.".format(ruleName) + ret["comment"] = f"Rule {ruleName} is set to be removed." ret["result"] = None return ret r = __salt__["boto_iot.delete_topic_rule"]( @@ -880,5 +878,5 @@ def topic_rule_absent(name, ruleName, region=None, key=None, keyid=None, profile return ret ret["changes"]["old"] = {"rule": ruleName} ret["changes"]["new"] = {"rule": None} - ret["comment"] = "Rule {} deleted.".format(ruleName) + ret["comment"] = f"Rule {ruleName} deleted." return ret diff --git a/salt/states/boto_kinesis.py b/salt/states/boto_kinesis.py index 5809ef711e5..938449515c2 100644 --- a/salt/states/boto_kinesis.py +++ b/salt/states/boto_kinesis.py @@ -140,7 +140,7 @@ def present( if exists["result"] is False: if __opts__["test"]: ret["result"] = None - comments.append("Kinesis stream {} would be created".format(name)) + comments.append(f"Kinesis stream {name} would be created") _add_changes(ret, changes_old, changes_new, comments) return ret else: @@ -155,11 +155,11 @@ def present( _add_changes(ret, changes_old, changes_new, comments) return ret - comments.append("Kinesis stream {} successfully created".format(name)) + comments.append(f"Kinesis stream {name} successfully created") changes_new["name"] = name changes_new["num_shards"] = num_shards else: - comments.append("Kinesis stream {} already exists".format(name)) + comments.append(f"Kinesis stream {name} already exists") stream_response = __salt__["boto_kinesis.get_stream_when_active"]( name, region, key, keyid, profile @@ -238,9 +238,7 @@ def present( " at {}".format(name, old_retention_hours) ) else: - comments.append( - "Kinesis stream {}: did not configure retention hours".format(name) - ) + comments.append(f"Kinesis stream {name}: did not configure retention hours") # Configure enhanced monitoring if enhanced_monitoring is not None: @@ -345,9 +343,7 @@ def present( enhanced_monitoring if len(enhanced_monitoring) > 0 else "None" ) else: - comments.append( - "Kinesis stream {}: did not configure enhanced monitoring".format(name) - ) + comments.append(f"Kinesis stream {name}: did not configure enhanced monitoring") # Reshard stream if necessary min_hash_key, max_hash_key, full_stream_details = __salt__[ @@ -439,11 +435,11 @@ def absent(name, region=None, key=None, keyid=None, profile=None): exists = __salt__["boto_kinesis.exists"](name, region, key, keyid, profile) if exists["result"] is False: - ret["comment"] = "Kinesis stream {} does not exist".format(name) + ret["comment"] = f"Kinesis stream {name} does not exist" return ret if __opts__["test"]: - ret["comment"] = "Kinesis stream {} would be deleted".format(name) + ret["comment"] = f"Kinesis stream {name} would be deleted" ret["result"] = None return ret @@ -456,9 +452,9 @@ def absent(name, region=None, key=None, keyid=None, profile=None): ) ret["result"] = False else: - ret["comment"] = "Deleted stream {}".format(name) - ret["changes"].setdefault("old", "Stream {} exists".format(name)) - ret["changes"].setdefault("new", "Stream {} deleted".format(name)) + ret["comment"] = f"Deleted stream {name}" + ret["changes"].setdefault("old", f"Stream {name} exists") + ret["changes"].setdefault("new", f"Stream {name} deleted") return ret diff --git a/salt/states/boto_kms.py b/salt/states/boto_kms.py index aadc02093e8..3c542541304 100644 --- a/salt/states/boto_kms.py +++ b/salt/states/boto_kms.py @@ -174,7 +174,7 @@ def _key_present( profile, ): ret = {"result": True, "comment": "", "changes": {}} - alias = "alias/{}".format(name) + alias = f"alias/{name}" r = __salt__["boto_kms.key_exists"](alias, region, key, keyid, profile) if "error" in r: ret["result"] = False @@ -212,7 +212,7 @@ def _key_present( return ret ret["changes"]["old"] = {"key": None} ret["changes"]["new"] = {"key": name} - ret["comment"] = "Key {} created.".format(name) + ret["comment"] = f"Key {name} created." else: rd = __salt__["boto_kms.describe_key"](alias, region, key, keyid, profile) if "error" in rd: @@ -271,7 +271,7 @@ def _key_enabled(key_metadata, enabled, region, key, keyid, profile): re["error"]["message"] ) else: - ret["comment"] = "{} key.".format(event) + ret["comment"] = f"{event} key." return ret @@ -339,7 +339,7 @@ def _key_rotation(key_metadata, key_rotation, region, key, keyid, profile): "old": {"key_rotation": not key_rotation}, "new": {"key_rotation": key_rotation}, } - ret["comment"] = "Set key rotation policy to {}.".format(key_rotation) + ret["comment"] = f"Set key rotation policy to {key_rotation}." return ret diff --git a/salt/states/boto_lambda.py b/salt/states/boto_lambda.py index cd8bca05f52..0ce5a513c06 100644 --- a/salt/states/boto_lambda.py +++ b/salt/states/boto_lambda.py @@ -59,7 +59,6 @@ config: """ - import hashlib import logging import os @@ -249,7 +248,7 @@ def function_present( if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "Function {} is set to be created.".format(FunctionName) + ret["comment"] = f"Function {FunctionName} is set to be created." ret["result"] = None return ret r = __salt__["boto_lambda.create_function"]( @@ -289,7 +288,7 @@ def function_present( key=key, keyid=keyid, profile=profile, - **permission + **permission, ) if not r.get("updated"): ret["result"] = False @@ -305,11 +304,11 @@ def function_present( )["permissions"] ret["changes"]["old"] = {"function": None} ret["changes"]["new"] = _describe - ret["comment"] = "Function {} created.".format(FunctionName) + ret["comment"] = f"Function {FunctionName} created." return ret ret["comment"] = os.linesep.join( - [ret["comment"], "Function {} is present.".format(FunctionName)] + [ret["comment"], f"Function {FunctionName} is present."] ) ret["changes"] = {} # function exists, ensure config matches @@ -373,7 +372,7 @@ def _get_role_arn(name, region=None, key=None, keyid=None, profile=None): account_id = __salt__["boto_iam.get_account_id"]( region=region, key=key, keyid=keyid, profile=profile ) - return "arn:aws:iam::{}:role/{}".format(account_id, name) + return f"arn:aws:iam::{account_id}:role/{name}" def _resolve_vpcconfig(conf, region=None, key=None, keyid=None, profile=None): @@ -461,7 +460,7 @@ def _function_config_present( [ret["comment"], "Function config to be modified"] ) if __opts__["test"]: - ret["comment"] = "Function {} set to be modified.".format(FunctionName) + ret["comment"] = f"Function {FunctionName} set to be modified." ret["result"] = None return ret _r = __salt__["boto_lambda.update_function_config"]( @@ -502,7 +501,7 @@ def _function_code_present( dlZipFile = __salt__["cp.cache_file"](path=ZipFile) if dlZipFile is False: ret["result"] = False - ret["comment"] = "Failed to cache ZipFile `{}`.".format(ZipFile) + ret["comment"] = f"Failed to cache ZipFile `{ZipFile}`." return ret ZipFile = dlZipFile size = os.path.getsize(ZipFile) @@ -522,7 +521,7 @@ def _function_code_present( update = True if update: if __opts__["test"]: - ret["comment"] = "Function {} set to be modified.".format(FunctionName) + ret["comment"] = f"Function {FunctionName} set to be modified." ret["result"] = None return ret ret["changes"]["old"] = { @@ -580,7 +579,7 @@ def _function_permissions_present( [ret["comment"], "Function permissions to be modified"] ) if __opts__["test"]: - ret["comment"] = "Function {} set to be modified.".format(FunctionName) + ret["comment"] = f"Function {FunctionName} set to be modified." ret["result"] = None return ret for sid, diff in diffs.items(): @@ -609,7 +608,7 @@ def _function_permissions_present( key=key, keyid=keyid, profile=profile, - **diff["new"] + **diff["new"], ) ret["changes"].setdefault("new", {}).setdefault("Permissions", {})[ sid @@ -665,11 +664,11 @@ def function_absent( return ret if r and not r["exists"]: - ret["comment"] = "Function {} does not exist.".format(FunctionName) + ret["comment"] = f"Function {FunctionName} does not exist." return ret if __opts__["test"]: - ret["comment"] = "Function {} is set to be removed.".format(FunctionName) + ret["comment"] = f"Function {FunctionName} is set to be removed." ret["result"] = None return ret r = __salt__["boto_lambda.delete_function"]( @@ -681,7 +680,7 @@ def function_absent( return ret ret["changes"]["old"] = {"function": FunctionName} ret["changes"]["new"] = {"function": None} - ret["comment"] = "Function {} deleted.".format(FunctionName) + ret["comment"] = f"Function {FunctionName} deleted." return ret @@ -746,7 +745,7 @@ def alias_present( if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "Alias {} is set to be created.".format(Name) + ret["comment"] = f"Alias {Name} is set to be created." ret["result"] = None return ret r = __salt__["boto_lambda.create_alias"]( @@ -768,12 +767,10 @@ def alias_present( ) ret["changes"]["old"] = {"alias": None} ret["changes"]["new"] = _describe - ret["comment"] = "Alias {} created.".format(Name) + ret["comment"] = f"Alias {Name} created." return ret - ret["comment"] = os.linesep.join( - [ret["comment"], "Alias {} is present.".format(Name)] - ) + ret["comment"] = os.linesep.join([ret["comment"], f"Alias {Name} is present."]) ret["changes"] = {} _describe = __salt__["boto_lambda.describe_alias"]( FunctionName, Name, region=region, key=key, keyid=keyid, profile=profile @@ -792,7 +789,7 @@ def alias_present( [ret["comment"], "Alias config to be modified"] ) if __opts__["test"]: - ret["comment"] = "Alias {} set to be modified.".format(Name) + ret["comment"] = f"Alias {Name} set to be modified." ret["result"] = None return ret _r = __salt__["boto_lambda.update_alias"]( @@ -854,11 +851,11 @@ def alias_absent( return ret if r and not r["exists"]: - ret["comment"] = "Alias {} does not exist.".format(Name) + ret["comment"] = f"Alias {Name} does not exist." return ret if __opts__["test"]: - ret["comment"] = "Alias {} is set to be removed.".format(Name) + ret["comment"] = f"Alias {Name} is set to be removed." ret["result"] = None return ret r = __salt__["boto_lambda.delete_alias"]( @@ -870,7 +867,7 @@ def alias_absent( return ret ret["changes"]["old"] = {"alias": Name} ret["changes"]["new"] = {"alias": None} - ret["comment"] = "Alias {} deleted.".format(Name) + ret["comment"] = f"Alias {Name} deleted." return ret @@ -885,7 +882,7 @@ def _get_function_arn(name, region=None, key=None, keyid=None, profile=None): region = profile["region"] if region is None: region = "us-east-1" - return "arn:aws:lambda:{}:{}:function:{}".format(region, account_id, name) + return f"arn:aws:lambda:{region}:{account_id}:function:{name}" def event_source_mapping_present( diff --git a/salt/states/boto_rds.py b/salt/states/boto_rds.py index b5894c1fbd3..5d33a01925f 100644 --- a/salt/states/boto_rds.py +++ b/salt/states/boto_rds.py @@ -68,7 +68,6 @@ config: """ - import logging import os @@ -306,7 +305,7 @@ def present( if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "RDS instance {} would be created.".format(name) + ret["comment"] = f"RDS instance {name} would be created." ret["result"] = None return ret @@ -374,9 +373,9 @@ def present( profile=profile, ) } - ret["comment"] = "RDS instance {} created.".format(name) + ret["comment"] = f"RDS instance {name} created." else: - ret["comment"] = "RDS instance {} exists.".format(name) + ret["comment"] = f"RDS instance {name} exists." return ret @@ -413,7 +412,7 @@ def replica_present( ) if not replica_exists.get("exists"): if __opts__["test"]: - ret["comment"] = "RDS read replica {} is set to be created ".format(name) + ret["comment"] = f"RDS read replica {name} is set to be created " ret["result"] = None return ret created = __salt__["boto_rds.create_read_replica"]( @@ -433,7 +432,7 @@ def replica_present( profile, ) if created: - ret["comment"] = "RDS replica {} created.".format(name) + ret["comment"] = f"RDS replica {name} created." ret["changes"]["old"] = {"instance": None} ret["changes"]["new"] = { "instance": __salt__["boto_rds.describe_db_instances"]( @@ -447,7 +446,7 @@ def replica_present( } else: ret["result"] = False - ret["comment"] = "Failed to create RDS replica {}.".format(name) + ret["comment"] = f"Failed to create RDS replica {name}." else: jmespath = "DBInstances[0].DBParameterGroups[0].DBParameterGroupName" pmg_name = __salt__["boto_rds.describe_db_instances"]( @@ -470,13 +469,13 @@ def replica_present( ) if not modified: ret["result"] = False - ret[ - "comment" - ] = "Failed to update parameter group of {} RDS instance.".format(name) + ret["comment"] = ( + f"Failed to update parameter group of {name} RDS instance." + ) ret["changes"]["old"] = pmg_name ret["changes"]["new"] = db_parameter_group_name ret["result"] = True - ret["comment"] = "RDS replica {} exists.".format(name) + ret["comment"] = f"RDS replica {name} exists." return ret @@ -547,7 +546,7 @@ def subnet_group_present( ret["result"] = False return ret if r["id"] is None: - ret["comment"] = "Subnet {} does not exist.".format(i) + ret["comment"] = f"Subnet {i} does not exist." ret["result"] = False return ret subnet_ids.append(r["id"]) @@ -557,7 +556,7 @@ def subnet_group_present( ) if not exists.get("exists"): if __opts__["test"]: - ret["comment"] = "Subnet group {} is set to be created.".format(name) + ret["comment"] = f"Subnet group {name} is set to be created." ret["result"] = None return ret created = __salt__["boto_rds.create_subnet_group"]( @@ -573,14 +572,14 @@ def subnet_group_present( if not created: ret["result"] = False - ret["comment"] = "Failed to create {} subnet group.".format(name) + ret["comment"] = f"Failed to create {name} subnet group." return ret ret["changes"]["old"] = None ret["changes"]["new"] = name - ret["comment"] = "Subnet {} created.".format(name) + ret["comment"] = f"Subnet {name} created." return ret else: - ret["comment"] = "Subnet {} present.".format(name) + ret["comment"] = f"Subnet {name} present." return ret @@ -642,11 +641,11 @@ def absent( ) if not current: ret["result"] = True - ret["comment"] = "{} RDS already absent.".format(name) + ret["comment"] = f"{name} RDS already absent." return ret if __opts__["test"]: - ret["comment"] = "RDS {} would be removed.".format(name) + ret["comment"] = f"RDS {name} would be removed." ret["result"] = None return ret deleted = __salt__["boto_rds.delete"]( @@ -663,11 +662,11 @@ def absent( ) if not deleted: ret["result"] = False - ret["comment"] = "Failed to delete {} RDS.".format(name) + ret["comment"] = f"Failed to delete {name} RDS." return ret ret["changes"]["old"] = {"instance": current[0]} ret["changes"]["new"] = {"instance": None} - ret["comment"] = "RDS {} deleted.".format(name) + ret["comment"] = f"RDS {name} deleted." return ret @@ -681,11 +680,11 @@ def subnet_group_absent( ) if not exists: ret["result"] = True - ret["comment"] = "{} RDS subnet group does not exist.".format(name) + ret["comment"] = f"{name} RDS subnet group does not exist." return ret if __opts__["test"]: - ret["comment"] = "RDS subnet group {} is set to be removed.".format(name) + ret["comment"] = f"RDS subnet group {name} is set to be removed." ret["result"] = None return ret deleted = __salt__["boto_rds.delete_subnet_group"]( @@ -693,11 +692,11 @@ def subnet_group_absent( ) if not deleted: ret["result"] = False - ret["comment"] = "Failed to delete {} RDS subnet group.".format(name) + ret["comment"] = f"Failed to delete {name} RDS subnet group." return ret ret["changes"]["old"] = name ret["changes"]["new"] = None - ret["comment"] = "RDS subnet group {} deleted.".format(name) + ret["comment"] = f"RDS subnet group {name} deleted." return ret @@ -762,7 +761,7 @@ def parameter_present( ) if not res.get("exists"): if __opts__["test"]: - ret["comment"] = "Parameter group {} is set to be created.".format(name) + ret["comment"] = f"Parameter group {name} is set to be created." ret["result"] = None return ret created = __salt__["boto_rds.create_parameter_group"]( @@ -777,12 +776,12 @@ def parameter_present( ) if not created: ret["result"] = False - ret["comment"] = "Failed to create {} parameter group.".format(name) + ret["comment"] = f"Failed to create {name} parameter group." return ret ret["changes"]["New Parameter Group"] = name - ret["comment"] = "Parameter group {} created.".format(name) + ret["comment"] = f"Parameter group {name} created." else: - ret["comment"] = "Parameter group {} present.".format(name) + ret["comment"] = f"Parameter group {name} present." if parameters is not None: params = {} changed = {} @@ -799,7 +798,7 @@ def parameter_present( if not options.get("result"): ret["result"] = False ret["comment"] = os.linesep.join( - [ret["comment"], "Faled to get parameters for group {}.".format(name)] + [ret["comment"], f"Faled to get parameters for group {name}."] ) return ret for parameter in options["parameters"].values(): @@ -853,14 +852,14 @@ def parameter_present( ret["comment"] = os.linesep.join( [ ret["comment"], - "Parameters {} for group {} are changed.".format(changed, name), + f"Parameters {changed} for group {name} are changed.", ] ) else: ret["comment"] = os.linesep.join( [ ret["comment"], - "Parameters {} for group {} are present.".format(params, name), + f"Parameters {params} for group {name} are present.", ] ) return ret diff --git a/salt/states/boto_route53.py b/salt/states/boto_route53.py index 0143c4e276f..39ed57aca52 100644 --- a/salt/states/boto_route53.py +++ b/salt/states/boto_route53.py @@ -70,7 +70,6 @@ passed in as a dict, or as a string to pull from pillars or minion config: key: askdjghsdfjkghWupUjasdflkdfklgjsdfjajkghs """ - import logging import uuid @@ -186,10 +185,10 @@ def present( log.info("Found private IP %s for instance %s", private_ip, name_tag) else: if public_ip is None: - ret[ - "comment" - ] = "Error: No Public IP assigned to instance with Name {}".format( - name_tag + ret["comment"] = ( + "Error: No Public IP assigned to instance with Name {}".format( + name_tag + ) ) ret["result"] = False return ret @@ -211,13 +210,13 @@ def present( identifier, ) except SaltInvocationError as err: - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" ret["result"] = False return ret if isinstance(record, dict) and not record: if __opts__["test"]: - ret["comment"] = "Route53 record {} set to be added.".format(name) + ret["comment"] = f"Route53 record {name} set to be added." ret["result"] = None return ret added = __salt__["boto_route53.add_record"]( @@ -244,10 +243,10 @@ def present( "ttl": ttl, "identifier": identifier, } - ret["comment"] = "Added {} Route53 record.".format(name) + ret["comment"] = f"Added {name} Route53 record." else: ret["result"] = False - ret["comment"] = "Failed to add {} Route53 record.".format(name) + ret["comment"] = f"Failed to add {name} Route53 record." return ret elif record: need_to_update = False @@ -268,7 +267,7 @@ def present( need_to_update = True if need_to_update: if __opts__["test"]: - ret["comment"] = "Route53 record {} set to be updated.".format(name) + ret["comment"] = f"Route53 record {name} set to be updated." ret["result"] = None return ret updated = __salt__["boto_route53.update_record"]( @@ -295,12 +294,12 @@ def present( "ttl": ttl, "identifier": identifier, } - ret["comment"] = "Updated {} Route53 record.".format(name) + ret["comment"] = f"Updated {name} Route53 record." else: ret["result"] = False - ret["comment"] = "Failed to update {} Route53 record.".format(name) + ret["comment"] = f"Failed to update {name} Route53 record." else: - ret["comment"] = "{} exists.".format(name) + ret["comment"] = f"{name} exists." return ret @@ -376,7 +375,7 @@ def absent( ) if record: if __opts__["test"]: - ret["comment"] = "Route53 record {} set to be deleted.".format(name) + ret["comment"] = f"Route53 record {name} set to be deleted." ret["result"] = None return ret deleted = __salt__["boto_route53.delete_record"]( @@ -396,12 +395,12 @@ def absent( if deleted: ret["changes"]["old"] = record ret["changes"]["new"] = None - ret["comment"] = "Deleted {} Route53 record.".format(name) + ret["comment"] = f"Deleted {name} Route53 record." else: ret["result"] = False - ret["comment"] = "Failed to delete {} Route53 record.".format(name) + ret["comment"] = f"Failed to delete {name} Route53 record." else: - ret["comment"] = "{} does not exist.".format(name) + ret["comment"] = f"{name} does not exist." return ret @@ -575,13 +574,13 @@ def hosted_zone_present( profile=profile, ) if res: - msg = "Hosted Zone {} successfully created".format(domain_name) + msg = f"Hosted Zone {domain_name} successfully created" log.info(msg) ret["comment"] = msg ret["changes"]["old"] = None ret["changes"]["new"] = res else: - ret["comment"] = "Creating Hosted Zone {} failed".format(domain_name) + ret["comment"] = f"Creating Hosted Zone {domain_name} failed" ret["result"] = False return ret @@ -609,11 +608,11 @@ def hosted_zone_absent( domain_name=domain_name, region=region, key=key, keyid=keyid, profile=profile ) if not deets: - ret["comment"] = "Hosted Zone {} already absent".format(domain_name) + ret["comment"] = f"Hosted Zone {domain_name} already absent" log.info(ret["comment"]) return ret if __opts__["test"]: - ret["comment"] = "Route53 Hosted Zone {} set to be deleted.".format(domain_name) + ret["comment"] = f"Route53 Hosted Zone {domain_name} set to be deleted." ret["result"] = None return ret # Not entirely comfortable with this - no safety checks around pub/priv, VPCs @@ -622,7 +621,7 @@ def hosted_zone_absent( if __salt__["boto_route53.delete_zone"]( zone=domain_name, region=region, key=key, keyid=keyid, profile=profile ): - ret["comment"] = "Route53 Hosted Zone {} deleted".format(domain_name) + ret["comment"] = f"Route53 Hosted Zone {domain_name} deleted" log.info(ret["comment"]) ret["changes"]["old"] = deets ret["changes"]["new"] = None diff --git a/salt/states/boto_s3.py b/salt/states/boto_s3.py index d466374cc27..e80f25c8539 100644 --- a/salt/states/boto_s3.py +++ b/salt/states/boto_s3.py @@ -48,7 +48,6 @@ config: :depends: boto3 """ - import copy import difflib import logging @@ -177,7 +176,7 @@ def object_present( combined_extra_args_keys = frozenset(combined_extra_args.keys()) extra_keys = combined_extra_args_keys - supported_args if extra_keys: - msg = "extra_args keys {} are not supported".format(extra_keys) + msg = f"extra_args keys {extra_keys} are not supported" return {"error": msg} # Get the hash of the local file @@ -253,7 +252,7 @@ def object_present( } if s3_metadata == desired_metadata: ret["result"] = True - ret["comment"] = "S3 object {} is present.".format(name) + ret["comment"] = f"S3 object {name} is present." return ret action = "update" else: @@ -277,8 +276,8 @@ def object_present( if __opts__["test"]: ret["result"] = None - ret["comment"] = "S3 object {} set to be {}d.".format(name, action) - ret["comment"] += "\nChanges:\n{}".format(changes_diff) + ret["comment"] = f"S3 object {name} set to be {action}d." + ret["comment"] += f"\nChanges:\n{changes_diff}" ret["changes"] = {"diff": changes_diff} return ret @@ -301,7 +300,7 @@ def object_present( return ret ret["result"] = True - ret["comment"] = "S3 object {} {}d.".format(name, action) - ret["comment"] += "\nChanges:\n{}".format(changes_diff) + ret["comment"] = f"S3 object {name} {action}d." + ret["comment"] += f"\nChanges:\n{changes_diff}" ret["changes"] = {"diff": changes_diff} return ret diff --git a/salt/states/boto_s3_bucket.py b/salt/states/boto_s3_bucket.py index 66dc68db08d..9baee1f5350 100644 --- a/salt/states/boto_s3_bucket.py +++ b/salt/states/boto_s3_bucket.py @@ -137,7 +137,6 @@ config: """ - import copy import logging @@ -299,7 +298,7 @@ def _get_role_arn(name, region=None, key=None, keyid=None, profile=None): region = profile["region"] if region is None: region = "us-east-1" - return "arn:aws:iam::{}:role/{}".format(account_id, name) + return f"arn:aws:iam::{account_id}:role/{name}" def _compare_json(current, desired, region, key, keyid, profile): @@ -440,7 +439,7 @@ def present( if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "S3 bucket {} is set to be created.".format(Bucket) + ret["comment"] = f"S3 bucket {Bucket} is set to be created." ret["result"] = None return ret r = __salt__["boto_s3_bucket.create"]( @@ -481,13 +480,13 @@ def present( ("put_website", Website, Website), ): if testval is not None: - r = __salt__["boto_s3_bucket.{}".format(setter)]( + r = __salt__[f"boto_s3_bucket.{setter}"]( Bucket=Bucket, region=region, key=key, keyid=keyid, profile=profile, - **funcargs + **funcargs, ) if not r.get("updated"): ret["result"] = False @@ -501,14 +500,12 @@ def present( ) ret["changes"]["old"] = {"bucket": None} ret["changes"]["new"] = _describe - ret["comment"] = "S3 bucket {} created.".format(Bucket) + ret["comment"] = f"S3 bucket {Bucket} created." return ret # bucket exists, ensure config matches - ret["comment"] = " ".join( - [ret["comment"], "S3 bucket {} is present.".format(Bucket)] - ) + ret["comment"] = " ".join([ret["comment"], f"S3 bucket {Bucket} is present."]) ret["changes"] = {} _describe = __salt__["boto_s3_bucket.describe"]( Bucket=Bucket, region=region, key=key, keyid=keyid, profile=profile @@ -647,7 +644,7 @@ def present( if not __opts__["test"]: if deleter and desired is None: # Setting can be deleted, so use that to unset it - r = __salt__["boto_s3_bucket.{}".format(deleter)]( + r = __salt__[f"boto_s3_bucket.{deleter}"]( Bucket=Bucket, region=region, key=key, @@ -662,13 +659,13 @@ def present( ret["changes"] = {} return ret else: - r = __salt__["boto_s3_bucket.{}".format(setter)]( + r = __salt__[f"boto_s3_bucket.{setter}"]( Bucket=Bucket, region=region, key=key, keyid=keyid, profile=profile, - **(desired or {}) + **(desired or {}), ) if not r.get("updated"): ret["result"] = False @@ -678,7 +675,7 @@ def present( ret["changes"] = {} return ret if update and __opts__["test"]: - msg = "S3 bucket {} set to be modified.".format(Bucket) + msg = f"S3 bucket {Bucket} set to be modified." ret["comment"] = msg ret["result"] = None return ret @@ -693,7 +690,7 @@ def present( ) log.warning(msg) ret["result"] = False - ret["comment"] = "Failed to update bucket: {}.".format(msg) + ret["comment"] = f"Failed to update bucket: {msg}." return ret return ret @@ -737,11 +734,11 @@ def absent(name, Bucket, Force=False, region=None, key=None, keyid=None, profile return ret if r and not r["exists"]: - ret["comment"] = "S3 bucket {} does not exist.".format(Bucket) + ret["comment"] = f"S3 bucket {Bucket} does not exist." return ret if __opts__["test"]: - ret["comment"] = "S3 bucket {} is set to be removed.".format(Bucket) + ret["comment"] = f"S3 bucket {Bucket} is set to be removed." ret["result"] = None return ret r = __salt__["boto_s3_bucket.delete"]( @@ -753,5 +750,5 @@ def absent(name, Bucket, Force=False, region=None, key=None, keyid=None, profile return ret ret["changes"]["old"] = {"bucket": Bucket} ret["changes"]["new"] = {"bucket": None} - ret["comment"] = "S3 bucket {} deleted.".format(Bucket) + ret["comment"] = f"S3 bucket {Bucket} deleted." return ret diff --git a/salt/states/boto_secgroup.py b/salt/states/boto_secgroup.py index b4037ad11a2..23ef79e32f9 100644 --- a/salt/states/boto_secgroup.py +++ b/salt/states/boto_secgroup.py @@ -283,7 +283,7 @@ def _security_group_present( ) if not exists: if __opts__["test"]: - ret["comment"] = "Security group {} is set to be created.".format(name) + ret["comment"] = f"Security group {name} is set to be created." ret["result"] = None return ret created = __salt__["boto_secgroup.create"]( @@ -309,12 +309,12 @@ def _security_group_present( vpc_name=vpc_name, ) ret["changes"]["new"] = {"secgroup": sg} - ret["comment"] = "Security group {} created.".format(name) + ret["comment"] = f"Security group {name} created." else: ret["result"] = False - ret["comment"] = "Failed to create {} security group.".format(name) + ret["comment"] = f"Failed to create {name} security group." else: - ret["comment"] = "Security group {} present.".format(name) + ret["comment"] = f"Security group {name} present." return ret @@ -422,7 +422,7 @@ def _get_rule_changes(rules, _rules): -1, ] if ip_protocol not in supported_protocols and ( - not "{}".format(ip_protocol).isdigit() or int(ip_protocol) > 255 + not f"{ip_protocol}".isdigit() or int(ip_protocol) > 255 ): raise SaltInvocationError( "Invalid ip_protocol {} specified in security group rule.".format( @@ -509,9 +509,7 @@ def _rules_present( vpc_name=vpc_name, ) if not sg: - ret[ - "comment" - ] = "{} security group configuration could not be retrieved.".format(name) + ret["comment"] = f"{name} security group configuration could not be retrieved." ret["result"] = False return ret rules = _split_rules(rules) @@ -568,12 +566,12 @@ def _rules_present( key=key, keyid=keyid, profile=profile, - **rule + **rule, ) if not _deleted: deleted = False if deleted: - ret["comment"] = "Removed rules on {} security group.".format(name) + ret["comment"] = f"Removed rules on {name} security group." else: ret["comment"] = "Failed to remove rules on {} security group.".format( name @@ -590,7 +588,7 @@ def _rules_present( key=key, keyid=keyid, profile=profile, - **rule + **rule, ) if not _created: created = False @@ -598,14 +596,14 @@ def _rules_present( ret["comment"] = " ".join( [ ret["comment"], - "Created rules on {} security group.".format(name), + f"Created rules on {name} security group.", ] ) else: ret["comment"] = " ".join( [ ret["comment"], - "Failed to create rules on {} security group.".format(name), + f"Failed to create rules on {name} security group.", ] ) ret["result"] = False @@ -654,9 +652,7 @@ def _rules_egress_present( vpc_name=vpc_name, ) if not sg: - ret[ - "comment" - ] = "{} security group configuration could not be retrieved.".format(name) + ret["comment"] = f"{name} security group configuration could not be retrieved." ret["result"] = False return ret rules_egress = _split_rules(rules_egress) @@ -714,7 +710,7 @@ def _rules_egress_present( keyid=keyid, profile=profile, egress=True, - **rule + **rule, ) if not _deleted: deleted = False @@ -722,7 +718,7 @@ def _rules_egress_present( ret["comment"] = " ".join( [ ret["comment"], - "Removed egress rule on {} security group.".format(name), + f"Removed egress rule on {name} security group.", ] ) else: @@ -747,7 +743,7 @@ def _rules_egress_present( keyid=keyid, profile=profile, egress=True, - **rule + **rule, ) if not _created: created = False @@ -755,7 +751,7 @@ def _rules_egress_present( ret["comment"] = " ".join( [ ret["comment"], - "Created egress rules on {} security group.".format(name), + f"Created egress rules on {name} security group.", ] ) else: @@ -831,7 +827,7 @@ def absent( if sg: if __opts__["test"]: - ret["comment"] = "Security group {} is set to be removed.".format(name) + ret["comment"] = f"Security group {name} is set to be removed." ret["result"] = None return ret deleted = __salt__["boto_secgroup.delete"]( @@ -847,12 +843,12 @@ def absent( if deleted: ret["changes"]["old"] = {"secgroup": sg} ret["changes"]["new"] = {"secgroup": None} - ret["comment"] = "Security group {} deleted.".format(name) + ret["comment"] = f"Security group {name} deleted." else: ret["result"] = False - ret["comment"] = "Failed to delete {} security group.".format(name) + ret["comment"] = f"Failed to delete {name} security group." else: - ret["comment"] = "{} security group does not exist.".format(name) + ret["comment"] = f"{name} security group does not exist." return ret @@ -882,9 +878,9 @@ def _tags_present( vpc_name=vpc_name, ) if not sg: - ret[ - "comment" - ] = "{} security group configuration could not be retrieved.".format(name) + ret["comment"] = ( + f"{name} security group configuration could not be retrieved." + ) ret["result"] = False return ret tags_to_add = tags diff --git a/salt/states/boto_sns.py b/salt/states/boto_sns.py index d4e4c05133b..387a29868c9 100644 --- a/salt/states/boto_sns.py +++ b/salt/states/boto_sns.py @@ -106,10 +106,10 @@ def present(name, subscriptions=None, region=None, key=None, keyid=None, profile ) if is_present: ret["result"] = True - ret["comment"] = "AWS SNS topic {} present.".format(name) + ret["comment"] = f"AWS SNS topic {name} present." else: if __opts__["test"]: - msg = "AWS SNS topic {} is set to be created.".format(name) + msg = f"AWS SNS topic {name} is set to be created." ret["comment"] = msg ret["result"] = None return ret @@ -118,13 +118,13 @@ def present(name, subscriptions=None, region=None, key=None, keyid=None, profile name, region=region, key=key, keyid=keyid, profile=profile ) if created: - msg = "AWS SNS topic {} created.".format(name) + msg = f"AWS SNS topic {name} created." ret["comment"] = msg ret["changes"]["old"] = None ret["changes"]["new"] = {"topic": name, "subscriptions": []} ret["result"] = True else: - ret["comment"] = "Failed to create {} AWS SNS topic".format(name) + ret["comment"] = f"Failed to create {name} AWS SNS topic" ret["result"] = False return ret @@ -264,7 +264,7 @@ def absent(name, region=None, key=None, keyid=None, profile=None, unsubscribe=Fa name, region=region, key=key, keyid=keyid, profile=profile ) if deleted: - ret["comment"] = "AWS SNS topic {} deleted.".format(name) + ret["comment"] = f"AWS SNS topic {name} deleted." ret["changes"]["new"] = None if unsubscribe is False: ret["changes"]["old"] = {"topic": name} @@ -276,8 +276,8 @@ def absent(name, region=None, key=None, keyid=None, profile=None, unsubscribe=Fa } else: ret["result"] = False - ret["comment"] = "Failed to delete {} AWS SNS topic.".format(name) + ret["comment"] = f"Failed to delete {name} AWS SNS topic." else: - ret["comment"] = "AWS SNS topic {} does not exist.".format(name) + ret["comment"] = f"AWS SNS topic {name} does not exist." return ret diff --git a/salt/states/boto_sqs.py b/salt/states/boto_sqs.py index 0c3784070c9..6f0e4b3a61a 100644 --- a/salt/states/boto_sqs.py +++ b/salt/states/boto_sqs.py @@ -124,12 +124,12 @@ def present( return ret if r["result"]: - ret["comment"].append("SQS queue {} present.".format(name)) + ret["comment"].append(f"SQS queue {name} present.") else: if __opts__["test"]: ret["result"] = None ret["comment"].append( - "SQS queue {} is set to be created.".format(name), + f"SQS queue {name} is set to be created.", ) ret["changes"] = {"old": None, "new": name} return ret @@ -149,7 +149,7 @@ def present( ) return ret - ret["comment"].append("SQS queue {} created.".format(name)) + ret["comment"].append(f"SQS queue {name} created.") ret["changes"]["old"] = None ret["changes"]["new"] = name # Return immediately, as the create call also set all attributes @@ -238,7 +238,7 @@ def present( return ret ret["comment"].append( - "Updated SQS queue attribute(s) {}.".format(attr_names), + f"Updated SQS queue attribute(s) {attr_names}.", ) ret["changes"]["attributes"] = {"diff": attributes_diff} return ret @@ -293,7 +293,7 @@ def absent( if __opts__["test"]: ret["result"] = None - ret["comment"] = "SQS queue {} is set to be removed.".format(name) + ret["comment"] = f"SQS queue {name} is set to be removed." ret["changes"] = {"old": name, "new": None} return ret @@ -309,7 +309,7 @@ def absent( ret["comment"] = str(r["error"]) return ret - ret["comment"] = "SQS queue {} was deleted.".format(name) + ret["comment"] = f"SQS queue {name} was deleted." ret["changes"]["old"] = name ret["changes"]["new"] = None return ret diff --git a/salt/states/boto_vpc.py b/salt/states/boto_vpc.py index d822adbbeb7..d65d3ca7255 100644 --- a/salt/states/boto_vpc.py +++ b/salt/states/boto_vpc.py @@ -141,7 +141,6 @@ Delete also accepts a VPC peering connection id. """ - import logging import salt.utils.dictupdate as dictupdate @@ -228,7 +227,7 @@ def present( if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "VPC {} is set to be created.".format(name) + ret["comment"] = f"VPC {name} is set to be created." ret["result"] = None return ret r = __salt__["boto_vpc.create"]( @@ -252,7 +251,7 @@ def present( ) ret["changes"]["old"] = {"vpc": None} ret["changes"]["new"] = _describe - ret["comment"] = "VPC {} created.".format(name) + ret["comment"] = f"VPC {name} created." return ret ret["comment"] = "VPC present." return ret @@ -294,11 +293,11 @@ def absent(name, tags=None, region=None, key=None, keyid=None, profile=None): _id = r.get("id") if not _id: - ret["comment"] = "{} VPC does not exist.".format(name) + ret["comment"] = f"{name} VPC does not exist." return ret if __opts__["test"]: - ret["comment"] = "VPC {} is set to be removed.".format(name) + ret["comment"] = f"VPC {name} is set to be removed." ret["result"] = None return ret r = __salt__["boto_vpc.delete"]( @@ -310,7 +309,7 @@ def absent(name, tags=None, region=None, key=None, keyid=None, profile=None): return ret ret["changes"]["old"] = {"vpc": _id} ret["changes"]["new"] = {"vpc": None} - ret["comment"] = "VPC {} deleted.".format(name) + ret["comment"] = f"VPC {name} deleted." return ret @@ -429,7 +428,7 @@ def dhcp_options_present( return ret else: if __opts__["test"]: - ret["comment"] = "DHCP options {} are set to be created.".format(name) + ret["comment"] = f"DHCP options {name} are set to be created." ret["result"] = None return ret @@ -457,7 +456,7 @@ def dhcp_options_present( ret["changes"]["old"] = {"dhcp_options": None} ret["changes"]["new"] = {"dhcp_options": _new} - ret["comment"] = "DHCP options {} created.".format(name) + ret["comment"] = f"DHCP options {name} created." return ret @@ -509,11 +508,11 @@ def dhcp_options_absent( _id = r.get("id") if not _id: - ret["comment"] = "DHCP options {} do not exist.".format(name) + ret["comment"] = f"DHCP options {name} do not exist." return ret if __opts__["test"]: - ret["comment"] = "DHCP options {} are set to be deleted.".format(name) + ret["comment"] = f"DHCP options {name} are set to be deleted." ret["result"] = None return ret @@ -529,7 +528,7 @@ def dhcp_options_absent( ret["changes"]["old"] = {"dhcp_options": _id} ret["changes"]["new"] = {"dhcp_options": None} - ret["comment"] = "DHCP options {} deleted.".format(name) + ret["comment"] = f"DHCP options {name} deleted." return ret @@ -548,7 +547,6 @@ def subnet_present( route_table_name=None, auto_assign_public_ipv4=False, ): - """ Ensure a subnet exists. @@ -669,7 +667,7 @@ def subnet_present( if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "Subnet {} is set to be created.".format(name) + ret["comment"] = f"Subnet {name} is set to be created." ret["result"] = None return ret r = __salt__["boto_vpc.create_subnet"]( @@ -694,7 +692,7 @@ def subnet_present( ) ret["changes"]["old"] = {"subnet": None} ret["changes"]["new"] = _describe - ret["comment"] = "Subnet {} created.".format(name) + ret["comment"] = f"Subnet {name} created." else: ret["comment"] = "Subnet present." @@ -705,7 +703,7 @@ def subnet_present( ) if not _verify_subnet_association(route_table_desc, _describe["subnet"]["id"]): if __opts__["test"]: - msg = "Subnet is set to be associated with route table {}".format(rtid) + msg = f"Subnet is set to be associated with route table {rtid}" ret["comment"] = " ".join([ret["comment"], msg]) ret["result"] = None return ret @@ -743,7 +741,7 @@ def subnet_present( ret["result"] = False return ret else: - msg = "Subnet successfully associated with route table {}.".format(rtid) + msg = f"Subnet successfully associated with route table {rtid}." ret["comment"] = " ".join([ret["comment"], msg]) if "new" not in ret["changes"]: ret["changes"]["new"] = __salt__["boto_vpc.describe_subnet"]( @@ -761,7 +759,7 @@ def subnet_present( ret["comment"] = " ".join( [ ret["comment"], - "Subnet is already associated with route table {}".format(rtid), + f"Subnet is already associated with route table {rtid}", ] ) return ret @@ -823,7 +821,7 @@ def subnet_absent( _id = r.get("id") if not _id: - ret["comment"] = "{} subnet does not exist.".format(name) + ret["comment"] = f"{name} subnet does not exist." return ret if __opts__["test"]: @@ -841,7 +839,7 @@ def subnet_absent( ret["changes"]["old"] = {"subnet": _id} ret["changes"]["new"] = {"subnet": None} - ret["comment"] = "Subnet {} deleted.".format(name) + ret["comment"] = f"Subnet {name} deleted." return ret @@ -904,7 +902,7 @@ def internet_gateway_present( if not r.get("exists"): if __opts__["test"]: - ret["comment"] = "Internet gateway {} is set to be created.".format(name) + ret["comment"] = f"Internet gateway {name} is set to be created." ret["result"] = None return ret r = __salt__["boto_vpc.create_internet_gateway"]( @@ -926,9 +924,9 @@ def internet_gateway_present( ret["changes"]["old"] = {"internet_gateway": None} ret["changes"]["new"] = {"internet_gateway": r["id"]} - ret["comment"] = "Internet gateway {} created.".format(name) + ret["comment"] = f"Internet gateway {name} created." return ret - ret["comment"] = "Internet gateway {} present.".format(name) + ret["comment"] = f"Internet gateway {name} present." return ret @@ -977,11 +975,11 @@ def internet_gateway_absent( igw_id = r["id"] if not igw_id: - ret["comment"] = "Internet gateway {} does not exist.".format(name) + ret["comment"] = f"Internet gateway {name} does not exist." return ret if __opts__["test"]: - ret["comment"] = "Internet gateway {} is set to be removed.".format(name) + ret["comment"] = f"Internet gateway {name} is set to be removed." ret["result"] = None return ret r = __salt__["boto_vpc.delete_internet_gateway"]( @@ -1000,7 +998,7 @@ def internet_gateway_absent( return ret ret["changes"]["old"] = {"internet_gateway": igw_id} ret["changes"]["new"] = {"internet_gateway": None} - ret["comment"] = "Internet gateway {} deleted.".format(name) + ret["comment"] = f"Internet gateway {name} deleted." return ret @@ -1162,7 +1160,7 @@ def _route_table_present( if not _id: if __opts__["test"]: - msg = "Route table {} is set to be created.".format(name) + msg = f"Route table {name} is set to be created." ret["comment"] = msg ret["result"] = None return ret @@ -1186,9 +1184,9 @@ def _route_table_present( ret["changes"]["old"] = {"route_table": None} ret["changes"]["new"] = {"route_table": r["id"]} - ret["comment"] = "Route table {} created.".format(name) + ret["comment"] = f"Route table {name} created." return ret - ret["comment"] = "Route table {} ({}) present.".format(name, _id) + ret["comment"] = f"Route table {name} ({_id}) present." return ret @@ -1247,7 +1245,7 @@ def _routes_present( ret["result"] = False return ret if r["id"] is None: - msg = "Internet gateway {} does not exist.".format(i) + msg = f"Internet gateway {i} does not exist." ret["comment"] = msg ret["result"] = False return ret @@ -1271,7 +1269,7 @@ def _routes_present( ret["result"] = False return ret if r["id"] is None: - msg = "VPC peering connection {} does not exist.".format(i) + msg = f"VPC peering connection {i} does not exist." ret["comment"] = msg ret["result"] = False return ret @@ -1325,7 +1323,7 @@ def _routes_present( to_delete.append(route) if to_create or to_delete: if __opts__["test"]: - msg = "Route table {} set to have routes modified.".format(route_table_name) + msg = f"Route table {route_table_name} set to have routes modified." ret["comment"] = msg ret["result"] = None return ret @@ -1359,7 +1357,7 @@ def _routes_present( key=key, keyid=keyid, profile=profile, - **r + **r, ) if not res["created"]: msg = "Failed to create route {} in route table {}: {}.".format( @@ -1414,7 +1412,7 @@ def _subnets_present( ret["result"] = False return ret if r["id"] is None: - msg = "Subnet {} does not exist.".format(i) + msg = f"Subnet {i} does not exist." ret["comment"] = msg ret["result"] = False return ret @@ -1538,11 +1536,11 @@ def route_table_absent(name, region=None, key=None, keyid=None, profile=None): rtbl_id = r["id"] if not rtbl_id: - ret["comment"] = "Route table {} does not exist.".format(name) + ret["comment"] = f"Route table {name} does not exist." return ret if __opts__["test"]: - ret["comment"] = "Route table {} is set to be removed.".format(name) + ret["comment"] = f"Route table {name} is set to be removed." ret["result"] = None return ret @@ -1557,7 +1555,7 @@ def route_table_absent(name, region=None, key=None, keyid=None, profile=None): return ret ret["changes"]["old"] = {"route_table": rtbl_id} ret["changes"]["new"] = {"route_table": None} - ret["comment"] = "Route table {} deleted.".format(name) + ret["comment"] = f"Route table {name} deleted." return ret @@ -1652,7 +1650,7 @@ def nat_gateway_present( inst = r[0] _id = inst.get("NatGatewayId") - ret["comment"] = "Nat gateway {} present.".format(_id) + ret["comment"] = f"Nat gateway {_id} present." return ret @@ -1742,9 +1740,7 @@ def nat_gateway_absent( r["error"]["message"] ) return ret - ret["comment"] = ", ".join( - (ret["comment"], "Nat gateway {} deleted.".format(rtbl_id)) - ) + ret["comment"] = ", ".join((ret["comment"], f"Nat gateway {rtbl_id} deleted.")) ret["changes"]["old"] = {"nat_gateway": rtbl_id} ret["changes"]["new"] = {"nat_gateway": None} return ret @@ -2053,10 +2049,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/bower.py b/salt/states/bower.py index 0c1928ca47c..e7966345273 100644 --- a/salt/states/bower.py +++ b/salt/states/bower.py @@ -29,7 +29,6 @@ Example: - npm: bower """ - from salt.exceptions import CommandExecutionError, CommandNotFoundError @@ -88,7 +87,7 @@ def installed(name, dir, pkgs=None, user=None, env=None): installed_pkgs = __salt__["bower.list"](dir=dir, runas=user, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret["result"] = False - ret["comment"] = "Error looking up '{}': {}".format(name, err) + ret["comment"] = f"Error looking up '{name}': {err}" return ret else: installed_pkgs = {p: info for p, info in installed_pkgs.items()} @@ -106,7 +105,7 @@ def installed(name, dir, pkgs=None, user=None, env=None): if pkg_name in installed_pkgs: installed_pkg = installed_pkgs[pkg_name] installed_pkg_ver = installed_pkg.get("pkgMeta").get("version") - installed_name_ver = "{}#{}".format(pkg_name, installed_pkg_ver) + installed_name_ver = f"{pkg_name}#{installed_pkg_ver}" # If given an explicit version check the installed version matches. if pkg_ver: @@ -200,30 +199,30 @@ def removed(name, dir, user=None): installed_pkgs = __salt__["bower.list"](dir=dir, runas=user) except (CommandExecutionError, CommandNotFoundError) as err: ret["result"] = False - ret["comment"] = "Error removing '{}': {}".format(name, err) + ret["comment"] = f"Error removing '{name}': {err}" return ret if name not in installed_pkgs: ret["result"] = True - ret["comment"] = "Package '{}' is not installed".format(name) + ret["comment"] = f"Package '{name}' is not installed" return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Package '{}' is set to be removed".format(name) + ret["comment"] = f"Package '{name}' is set to be removed" return ret try: if __salt__["bower.uninstall"](pkg=name, dir=dir, runas=user): ret["result"] = True ret["changes"] = {name: "Removed"} - ret["comment"] = "Package '{}' was successfully removed".format(name) + ret["comment"] = f"Package '{name}' was successfully removed" else: ret["result"] = False - ret["comment"] = "Error removing '{}'".format(name) + ret["comment"] = f"Error removing '{name}'" except (CommandExecutionError, CommandNotFoundError) as err: ret["result"] = False - ret["comment"] = "Error removing '{}': {}".format(name, err) + ret["comment"] = f"Error removing '{name}': {err}" return ret @@ -242,14 +241,14 @@ def bootstrap(name, user=None): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Directory '{}' is set to be bootstrapped".format(name) + ret["comment"] = f"Directory '{name}' is set to be bootstrapped" return ret try: call = __salt__["bower.install"](pkg=None, dir=name, runas=user) except (CommandNotFoundError, CommandExecutionError) as err: ret["result"] = False - ret["comment"] = "Error bootstrapping '{}': {}".format(name, err) + ret["comment"] = f"Error bootstrapping '{name}': {err}" return ret if not call: @@ -280,21 +279,21 @@ def pruned(name, user=None, env=None): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Directory '{}' is set to be pruned".format(name) + ret["comment"] = f"Directory '{name}' is set to be pruned" return ret try: call = __salt__["bower.prune"](dir=name, runas=user, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret["result"] = False - ret["comment"] = "Error pruning '{}': {}".format(name, err) + ret["comment"] = f"Error pruning '{name}': {err}" return ret ret["result"] = True if call: - ret["comment"] = "Directory '{}' was successfully pruned".format(name) + ret["comment"] = f"Directory '{name}' was successfully pruned" ret["changes"] = {"old": [], "new": call} else: - ret["comment"] = "No packages were pruned from directory '{}'".format(name) + ret["comment"] = f"No packages were pruned from directory '{name}'" return ret diff --git a/salt/states/btrfs.py b/salt/states/btrfs.py index 68ab8f869c9..2c17192754e 100644 --- a/salt/states/btrfs.py +++ b/salt/states/btrfs.py @@ -97,7 +97,7 @@ def __mount_device(action): if device: dest = _mount(device, use_default) if not dest: - msg = "Device {} cannot be mounted".format(device) + msg = f"Device {device} cannot be mounted" ret["comment"].append(msg) kwargs["__dest"] = dest ret = action(*args, **kwargs) @@ -157,7 +157,7 @@ def subvolume_created( exists = __salt__["btrfs.subvolume_exists"](path) if exists: - ret["comment"].append("Subvolume {} already present".format(name)) + ret["comment"].append(f"Subvolume {name} already present") # Resolve first the test case. The check is not complete, but at # least we will report if a subvolume needs to be created. Can @@ -166,7 +166,7 @@ def subvolume_created( if __opts__["test"]: ret["result"] = None if not exists: - ret["changes"][name] = "Subvolume {} will be created".format(name) + ret["changes"][name] = f"Subvolume {name} will be created" return ret if not exists: @@ -174,16 +174,16 @@ def subvolume_created( _path = os.path.dirname(path) res = __states__["file.directory"](_path, makedirs=True) if not res["result"]: - ret["comment"].append("Error creating {} directory".format(_path)) + ret["comment"].append(f"Error creating {_path} directory") return ret try: __salt__["btrfs.subvolume_create"](name, dest=__dest, qgroupids=qgroupids) except CommandExecutionError: - ret["comment"].append("Error creating subvolume {}".format(name)) + ret["comment"].append(f"Error creating subvolume {name}") return ret - ret["changes"][name] = "Created subvolume {}".format(name) + ret["changes"][name] = f"Created subvolume {name}" # If the volume was already present, we can opt-out the check for # default subvolume. @@ -227,12 +227,12 @@ def subvolume_deleted(name, device, commit=False, __dest=None): exists = __salt__["btrfs.subvolume_exists"](path) if not exists: - ret["comment"].append("Subvolume {} already missing".format(name)) + ret["comment"].append(f"Subvolume {name} already missing") if __opts__["test"]: ret["result"] = None if exists: - ret["changes"][name] = "Subvolume {} will be removed".format(name) + ret["changes"][name] = f"Subvolume {name} will be removed" return ret # If commit is set, we wait until all is over @@ -242,10 +242,10 @@ def subvolume_deleted(name, device, commit=False, __dest=None): try: __salt__["btrfs.subvolume_delete"](path, commit=commit) except CommandExecutionError: - ret["comment"].append("Error removing subvolume {}".format(name)) + ret["comment"].append(f"Error removing subvolume {name}") return ret - ret["changes"][name] = "Removed subvolume {}".format(name) + ret["changes"][name] = f"Removed subvolume {name}" ret["result"] = True return ret @@ -320,7 +320,7 @@ def properties(name, device, use_default=False, __dest=None, **properties): path = name if not os.path.exists(path): - ret["comment"].append("Object {} not found".format(name)) + ret["comment"].append(f"Object {name} not found") return ret # Convert the booleans to lowercase @@ -332,14 +332,14 @@ def properties(name, device, use_default=False, __dest=None, **properties): try: current_properties = __salt__["btrfs.properties"](path) except CommandExecutionError as e: - ret["comment"].append("Error reading properties from {}".format(name)) - ret["comment"].append("Current error {}".format(e)) + ret["comment"].append(f"Error reading properties from {name}") + ret["comment"].append(f"Current error {e}") return ret try: properties_to_set = _diff_properties(properties, current_properties) except KeyError: - ret["comment"].append("Some property not found in {}".format(name)) + ret["comment"].append(f"Some property not found in {name}") return ret if __opts__["test"]: @@ -347,14 +347,12 @@ def properties(name, device, use_default=False, __dest=None, **properties): if properties_to_set: ret["changes"] = properties_to_set else: - msg = "No properties will be changed in {}".format(name) + msg = f"No properties will be changed in {name}" ret["comment"].append(msg) return ret if properties_to_set: - _properties = ",".join( - "{}={}".format(k, v) for k, v in properties_to_set.items() - ) + _properties = ",".join(f"{k}={v}" for k, v in properties_to_set.items()) __salt__["btrfs.properties"](path, set=_properties) current_properties = __salt__["btrfs.properties"](path) @@ -366,10 +364,10 @@ def properties(name, device, use_default=False, __dest=None, **properties): ret["comment"].append(msg) return ret - ret["comment"].append("Properties changed in {}".format(name)) + ret["comment"].append(f"Properties changed in {name}") ret["changes"] = properties_to_set else: - ret["comment"].append("Properties not changed in {}".format(name)) + ret["comment"].append(f"Properties not changed in {name}") ret["result"] = True return ret diff --git a/salt/states/cabal.py b/salt/states/cabal.py index 8c415e32c4f..5190d850a9a 100644 --- a/salt/states/cabal.py +++ b/salt/states/cabal.py @@ -22,7 +22,6 @@ pkg.installed state for the package which provides cabal """ - import salt.utils.path from salt.exceptions import CommandExecutionError, CommandNotFoundError @@ -84,7 +83,7 @@ def installed(name, pkgs=None, user=None, install_global=False, env=None): call = __salt__["cabal.update"](user=user, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret["result"] = False - ret["comment"] = "Could not run cabal update {}".format(err) + ret["comment"] = f"Could not run cabal update {err}" return ret if pkgs is not None: @@ -96,7 +95,7 @@ def installed(name, pkgs=None, user=None, install_global=False, env=None): installed_pkgs = __salt__["cabal.list"](user=user, installed=True, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret["result"] = False - ret["comment"] = "Error looking up '{}': {}".format(name, err) + ret["comment"] = f"Error looking up '{name}': {err}" return ret pkgs_satisfied = [] @@ -181,24 +180,24 @@ def removed(name, user=None, env=None): installed_pkgs = __salt__["cabal.list"](user=user, installed=True, env=env) except (CommandNotFoundError, CommandExecutionError) as err: ret["result"] = False - ret["comment"] = "Error looking up '{}': {}".format(name, err) + ret["comment"] = f"Error looking up '{name}': {err}" if name not in installed_pkgs: ret["result"] = True - ret["comment"] = "Package '{}' is not installed".format(name) + ret["comment"] = f"Package '{name}' is not installed" return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Package '{}' is set to be removed".format(name) + ret["comment"] = f"Package '{name}' is set to be removed" return ret if __salt__["cabal.uninstall"](pkg=name, user=user, env=env): ret["result"] = True ret["changes"][name] = "Removed" - ret["comment"] = "Package '{}' was successfully removed".format(name) + ret["comment"] = f"Package '{name}' was successfully removed" else: ret["result"] = False - ret["comment"] = "Error removing package '{}'".format(name) + ret["comment"] = f"Error removing package '{name}'" return ret diff --git a/salt/states/chocolatey.py b/salt/states/chocolatey.py index 87dad46a751..5e49113607e 100644 --- a/salt/states/chocolatey.py +++ b/salt/states/chocolatey.py @@ -141,13 +141,13 @@ def installed( ret["comment"] = f"{name} {version} is already installed" else: if allow_multiple: - ret[ - "comment" - ] = f"{name} {version} will be installed side by side with {name} {installed_version} if supported" + ret["comment"] = ( + f"{name} {version} will be installed side by side with {name} {installed_version} if supported" + ) else: - ret[ - "comment" - ] = f"{name} {version} will be installed over {name} {installed_version}" + ret["comment"] = ( + f"{name} {version} will be installed over {name} {installed_version}" + ) force = True else: version = installed_version @@ -374,14 +374,14 @@ def upgraded( if salt.utils.versions.compare( ver1=installed_version, oper="<", ver2=version ): - ret[ - "comment" - ] = f"{name} {installed_version} will be upgraded to version {version}" + ret["comment"] = ( + f"{name} {installed_version} will be upgraded to version {version}" + ) # If installed version is newer than new version else: - ret[ - "comment" - ] = f"{name} {installed_version} (newer) is already installed" + ret["comment"] = ( + f"{name} {installed_version} (newer) is already installed" + ) return ret # Catch all for a condition where version is not passed and there is no # available version diff --git a/salt/states/chronos_job.py b/salt/states/chronos_job.py index 7bea17b8335..dc016eb3718 100644 --- a/salt/states/chronos_job.py +++ b/salt/states/chronos_job.py @@ -97,7 +97,7 @@ def config(name, config): # if test report there will be an update if __opts__["test"]: ret["result"] = None - ret["comment"] = "Chronos job {} is set to be updated".format(name) + ret["comment"] = f"Chronos job {name} is set to be updated" return ret update_result = __salt__["chronos.update_job"](name, update_config) @@ -110,10 +110,10 @@ def config(name, config): return ret else: ret["result"] = True - ret["comment"] = "Updated job config for {}".format(name) + ret["comment"] = f"Updated job config for {name}" return ret ret["result"] = True - ret["comment"] = "Chronos job {} configured correctly".format(name) + ret["comment"] = f"Chronos job {name} configured correctly" return ret @@ -127,18 +127,18 @@ def absent(name): ret = {"name": name, "changes": {}, "result": False, "comment": ""} if not __salt__["chronos.has_job"](name): ret["result"] = True - ret["comment"] = "Job {} already absent".format(name) + ret["comment"] = f"Job {name} already absent" return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Job {} is set to be removed".format(name) + ret["comment"] = f"Job {name} is set to be removed" return ret if __salt__["chronos.rm_job"](name): ret["changes"] = {"job": name} ret["result"] = True - ret["comment"] = "Removed job {}".format(name) + ret["comment"] = f"Removed job {name}" return ret else: ret["result"] = False - ret["comment"] = "Failed to remove job {}".format(name) + ret["comment"] = f"Failed to remove job {name}" return ret diff --git a/salt/states/cimc.py b/salt/states/cimc.py index 09832c99ed4..ac6996211bc 100644 --- a/salt/states/cimc.py +++ b/salt/states/cimc.py @@ -17,7 +17,6 @@ relies on the CIMC proxy module to interface with the device. """ - import logging log = logging.getLogger(__name__) @@ -477,9 +476,9 @@ def user(name, id="", user="", priv="", password="", status="active"): if not conf: ret["result"] = False - ret[ - "comment" - ] = "Unable to find requested user id on device. Please verify id is valid." + ret["comment"] = ( + "Unable to find requested user id on device. Please verify id is valid." + ) return ret updates = __salt__["cimc.set_user"](str(id), user, password, priv, status) diff --git a/salt/states/cloud.py b/salt/states/cloud.py index adb55dcab0f..8b7afc71c0d 100644 --- a/salt/states/cloud.py +++ b/salt/states/cloud.py @@ -13,7 +13,6 @@ Use this minion to spin up a cloud instance: my-ec2-config """ - import pprint import salt.utils.cloud as suc @@ -103,21 +102,21 @@ def present(name, cloud_provider, onlyif=None, unless=None, opts=None, **kwargs) # need to ensure ALL providers don't have the instance if __salt__["cloud.has_instance"](name=name, provider=None): ret["result"] = True - ret["comment"] = "Already present instance {}".format(name) + ret["comment"] = f"Already present instance {name}" return ret if __opts__["test"]: - ret["comment"] = "Instance {} needs to be created".format(name) + ret["comment"] = f"Instance {name} needs to be created" return ret info = __salt__["cloud.create"](cloud_provider, name, opts=opts, **kwargs) if info and "Error" not in info: ret["changes"] = info ret["result"] = True - ret[ - "comment" - ] = "Created instance {} using provider {} and the following options: {}".format( - name, cloud_provider, pprint.pformat(kwargs) + ret["comment"] = ( + "Created instance {} using provider {} and the following options: {}".format( + name, cloud_provider, pprint.pformat(kwargs) + ) ) elif info and "Error" in info: ret["result"] = False @@ -173,18 +172,18 @@ def absent(name, onlyif=None, unless=None): if not __salt__["cloud.has_instance"](name=name, provider=None): ret["result"] = True - ret["comment"] = "Already absent instance {}".format(name) + ret["comment"] = f"Already absent instance {name}" return ret if __opts__["test"]: - ret["comment"] = "Instance {} needs to be destroyed".format(name) + ret["comment"] = f"Instance {name} needs to be destroyed" return ret info = __salt__["cloud.destroy"](name) if info and "Error" not in info: ret["changes"] = info ret["result"] = True - ret["comment"] = "Destroyed instance {}".format(name) + ret["comment"] = f"Destroyed instance {name}" elif "Error" in info: ret["result"] = False ret["comment"] = "Failed to destroy instance {}: {}".format( @@ -193,7 +192,7 @@ def absent(name, onlyif=None, unless=None): ) else: ret["result"] = False - ret["comment"] = "Failed to destroy instance {}".format(name) + ret["comment"] = f"Failed to destroy instance {name}" return ret @@ -244,11 +243,11 @@ def profile(name, profile, onlyif=None, unless=None, opts=None, **kwargs): instance = _get_instance([name]) if instance and not any("Not Actioned" in key for key in instance): ret["result"] = True - ret["comment"] = "Already present instance {}".format(name) + ret["comment"] = f"Already present instance {name}" return ret if __opts__["test"]: - ret["comment"] = "Instance {} needs to be created".format(name) + ret["comment"] = f"Instance {name} needs to be created" return ret info = __salt__["cloud.profile"](profile, name, vm_overrides=kwargs, opts=opts) @@ -281,7 +280,7 @@ def profile(name, profile, onlyif=None, unless=None, opts=None, **kwargs): ret["comment"] = "Failed to create instance {} using profile {}: {}".format( name, profile, - "{}\n{}\n".format(main_error, name_error).strip(), + f"{main_error}\n{name_error}\n".strip(), ) else: ret["result"] = False @@ -303,22 +302,22 @@ def volume_present(name, provider=None, **kwargs): volumes = __salt__["cloud.volume_list"](provider=provider) if name in volumes: - ret["comment"] = "Volume exists: {}".format(name) + ret["comment"] = f"Volume exists: {name}" ret["result"] = True return ret elif __opts__["test"]: - ret["comment"] = "Volume {} will be created.".format(name) + ret["comment"] = f"Volume {name} will be created." ret["result"] = None return ret response = __salt__["cloud.volume_create"](names=name, provider=provider, **kwargs) if response: ret["result"] = True - ret["comment"] = "Volume {} was created".format(name) + ret["comment"] = f"Volume {name} was created" ret["changes"] = {"old": None, "new": response} else: ret["result"] = False - ret["comment"] = "Volume {} failed to create.".format(name) + ret["comment"] = f"Volume {name} failed to create." return ret @@ -337,18 +336,18 @@ def volume_absent(name, provider=None, **kwargs): ret["result"] = True return ret elif __opts__["test"]: - ret["comment"] = "Volume {} will be deleted.".format(name) + ret["comment"] = f"Volume {name} will be deleted." ret["result"] = None return ret response = __salt__["cloud.volume_delete"](names=name, provider=provider, **kwargs) if response: ret["result"] = True - ret["comment"] = "Volume {} was deleted".format(name) + ret["comment"] = f"Volume {name} was deleted" ret["changes"] = {"old": volumes[name], "new": response} else: ret["result"] = False - ret["comment"] = "Volume {} failed to delete.".format(name) + ret["comment"] = f"Volume {name} failed to delete." return ret @@ -375,15 +374,15 @@ def volume_attached(name, server_name, provider=None, **kwargs): ret["result"] = True return ret elif name not in volumes: - ret["comment"] = "Volume {} does not exist".format(name) + ret["comment"] = f"Volume {name} does not exist" ret["result"] = False return ret elif not instance: - ret["comment"] = "Server {} does not exist".format(server_name) + ret["comment"] = f"Server {server_name} does not exist" ret["result"] = False return ret elif __opts__["test"]: - ret["comment"] = "Volume {} will be will be attached.".format(name) + ret["comment"] = f"Volume {name} will be will be attached." ret["result"] = None return ret @@ -392,11 +391,11 @@ def volume_attached(name, server_name, provider=None, **kwargs): ) if response: ret["result"] = True - ret["comment"] = "Volume {} was created".format(name) + ret["comment"] = f"Volume {name} was created" ret["changes"] = {"old": volumes[name], "new": response} else: ret["result"] = False - ret["comment"] = "Volume {} failed to attach.".format(name) + ret["comment"] = f"Volume {name} failed to attach." return ret @@ -429,15 +428,15 @@ def volume_detached(name, server_name=None, provider=None, **kwargs): ret["result"] = True return ret elif name not in volumes: - ret["comment"] = "Volume {} does not exist".format(name) + ret["comment"] = f"Volume {name} does not exist" ret["result"] = True return ret elif not instance and server_name is not None: - ret["comment"] = "Server {} does not exist".format(server_name) + ret["comment"] = f"Server {server_name} does not exist" ret["result"] = True return ret elif __opts__["test"]: - ret["comment"] = "Volume {} will be will be detached.".format(name) + ret["comment"] = f"Volume {name} will be will be detached." ret["result"] = None return ret @@ -446,9 +445,9 @@ def volume_detached(name, server_name=None, provider=None, **kwargs): ) if response: ret["result"] = True - ret["comment"] = "Volume {} was created".format(name) + ret["comment"] = f"Volume {name} was created" ret["changes"] = {"old": volumes[name], "new": response} else: ret["result"] = False - ret["comment"] = "Volume {} failed to detach.".format(name) + ret["comment"] = f"Volume {name} failed to detach." return ret diff --git a/salt/states/cmd.py b/salt/states/cmd.py index 5a859c8092c..df0aec96ef8 100644 --- a/salt/states/cmd.py +++ b/salt/states/cmd.py @@ -231,7 +231,6 @@ To use it, one may pass it like this. Example: """ - import copy import logging import os @@ -317,7 +316,7 @@ def _is_true(val): return True elif str(val).lower() in ("false", "no", "0"): return False - raise ValueError("Failed parsing boolean value: {}".format(val)) + raise ValueError(f"Failed parsing boolean value: {val}") def wait( @@ -334,7 +333,7 @@ def wait( success_retcodes=None, success_stdout=None, success_stderr=None, - **kwargs + **kwargs, ): """ Run the given command only if the watch statement calls it. @@ -485,7 +484,7 @@ def wait_script( success_retcodes=None, success_stdout=None, success_stderr=None, - **kwargs + **kwargs, ): """ Download a script from a remote source and execute it only if a watch @@ -630,7 +629,7 @@ def run( success_retcodes=None, success_stdout=None, success_stderr=None, - **kwargs + **kwargs, ): """ Run a command if certain circumstances are met. Use ``cmd.wait`` if you @@ -848,12 +847,12 @@ def run( if __opts__["test"] and not test_name: ret["result"] = None - ret["comment"] = 'Command "{}" would have been executed'.format(name) + ret["comment"] = f'Command "{name}" would have been executed' ret["changes"] = {"cmd": name} return _reinterpreted_state(ret) if stateful else ret if cwd and not os.path.isdir(cwd): - ret["comment"] = 'Desired working directory "{}" is not available'.format(cwd) + ret["comment"] = f'Desired working directory "{cwd}" is not available' return ret # Wow, we passed the test, run this sucker! @@ -868,7 +867,7 @@ def run( ret["changes"] = cmd_all ret["result"] = not bool(cmd_all["retcode"]) - ret["comment"] = 'Command "{}" run'.format(name) + ret["comment"] = f'Command "{name}" run' # Ignore timeout errors if asked (for nohups) and treat cmd as a success if ignore_timeout: @@ -905,7 +904,7 @@ def script( success_retcodes=None, success_stdout=None, success_stderr=None, - **kwargs + **kwargs, ): """ Download a script and execute it with specified arguments. @@ -1100,14 +1099,14 @@ def script( return ret if context and not isinstance(context, dict): - ret[ - "comment" - ] = "Invalidly-formatted 'context' parameter. Must be formed as a dict." + ret["comment"] = ( + "Invalidly-formatted 'context' parameter. Must be formed as a dict." + ) return ret if defaults and not isinstance(defaults, dict): - ret[ - "comment" - ] = "Invalidly-formatted 'defaults' parameter. Must be formed as a dict." + ret["comment"] = ( + "Invalidly-formatted 'defaults' parameter. Must be formed as a dict." + ) return ret if runas and salt.utils.platform.is_windows() and not password: @@ -1155,11 +1154,11 @@ def script( if __opts__["test"] and not test_name: ret["result"] = None - ret["comment"] = "Command '{}' would have been executed".format(name) + ret["comment"] = f"Command '{name}' would have been executed" return _reinterpreted_state(ret) if stateful else ret if cwd and not os.path.isdir(cwd): - ret["comment"] = 'Desired working directory "{}" is not available'.format(cwd) + ret["comment"] = f'Desired working directory "{cwd}" is not available' return ret # Wow, we passed the test, run this sucker! @@ -1179,7 +1178,7 @@ def script( source, __env__ ) else: - ret["comment"] = "Command '{}' run".format(name) + ret["comment"] = f"Command '{name}' run" if stateful: ret = _reinterpreted_state(ret) if __opts__["test"] and cmd_all["retcode"] == 0 and ret["changes"]: @@ -1195,7 +1194,7 @@ def call( output_loglevel="debug", hide_output=False, use_vt=False, - **kwargs + **kwargs, ): """ Invoke a pre-defined Python function with arguments specified in the state @@ -1258,7 +1257,7 @@ def wait_call( use_vt=False, output_loglevel="debug", hide_output=False, - **kwargs + **kwargs, ): # Ignoring our arguments is intentional. return {"name": name, "changes": {}, "result": True, "comment": ""} diff --git a/salt/states/composer.py b/salt/states/composer.py index c21ae515098..9578507066b 100644 --- a/salt/states/composer.py +++ b/salt/states/composer.py @@ -137,10 +137,10 @@ def installed( else: install_status = "not " - ret["comment"] = 'The state of "{}" will be changed.'.format(name) + ret["comment"] = f'The state of "{name}" will be changed.' ret["changes"] = { - "old": "composer install has {}been run in {}".format(install_status, name), - "new": "composer install will be run in {}".format(name), + "old": f"composer install has {install_status}been run in {name}", + "new": f"composer install will be run in {name}", } ret["result"] = None return ret @@ -161,9 +161,9 @@ def installed( composer_home=composer_home, env=env, ) - except (SaltException) as err: + except SaltException as err: ret["result"] = False - ret["comment"] = "Error executing composer in '{}': {}".format(name, err) + ret["comment"] = f"Error executing composer in '{name}': {err}" return ret # If composer retcode != 0 then an exception was thrown and we dealt with it. @@ -172,9 +172,9 @@ def installed( ret["result"] = True if quiet is True: - ret[ - "comment" - ] = "Composer install completed successfully, output silenced by quiet flag" + ret["comment"] = ( + "Composer install completed successfully, output silenced by quiet flag" + ) else: ret["comment"] = "Composer install completed successfully" ret["changes"] = {"stderr": call["stderr"], "stdout": call["stdout"]} @@ -250,17 +250,17 @@ def update( # Check if composer.lock exists, if so we already ran `composer install` is_installed = __salt__["composer.did_composer_install"](name) if is_installed: - old_status = "composer install has not yet been run in {}".format(name) + old_status = f"composer install has not yet been run in {name}" else: - old_status = "composer install has been run in {}".format(name) + old_status = f"composer install has been run in {name}" # The state of the system does need to be changed. Check if we're running # in ``test=true`` mode. if __opts__["test"] is True: - ret["comment"] = 'The state of "{}" will be changed.'.format(name) + ret["comment"] = f'The state of "{name}" will be changed.' ret["changes"] = { "old": old_status, - "new": "composer install/update will be run in {}".format(name), + "new": f"composer install/update will be run in {name}", } ret["result"] = None return ret @@ -281,9 +281,9 @@ def update( composer_home=composer_home, env=env, ) - except (SaltException) as err: + except SaltException as err: ret["result"] = False - ret["comment"] = "Error executing composer in '{}': {}".format(name, err) + ret["comment"] = f"Error executing composer in '{name}': {err}" return ret # If composer retcode != 0 then an exception was thrown and we dealt with it. @@ -292,9 +292,9 @@ def update( ret["result"] = True if quiet is True: - ret[ - "comment" - ] = "Composer update completed successfully, output silenced by quiet flag" + ret["comment"] = ( + "Composer update completed successfully, output silenced by quiet flag" + ) else: ret["comment"] = "Composer update completed successfully" ret["changes"] = {"stderr": call["stderr"], "stdout": call["stdout"]} diff --git a/salt/states/consul.py b/salt/states/consul.py index b35b72649ed..f76bac8f7c9 100644 --- a/salt/states/consul.py +++ b/salt/states/consul.py @@ -20,6 +20,7 @@ The consul module is used to create and manage Consul ACLs consul.acl_absent: - id: 38AC8470-4A83-4140-8DFD-F924CD32917F """ + import logging log = logging.getLogger(__name__) @@ -103,7 +104,7 @@ def acl_present( "name": name, "changes": {}, "result": True, - "comment": 'ACL "{}" exists and is up to date'.format(name), + "comment": f'ACL "{name}" exists and is up to date', } exists = _acl_exists(name, id, token, consul_url) @@ -180,7 +181,7 @@ def acl_absent(name, id=None, token=None, consul_url="http://localhost:8500"): "name": id, "changes": {}, "result": True, - "comment": 'ACL "{}" does not exist'.format(id), + "comment": f'ACL "{id}" does not exist', } exists = _acl_exists(name, id, token, consul_url) diff --git a/salt/states/cron.py b/salt/states/cron.py index c8576727190..c06980fccfe 100644 --- a/salt/states/cron.py +++ b/salt/states/cron.py @@ -346,12 +346,12 @@ def present( ) ret["result"] = None if status == "absent": - ret["comment"] = "Cron {} is set to be added".format(name) + ret["comment"] = f"Cron {name} is set to be added" elif status == "present": ret["result"] = True - ret["comment"] = "Cron {} already present".format(name) + ret["comment"] = f"Cron {name} already present" elif status == "update": - ret["comment"] = "Cron {} is set to be updated".format(name) + ret["comment"] = f"Cron {name} is set to be updated" return ret if special is None: @@ -377,16 +377,16 @@ def present( identifier=identifier, ) if data == "present": - ret["comment"] = "Cron {} already present".format(name) + ret["comment"] = f"Cron {name} already present" return ret if data == "new": - ret["comment"] = "Cron {} added to {}'s crontab".format(name, user) + ret["comment"] = f"Cron {name} added to {user}'s crontab" ret["changes"] = {user: name} return ret if data == "updated": - ret["comment"] = "Cron {} updated".format(name) + ret["comment"] = f"Cron {name} updated" ret["changes"] = {user: name} return ret ret["comment"] = "Cron {} for user {} failed to commit with error \n{}".format( @@ -432,9 +432,9 @@ def absent(name, user="root", identifier=False, special=None, **kwargs): ret["result"] = None if status == "absent": ret["result"] = True - ret["comment"] = "Cron {} is absent".format(name) + ret["comment"] = f"Cron {name} is absent" elif status == "present" or status == "update": - ret["comment"] = "Cron {} is set to be removed".format(name) + ret["comment"] = f"Cron {name} is set to be removed" return ret if special is None: @@ -445,10 +445,10 @@ def absent(name, user="root", identifier=False, special=None, **kwargs): ) if data == "absent": - ret["comment"] = "Cron {} already absent".format(name) + ret["comment"] = f"Cron {name} already absent" return ret if data == "removed": - ret["comment"] = "Cron {} removed from {}'s crontab".format(name, user) + ret["comment"] = f"Cron {name} removed from {user}'s crontab" ret["changes"] = {user: name} return ret ret["comment"] = "Cron {} for user {} failed to commit with error {}".format( @@ -468,7 +468,7 @@ def file( replace=True, defaults=None, backup="", - **kwargs + **kwargs, ): """ Provides file.managed-like functionality (templating, etc.) for a pre-made @@ -559,7 +559,7 @@ def file( except Exception: # pylint: disable=broad-except ret = { "changes": {}, - "comment": "Could not identify group for user {}".format(user), + "comment": f"Could not identify group for user {user}", "name": name, "result": False, } @@ -569,7 +569,7 @@ def file( with salt.utils.files.fopen(cron_path, "w+") as fp_: raw_cron = __salt__["cron.raw_cron"](user) if not raw_cron.endswith("\n"): - raw_cron = "{}\n".format(raw_cron) + raw_cron = f"{raw_cron}\n" fp_.write(salt.utils.stringutils.to_str(raw_cron)) ret = {"changes": {}, "comment": "", "name": name, "result": True} @@ -579,7 +579,7 @@ def file( source = name if not replace and os.stat(cron_path).st_size > 0: - ret["comment"] = "User {} already has a crontab. No changes made".format(user) + ret["comment"] = f"User {user} already has a crontab. No changes made" os.unlink(cron_path) return ret @@ -597,7 +597,7 @@ def file( context=context, defaults=defaults, saltenv=__env__, - **kwargs + **kwargs, ) ret["result"], ret["comment"] = fcm os.unlink(cron_path) @@ -622,12 +622,12 @@ def file( context=context, defaults=defaults, skip_verify=False, # skip_verify - **kwargs + **kwargs, ) except Exception as exc: # pylint: disable=broad-except ret["result"] = False ret["changes"] = {} - ret["comment"] = "Unable to manage file: {}".format(exc) + ret["comment"] = f"Unable to manage file: {exc}" return ret if comment: @@ -653,7 +653,7 @@ def file( except Exception as exc: # pylint: disable=broad-except ret["result"] = False ret["changes"] = {} - ret["comment"] = "Unable to manage file: {}".format(exc) + ret["comment"] = f"Unable to manage file: {exc}" return ret cron_ret = None @@ -661,7 +661,7 @@ def file( cron_ret = __salt__["cron.write_cron_file_verbose"](user, cron_path) # Check cmd return code and show success or failure if cron_ret["retcode"] == 0: - ret["comment"] = "Crontab for user {} was updated".format(user) + ret["comment"] = f"Crontab for user {user} was updated" ret["result"] = True ret["changes"] = ret["changes"] else: @@ -671,7 +671,7 @@ def file( ret["result"] = False ret["changes"] = {} elif ret["result"]: - ret["comment"] = "Crontab for user {} is in the correct state".format(user) + ret["comment"] = f"Crontab for user {user} is in the correct state" ret["changes"] = {} os.unlink(cron_path) @@ -698,26 +698,26 @@ def env_present(name, value=None, user="root"): status = _check_cron_env(user, name, value=value) ret["result"] = None if status == "absent": - ret["comment"] = "Cron env {} is set to be added".format(name) + ret["comment"] = f"Cron env {name} is set to be added" elif status == "present": ret["result"] = True - ret["comment"] = "Cron env {} already present".format(name) + ret["comment"] = f"Cron env {name} already present" elif status == "update": - ret["comment"] = "Cron env {} is set to be updated".format(name) + ret["comment"] = f"Cron env {name} is set to be updated" return ret data = __salt__["cron.set_env"](user, name, value=value) if data == "present": - ret["comment"] = "Cron env {} already present".format(name) + ret["comment"] = f"Cron env {name} already present" return ret if data == "new": - ret["comment"] = "Cron env {} added to {}'s crontab".format(name, user) + ret["comment"] = f"Cron env {name} added to {user}'s crontab" ret["changes"] = {user: name} return ret if data == "updated": - ret["comment"] = "Cron env {} updated".format(name) + ret["comment"] = f"Cron env {name} updated" ret["changes"] = {user: name} return ret ret["comment"] = "Cron env {} for user {} failed to commit with error \n{}".format( @@ -748,17 +748,17 @@ def env_absent(name, user="root"): ret["result"] = None if status == "absent": ret["result"] = True - ret["comment"] = "Cron env {} is absent".format(name) + ret["comment"] = f"Cron env {name} is absent" elif status == "present" or status == "update": - ret["comment"] = "Cron env {} is set to be removed".format(name) + ret["comment"] = f"Cron env {name} is set to be removed" return ret data = __salt__["cron.rm_env"](user, name) if data == "absent": - ret["comment"] = "Cron env {} already absent".format(name) + ret["comment"] = f"Cron env {name} already absent" return ret if data == "removed": - ret["comment"] = "Cron env {} removed from {}'s crontab".format(name, user) + ret["comment"] = f"Cron env {name} removed from {user}'s crontab" ret["changes"] = {user: name} return ret ret["comment"] = "Cron env {} for user {} failed to commit with error {}".format( diff --git a/salt/states/cryptdev.py b/salt/states/cryptdev.py index d30ed73168d..d80aeed735e 100644 --- a/salt/states/cryptdev.py +++ b/salt/states/cryptdev.py @@ -85,9 +85,9 @@ def mapped( # If neither option is set, we've been asked to do nothing. if not immediate and not persist: ret["result"] = False - ret[ - "comment" - ] = "Either persist or immediate must be set, otherwise this state does nothing" + ret["comment"] = ( + "Either persist or immediate must be set, otherwise this state does nothing" + ) return ret if immediate and (keyfile is None or keyfile == "none" or keyfile == "-"): @@ -128,7 +128,7 @@ def mapped( ) if crypttab_result: if crypttab_result == "new": - ret["changes"]["crypttab"] = "Entry added in {}".format(config) + ret["changes"]["crypttab"] = f"Entry added in {config}" if crypttab_result == "change": ret["changes"]["crypttab"] = "Existing entry in {} changed".format( @@ -136,7 +136,7 @@ def mapped( ) else: - ret["changes"]["crypttab"] = "Unable to set entry in {}".format(config) + ret["changes"]["crypttab"] = f"Unable to set entry in {config}" ret["result"] = False return ret @@ -183,10 +183,10 @@ def unmapped(name, config="/etc/crypttab", persist=True, immediate=False): crypttab_result = __salt__["cryptdev.rm_crypttab"](name, config=config) if crypttab_result: if crypttab_result == "change": - ret["changes"]["crypttab"] = "Entry removed from {}".format(config) + ret["changes"]["crypttab"] = f"Entry removed from {config}" else: - ret["changes"]["crypttab"] = "Unable to remove entry in {}".format(config) + ret["changes"]["crypttab"] = f"Unable to remove entry in {config}" ret["result"] = False return ret diff --git a/salt/states/csf.py b/salt/states/csf.py index 4a66377031c..57118c75d02 100644 --- a/salt/states/csf.py +++ b/salt/states/csf.py @@ -107,8 +107,8 @@ def rule_present( return ret else: if ttl: - method = "temp{}".format(method) - func = __salt__["csf.{}".format(method)] + method = f"temp{method}" + func = __salt__[f"csf.{method}"] rule = func( ip, port=port, @@ -387,7 +387,7 @@ def option_present(name, value, reload=False): if current_option: l = __salt__["csf.split_option"](current_option) option_value = l[1] - if '"{}"'.format(value) == option_value: + if f'"{value}"' == option_value: return ret else: result = __salt__["csf.set_option"](option, value) @@ -395,7 +395,7 @@ def option_present(name, value, reload=False): ret["changes"]["Option"] = "Changed" else: result = __salt__["file.append"]( - "/etc/csf/csf.conf", args='{} = "{}"'.format(option, value) + "/etc/csf/csf.conf", args=f'{option} = "{value}"' ) ret["comment"] = "Option not present. Appended to csf.conf" ret["changes"]["Option"] = "Changed." diff --git a/salt/states/cyg.py b/salt/states/cyg.py index 957b194c724..e4ea5925979 100644 --- a/salt/states/cyg.py +++ b/salt/states/cyg.py @@ -72,7 +72,7 @@ def installed(name, cyg_arch="x86_64", mirrors=None): return ret if __opts__["test"]: - ret["comment"] = "The package {} would have been installed".format(name) + ret["comment"] = f"The package {name} would have been installed" return ret if __salt__["cyg.install"](name, cyg_arch=cyg_arch, mirrors=mirrors): @@ -131,7 +131,7 @@ def removed(name, cyg_arch="x86_64", mirrors=None): return ret if __opts__["test"]: - ret["comment"] = "The package {} would have been removed".format(name) + ret["comment"] = f"The package {name} would have been removed" return ret if __salt__["cyg.uninstall"](name, cyg_arch): ret["result"] = True diff --git a/salt/states/ddns.py b/salt/states/ddns.py index 8fd2e9c0508..0260fc10916 100644 --- a/salt/states/ddns.py +++ b/salt/states/ddns.py @@ -64,7 +64,7 @@ def present(name, zone, ttl, data, rdtype="A", **kwargs): if __opts__["test"]: ret["result"] = None - ret["comment"] = '{} record "{}" will be updated'.format(rdtype, name) + ret["comment"] = f'{rdtype} record "{name}" will be updated' return ret status = __salt__["ddns.update"](zone, name, ttl, rdtype, data, **kwargs) @@ -76,7 +76,7 @@ def present(name, zone, ttl, data, rdtype="A", **kwargs): ) elif status: ret["result"] = True - ret["comment"] = 'Updated {} record for "{}"'.format(rdtype, name) + ret["comment"] = f'Updated {rdtype} record for "{name}"' ret["changes"] = { "name": name, "zone": zone, @@ -122,7 +122,7 @@ def absent(name, zone, data=None, rdtype=None, **kwargs): if __opts__["test"]: ret["result"] = None - ret["comment"] = '{} record "{}" will be deleted'.format(rdtype, name) + ret["comment"] = f'{rdtype} record "{name}" will be deleted' return ret status = __salt__["ddns.delete"](zone, name, rdtype, data, **kwargs) diff --git a/salt/states/debconfmod.py b/salt/states/debconfmod.py index cb93d0d721c..4d399408341 100644 --- a/salt/states/debconfmod.py +++ b/salt/states/debconfmod.py @@ -184,7 +184,7 @@ def set(name, data, **kwargs): current = __salt__["debconf.show"](name) - for (key, args) in data.items(): + for key, args in data.items(): # For debconf data, valid booleans are 'true' and 'false'; # But str()'ing the args['value'] will result in 'True' and 'False' # which will be ignored and overridden by a dpkg-reconfigure. @@ -198,7 +198,7 @@ def set(name, data, **kwargs): if current is not None and [key, args["type"], str(args["value"])] in current: if ret["comment"] == "": ret["comment"] = "Unchanged answers: " - ret["comment"] += "{} ".format(key) + ret["comment"] += f"{key} " else: if __opts__["test"]: ret["result"] = None diff --git a/salt/states/dellchassis.py b/salt/states/dellchassis.py index 2ac905c8ad2..23487b6dfad 100644 --- a/salt/states/dellchassis.py +++ b/salt/states/dellchassis.py @@ -153,7 +153,6 @@ pillar stated above: """ - import logging import os @@ -701,9 +700,9 @@ def switch( if any([password_ret, snmp_ret, net_ret, dhcp_ret]) is False: ret["result"] = False - ret["comment"] = "There was an error setting the switch {}.".format(name) + ret["comment"] = f"There was an error setting the switch {name}." - ret["comment"] = "Dell chassis switch {} was updated.".format(name) + ret["comment"] = f"Dell chassis switch {name} was updated." return ret @@ -756,7 +755,7 @@ def firmware_update(hosts=None, directory=""): ret["changes"].update( { "host": { - "comment": "Firmware update submitted for {}".format(host), + "comment": f"Firmware update submitted for {host}", "success": True, } } @@ -766,7 +765,7 @@ def firmware_update(hosts=None, directory=""): ret["changes"].update( { "host": { - "comment": "FAILED to update firmware for {}".format(host), + "comment": f"FAILED to update firmware for {host}", "success": False, "reason": str(err), } diff --git a/salt/states/disk.py b/salt/states/disk.py index c257870c1be..47d7177b59b 100644 --- a/salt/states/disk.py +++ b/salt/states/disk.py @@ -62,7 +62,7 @@ def _validate_int(name, value, limits=(), strip="%"): value = value.strip(" " + strip) value = int(value) except (TypeError, ValueError): - comment += "{} must be an integer ".format(name) + comment += f"{name} must be an integer " # Must be in range else: if len(limits) == 2: @@ -136,10 +136,10 @@ def _check_min_max(absolute, free, available, used, maximum, minimum, ret): return ret else: if used < minimum: - ret[ - "comment" - ] = "Disk used space is below minimum of {0} {2} at {1} {2}".format( - minimum, used, unit + ret["comment"] = ( + "Disk used space is below minimum of {0} {2} at {1} {2}".format( + minimum, used, unit + ) ) return ret if maximum is not None: @@ -153,10 +153,10 @@ def _check_min_max(absolute, free, available, used, maximum, minimum, ret): return ret else: if used > maximum: - ret[ - "comment" - ] = "Disk used space is above maximum of {0} {2} at {1} {2}".format( - maximum, used, unit + ret["comment"] = ( + "Disk used space is above maximum of {0} {2} at {1} {2}".format( + maximum, used, unit + ) ) return ret ret["comment"] = "Disk used space in acceptable range" @@ -219,7 +219,7 @@ def status(name, maximum=None, minimum=None, absolute=False, free=False): # Validate name if name not in data: - ret["comment"] += "Disk mount {} not present. ".format(name) + ret["comment"] += f"Disk mount {name} not present. " return _status_path(name, ret, minimum, maximum, absolute, free) else: return _status_mount(name, ret, minimum, maximum, absolute, free, data) diff --git a/salt/states/docker_container.py b/salt/states/docker_container.py index 543f35b6902..8008e8a5952 100644 --- a/salt/states/docker_container.py +++ b/salt/states/docker_container.py @@ -1883,9 +1883,9 @@ def running( if not _replace(name, temp_container_name): ret["result"] = False return _format_comments(ret, comments) - ret["changes"].setdefault("container_id", {})[ - "added" - ] = temp_container["Id"] + ret["changes"].setdefault("container_id", {})["added"] = ( + temp_container["Id"] + ) else: # No changes between existing container and temp container. # First check if a requisite is asking to send a signal to the @@ -2231,9 +2231,9 @@ def run( if remove is not None: if not ignore_collisions: ret["result"] = False - ret[ - "comment" - ] = "'rm' is an alias for 'auto_remove', they cannot both be used" + ret["comment"] = ( + "'rm' is an alias for 'auto_remove', they cannot both be used" + ) return ret else: remove = bool(val) @@ -2271,9 +2271,9 @@ def run( pass else: ret["result"] = False if failhard and retcode != 0 else True - ret[ - "comment" - ] = f"Container ran and exited with a return code of {retcode}" + ret["comment"] = ( + f"Container ran and exited with a return code of {retcode}" + ) if remove: id_ = ret.get("changes", {}).get("Id") diff --git a/salt/states/docker_image.py b/salt/states/docker_image.py index 030c9b6924e..25a069cb399 100644 --- a/salt/states/docker_image.py +++ b/salt/states/docker_image.py @@ -316,10 +316,10 @@ def present( repository=name, tag=tag, base=base, mods=sls, **sls_build_kwargs ) except Exception as exc: # pylint: disable=broad-except - ret[ - "comment" - ] = "Encountered error using SLS {} for building {}: {}".format( - sls, full_image, exc + ret["comment"] = ( + "Encountered error using SLS {} for building {}: {}".format( + sls, full_image, exc + ) ) return ret if image_info is None or image_update["Id"] != image_info["Id"][:12]: diff --git a/salt/states/docker_network.py b/salt/states/docker_network.py index 31b19537b43..2710c69133b 100644 --- a/salt/states/docker_network.py +++ b/salt/states/docker_network.py @@ -625,9 +625,9 @@ 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" - ] = f"Network '{name}' already exists, and is configured as specified" + ret["comment"] = ( + f"Network '{name}' already exists, and is configured as specified" + ) log.trace("Details of docker network '%s': %s", name, network) temp_net_name = "".join( @@ -696,8 +696,8 @@ def present( existing_pool_count = len(network["IPAM"]["Config"]) desired_pool_count = len(temp_net_info["IPAM"]["Config"]) - is_default_pool = ( - lambda x: True if sorted(x) == ["Gateway", "Subnet"] else False + is_default_pool = lambda x: ( + True if sorted(x) == ["Gateway", "Subnet"] else False ) if ( @@ -875,9 +875,11 @@ def present( errors.append(exc.__str__()) else: ret["changes"].setdefault( - "reconnected" - if cid in disconnected_containers - else "connected", + ( + "reconnected" + if cid in disconnected_containers + else "connected" + ), [], ).append(connect_info["Name"]) else: diff --git a/salt/states/drac.py b/salt/states/drac.py index 29a3a6fa7a6..c3a7b4258de 100644 --- a/salt/states/drac.py +++ b/salt/states/drac.py @@ -68,18 +68,18 @@ def present(name, password, permission): if __opts__["test"]: if name in users: - ret["comment"] = "`{}` already exists".format(name) + ret["comment"] = f"`{name}` already exists" else: - ret["comment"] = "`{}` will be created".format(name) + ret["comment"] = f"`{name}` will be created" ret["changes"] = {name: "will be created"} return ret if name in users: - ret["comment"] = "`{}` already exists".format(name) + ret["comment"] = f"`{name}` already exists" else: if __salt__["drac.create_user"](name, password, permission, users): - ret["comment"] = "`{}` user created".format(name) + ret["comment"] = f"`{name}` user created" ret["changes"] = {name: "new user created"} else: ret["comment"] = "Unable to create user" @@ -101,22 +101,22 @@ def absent(name): if __opts__["test"]: if name in users: - ret["comment"] = "`{}` is set to be deleted".format(name) + ret["comment"] = f"`{name}` is set to be deleted" ret["changes"] = {name: "will be deleted"} else: - ret["comment"] = "`{}` does not exist".format(name) + ret["comment"] = f"`{name}` does not exist" return ret if name in users: if __salt__["drac.delete_user"](name, users[name]["index"]): - ret["comment"] = "`{}` deleted".format(name) + ret["comment"] = f"`{name}` deleted" ret["changes"] = {name: "deleted"} else: ret["comment"] = "Unable to delete user" ret["result"] = False else: - ret["comment"] = "`{}` does not exist".format(name) + ret["comment"] = f"`{name}` does not exist" return ret diff --git a/salt/states/dvs.py b/salt/states/dvs.py index 7b4cdf4ba00..6333395c490 100644 --- a/salt/states/dvs.py +++ b/salt/states/dvs.py @@ -200,7 +200,6 @@ The 5.5.0.2014.1.1 is a known stable version that this original ESXi State Module was developed against. """ - import logging import sys @@ -258,7 +257,7 @@ def _get_datacenter_name(): details = __salt__["esxdatacenter.get_details"]() if not details: raise salt.exceptions.CommandExecutionError( - "details for proxy type '{}' not loaded".format(proxy_type) + f"details for proxy type '{proxy_type}' not loaded" ) return details["datacenter"] @@ -363,12 +362,12 @@ def dvs_configured(name, dvs): ) updated_infra_res_pools.append(dict(dvs[infra_prop][idx])) if updated_infra_res_pools: - props_to_original_values[ - "infrastructure_traffic_resource_pools" - ] = original_infra_res_pools - props_to_updated_values[ - "infrastructure_traffic_resource_pools" - ] = updated_infra_res_pools + props_to_original_values["infrastructure_traffic_resource_pools"] = ( + original_infra_res_pools + ) + props_to_updated_values["infrastructure_traffic_resource_pools"] = ( + updated_infra_res_pools + ) if props_to_updated_values: if __opts__["test"]: changes_string = "" @@ -476,7 +475,7 @@ def _get_val2_dict_from_diff_dict(diff_dict): ret_dict = {} for p in diff_dict.keys(): if not isinstance(diff_dict[p], dict): - raise ValueError("Unexpected diff difct '{}'".format(diff_dict)) + raise ValueError(f"Unexpected diff difct '{diff_dict}'") if "val2" in diff_dict[p].keys(): ret_dict.update({p: diff_dict[p]["val2"]}) else: @@ -491,7 +490,7 @@ def _get_val1_dict_from_diff_dict(diff_dict): ret_dict = {} for p in diff_dict.keys(): if not isinstance(diff_dict[p], dict): - raise ValueError("Unexpected diff difct '{}'".format(diff_dict)) + raise ValueError(f"Unexpected diff difct '{diff_dict}'") if "val1" in diff_dict[p].keys(): ret_dict.update({p: diff_dict[p]["val1"]}) else: @@ -508,7 +507,7 @@ def _get_changes_from_diff_dict(diff_dict): changes_strings = [] for p in diff_dict.keys(): if not isinstance(diff_dict[p], dict): - raise ValueError("Unexpected diff difct '{}'".format(diff_dict)) + raise ValueError(f"Unexpected diff difct '{diff_dict}'") if sorted(diff_dict[p].keys()) == ["val1", "val2"]: # Some string formatting from_str = diff_dict[p]["val1"] @@ -521,12 +520,12 @@ def _get_changes_from_diff_dict(diff_dict): to_str = "'{}'".format(diff_dict[p]["val2"]) elif isinstance(diff_dict[p]["val2"], list): to_str = "'{}'".format(", ".join(diff_dict[p]["val2"])) - changes_strings.append("{} from {} to {}".format(p, from_str, to_str)) + changes_strings.append(f"{p} from {from_str} to {to_str}") else: sub_changes = _get_changes_from_diff_dict(diff_dict[p]) if sub_changes: - changes_strings.append("{}:".format(p)) - changes_strings.extend(["\t{}".format(c) for c in sub_changes]) + changes_strings.append(f"{p}:") + changes_strings.extend([f"\t{c}" for c in sub_changes]) return changes_strings @@ -609,7 +608,7 @@ def portgroups_configured(name, dvs, portgroups): pg_name, dvs, datacenter, - "\n".join(["\t{}".format(c) for c in changes_strings]), + "\n".join([f"\t{c}" for c in changes_strings]), ) ) else: @@ -735,7 +734,7 @@ def uplink_portgroup_configured(name, dvs, uplink_portgroup): name, dvs, datacenter, - "\n".join(["\t{}".format(c) for c in changes_strings]), + "\n".join([f"\t{c}" for c in changes_strings]), ) ) else: diff --git a/salt/states/elasticsearch.py b/salt/states/elasticsearch.py index bf58af5913d..962ac1d8ddf 100644 --- a/salt/states/elasticsearch.py +++ b/salt/states/elasticsearch.py @@ -4,7 +4,6 @@ State module to manage Elasticsearch. .. versionadded:: 2017.7.0 """ - import logging import salt.utils.json @@ -26,20 +25,20 @@ def index_absent(name): index = __salt__["elasticsearch.index_get"](index=name) if index and name in index: if __opts__["test"]: - ret["comment"] = "Index {} will be removed".format(name) + ret["comment"] = f"Index {name} will be removed" ret["changes"]["old"] = index[name] ret["result"] = None else: ret["result"] = __salt__["elasticsearch.index_delete"](index=name) if ret["result"]: - ret["comment"] = "Successfully removed index {}".format(name) + ret["comment"] = f"Successfully removed index {name}" ret["changes"]["old"] = index[name] else: - ret[ - "comment" - ] = "Failed to remove index {} for unknown reasons".format(name) + ret["comment"] = ( + f"Failed to remove index {name} for unknown reasons" + ) else: - ret["comment"] = "Index {} is already absent".format(name) + ret["comment"] = f"Index {name} is already absent" except Exception as err: # pylint: disable=broad-except ret["result"] = False ret["comment"] = str(err) @@ -89,15 +88,15 @@ def index_present(name, definition=None): index=name, body=definition ) if output: - ret["comment"] = "Successfully created index {}".format(name) + ret["comment"] = f"Successfully created index {name}" ret["changes"] = { "new": __salt__["elasticsearch.index_get"](index=name)[name] } else: ret["result"] = False - ret["comment"] = "Cannot create index {}, {}".format(name, output) + ret["comment"] = f"Cannot create index {name}, {output}" else: - ret["comment"] = "Index {} is already present".format(name) + ret["comment"] = f"Index {name} is already present" except Exception as err: # pylint: disable=broad-except ret["result"] = False ret["comment"] = str(err) @@ -136,17 +135,17 @@ def alias_absent(name, index): aliases=name, indices=index ) if ret["result"]: - ret[ - "comment" - ] = "Successfully removed alias {} for index {}".format(name, index) + ret["comment"] = ( + f"Successfully removed alias {name} for index {index}" + ) ret["changes"]["old"] = ( alias.get(index, {}).get("aliases", {}).get(name, {}) ) else: - ret[ - "comment" - ] = "Failed to remove alias {} for index {} for unknown reasons".format( - name, index + ret["comment"] = ( + "Failed to remove alias {} for index {} for unknown reasons".format( + name, index + ) ) else: ret["comment"] = "Alias {} for index {} is already absent".format( @@ -198,10 +197,10 @@ def alias_present(name, index, definition=None): if ret["changes"] or not definition: if __opts__["test"]: if not old: - ret[ - "comment" - ] = "Alias {} for index {} does not exist and will be created".format( - name, index + ret["comment"] = ( + "Alias {} for index {} does not exist and will be created".format( + name, index + ) ) else: ret["comment"] = ( @@ -216,16 +215,16 @@ def alias_present(name, index, definition=None): ) if output: if not old: - ret[ - "comment" - ] = "Successfully created alias {} for index {}".format( - name, index + ret["comment"] = ( + "Successfully created alias {} for index {}".format( + name, index + ) ) else: - ret[ - "comment" - ] = "Successfully replaced alias {} for index {}".format( - name, index + ret["comment"] = ( + "Successfully replaced alias {} for index {}".format( + name, index + ) ) else: ret["result"] = False @@ -257,7 +256,7 @@ def index_template_absent(name): index_template = __salt__["elasticsearch.index_template_get"](name=name) if index_template and name in index_template: if __opts__["test"]: - ret["comment"] = "Index template {} will be removed".format(name) + ret["comment"] = f"Index template {name} will be removed" ret["changes"]["old"] = index_template[name] ret["result"] = None else: @@ -270,13 +269,13 @@ def index_template_absent(name): ) ret["changes"]["old"] = index_template[name] else: - ret[ - "comment" - ] = "Failed to remove index template {} for unknown reasons".format( - name + ret["comment"] = ( + "Failed to remove index template {} for unknown reasons".format( + name + ) ) else: - ret["comment"] = "Index template {} is already absent".format(name) + ret["comment"] = f"Index template {name} is already absent" except Exception as err: # pylint: disable=broad-except ret["result"] = False ret["comment"] = str(err) @@ -316,9 +315,9 @@ def index_template_present(name, definition, check_definition=False): ) if not index_template_exists: if __opts__["test"]: - ret[ - "comment" - ] = "Index template {} does not exist and will be created".format(name) + ret["comment"] = ( + f"Index template {name} does not exist and will be created" + ) ret["changes"] = {"new": definition} ret["result"] = None else: @@ -357,10 +356,10 @@ def index_template_present(name, definition, check_definition=False): ) if len(diff) != 0: if __opts__["test"]: - ret[ - "comment" - ] = "Index template {} exist but need to be updated".format( - name + ret["comment"] = ( + "Index template {} exist but need to be updated".format( + name + ) ) ret["changes"] = diff ret["result"] = None @@ -369,25 +368,25 @@ def index_template_present(name, definition, check_definition=False): name=name, body=definition ) if output: - ret[ - "comment" - ] = "Successfully updated index template {}".format(name) + ret["comment"] = ( + f"Successfully updated index template {name}" + ) ret["changes"] = diff else: ret["result"] = False - ret[ - "comment" - ] = "Cannot update index template {}, {}".format( - name, output + ret["comment"] = ( + "Cannot update index template {}, {}".format( + name, output + ) ) else: - ret[ - "comment" - ] = "Index template {} is already present and up to date".format( - name + ret["comment"] = ( + "Index template {} is already present and up to date".format( + name + ) ) else: - ret["comment"] = "Index template {} is already present".format(name) + ret["comment"] = f"Index template {name} is already present" except Exception as err: # pylint: disable=broad-except ret["result"] = False ret["comment"] = str(err) @@ -409,20 +408,20 @@ def pipeline_absent(name): pipeline = __salt__["elasticsearch.pipeline_get"](id=name) if pipeline and name in pipeline: if __opts__["test"]: - ret["comment"] = "Pipeline {} will be removed".format(name) + ret["comment"] = f"Pipeline {name} will be removed" ret["changes"]["old"] = pipeline[name] ret["result"] = None else: ret["result"] = __salt__["elasticsearch.pipeline_delete"](id=name) if ret["result"]: - ret["comment"] = "Successfully removed pipeline {}".format(name) + ret["comment"] = f"Successfully removed pipeline {name}" ret["changes"]["old"] = pipeline[name] else: - ret[ - "comment" - ] = "Failed to remove pipeline {} for unknown reasons".format(name) + ret["comment"] = ( + f"Failed to remove pipeline {name} for unknown reasons" + ) else: - ret["comment"] = "Pipeline {} is already absent".format(name) + ret["comment"] = f"Pipeline {name} is already absent" except Exception as err: # pylint: disable=broad-except ret["result"] = False ret["comment"] = str(err) @@ -465,9 +464,9 @@ def pipeline_present(name, definition): if ret["changes"] or not definition: if __opts__["test"]: if not pipeline: - ret[ - "comment" - ] = "Pipeline {} does not exist and will be created".format(name) + ret["comment"] = ( + f"Pipeline {name} does not exist and will be created" + ) else: ret["comment"] = ( "Pipeline {} exists with wrong configuration and will be" @@ -481,7 +480,7 @@ def pipeline_present(name, definition): ) if output: if not pipeline: - ret["comment"] = "Successfully created pipeline {}".format(name) + ret["comment"] = f"Successfully created pipeline {name}" else: ret["comment"] = "Successfully replaced pipeline {}".format( name @@ -492,7 +491,7 @@ def pipeline_present(name, definition): name, output ) else: - ret["comment"] = "Pipeline {} is already present".format(name) + ret["comment"] = f"Pipeline {name} is already present" except Exception as err: # pylint: disable=broad-except ret["result"] = False ret["comment"] = str(err) @@ -514,7 +513,7 @@ def search_template_absent(name): template = __salt__["elasticsearch.search_template_get"](id=name) if template: if __opts__["test"]: - ret["comment"] = "Search template {} will be removed".format(name) + ret["comment"] = f"Search template {name} will be removed" ret["changes"]["old"] = salt.utils.json.loads(template["template"]) ret["result"] = None else: @@ -527,13 +526,13 @@ def search_template_absent(name): ) ret["changes"]["old"] = salt.utils.json.loads(template["template"]) else: - ret[ - "comment" - ] = "Failed to remove search template {} for unknown reasons".format( - name + ret["comment"] = ( + "Failed to remove search template {} for unknown reasons".format( + name + ) ) else: - ret["comment"] = "Search template {} is already absent".format(name) + ret["comment"] = f"Search template {name} is already absent" except Exception as err: # pylint: disable=broad-except ret["result"] = False ret["comment"] = str(err) @@ -575,10 +574,10 @@ def search_template_present(name, definition): if ret["changes"] or not definition: if __opts__["test"]: if not template: - ret[ - "comment" - ] = "Search template {} does not exist and will be created".format( - name + ret["comment"] = ( + "Search template {} does not exist and will be created".format( + name + ) ) else: ret["comment"] = ( @@ -593,20 +592,16 @@ def search_template_present(name, definition): ) if output: if not template: - ret[ - "comment" - ] = "Successfully created search template {}".format(name) + ret["comment"] = f"Successfully created search template {name}" else: - ret[ - "comment" - ] = "Successfully replaced search template {}".format(name) + ret["comment"] = f"Successfully replaced search template {name}" else: ret["result"] = False ret["comment"] = "Cannot create search template {}, {}".format( name, output ) else: - ret["comment"] = "Search template {} is already present".format(name) + ret["comment"] = f"Search template {name} is already present" except Exception as err: # pylint: disable=broad-except ret["result"] = False ret["comment"] = str(err) diff --git a/salt/states/elasticsearch_index.py b/salt/states/elasticsearch_index.py index 9acd98a629c..dcf0d442579 100644 --- a/salt/states/elasticsearch_index.py +++ b/salt/states/elasticsearch_index.py @@ -6,7 +6,6 @@ State module to manage Elasticsearch indices Use elasticsearch state instead """ - import logging log = logging.getLogger(__name__) @@ -26,20 +25,20 @@ def absent(name): index = __salt__["elasticsearch.index_get"](index=name) if index and name in index: if __opts__["test"]: - ret["comment"] = "Index {} will be removed".format(name) + ret["comment"] = f"Index {name} will be removed" ret["changes"]["old"] = index[name] ret["result"] = None else: ret["result"] = __salt__["elasticsearch.index_delete"](index=name) if ret["result"]: - ret["comment"] = "Successfully removed index {}".format(name) + ret["comment"] = f"Successfully removed index {name}" ret["changes"]["old"] = index[name] else: - ret[ - "comment" - ] = "Failed to remove index {} for unknown reasons".format(name) + ret["comment"] = ( + f"Failed to remove index {name} for unknown reasons" + ) else: - ret["comment"] = "Index {} is already absent".format(name) + ret["comment"] = f"Index {name} is already absent" except Exception as err: # pylint: disable=broad-except ret["result"] = False ret["comment"] = str(err) @@ -94,15 +93,15 @@ def present(name, definition=None): index=name, body=definition ) if output: - ret["comment"] = "Successfully created index {}".format(name) + ret["comment"] = f"Successfully created index {name}" ret["changes"] = { "new": __salt__["elasticsearch.index_get"](index=name)[name] } else: ret["result"] = False - ret["comment"] = "Cannot create index {}, {}".format(name, output) + ret["comment"] = f"Cannot create index {name}, {output}" else: - ret["comment"] = "Index {} is already present".format(name) + ret["comment"] = f"Index {name} is already present" except Exception as err: # pylint: disable=broad-except ret["result"] = False ret["comment"] = str(err) diff --git a/salt/states/elasticsearch_index_template.py b/salt/states/elasticsearch_index_template.py index 841fa381b43..c4574bd9dc7 100644 --- a/salt/states/elasticsearch_index_template.py +++ b/salt/states/elasticsearch_index_template.py @@ -6,7 +6,6 @@ State module to manage Elasticsearch index templates Use elasticsearch state instead """ - import logging log = logging.getLogger(__name__) @@ -26,7 +25,7 @@ def absent(name): index_template = __salt__["elasticsearch.index_template_get"](name=name) if index_template and name in index_template: if __opts__["test"]: - ret["comment"] = "Index template {} will be removed".format(name) + ret["comment"] = f"Index template {name} will be removed" ret["changes"]["old"] = index_template[name] ret["result"] = None else: @@ -39,13 +38,13 @@ def absent(name): ) ret["changes"]["old"] = index_template[name] else: - ret[ - "comment" - ] = "Failed to remove index template {} for unknown reasons".format( - name + ret["comment"] = ( + "Failed to remove index template {} for unknown reasons".format( + name + ) ) else: - ret["comment"] = "Index template {} is already absent".format(name) + ret["comment"] = f"Index template {name} is already absent" except Exception as err: # pylint: disable=broad-except ret["result"] = False ret["comment"] = str(err) @@ -88,9 +87,9 @@ def present(name, definition): ) if not index_template_exists: if __opts__["test"]: - ret[ - "comment" - ] = "Index template {} does not exist and will be created".format(name) + ret["comment"] = ( + f"Index template {name} does not exist and will be created" + ) ret["changes"] = {"new": definition} ret["result"] = None else: @@ -112,7 +111,7 @@ def present(name, definition): name, output ) else: - ret["comment"] = "Index template {} is already present".format(name) + ret["comment"] = f"Index template {name} is already present" except Exception as err: # pylint: disable=broad-except ret["result"] = False ret["comment"] = str(err) diff --git a/salt/states/environ.py b/salt/states/environ.py index fb495d1af44..ad574b10344 100644 --- a/salt/states/environ.py +++ b/salt/states/environ.py @@ -3,7 +3,6 @@ Support for getting and setting the environment variables of the current salt process. """ - import os import salt.utils.platform diff --git a/salt/states/eselect.py b/salt/states/eselect.py index 18d4f644771..2b5196cea17 100644 --- a/salt/states/eselect.py +++ b/salt/states/eselect.py @@ -6,7 +6,6 @@ A state module to manage Gentoo configuration via eselect """ - # Define a function alias in order not to shadow built-in's __func_alias__ = {"set_": "set"} @@ -60,7 +59,7 @@ def set_(name, target, module_parameter=None, action_parameter=None): ) ret["result"] = False elif __opts__["test"]: - ret["comment"] = "Target '{}' will be set on '{}' module.".format(target, name) + ret["comment"] = f"Target '{target}' will be set on '{name}' module." ret["result"] = None else: result = __salt__["eselect.set_target"]( @@ -71,7 +70,7 @@ def set_(name, target, module_parameter=None, action_parameter=None): ) if result: ret["changes"][name] = {"old": old_target, "new": target} - ret["comment"] = "Target '{}' set on '{}' module.".format(target, name) + ret["comment"] = f"Target '{target}' set on '{name}' module." else: ret["comment"] = "Target '{}' failed to be set on '{}' module.".format( target, name diff --git a/salt/states/esxcluster.py b/salt/states/esxcluster.py index f2d7fbc9c36..700f12830d9 100644 --- a/salt/states/esxcluster.py +++ b/salt/states/esxcluster.py @@ -48,7 +48,6 @@ The 5.5.0.2014.1.1 is a known stable version that this original ESXi State Module was developed against. """ - import logging import sys from functools import wraps @@ -402,11 +401,11 @@ def vsan_datastore_configured(name, datastore_name): ret.update( { - "result": True - if (not changes_required) - else None - if __opts__["test"] - else True, + "result": ( + True + if (not changes_required) + else None if __opts__["test"] else True + ), "comment": "\n".join(comments), "changes": changes, } @@ -600,13 +599,11 @@ def licenses_configured(name, licenses=None): ret.update( { - "result": True - if (not needs_changes) - else None - if __opts__["test"] - else False - if has_errors - else True, + "result": ( + True + if (not needs_changes) + else None if __opts__["test"] else False if has_errors else True + ), "comment": "\n".join(comments), "changes": changes if not __opts__["test"] else {}, } diff --git a/salt/states/esxdatacenter.py b/salt/states/esxdatacenter.py index 10cd01d5507..0ee6f685ff7 100644 --- a/salt/states/esxdatacenter.py +++ b/salt/states/esxdatacenter.py @@ -58,7 +58,6 @@ State configuration: esxdatacenter.datacenter_configured """ - import logging from functools import wraps diff --git a/salt/states/esxi.py b/salt/states/esxi.py index 6a910c5f114..a0e4fd0edbb 100644 --- a/salt/states/esxi.py +++ b/salt/states/esxi.py @@ -1397,11 +1397,11 @@ def diskgroups_configured(name, diskgroups, erase_disks=False): result = ( True if not (changes or errors) - else None # no changes/errors - if __opts__["test"] - else False # running in test mode - if errors - else True + else ( + None # no changes/errors + if __opts__["test"] + else False if errors else True # running in test mode + ) ) # found errors; defaults to True ret.update( {"result": result, "comment": "\n".join(comments), "changes": diskgroup_changes} diff --git a/salt/states/esxvm.py b/salt/states/esxvm.py index 8fa551c2b19..0a1efed9a56 100644 --- a/salt/states/esxvm.py +++ b/salt/states/esxvm.py @@ -192,7 +192,6 @@ execution functions against ESXi hosts via a Salt Proxy Minion, and a larger sta example. """ - import logging import sys from functools import wraps diff --git a/salt/states/etcd_mod.py b/salt/states/etcd_mod.py index ec8cc96c355..b86e89680c7 100644 --- a/salt/states/etcd_mod.py +++ b/salt/states/etcd_mod.py @@ -154,7 +154,6 @@ Available Functions - file: /some/file.txt """ - # Define the module's virtual name __virtualname__ = "etcd" @@ -187,7 +186,7 @@ def __virtual__(): def _etcd_action(*, action, key, profile, value=None, **kwargs): try: - ret = __salt__["etcd.{}".format(action)]( + ret = __salt__[f"etcd.{action}"]( key=key, profile=profile, value=value, **kwargs ) except Exception: # pylint: disable=broad-except diff --git a/salt/states/ethtool.py b/salt/states/ethtool.py index 3d9fff691ec..25367cd8e48 100644 --- a/salt/states/ethtool.py +++ b/salt/states/ethtool.py @@ -29,7 +29,6 @@ Configuration of network device """ - import logging from salt.exceptions import CommandExecutionError @@ -87,7 +86,7 @@ def coalesce(name, **kwargs): "name": name, "changes": {}, "result": True, - "comment": "Network device {} coalescing settings are up to date.".format(name), + "comment": f"Network device {name} coalescing settings are up to date.", } apply_coalescing = False if "test" not in kwargs: @@ -110,7 +109,7 @@ def coalesce(name, **kwargs): for key, value in kwargs.items(): if key in old and value != old[key]: new.update({key: value}) - diff.append("{}: {}".format(key, value)) + diff.append(f"{key}: {value}") # Dry run if kwargs["test"]: @@ -118,17 +117,17 @@ def coalesce(name, **kwargs): return ret if new: ret["result"] = None - ret[ - "comment" - ] = "Device {} coalescing settings are set to be updated:\n{}".format( - name, "\n".join(diff) + ret["comment"] = ( + "Device {} coalescing settings are set to be updated:\n{}".format( + name, "\n".join(diff) + ) ) return ret # Prepare return output if new: apply_coalescing = True - ret["comment"] = "Device {} coalescing settings updated.".format(name) + ret["comment"] = f"Device {name} coalescing settings updated." ret["changes"]["ethtool_coalesce"] = "\n".join(diff) except AttributeError as error: @@ -172,7 +171,7 @@ def ring(name, **kwargs): "name": name, "changes": {}, "result": True, - "comment": "Network device {} ring parameters are up to date.".format(name), + "comment": f"Network device {name} ring parameters are up to date.", } apply_ring = False if "test" not in kwargs: @@ -183,7 +182,7 @@ def ring(name, **kwargs): old = __salt__["ethtool.show_ring"](name) if not isinstance(old, dict): ret["result"] = False - ret["comment"] = "Device {} ring parameters are not supported".format(name) + ret["comment"] = f"Device {name} ring parameters are not supported" return ret new = {} @@ -193,11 +192,11 @@ def ring(name, **kwargs): for key, value in kwargs.items(): if key in old: if value == "max": - value = old["{}_max".format(key)] + value = old[f"{key}_max"] if value != old[key]: new.update({key: value}) - diff.append("{}: {}".format(key, value)) + diff.append(f"{key}: {value}") # Dry run if kwargs["test"]: @@ -205,17 +204,17 @@ 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 # Prepare return output if new: apply_ring = True - ret["comment"] = "Device {} ring parameters updated.".format(name) + ret["comment"] = f"Device {name} ring parameters updated." ret["changes"]["ethtool_ring"] = "\n".join(diff) except AttributeError as error: @@ -254,7 +253,7 @@ def offload(name, **kwargs): "name": name, "changes": {}, "result": True, - "comment": "Network device {} offload settings are up to date.".format(name), + "comment": f"Network device {name} offload settings are up to date.", } apply_offload = False if "test" not in kwargs: @@ -265,7 +264,7 @@ def offload(name, **kwargs): old = __salt__["ethtool.show_offload"](name) if not isinstance(old, dict): ret["result"] = False - ret["comment"] = "Device {} offload settings are not supported".format(name) + ret["comment"] = f"Device {name} offload settings are not supported" return ret new = {} @@ -276,7 +275,7 @@ def offload(name, **kwargs): value = value and "on" or "off" if key in old and value != old[key]: new.update({key: value}) - diff.append("{}: {}".format(key, value)) + diff.append(f"{key}: {value}") # Dry run if kwargs["test"]: @@ -284,17 +283,17 @@ 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 # Prepare return output if new: apply_offload = True - ret["comment"] = "Device {} offload settings updated.".format(name) + ret["comment"] = f"Device {name} offload settings updated." ret["changes"]["ethtool_offload"] = "\n".join(diff) except AttributeError as error: @@ -337,7 +336,7 @@ def pause(name, **kwargs): "name": name, "changes": {}, "result": True, - "comment": "Network device {} pause parameters are up to date.".format(name), + "comment": f"Network device {name} pause parameters are up to date.", } apply_pause = False @@ -346,7 +345,7 @@ def pause(name, **kwargs): old = __salt__["ethtool.show_pause"](name) except CommandExecutionError: ret["result"] = False - ret["comment"] = "Device {} pause parameters are not supported".format(name) + ret["comment"] = f"Device {name} pause parameters are not supported" return ret # map ethtool command input to output text @@ -369,7 +368,7 @@ def pause(name, **kwargs): value = "on" elif value is False: value = "off" - diff.append("{}: {}".format(key, value)) + diff.append(f"{key}: {value}") if not new: return ret @@ -386,7 +385,7 @@ def pause(name, **kwargs): try: __salt__["ethtool.set_pause"](name, **new) # Prepare return output - ret["comment"] = "Device {} pause parameters updated.".format(name) + ret["comment"] = f"Device {name} pause parameters updated." ret["changes"]["ethtool_pause"] = "\n".join(diff) except CommandExecutionError as exc: ret["result"] = False diff --git a/salt/states/event.py b/salt/states/event.py index 2026b2e2032..759bd16dd83 100644 --- a/salt/states/event.py +++ b/salt/states/event.py @@ -2,7 +2,6 @@ Send events through Salt's event system during state runs """ - import salt.utils.functools diff --git a/salt/states/file.py b/salt/states/file.py index 8daf99c5f08..1eecd5bd673 100644 --- a/salt/states/file.py +++ b/salt/states/file.py @@ -277,7 +277,6 @@ For example: """ - import copy import difflib import itertools @@ -1137,7 +1136,7 @@ def _get_template_texts( txtl = [] - for (source, source_hash) in source_list: + for source, source_hash in source_list: tmpctx = defaults if defaults else {} if context: @@ -1898,9 +1897,7 @@ def symlink( fs_entry_type = ( "File" if os.path.isfile(name) - else "Directory" - if os.path.isdir(name) - else "File system entry" + else "Directory" if os.path.isdir(name) else "File system entry" ) return _error( ret, @@ -3261,9 +3258,9 @@ def managed( else: ret["comment"] = f"File {name} not updated" elif not ret["changes"] and ret["result"]: - ret[ - "comment" - ] = f"File {name} exists with proper permissions. No changes made." + ret["comment"] = ( + f"File {name} exists with proper permissions. No changes made." + ) return ret accum_data, _ = _load_accumulators() @@ -4183,9 +4180,9 @@ def directory( # As above with user, we need to make sure group exists. if isinstance(gid, str): ret["result"] = False - ret[ - "comment" - ] = f"Failed to enforce group ownership for group {group}" + ret["comment"] = ( + f"Failed to enforce group ownership for group {group}" + ) else: ret["result"] = False ret["comment"] = ( @@ -6199,9 +6196,9 @@ def blockreplace( ) except Exception as exc: # pylint: disable=broad-except log.exception("Encountered error managing block") - ret[ - "comment" - ] = f"Encountered error managing block: {exc}. See the log for details." + ret["comment"] = ( + f"Encountered error managing block: {exc}. See the log for details." + ) return ret if changes: @@ -7700,9 +7697,9 @@ def copy_( ) ret["result"] = None else: - ret[ - "comment" - ] = f'The target file "{name}" exists and will not be overwritten' + ret["comment"] = ( + f'The target file "{name}" exists and will not be overwritten' + ) ret["result"] = True return ret @@ -7802,9 +7799,9 @@ def rename(name, source, force=False, makedirs=False, **kwargs): if os.path.lexists(source) and os.path.lexists(name): if not force: - ret[ - "comment" - ] = f'The target file "{name}" exists and will not be overwritten' + ret["comment"] = ( + f'The target file "{name}" exists and will not be overwritten' + ) return ret elif not __opts__["test"]: # Remove the destination to prevent problems later @@ -8561,10 +8558,10 @@ def mknod(name, ntype, major=0, minor=0, user=None, group=None, mode="0600"): elif ntype == "b": # Check for file existence if __salt__["file.file_exists"](name): - ret[ - "comment" - ] = "File {} exists and is not a block device. Refusing to continue".format( - name + ret["comment"] = ( + "File {} exists and is not a block device. Refusing to continue".format( + name + ) ) # Check if it is a block device @@ -8596,10 +8593,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 @@ -9260,10 +9257,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"] = ( @@ -9321,10 +9318,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/firewalld.py b/salt/states/firewalld.py index 7aab15e1382..d3e69560a25 100644 --- a/salt/states/firewalld.py +++ b/salt/states/firewalld.py @@ -102,7 +102,6 @@ with an example output of: rule service name="snmp" accept """ - import logging import salt.utils.path @@ -204,7 +203,6 @@ def present( rich_rules=None, prune_rich_rules=False, ): - """ Ensure a zone has specific attributes. diff --git a/salt/states/gem.py b/salt/states/gem.py index e5a1ab26b8b..66477e60cff 100644 --- a/salt/states/gem.py +++ b/salt/states/gem.py @@ -118,7 +118,7 @@ def installed( return ret if __opts__["test"]: - ret["comment"] = "The gem {} would have been installed".format(name) + ret["comment"] = f"The gem {name} would have been installed" return ret if __salt__["gem.install"]( name, @@ -169,7 +169,7 @@ def removed(name, ruby=None, user=None, gem_bin=None): return ret if __opts__["test"]: - ret["comment"] = "The gem {} would have been removed".format(name) + ret["comment"] = f"The gem {name} would have been removed" return ret if __salt__["gem.uninstall"](name, ruby, gem_bin=gem_bin, runas=user): ret["result"] = True @@ -203,7 +203,7 @@ def sources_add(name, ruby=None, user=None): ret["comment"] = "Gem source is already added." return ret if __opts__["test"]: - ret["comment"] = "The gem source {} would have been added.".format(name) + ret["comment"] = f"The gem source {name} would have been added." return ret if __salt__["gem.sources_add"](source_uri=name, ruby=ruby, runas=user): ret["result"] = True diff --git a/salt/states/git.py b/salt/states/git.py index 0f3f977442e..d4d91f0383f 100644 --- a/salt/states/git.py +++ b/salt/states/git.py @@ -144,7 +144,7 @@ def _strip_exc(exc): def _uptodate(ret, target, comments=None, local_changes=False): - ret["comment"] = "Repository {} is up-to-date".format(target) + ret["comment"] = f"Repository {target} is up-to-date" if local_changes: ret["comment"] += ( ", but with uncommitted changes. Set 'force_reset' to True to " @@ -177,7 +177,7 @@ def _fail(ret, msg, comments=None): def _already_cloned(ret, target, branch=None, comments=None): ret["result"] = True ret["comment"] = "Repository already exists at {}{}".format( - target, " and is checked out to branch '{}'".format(branch) if branch else "" + target, f" and is checked out to branch '{branch}'" if branch else "" ) if comments: ret["comment"] += "\n\nChanges {}made: {}".format( @@ -234,15 +234,17 @@ def _not_fast_forward( ret, "Repository would be updated {}{}, but {}. Set 'force_reset' to " "True{} to force this update{}.{}".format( - "from {} to {}".format(pre, post) - if local_changes and pre != post - else "to {}".format(post), - " (after checking out local branch '{}')".format(branch) - if _need_branch_change(branch, local_branch) - else "", - "this is not a fast-forward merge" - if not local_changes - else "there are uncommitted changes", + f"from {pre} to {post}" if local_changes and pre != post else f"to {post}", + ( + f" (after checking out local branch '{branch}')" + if _need_branch_change(branch, local_branch) + else "" + ), + ( + "this is not a fast-forward merge" + if not local_changes + else "there are uncommitted changes" + ), " (or 'remote-changes')" if local_changes else "", " and discard these changes" if local_changes else "", branch_msg, @@ -276,7 +278,7 @@ def latest( refspec_branch="*", refspec_tag="*", output_encoding=None, - **kwargs + **kwargs, ): """ Make sure the repository is cloned to the given directory and is @@ -619,9 +621,7 @@ def latest( return _fail(ret, "'target' argument is required") if not rev: - return _fail( - ret, "'{}' is not a valid value for the 'rev' argument".format(rev) - ) + return _fail(ret, f"'{rev}' is not a valid value for the 'rev' argument") if force_reset not in (True, False, "remote-changes"): return _fail( @@ -635,7 +635,7 @@ def latest( if not isinstance(target, str): target = str(target) if not os.path.isabs(target): - return _fail(ret, "target '{}' is not an absolute path".format(target)) + return _fail(ret, f"target '{target}' is not an absolute path") if branch is not None and not isinstance(branch, str): branch = str(branch) if user is not None and not isinstance(user, str): @@ -656,13 +656,9 @@ def latest( ident_path = __salt__["cp.cache_file"](ident_path, __env__) except OSError as exc: log.exception("Failed to cache %s", ident_path) - return _fail( - ret, "identity '{}' does not exist.".format(ident_path) - ) + return _fail(ret, f"identity '{ident_path}' does not exist.") if not os.path.isabs(ident_path): - return _fail( - ret, "identity '{}' is not an absolute path".format(ident_path) - ) + return _fail(ret, f"identity '{ident_path}' is not an absolute path") if https_user is not None and not isinstance(https_user, str): https_user = str(https_user) if https_pass is not None and not isinstance(https_pass, str): @@ -681,7 +677,7 @@ def latest( if os.path.isfile(target): return _fail( ret, - "Target '{}' exists and is a regular file, cannot proceed".format(target), + f"Target '{target}' exists and is a regular file, cannot proceed", ) try: @@ -731,7 +727,7 @@ def latest( output_encoding=output_encoding, ) except CommandExecutionError as exc: - return _fail(ret, "Failed to check remote refs: {}".format(_strip_exc(exc))) + return _fail(ret, f"Failed to check remote refs: {_strip_exc(exc)}") if "HEAD" in all_remote_refs: head_rev = all_remote_refs["HEAD"] @@ -825,7 +821,7 @@ def latest( # remote repo. return _fail( ret, - "No revision matching '{}' exists in the remote repository".format(rev), + f"No revision matching '{rev}' exists in the remote repository", ) git_ver = Version(__salt__["git.version"](versioninfo=False)) @@ -1200,9 +1196,7 @@ def latest( output_encoding=output_encoding, ) if fetch_url is None: - comments.append( - "Remote '{}' set to {}".format(remote, redacted_fetch_url) - ) + comments.append(f"Remote '{remote}' set to {redacted_fetch_url}") ret["changes"]["new"] = name + " => " + remote else: comments.append( @@ -1217,7 +1211,7 @@ def latest( if __opts__["test"]: actions = [] if not has_remote_rev: - actions.append("Remote '{}' would be fetched".format(remote)) + actions.append(f"Remote '{remote}' would be fetched") if (not revs_match) and ( update_head or (branch is not None and branch != local_branch) ): @@ -1258,9 +1252,11 @@ def latest( else: actions.append( "Repository would be {} from {} to {}".format( - "hard-reset" - if force_reset and has_remote_rev - else "updated", + ( + "hard-reset" + if force_reset and has_remote_rev + else "updated" + ), _short_sha(local_rev), _short_sha(remote_rev), ) @@ -1418,7 +1414,7 @@ def latest( else: if fetch_changes: comments.append( - "{} was fetched, resulting in updated refs".format(name) + f"{name} was fetched, resulting in updated refs" ) try: @@ -1518,7 +1514,7 @@ def latest( "as a starting point".format(branch, remote_loc) ) else: - comments.append("'{}' was checked out".format(checkout_rev)) + comments.append(f"'{checkout_rev}' was checked out") if fast_forward is False: __salt__["git.reset"]( @@ -1527,14 +1523,12 @@ def latest( user=user, password=password, output_encoding=output_encoding, - **lfs_opts + **lfs_opts, ) ret["changes"]["forced update"] = True if local_changes: comments.append("Uncommitted changes were discarded") - comments.append( - "Repository was hard-reset to {}".format(remote_loc) - ) + comments.append(f"Repository was hard-reset to {remote_loc}") elif ( fast_forward is True and local_changes and force_reset is not False ): @@ -1595,10 +1589,10 @@ def latest( user=user, password=password, output_encoding=output_encoding, - **lfs_opts + **lfs_opts, ) comments.append( - "Repository was fast-forwarded to {}".format(remote_loc) + f"Repository was fast-forwarded to {remote_loc}" ) else: return _fail( @@ -1615,11 +1609,9 @@ def latest( user=user, password=password, output_encoding=output_encoding, - **lfs_opts - ) - comments.append( - "Repository was reset to {} (fast-forward)".format(rev) + **lfs_opts, ) + comments.append(f"Repository was reset to {rev} (fast-forward)") # TODO: Figure out how to add submodule update info to # test=True return data, and changes dict. @@ -1639,7 +1631,7 @@ def latest( return _failed_submodule_update(ret, exc, comments) elif bare: if __opts__["test"]: - msg = "Bare repository at {} would be fetched".format(target) + msg = f"Bare repository at {target} would be fetched" if ret["changes"]: return _neutral_test(ret, msg) else: @@ -1724,9 +1716,7 @@ def latest( if exc.errno != errno.ENOENT: removal_errors[target_path] = exc if removal_errors: - err_strings = [ - " {}\n {}".format(k, v) for k, v in removal_errors.items() - ] + err_strings = [f" {k}\n {v}" for k, v in removal_errors.items()] return _fail( ret, "Unable to remove\n{}".format("\n".join(err_strings)), @@ -1747,9 +1737,7 @@ def latest( log.debug("Target %s is not found, 'git clone' is required", target) if __opts__["test"]: ret["changes"]["new"] = name + " => " + target - return _neutral_test( - ret, "Repository {} would be cloned to {}".format(name, target) - ) + return _neutral_test(ret, f"Repository {name} would be cloned to {target}") try: clone_opts = ["--mirror"] if mirror else ["--bare"] if bare else [] if remote != "origin": @@ -1774,7 +1762,7 @@ def latest( output_encoding=output_encoding, ) except CommandExecutionError as exc: - msg = "Clone failed: {}".format(_strip_exc(exc)) + msg = f"Clone failed: {_strip_exc(exc)}" return _fail(ret, msg, comments) ret["changes"]["new"] = name + " => " + target @@ -1813,7 +1801,7 @@ def latest( ): return _fail( ret, - "Revision '{}' does not exist in clone".format(rev), + f"Revision '{rev}' does not exist in clone", comments, ) @@ -1872,7 +1860,7 @@ def latest( password=password, output_encoding=output_encoding, ) - comments.append("Repository was reset to {}".format(remote_loc)) + comments.append(f"Repository was reset to {remote_loc}") try: upstream = __salt__["git.rev_parse"]( @@ -2110,7 +2098,7 @@ def present( else: salt.utils.files.rm_rf(name) except OSError as exc: - return _fail(ret, "Unable to remove {}: {}".format(name, exc)) + return _fail(ret, f"Unable to remove {name}: {exc}") else: ret["changes"]["forced init"] = True elif os.listdir(name): @@ -2142,9 +2130,9 @@ def present( actions = ["Initialized {}repository in {}".format("bare " if bare else "", name)] if template: - actions.append("Template directory set to {}".format(template)) + actions.append(f"Template directory set to {template}") if separate_git_dir: - actions.append("Gitdir set to {}".format(separate_git_dir)) + actions.append(f"Gitdir set to {separate_git_dir}") message = ". ".join(actions) if len(actions) > 1: message += "." @@ -2170,7 +2158,7 @@ def detached( https_user=None, https_pass=None, output_encoding=None, - **kwargs + **kwargs, ): """ .. versionadded:: 2016.3.0 @@ -2261,14 +2249,10 @@ def detached( return _fail(ret, salt.utils.args.invalid_kwargs(kwargs, raise_exc=False)) if not rev: - return _fail( - ret, "'{}' is not a valid value for the 'rev' argument".format(rev) - ) + return _fail(ret, f"'{rev}' is not a valid value for the 'rev' argument") if not target: - return _fail( - ret, "'{}' is not a valid value for the 'target' argument".format(rev) - ) + return _fail(ret, f"'{rev}' is not a valid value for the 'target' argument") # Ensure that certain arguments are strings to ensure that comparisons work if not isinstance(rev, str): @@ -2277,7 +2261,7 @@ def detached( if not isinstance(target, str): target = str(target) if not os.path.isabs(target): - return _fail(ret, "Target '{}' is not an absolute path".format(target)) + return _fail(ret, f"Target '{target}' is not an absolute path") if user is not None and not isinstance(user, str): user = str(user) if remote is not None and not isinstance(remote, str): @@ -2294,13 +2278,9 @@ def detached( ident_path = __salt__["cp.cache_file"](ident_path) except OSError as exc: log.error("Failed to cache %s: %s", ident_path, exc) - return _fail( - ret, "Identity '{}' does not exist.".format(ident_path) - ) + return _fail(ret, f"Identity '{ident_path}' does not exist.") if not os.path.isabs(ident_path): - return _fail( - ret, "Identity '{}' is not an absolute path".format(ident_path) - ) + return _fail(ret, f"Identity '{ident_path}' is not an absolute path") if https_user is not None and not isinstance(https_user, str): https_user = str(https_user) if https_pass is not None and not isinstance(https_pass, str): @@ -2309,7 +2289,7 @@ def detached( if os.path.isfile(target): return _fail( ret, - "Target '{}' exists and is a regular file, cannot proceed".format(target), + f"Target '{target}' exists and is a regular file, cannot proceed", ) try: @@ -2377,9 +2357,7 @@ def detached( current_fetch_url = remotes[remote]["fetch"] if __opts__["test"]: - return _neutral_test( - ret, "Remote {} would be set to {}".format(remote, name) - ) + return _neutral_test(ret, f"Remote {remote} would be set to {name}") __salt__["git.remote_set"]( target, @@ -2427,9 +2405,7 @@ def detached( if exc.errno != errno.ENOENT: removal_errors[target_path] = exc if removal_errors: - err_strings = [ - " {}\n {}".format(k, v) for k, v in removal_errors.items() - ] + err_strings = [f" {k}\n {v}" for k, v in removal_errors.items()] return _fail( ret, "Unable to remove\n{}".format("\n".join(err_strings)), @@ -2449,9 +2425,7 @@ def detached( log.debug("Target %s is not found, 'git clone' is required", target) if __opts__["test"]: - return _neutral_test( - ret, "Repository {} would be cloned to {}".format(name, target) - ) + return _neutral_test(ret, f"Repository {name} would be cloned to {target}") try: clone_opts = ["--no-checkout"] if remote != "origin": @@ -2469,7 +2443,7 @@ def detached( saltenv=__env__, output_encoding=output_encoding, ) - comments.append("{} cloned to {}".format(name, target)) + comments.append(f"{name} cloned to {target}") except Exception as exc: # pylint: disable=broad-except log.error("Unexpected exception in git.detached state", exc_info=True) @@ -2481,7 +2455,7 @@ def detached( # Repository exists and is ready for fetch/checkout refspecs = [ - "refs/heads/*:refs/remotes/{}/*".format(remote), + f"refs/heads/*:refs/remotes/{remote}/*", "+refs/tags/*:refs/tags/*", ] if hash_exists_locally or fetch_remote is False: @@ -2489,9 +2463,7 @@ def detached( else: # Fetch refs from remote if __opts__["test"]: - return _neutral_test( - ret, "Repository remote {} would be fetched".format(remote) - ) + return _neutral_test(ret, f"Repository remote {remote} would be fetched") try: fetch_changes = __salt__["git.fetch"]( target, @@ -2511,7 +2483,7 @@ def detached( else: if fetch_changes: comments.append( - "Remote {} was fetched, resulting in updated refs".format(remote) + f"Remote {remote} was fetched, resulting in updated refs" ) # get refs and checkout @@ -2522,7 +2494,7 @@ def detached( ): checkout_commit_id = rev else: - return _fail(ret, "Revision '{}' does not exist".format(rev)) + return _fail(ret, f"Revision '{rev}' does not exist") else: try: all_remote_refs = __salt__["git.remote_refs"]( @@ -2543,17 +2515,15 @@ def detached( elif "refs/tags/" + rev in all_remote_refs: checkout_commit_id = all_remote_refs["refs/tags/" + rev] else: - return _fail(ret, "Revision '{}' does not exist".format(rev)) + return _fail(ret, f"Revision '{rev}' does not exist") except CommandExecutionError as exc: - return _fail( - ret, "Failed to list refs for {}: {}".format(remote, _strip_exc(exc)) - ) + return _fail(ret, f"Failed to list refs for {remote}: {_strip_exc(exc)}") if hard_reset: if __opts__["test"]: return _neutral_test( - ret, "Hard reset to HEAD would be performed on {}".format(target) + ret, f"Hard reset to HEAD would be performed on {target}" ) __salt__["git.reset"]( target, @@ -2585,9 +2555,7 @@ def detached( password=password, output_encoding=output_encoding, ) - comments.append( - "Commit ID {} was checked out at {}".format(checkout_commit_id, target) - ) + comments.append(f"Commit ID {checkout_commit_id} was checked out at {target}") try: new_rev = __salt__["git.revision"]( @@ -2734,7 +2702,7 @@ def cloned( comment = "{} would be cloned to {}{}".format( name, target, - " with branch '{}'".format(branch) if branch is not None else "", + f" with branch '{branch}'" if branch is not None else "", ) return _neutral_test(ret, comment) clone_opts = ["--branch", branch] if branch is not None else None @@ -2751,14 +2719,14 @@ def cloned( output_encoding=output_encoding, ) except CommandExecutionError as exc: - msg = "Clone failed: {}".format(_strip_exc(exc)) + msg = f"Clone failed: {_strip_exc(exc)}" return _fail(ret, msg, comments) comments.append( "{} cloned to {}{}".format( name, target, - " with branch '{}'".format(branch) if branch is not None else "", + f" with branch '{branch}'" if branch is not None else "", ) ) _clone_changes(ret) @@ -2777,9 +2745,7 @@ def cloned( else: if __opts__["test"]: _branch_changes(ret, current_branch, branch) - return _neutral_test( - ret, "Branch would be changed to '{}'".format(branch) - ) + return _neutral_test(ret, f"Branch would be changed to '{branch}'") try: __salt__["git.rev_parse"]( target, @@ -2809,10 +2775,10 @@ def cloned( output_encoding=output_encoding, ) except CommandExecutionError as exc: - msg = "Failed to change branch to '{}': {}".format(branch, exc) + msg = f"Failed to change branch to '{branch}': {exc}" return _fail(ret, msg, comments) else: - comments.append("Branch changed to '{}'".format(branch)) + comments.append(f"Branch changed to '{branch}'") _branch_changes(ret, current_branch, branch) ret["comment"] = _format_comments(comments) ret["result"] = True @@ -2826,7 +2792,7 @@ def config_unset( user=None, password=None, output_encoding=None, - **kwargs + **kwargs, ): r""" .. versionadded:: 2015.8.0 @@ -2951,7 +2917,7 @@ def config_unset( password=password, ignore_retcode=True, output_encoding=output_encoding, - **{"global": global_} + **{"global": global_}, ) if not pre_matches: @@ -2984,7 +2950,7 @@ def config_unset( if __opts__["test"]: ret["changes"] = pre_matches return _neutral_test( - ret, "{} key(s) would have value(s) unset".format(len(pre_matches)) + ret, f"{len(pre_matches)} key(s) would have value(s) unset" ) if value_regex is None: @@ -3000,7 +2966,7 @@ def config_unset( password=password, ignore_retcode=True, output_encoding=output_encoding, - **{"global": global_} + **{"global": global_}, ) failed = [] @@ -3016,10 +2982,10 @@ def config_unset( user=user, password=password, output_encoding=output_encoding, - **{"global": global_} + **{"global": global_}, ) except CommandExecutionError as exc: - msg = "Failed to unset '{}'".format(key_name) + msg = f"Failed to unset '{key_name}'" if value_regex is not None: msg += " using value_regex '{1}'" msg += ": " + _strip_exc(exc) @@ -3041,7 +3007,7 @@ def config_unset( password=password, ignore_retcode=True, output_encoding=output_encoding, - **{"global": global_} + **{"global": global_}, ) for key_name in pre: @@ -3062,7 +3028,7 @@ def config_unset( password=password, ignore_retcode=True, output_encoding=output_encoding, - **{"global": global_} + **{"global": global_}, ) if post_matches: @@ -3081,7 +3047,7 @@ def config_set( user=None, password=None, output_encoding=None, - **kwargs + **kwargs, ): """ .. versionadded:: 2014.7.0 @@ -3219,7 +3185,7 @@ def config_set( password=password, ignore_retcode=True, output_encoding=output_encoding, - **{"all": True, "global": global_} + **{"all": True, "global": global_}, ) if desired == pre: @@ -3248,7 +3214,7 @@ def config_set( user=user, password=password, output_encoding=output_encoding, - **{"global": global_} + **{"global": global_}, ) except CommandExecutionError as exc: return _fail( diff --git a/salt/states/github.py b/salt/states/github.py index f93e6e8799d..e632cf679a5 100644 --- a/salt/states/github.py +++ b/salt/states/github.py @@ -55,15 +55,15 @@ def present(name, profile="github", **kwargs): # If the user has a valid github handle and is not in the org already if not target: ret["result"] = False - ret["comment"] = "Couldnt find user {}".format(name) + ret["comment"] = f"Couldnt find user {name}" elif isinstance(target, bool) and target: - ret["comment"] = "User {} is already in the org ".format(name) + ret["comment"] = f"User {name} is already in the org " ret["result"] = True elif ( not target.get("in_org", False) and target.get("membership_state") != "pending" ): if __opts__["test"]: - ret["comment"] = "User {} will be added to the org".format(name) + ret["comment"] = f"User {name} will be added to the org" return ret # add the user @@ -71,15 +71,13 @@ def present(name, profile="github", **kwargs): if result: ret["changes"].setdefault("old", None) - ret["changes"].setdefault( - "new", "User {} exists in the org now".format(name) - ) + ret["changes"].setdefault("new", f"User {name} exists in the org now") ret["result"] = True else: ret["result"] = False - ret["comment"] = "Failed to add user {} to the org".format(name) + ret["comment"] = f"Failed to add user {name} to the org" else: - ret["comment"] = "User {} has already been invited.".format(name) + ret["comment"] = f"User {name} has already been invited." ret["result"] = True return ret @@ -110,7 +108,7 @@ def absent(name, profile="github", **kwargs): "name": name, "changes": {}, "result": None, - "comment": "User {} is absent.".format(name), + "comment": f"User {name} is absent.", } target = __salt__["github.get_user"](name, profile=profile, **kwargs) @@ -118,25 +116,25 @@ def absent(name, profile="github", **kwargs): if target: if isinstance(target, bool) or target.get("in_org", False): if __opts__["test"]: - ret["comment"] = "User {} will be deleted".format(name) + ret["comment"] = f"User {name} will be deleted" ret["result"] = None return ret result = __salt__["github.remove_user"](name, profile=profile, **kwargs) if result: - ret["comment"] = "Deleted user {}".format(name) - ret["changes"].setdefault("old", "User {} exists".format(name)) - ret["changes"].setdefault("new", "User {} deleted".format(name)) + ret["comment"] = f"Deleted user {name}" + ret["changes"].setdefault("old", f"User {name} exists") + ret["changes"].setdefault("new", f"User {name} deleted") ret["result"] = True else: - ret["comment"] = "Failed to delete {}".format(name) + ret["comment"] = f"Failed to delete {name}" ret["result"] = False else: - ret["comment"] = "User {} has already been deleted!".format(name) + ret["comment"] = f"User {name} has already been deleted!" ret["result"] = True else: - ret["comment"] = "User {} does not exist".format(name) + ret["comment"] = f"User {name} does not exist" ret["result"] = True return ret @@ -153,7 +151,7 @@ def team_present( enforce_mfa=False, no_mfa_grace_seconds=0, profile="github", - **kwargs + **kwargs, ): """ Ensure a team is present @@ -229,7 +227,7 @@ def team_present( if len(parameters) > 0: if __opts__["test"]: test_comments.append( - "Team properties are set to be edited: {}".format(parameters) + f"Team properties are set to be edited: {parameters}" ) ret["result"] = None else: @@ -238,7 +236,7 @@ def team_present( ) if result: ret["changes"]["team"] = { - "old": "Team properties were {}".format(target), + "old": f"Team properties were {target}", "new": "Team properties (that changed) are {}".format( parameters ), @@ -272,8 +270,8 @@ def team_present( ) if result: ret["changes"][repo_name] = { - "old": "Repo {} is not in team {}".format(repo_name, name), - "new": "Repo {} is in team {}".format(repo_name, name), + "old": f"Repo {repo_name} is not in team {name}", + "new": f"Repo {repo_name} is in team {name}", } else: ret["result"] = False @@ -297,21 +295,21 @@ def team_present( ) if result: ret["changes"][repo_name] = { - "old": "Repo {} is in team {}".format(repo_name, name), - "new": "Repo {} is not in team {}".format(repo_name, name), + "old": f"Repo {repo_name} is in team {name}", + "new": f"Repo {repo_name} is not in team {name}", } else: ret["result"] = False - ret[ - "comment" - ] = "Failed to remove repo {} from team {}.".format( - repo_name, name + ret["comment"] = ( + "Failed to remove repo {} from team {}.".format( + repo_name, name + ) ) return ret else: # Team does not exist - it will be created. if __opts__["test"]: - ret["comment"] = "Team {} is set to be created.".format(name) + ret["comment"] = f"Team {name} is set to be created." ret["result"] = None return ret @@ -322,15 +320,15 @@ def team_present( permission=permission, privacy=privacy, profile=profile, - **kwargs + **kwargs, ) if result: ret["changes"]["team"] = {} ret["changes"]["team"]["old"] = None - ret["changes"]["team"]["new"] = "Team {} has been created".format(name) + ret["changes"]["team"]["new"] = f"Team {name} has been created" else: ret["result"] = False - ret["comment"] = "Failed to create team {}.".format(name) + ret["comment"] = f"Failed to create team {name}." return ret manage_members = members is not None @@ -363,9 +361,7 @@ def team_present( else: # Add to team member_change = True if __opts__["test"]: - test_comments.append( - "User {} set to be added to the team.".format(member) - ) + test_comments.append(f"User {member} set to be added to the team.") ret["result"] = None else: result = __salt__["github.add_team_member"]( @@ -375,7 +371,7 @@ def team_present( ret["changes"][member] = {} ret["changes"][member][ "old" - ] = "User {} is not in team {}".format(member, name) + ] = f"User {member} is not in team {name}" ret["changes"][member]["new"] = "User {} is in team {}".format( member, name ) @@ -407,7 +403,7 @@ def team_present( ) else: test_comments.append( - "User {} set to be removed from the team.".format(member) + f"User {member} set to be removed from the team." ) ret["result"] = None else: @@ -417,7 +413,7 @@ def team_present( if result: extra_changes = " due to MFA violation" if mfa_violation else "" ret["changes"][member] = { - "old": "User {} is in team {}".format(member, name), + "old": f"User {member} is in team {name}", "new": "User {} is not in team {}{}".format( member, name, extra_changes ), @@ -473,24 +469,24 @@ def team_absent(name, profile="github", **kwargs): target = __salt__["github.get_team"](name, profile=profile, **kwargs) if not target: - ret["comment"] = "Team {} does not exist".format(name) + ret["comment"] = f"Team {name} does not exist" ret["result"] = True return ret else: if __opts__["test"]: - ret["comment"] = "Team {} will be deleted".format(name) + ret["comment"] = f"Team {name} will be deleted" ret["result"] = None return ret result = __salt__["github.remove_team"](name, profile=profile, **kwargs) if result: - ret["comment"] = "Deleted team {}".format(name) - ret["changes"].setdefault("old", "Team {} exists".format(name)) - ret["changes"].setdefault("new", "Team {} deleted".format(name)) + ret["comment"] = f"Deleted team {name}" + ret["changes"].setdefault("old", f"Team {name} exists") + ret["changes"].setdefault("new", f"Team {name} deleted") ret["result"] = True else: - ret["comment"] = "Failed to delete {}".format(name) + ret["comment"] = f"Failed to delete {name}" ret["result"] = False return ret @@ -508,7 +504,7 @@ def repo_present( license_template=None, teams=None, profile="github", - **kwargs + **kwargs, ): """ Ensure a repository is present @@ -605,8 +601,8 @@ def repo_present( if len(parameters) > 0: repo_change = { - "old": "Repo properties were {}".format(old_parameters), - "new": "Repo properties (that changed) are {}".format(parameters), + "old": f"Repo properties were {old_parameters}", + "new": f"Repo properties (that changed) are {parameters}", } if __opts__["test"]: ret["changes"]["repo"] = repo_change @@ -623,7 +619,7 @@ def repo_present( return ret else: # Repo does not exist - it will be created. - repo_change = {"old": None, "new": "Repo {} has been created".format(name)} + repo_change = {"old": None, "new": f"Repo {name} has been created"} if __opts__["test"]: ret["changes"]["repo"] = repo_change ret["result"] = None @@ -634,7 +630,7 @@ def repo_present( if not result: ret["result"] = False - ret["comment"] = "Failed to create repo {}.".format(name) + ret["comment"] = f"Failed to create repo {name}." return ret # Turns out that trying to fetch teams for a new repo can 404 immediately @@ -652,7 +648,7 @@ def repo_present( if current_teams is None: ret["result"] = False - ret["comment"] = "Failed to verify repo {} after creation.".format(name) + ret["comment"] = f"Failed to verify repo {name} after creation." return ret ret["changes"]["repo"] = repo_change @@ -669,8 +665,8 @@ def repo_present( for team_name in current_team_names: if team_name not in teams: team_change = { - "old": "Repo {} is in team {}".format(name, team_name), - "new": "Repo {} is not in team {}".format(name, team_name), + "old": f"Repo {name} is in team {team_name}", + "new": f"Repo {name} is not in team {team_name}", } if __opts__["test"]: @@ -684,10 +680,10 @@ def repo_present( ret["changes"][team_name] = team_change else: ret["result"] = False - ret[ - "comment" - ] = "Failed to remove repo {} from team {}.".format( - name, team_name + ret["comment"] = ( + "Failed to remove repo {} from team {}.".format( + name, team_name + ) ) return ret @@ -695,8 +691,8 @@ def repo_present( for team_name, permission in teams.items(): if team_name not in current_team_names: # Need to add repo to team team_change = { - "old": "Repo {} is not in team {}".format(name, team_name), - "new": "Repo {} is in team {}".format(name, team_name), + "old": f"Repo {name} is not in team {team_name}", + "new": f"Repo {name} is in team {team_name}", } if __opts__["test"]: ret["changes"][team_name] = team_change @@ -709,10 +705,10 @@ def repo_present( ret["changes"][team_name] = team_change else: ret["result"] = False - ret[ - "comment" - ] = "Failed to remove repo {} from team {}.".format( - name, team_name + ret["comment"] = ( + "Failed to remove repo {} from team {}.".format( + name, team_name + ) ) return ret else: @@ -783,21 +779,21 @@ def repo_absent(name, profile="github", **kwargs): target = None if not target: - ret["comment"] = "Repo {} does not exist".format(name) + ret["comment"] = f"Repo {name} does not exist" ret["result"] = True return ret else: if __opts__["test"]: - ret["comment"] = "Repo {} will be deleted".format(name) + ret["comment"] = f"Repo {name} will be deleted" ret["result"] = None return ret result = __salt__["github.remove_repo"](name, profile=profile, **kwargs) if result: - ret["comment"] = "Deleted repo {}".format(name) - ret["changes"].setdefault("old", "Repo {} exists".format(name)) - ret["changes"].setdefault("new", "Repo {} deleted".format(name)) + ret["comment"] = f"Deleted repo {name}" + ret["changes"].setdefault("old", f"Repo {name} exists") + ret["changes"].setdefault("new", f"Repo {name} deleted") ret["result"] = True else: ret["comment"] = ( diff --git a/salt/states/glance_image.py b/salt/states/glance_image.py index fe8f7857ce7..b65ec5f353c 100644 --- a/salt/states/glance_image.py +++ b/salt/states/glance_image.py @@ -22,7 +22,6 @@ Example States - name: cirros """ - __virtualname__ = "glance_image" @@ -61,7 +60,7 @@ def present(name, auth=None, **kwargs): if __opts__["test"]: ret["result"] = None ret["changes"] = kwargs - ret["comment"] = "Image {} will be created.".format(name) + ret["comment"] = f"Image {name} will be created." return ret kwargs["name"] = name @@ -91,7 +90,7 @@ def absent(name, auth=None): if __opts__["test"]: ret["result"] = None ret["changes"] = {"name": name} - ret["comment"] = "Image {} will be deleted.".format(name) + ret["comment"] = f"Image {name} will be deleted." return ret __salt__["glanceng.image_delete"](name=image) diff --git a/salt/states/glassfish.py b/salt/states/glassfish.py index 913b7da2fb5..30778d17729 100644 --- a/salt/states/glassfish.py +++ b/salt/states/glassfish.py @@ -82,7 +82,7 @@ def _do_element_present(name, elem_type, data, server=None): """ ret = {"changes": {}, "update": False, "create": False, "error": None} try: - elements = __salt__["glassfish.enum_{}".format(elem_type)]() + elements = __salt__[f"glassfish.enum_{elem_type}"]() except requests.ConnectionError as error: if __opts__["test"]: ret["changes"] = {"Name": name, "Params": data} @@ -97,23 +97,19 @@ def _do_element_present(name, elem_type, data, server=None): ret["create"] = True if not __opts__["test"]: try: - __salt__["glassfish.create_{}".format(elem_type)]( - name, server=server, **data - ) + __salt__[f"glassfish.create_{elem_type}"](name, server=server, **data) except CommandExecutionError as error: ret["error"] = error return ret elif elements and any(data): - current_data = __salt__["glassfish.get_{}".format(elem_type)]( - name, server=server - ) + current_data = __salt__[f"glassfish.get_{elem_type}"](name, server=server) data_diff = _is_updated(current_data, data) if data_diff: ret["update"] = True ret["changes"] = data_diff if not __opts__["test"]: try: - __salt__["glassfish.update_{}".format(elem_type)]( + __salt__[f"glassfish.update_{elem_type}"]( name, server=server, **data ) except CommandExecutionError as error: @@ -127,7 +123,7 @@ def _do_element_absent(name, elem_type, data, server=None): """ ret = {"delete": False, "error": None} try: - elements = __salt__["glassfish.enum_{}".format(elem_type)]() + elements = __salt__[f"glassfish.enum_{elem_type}"]() except requests.ConnectionError as error: if __opts__["test"]: ret["create"] = True @@ -140,9 +136,7 @@ def _do_element_absent(name, elem_type, data, server=None): ret["delete"] = True if not __opts__["test"]: try: - __salt__["glassfish.delete_{}".format(elem_type)]( - name, server=server, **data - ) + __salt__[f"glassfish.delete_{elem_type}"](name, server=server, **data) except CommandExecutionError as error: ret["error"] = error return ret @@ -208,7 +202,7 @@ def connection_factory_present( # Manage parameters pool_data = {} res_data = {} - pool_name = "{}-Connection-Pool".format(name) + pool_name = f"{name}-Connection-Pool" if restype == "topic_connection_factory": pool_data["connectionDefinitionName"] = "javax.jms.TopicConnectionFactory" elif restype == "queue_connection_factory": @@ -285,7 +279,7 @@ def connection_factory_absent(name, both=True, server=None): Delete both the pool and the resource, defaults to ``true`` """ ret = {"name": name, "result": None, "comment": None, "changes": {}} - pool_name = "{}-Connection-Pool".format(name) + pool_name = f"{name}-Connection-Pool" pool_ret = _do_element_absent( pool_name, "connector_c_pool", {"cascade": both}, server ) @@ -466,7 +460,7 @@ def jdbc_datasource_present( ret = {"name": name, "result": None, "comment": None, "changes": {}} # Manage parameters - res_name = "jdbc/{}".format(name) + res_name = f"jdbc/{name}" pool_data = {} pool_data_properties = {} res_data = {} diff --git a/salt/states/glusterfs.py b/salt/states/glusterfs.py index bfe4fb63380..331053d2550 100644 --- a/salt/states/glusterfs.py +++ b/salt/states/glusterfs.py @@ -2,7 +2,6 @@ Manage GlusterFS pool. """ - import logging import salt.utils.cloud as suc @@ -84,11 +83,11 @@ def peered(name): if peers and any(name in v["hostnames"] for v in peers.values()): ret["result"] = True - ret["comment"] = "Host {} already peered".format(name) + ret["comment"] = f"Host {name} already peered" return ret if __opts__["test"]: - ret["comment"] = "Peer {} will be added.".format(name) + ret["comment"] = f"Peer {name} will be added." ret["result"] = None return ret @@ -102,13 +101,13 @@ def peered(name): newpeers = __salt__["glusterfs.peer_status"]() if newpeers and any(name in v["hostnames"] for v in newpeers.values()): ret["result"] = True - ret["comment"] = "Host {} successfully peered".format(name) + ret["comment"] = f"Host {name} successfully peered" ret["changes"] = {"new": newpeers, "old": peers} else: - ret[ - "comment" - ] = "Host {} was successfully peered but did not appear in the list of peers".format( - name + ret["comment"] = ( + "Host {} was successfully peered but did not appear in the list of peers".format( + name + ) ) return ret @@ -182,7 +181,7 @@ def volume_present( volumes = __salt__["glusterfs.list_volumes"]() if name not in volumes: if __opts__["test"]: - comment = "Volume {} will be created".format(name) + comment = f"Volume {name} will be created" if start: comment += " and started" ret["comment"] = comment @@ -194,16 +193,16 @@ def volume_present( ) if not vol_created: - ret["comment"] = "Creation of volume {} failed".format(name) + ret["comment"] = f"Creation of volume {name} failed" return ret old_volumes = volumes volumes = __salt__["glusterfs.list_volumes"]() if name in volumes: ret["changes"] = {"new": volumes, "old": old_volumes} - ret["comment"] = "Volume {} is created".format(name) + ret["comment"] = f"Volume {name} is created" else: - ret["comment"] = "Volume {} already exists".format(name) + ret["comment"] = f"Volume {name} already exists" if start: if __opts__["test"]: @@ -252,26 +251,26 @@ def started(name): volinfo = __salt__["glusterfs.info"]() if name not in volinfo: ret["result"] = False - ret["comment"] = "Volume {} does not exist".format(name) + ret["comment"] = f"Volume {name} does not exist" return ret if int(volinfo[name]["status"]) == 1: - ret["comment"] = "Volume {} is already started".format(name) + ret["comment"] = f"Volume {name} is already started" ret["result"] = True return ret elif __opts__["test"]: - ret["comment"] = "Volume {} will be started".format(name) + ret["comment"] = f"Volume {name} will be started" ret["result"] = None return ret vol_started = __salt__["glusterfs.start_volume"](name) if vol_started: ret["result"] = True - ret["comment"] = "Volume {} is started".format(name) + ret["comment"] = f"Volume {name} is started" ret["change"] = {"new": "started", "old": "stopped"} else: ret["result"] = False - ret["comment"] = "Failed to start volume {}".format(name) + ret["comment"] = f"Failed to start volume {name}" return ret @@ -305,23 +304,23 @@ def add_volume_bricks(name, bricks): volinfo = __salt__["glusterfs.info"]() if name not in volinfo: - ret["comment"] = "Volume {} does not exist".format(name) + ret["comment"] = f"Volume {name} does not exist" return ret if int(volinfo[name]["status"]) != 1: - ret["comment"] = "Volume {} is not started".format(name) + ret["comment"] = f"Volume {name} is not started" return ret current_bricks = [brick["path"] for brick in volinfo[name]["bricks"].values()] if not set(bricks) - set(current_bricks): ret["result"] = True - ret["comment"] = "Bricks already added in volume {}".format(name) + ret["comment"] = f"Bricks already added in volume {name}" return ret bricks_added = __salt__["glusterfs.add_volume_bricks"](name, bricks) if bricks_added: ret["result"] = True - ret["comment"] = "Bricks successfully added to volume {}".format(name) + ret["comment"] = f"Bricks successfully added to volume {name}" new_bricks = [ brick["path"] for brick in __salt__["glusterfs.info"]()[name]["bricks"].values() @@ -329,7 +328,7 @@ def add_volume_bricks(name, bricks): ret["changes"] = {"new": new_bricks, "old": current_bricks} return ret - ret["comment"] = "Adding bricks to volume {} failed".format(name) + ret["comment"] = f"Adding bricks to volume {name} failed" return ret @@ -368,10 +367,10 @@ def op_version(name, version): ret["result"] = True return ret elif __opts__["test"]: - ret[ - "comment" - ] = "An attempt would be made to set the cluster.op-version for {} to {}.".format( - name, version + ret["comment"] = ( + "An attempt would be made to set the cluster.op-version for {} to {}.".format( + name, version + ) ) ret["result"] = None return ret @@ -421,18 +420,18 @@ def max_op_version(name): return ret if current == max_version: - ret[ - "comment" - ] = "The cluster.op-version is already set to the cluster.max-op-version of {}".format( - current + ret["comment"] = ( + "The cluster.op-version is already set to the cluster.max-op-version of {}".format( + current + ) ) ret["result"] = True return ret elif __opts__["test"]: - ret[ - "comment" - ] = "An attempt would be made to set the cluster.op-version to {}.".format( - max_version + ret["comment"] = ( + "An attempt would be made to set the cluster.op-version to {}.".format( + max_version + ) ) ret["result"] = None return ret diff --git a/salt/states/gnomedesktop.py b/salt/states/gnomedesktop.py index 24c9df87796..6fb3c222a1b 100644 --- a/salt/states/gnomedesktop.py +++ b/salt/states/gnomedesktop.py @@ -68,12 +68,12 @@ def _do(name, gnome_kwargs, preferences): gnome_kwargs.update({"key": key, "value": value}) if _check_current_value(gnome_kwargs, value): - messages.append("{} is already set to {}".format(key, value)) + messages.append(f"{key} is already set to {value}") else: result = __salt__["gnome.set"](**gnome_kwargs) if result["retcode"] == 0: - messages.append("Setting {} to {}".format(key, value)) - ret["changes"][key] = "{}:{}".format(key, value) + messages.append(f"Setting {key} to {value}") + ret["changes"][key] = f"{key}:{value}" ret["result"] = True else: messages.append(result["stdout"]) @@ -108,7 +108,7 @@ def wm_preferences( visual_bell=None, visual_bell_type=None, workspace_names=None, - **kwargs + **kwargs, ): """ wm_preferences: sets values in the org.gnome.desktop.wm.preferences schema @@ -160,7 +160,7 @@ def desktop_lockdown( disable_save_to_disk=None, disable_user_switching=None, user_administration_disabled=None, - **kwargs + **kwargs, ): """ desktop_lockdown: sets values in the org.gnome.desktop.lockdown schema @@ -227,7 +227,7 @@ def desktop_interface( toolbar_icons_size=None, toolbar_style=None, toolkit_accessibility=None, - **kwargs + **kwargs, ): """ desktop_interface: sets values in the org.gnome.desktop.interface schema diff --git a/salt/states/grafana.py b/salt/states/grafana.py index e061b916fb2..b25a1d93d3c 100644 --- a/salt/states/grafana.py +++ b/salt/states/grafana.py @@ -189,7 +189,7 @@ def _parse_profile(profile): if isinstance(profile, str): _profile = __salt__["config.option"](profile) if not _profile: - msg = "Pillar key for profile {} not found.".format(profile) + msg = f"Pillar key for profile {profile} not found." raise SaltInvocationError(msg) else: _profile = profile @@ -292,7 +292,7 @@ def dashboard_present( " dashboard template was provided." ) if __opts__["test"]: - ret["comment"] = "Dashboard {} is set to be created.".format(name) + ret["comment"] = f"Dashboard {name} is set to be created." ret["result"] = None return ret _dashboard = dashboard @@ -330,12 +330,12 @@ def dashboard_present( update_rows.append(title) if not update_rows: ret["result"] = True - ret["comment"] = "Dashboard {} is up to date".format(name) + ret["comment"] = f"Dashboard {name} is up to date" return ret if __opts__["test"]: - msg = "Dashboard {} is set to be updated.".format(name) + msg = f"Dashboard {name} is set to be updated." if update_rows: - msg = "{} The following rows set to be updated: {}".format(msg, update_rows) + msg = f"{msg} The following rows set to be updated: {update_rows}" ret["comment"] = msg return ret body = { @@ -350,13 +350,13 @@ def dashboard_present( if updated: ret["result"] = True ret["changes"]["changed"] = name - msg = "Updated dashboard {}.".format(name) + msg = f"Updated dashboard {name}." if update_rows: - msg = "{} The following rows were updated: {}".format(msg, update_rows) + msg = f"{msg} The following rows were updated: {update_rows}" ret["comment"] = msg else: ret["result"] = False - msg = "Failed to update dashboard {}.".format(name) + msg = f"Failed to update dashboard {name}." ret["comment"] = msg return ret @@ -385,7 +385,7 @@ def dashboard_absent(name, hosts=None, profile="grafana"): if exists: if __opts__["test"]: - ret["comment"] = "Dashboard {} is set to be removed.".format(name) + ret["comment"] = f"Dashboard {name} is set to be removed." return ret deleted = __salt__["elasticsearch.delete"]( index=index, doc_type="dashboard", id=name, hosts=hosts @@ -396,9 +396,9 @@ def dashboard_absent(name, hosts=None, profile="grafana"): ret["changes"]["new"] = None else: ret["result"] = False - ret["comment"] = "Failed to delete {} dashboard.".format(name) + ret["comment"] = f"Failed to delete {name} dashboard." else: ret["result"] = True - ret["comment"] = "Dashboard {} does not exist.".format(name) + ret["comment"] = f"Dashboard {name} does not exist." return ret diff --git a/salt/states/grafana4_dashboard.py b/salt/states/grafana4_dashboard.py index 8f85ebad9cc..43d88734852 100644 --- a/salt/states/grafana4_dashboard.py +++ b/salt/states/grafana4_dashboard.py @@ -52,7 +52,6 @@ allowing users to manage their own custom rows. type: graph """ - import copy import salt.utils.json @@ -139,15 +138,15 @@ def present( if not old_dashboard: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Dashboard {} is set to be created.".format(name) + ret["comment"] = f"Dashboard {name} is set to be created." return ret response = __salt__["grafana4.create_update_dashboard"]( dashboard=new_dashboard, overwrite=True, profile=profile ) if response.get("status") == "success": - ret["comment"] = "Dashboard {} created.".format(name) - ret["changes"]["new"] = "Dashboard {} created.".format(name) + ret["comment"] = f"Dashboard {name} created." + ret["changes"]["new"] = f"Dashboard {name} created." else: ret["result"] = False ret["comment"] = "Failed to create dashboard {}, response={}".format( @@ -192,7 +191,7 @@ def present( dashboard_diff = DictDiffer( _cleaned(updated_dashboard), _cleaned(old_dashboard) ) - ret["comment"] = "Dashboard {} updated.".format(name) + ret["comment"] = f"Dashboard {name} updated." ret["changes"] = _dashboard_diff( _cleaned(new_dashboard), _cleaned(old_dashboard) ) @@ -230,12 +229,12 @@ def absent(name, orgname=None, profile="grafana"): if existing_dashboard: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Dashboard {} is set to be deleted.".format(name) + ret["comment"] = f"Dashboard {name} is set to be deleted." return ret __salt__["grafana4.delete_dashboard"](name, profile=profile) - ret["comment"] = "Dashboard {} deleted.".format(name) - ret["changes"]["new"] = "Dashboard {} deleted.".format(name) + ret["comment"] = f"Dashboard {name} deleted." + ret["changes"]["new"] = f"Dashboard {name} deleted." return ret ret["comment"] = "Dashboard absent" diff --git a/salt/states/grafana4_datasource.py b/salt/states/grafana4_datasource.py index b0ebe8d02d3..b3b2503071c 100644 --- a/salt/states/grafana4_datasource.py +++ b/salt/states/grafana4_datasource.py @@ -152,12 +152,12 @@ def present( if not datasource: if __opts__["test"]: - ret["comment"] = "Datasource {} will be created".format(name) + ret["comment"] = f"Datasource {name} will be created" return ret __salt__["grafana4.create_datasource"](profile=profile, **data) datasource = __salt__["grafana4.get_datasource"](name, profile=profile) ret["result"] = True - ret["comment"] = "New data source {} added".format(name) + ret["comment"] = f"New data source {name} added" ret["changes"] = data return ret @@ -168,16 +168,16 @@ def present( datasource[key] = None if data == datasource: - ret["comment"] = "Data source {} already up-to-date".format(name) + ret["comment"] = f"Data source {name} already up-to-date" return ret if __opts__["test"]: - ret["comment"] = "Datasource {} will be updated".format(name) + ret["comment"] = f"Datasource {name} will be updated" return ret __salt__["grafana4.update_datasource"](datasource["id"], profile=profile, **data) ret["result"] = True ret["changes"] = deep_diff(datasource, data, ignore=["id", "orgId", "readOnly"]) - ret["comment"] = "Data source {} updated".format(name) + ret["comment"] = f"Data source {name} updated" return ret @@ -203,17 +203,17 @@ def absent(name, orgname=None, profile="grafana"): if not datasource: ret["result"] = True - ret["comment"] = "Data source {} already absent".format(name) + ret["comment"] = f"Data source {name} already absent" return ret if __opts__["test"]: - ret["comment"] = "Datasource {} will be deleted".format(name) + ret["comment"] = f"Datasource {name} will be deleted" return ret __salt__["grafana4.delete_datasource"](datasource["id"], profile=profile) ret["result"] = True ret["changes"][name] = "Absent" - ret["comment"] = "Data source {} was deleted".format(name) + ret["comment"] = f"Data source {name} was deleted" return ret diff --git a/salt/states/grafana4_org.py b/salt/states/grafana4_org.py index 8d4aa5e1da9..c0167637e8e 100644 --- a/salt/states/grafana4_org.py +++ b/salt/states/grafana4_org.py @@ -130,12 +130,12 @@ def present( if create: if __opts__["test"]: - ret["comment"] = "Org {} will be created".format(name) + ret["comment"] = f"Org {name} will be created" return ret __salt__["grafana4.create_org"](profile=profile, name=name) org = __salt__["grafana4.get_org"](name, profile) ret["changes"] = org - ret["comment"] = "New org {} added".format(name) + ret["comment"] = f"New org {name} added" data = _get_json_data( address1=address1, @@ -148,7 +148,7 @@ def present( ) if data != org["address"]: if __opts__["test"]: - ret["comment"] = "Org {} address will be updated".format(name) + ret["comment"] = f"Org {name} address will be updated" return ret __salt__["grafana4.update_org_address"](name, profile=profile, **data) if create: @@ -165,7 +165,7 @@ def present( ) if data != prefs: if __opts__["test"]: - ret["comment"] = "Org {} prefs will be updated".format(name) + ret["comment"] = f"Org {name} prefs will be updated" return ret __salt__["grafana4.update_org_prefs"](name, profile=profile, **data) if create: @@ -227,10 +227,10 @@ def present( ret["result"] = True if not create: if ret["changes"]: - ret["comment"] = "Org {} updated".format(name) + ret["comment"] = f"Org {name} updated" else: ret["changes"] = {} - ret["comment"] = "Org {} already up-to-date".format(name) + ret["comment"] = f"Org {name} already up-to-date" return ret @@ -254,17 +254,17 @@ def absent(name, profile="grafana"): if not org: ret["result"] = True - ret["comment"] = "Org {} already absent".format(name) + ret["comment"] = f"Org {name} already absent" return ret if __opts__["test"]: - ret["comment"] = "Org {} will be deleted".format(name) + ret["comment"] = f"Org {name} will be deleted" return ret __salt__["grafana4.delete_org"](org["id"], profile=profile) ret["result"] = True ret["changes"][name] = "Absent" - ret["comment"] = "Org {} was deleted".format(name) + ret["comment"] = f"Org {name} was deleted" return ret diff --git a/salt/states/grafana4_user.py b/salt/states/grafana4_user.py index 813c4e5aae4..30c4c1e83f3 100644 --- a/salt/states/grafana4_user.py +++ b/salt/states/grafana4_user.py @@ -85,7 +85,7 @@ def present( if create: if __opts__["test"]: - ret["comment"] = "User {} will be created".format(name) + ret["comment"] = f"User {name} will be created" return ret __salt__["grafana4.create_user"]( login=name, password=password, email=email, name=fullname, profile=profile @@ -101,7 +101,7 @@ def present( login=None, email=None, name=None, theme=None, defaults=user_data ): if __opts__["test"]: - ret["comment"] = "User {} will be updated".format(name) + ret["comment"] = f"User {name} will be updated" return ret __salt__["grafana4.update_user"](user["id"], profile=profile, **data) dictupdate.update( @@ -111,7 +111,7 @@ def present( if user["isAdmin"] != is_admin: if __opts__["test"]: - ret["comment"] = "User {} isAdmin status will be updated".format(name) + ret["comment"] = f"User {name} isAdmin status will be updated" return ret __salt__["grafana4.update_user_permissions"]( user["id"], isGrafanaAdmin=is_admin, profile=profile @@ -124,13 +124,13 @@ def present( ret["result"] = True if create: ret["changes"] = ret["changes"]["new"] - ret["comment"] = "New user {} added".format(name) + ret["comment"] = f"New user {name} added" else: if ret["changes"]: - ret["comment"] = "User {} updated".format(name) + ret["comment"] = f"User {name} updated" else: ret["changes"] = {} - ret["comment"] = "User {} already up-to-date".format(name) + ret["comment"] = f"User {name} already up-to-date" return ret @@ -154,7 +154,7 @@ def absent(name, profile="grafana"): if user: if __opts__["test"]: - ret["comment"] = "User {} will be deleted".format(name) + ret["comment"] = f"User {name} will be deleted" return ret orgs = __salt__["grafana4.get_user_orgs"](user["id"], profile=profile) __salt__["grafana4.delete_user"](user["id"], profile=profile) @@ -171,12 +171,12 @@ def absent(name, profile="grafana"): ) else: ret["result"] = True - ret["comment"] = "User {} already absent".format(name) + ret["comment"] = f"User {name} already absent" return ret ret["result"] = True ret["changes"][name] = "Absent" - ret["comment"] = "User {} was deleted".format(name) + ret["comment"] = f"User {name} was deleted" return ret diff --git a/salt/states/grafana_dashboard.py b/salt/states/grafana_dashboard.py index a23d0f084e3..0e4538f8852 100644 --- a/salt/states/grafana_dashboard.py +++ b/salt/states/grafana_dashboard.py @@ -37,7 +37,6 @@ they exist in dashboards. The module will not manage rows that are not defined, allowing users to manage their own custom rows. """ - import copy import requests @@ -122,18 +121,18 @@ def present( _ensure_annotations(new_dashboard) # Create dashboard if it does not exist - url = "db/{}".format(name) + url = f"db/{name}" old_dashboard = _get(url, profile) if not old_dashboard: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Dashboard {} is set to be created.".format(name) + ret["comment"] = f"Dashboard {name} is set to be created." return ret response = _update(new_dashboard, profile) if response.get("status") == "success": - ret["comment"] = "Dashboard {} created.".format(name) - ret["changes"]["new"] = "Dashboard {} created.".format(name) + ret["comment"] = f"Dashboard {name} created." + ret["changes"]["new"] = f"Dashboard {name} created." else: ret["result"] = False ret["comment"] = "Failed to create dashboard {}, response={}".format( @@ -174,7 +173,7 @@ def present( dashboard_diff = DictDiffer( _cleaned(updated_dashboard), _cleaned(old_dashboard) ) - ret["comment"] = "Dashboard {} updated.".format(name) + ret["comment"] = f"Dashboard {name} updated." ret["changes"] = _dashboard_diff( _cleaned(new_dashboard), _cleaned(old_dashboard) ) @@ -204,17 +203,17 @@ def absent(name, profile="grafana"): if isinstance(profile, str): profile = __salt__["config.option"](profile) - url = "db/{}".format(name) + url = f"db/{name}" existing_dashboard = _get(url, profile) if existing_dashboard: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Dashboard {} is set to be deleted.".format(name) + ret["comment"] = f"Dashboard {name} is set to be deleted." return ret _delete(url, profile) - ret["comment"] = "Dashboard {} deleted.".format(name) - ret["changes"]["new"] = "Dashboard {} deleted.".format(name) + ret["comment"] = f"Dashboard {name} deleted." + ret["changes"]["new"] = f"Dashboard {name} deleted." return ret ret["comment"] = "Dashboard absent" diff --git a/salt/states/grafana_datasource.py b/salt/states/grafana_datasource.py index e513802c890..9daf0efa79f 100644 --- a/salt/states/grafana_datasource.py +++ b/salt/states/grafana_datasource.py @@ -110,10 +110,10 @@ def present( ret["result"] = True ret["changes"] = _diff(datasource, data) if ret["changes"]["new"] or ret["changes"]["old"]: - ret["comment"] = "Data source {} updated".format(name) + ret["comment"] = f"Data source {name} updated" else: ret["changes"] = {} - ret["comment"] = "Data source {} already up-to-date".format(name) + ret["comment"] = f"Data source {name} already up-to-date" else: requests.post( "{}/api/datasources".format(profile["grafana_url"]), @@ -122,7 +122,7 @@ def present( timeout=profile.get("grafana_timeout", 3), ) ret["result"] = True - ret["comment"] = "New data source {} added".format(name) + ret["comment"] = f"New data source {name} added" ret["changes"] = data return ret @@ -143,7 +143,7 @@ def absent(name, profile="grafana"): if not datasource: ret["result"] = True - ret["comment"] = "Data source {} already absent".format(name) + ret["comment"] = f"Data source {name} already absent" return ret requests.delete( @@ -153,7 +153,7 @@ def absent(name, profile="grafana"): ) ret["result"] = True - ret["comment"] = "Data source {} was deleted".format(name) + ret["comment"] = f"Data source {name} was deleted" return ret diff --git a/salt/states/grains.py b/salt/states/grains.py index 9e6399dd57f..d69a8779467 100644 --- a/salt/states/grains.py +++ b/salt/states/grains.py @@ -125,15 +125,15 @@ def present(name, value, delimiter=DEFAULT_TARGET_DELIM, force=False): if __opts__["test"]: ret["result"] = None if existing is _non_existent: - ret["comment"] = "Grain {} is set to be added".format(name) + ret["comment"] = f"Grain {name} is set to be added" ret["changes"] = {"new": name} else: - ret["comment"] = "Grain {} is set to be changed".format(name) + ret["comment"] = f"Grain {name} is set to be changed" ret["changes"] = {"changed": {name: value}} return ret ret = __salt__["grains.set"](name, value, force=force) if ret["result"] is True and ret["changes"] != {}: - ret["comment"] = "Set grain {} to {}".format(name, value) + ret["comment"] = f"Set grain {name} to {value}" ret["name"] = name return ret @@ -182,13 +182,13 @@ def list_present(name, value, delimiter=DEFAULT_TARGET_DELIM): # check whether grain is a list if not isinstance(grain, list): ret["result"] = False - ret["comment"] = "Grain {} is not a valid list".format(name) + ret["comment"] = f"Grain {name} is not a valid list" return ret if isinstance(value, list): if make_hashable(value).issubset( make_hashable(__salt__["grains.get"](name)) ): - ret["comment"] = "Value {1} is already in grain {0}".format(name, value) + ret["comment"] = f"Value {value} is already in grain {name}" return ret elif name in __context__.get("pending_grains", {}): # elements common to both @@ -199,10 +199,10 @@ def list_present(name, value, delimiter=DEFAULT_TARGET_DELIM): value = list( set(value).difference(__context__["pending_grains"][name]) ) - ret[ - "comment" - ] = 'Removed value {} from update due to context found in "{}".\n'.format( - value, name + ret["comment"] = ( + 'Removed value {} from update due to context found in "{}".\n'.format( + value, name + ) ) if "pending_grains" not in __context__: __context__["pending_grains"] = {} @@ -211,7 +211,7 @@ def list_present(name, value, delimiter=DEFAULT_TARGET_DELIM): __context__["pending_grains"][name].update(value) else: if value in grain: - ret["comment"] = "Value {1} is already in grain {0}".format(name, value) + ret["comment"] = f"Value {value} is already in grain {name}" return ret if __opts__["test"]: ret["result"] = None @@ -223,21 +223,21 @@ def list_present(name, value, delimiter=DEFAULT_TARGET_DELIM): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Grain {} is set to be added".format(name) + ret["comment"] = f"Grain {name} is set to be added" ret["changes"] = {"new": grain} return ret new_grains = __salt__["grains.append"](name, value) if isinstance(value, list): if not set(value).issubset(set(__salt__["grains.get"](name))): ret["result"] = False - ret["comment"] = "Failed append value {1} to grain {0}".format(name, value) + ret["comment"] = f"Failed append value {value} to grain {name}" return ret else: if value not in __salt__["grains.get"](name, delimiter=DEFAULT_TARGET_DELIM): ret["result"] = False - ret["comment"] = "Failed append value {1} to grain {0}".format(name, value) + ret["comment"] = f"Failed append value {value} to grain {name}" return ret - ret["comment"] = "Append value {1} to grain {0}".format(name, value) + ret["comment"] = f"Append value {value} to grain {name}" ret["changes"] = {"new": new_grains} return ret @@ -288,22 +288,16 @@ def list_absent(name, value, delimiter=DEFAULT_TARGET_DELIM): value = [value] for val in value: if val not in grain: - comments.append( - "Value {1} is absent from grain {0}".format(name, val) - ) + comments.append(f"Value {val} is absent from grain {name}") elif __opts__["test"]: ret["result"] = None - comments.append( - "Value {1} in grain {0} is set to be deleted".format(name, val) - ) + comments.append(f"Value {val} in grain {name} is set to be deleted") if "deleted" not in ret["changes"].keys(): ret["changes"] = {"deleted": []} ret["changes"]["deleted"].append(val) elif val in grain: __salt__["grains.remove"](name, val) - comments.append( - "Value {1} was deleted from grain {0}".format(name, val) - ) + comments.append(f"Value {val} was deleted from grain {name}") if "deleted" not in ret["changes"].keys(): ret["changes"] = {"deleted": []} ret["changes"]["deleted"].append(val) @@ -311,9 +305,9 @@ def list_absent(name, value, delimiter=DEFAULT_TARGET_DELIM): return ret else: ret["result"] = False - ret["comment"] = "Grain {} is not a valid list".format(name) + ret["comment"] = f"Grain {name} is not a valid list" else: - ret["comment"] = "Grain {} does not exist".format(name) + ret["comment"] = f"Grain {name} does not exist" return ret @@ -362,38 +356,36 @@ def absent(name, destructive=False, delimiter=DEFAULT_TARGET_DELIM, force=False) if __opts__["test"]: ret["result"] = None if destructive is True: - ret["comment"] = "Grain {} is set to be deleted".format(name) + ret["comment"] = f"Grain {name} is set to be deleted" ret["changes"] = {"deleted": name} return ret ret = __salt__["grains.set"](name, None, destructive=destructive, force=force) if ret["result"]: if destructive is True: - ret["comment"] = "Grain {} was deleted".format(name) + ret["comment"] = f"Grain {name} was deleted" ret["changes"] = {"deleted": name} ret["name"] = name elif grain is not _non_existent: if __opts__["test"]: ret["result"] = None if destructive is True: - ret["comment"] = "Grain {} is set to be deleted".format(name) + ret["comment"] = f"Grain {name} is set to be deleted" ret["changes"] = {"deleted": name} else: - ret[ - "comment" - ] = "Value for grain {} is set to be deleted (None)".format(name) + ret["comment"] = f"Value for grain {name} is set to be deleted (None)" ret["changes"] = {"grain": name, "value": None} return ret ret = __salt__["grains.set"](name, None, destructive=destructive, force=force) if ret["result"]: if destructive is True: - ret["comment"] = "Grain {} was deleted".format(name) + ret["comment"] = f"Grain {name} was deleted" ret["changes"] = {"deleted": name} else: - ret["comment"] = "Value for grain {} was set to None".format(name) + ret["comment"] = f"Value for grain {name} was set to None" ret["changes"] = {"grain": name, "value": None} ret["name"] = name else: - ret["comment"] = "Grain {} does not exist".format(name) + ret["comment"] = f"Grain {name} does not exist" return ret @@ -436,9 +428,9 @@ 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"] = ( + f"Value {value} is already in the list for grain {name}" + ) return ret if __opts__["test"]: ret["result"] = None @@ -448,7 +440,7 @@ def append(name, value, convert=False, delimiter=DEFAULT_TARGET_DELIM): ret["changes"] = {"added": value} return ret __salt__["grains.append"](name, value) - ret["comment"] = "Value {1} was added to grain {0}".format(name, value) + ret["comment"] = f"Value {value} was added to grain {name}" ret["changes"] = {"added": value} else: if convert is True: @@ -464,12 +456,12 @@ def append(name, value, convert=False, delimiter=DEFAULT_TARGET_DELIM): grain = [] if grain is None else [grain] grain.append(value) __salt__["grains.setval"](name, grain) - ret["comment"] = "Value {1} was added to grain {0}".format(name, value) + ret["comment"] = f"Value {value} was added to grain {name}" ret["changes"] = {"added": value} else: ret["result"] = False - ret["comment"] = "Grain {} is not a valid list".format(name) + ret["comment"] = f"Grain {name} is not a valid list" else: ret["result"] = False - ret["comment"] = "Grain {} does not exist".format(name) + ret["comment"] = f"Grain {name} does not exist" return ret diff --git a/salt/states/group.py b/salt/states/group.py index 1fe30589c06..3a2bcf1c3be 100644 --- a/salt/states/group.py +++ b/salt/states/group.py @@ -33,7 +33,6 @@ In Windows, if no domain is specified in the user or group name (i.e. - user2 """ - import sys import salt.utils.platform @@ -204,9 +203,9 @@ def present( # -- if trying to add and delete the same user(s) at the same time. if not set(addusers).isdisjoint(set(delusers)): ret["result"] = None - ret[ - "comment" - ] = "Error. Same user(s) can not be added and deleted simultaneously" + ret["comment"] = ( + "Error. Same user(s) can not be added and deleted simultaneously" + ) return ret changes = _changes(name, gid, addusers, delusers, members, local=local) diff --git a/salt/states/heat.py b/salt/states/heat.py index c4a63133ee4..2e86486c972 100644 --- a/salt/states/heat.py +++ b/salt/states/heat.py @@ -108,7 +108,7 @@ def deployed( timeout=60, update=False, profile=None, - **connection_args + **connection_args, ): """ Deploy stack with the specified properties @@ -168,7 +168,7 @@ def deployed( existing_stack = __salt__["heat.show_stack"](name, profile=profile) if existing_stack["result"] and not update: - ret["comment"] = "Stack {} is deployed".format(name) + ret["comment"] = f"Stack {name} is deployed" return ret if existing_stack["result"] and update: if template: @@ -223,7 +223,7 @@ def deployed( salt.utils.files.safe_rm(template_tmp_file) except ValueError as ex: ret["result"] = False - ret["comment"] = "Error parsing template {}".format(ex) + ret["comment"] = f"Error parsing template {ex}" else: ret["result"] = False ret["comment"] = "Can not open template: {} {}".format( @@ -245,13 +245,13 @@ def deployed( checksum_stack = __salt__["hashutil.digest"](template_stack["template"]) except salt.exceptions.CommandExecutionError as cmdexc: ret["result"] = False - ret["comment"] = "{}".format(cmdexc) + ret["comment"] = f"{cmdexc}" if ret["result"] is True: if checksum_template == checksum_stack: if __opts__["test"]: ret["result"] = True - ret["comment"] = "Stack {} is deployed".format(name) + ret["comment"] = f"Stack {name} is deployed" return ret else: ret["result"] = False @@ -263,7 +263,7 @@ def deployed( if __opts__["test"]: stack = { "result": None, - "comment": "Stack {} is set to be updated".format(name), + "comment": f"Stack {name} is set to be updated", } else: stack = __salt__["heat.update_stack"]( @@ -282,7 +282,7 @@ def deployed( if __opts__["test"]: stack = { "result": None, - "comment": "Stack {} is set to be created".format(name), + "comment": f"Stack {name} is set to be created", } else: stack = __salt__["heat.create_stack"]( @@ -337,7 +337,7 @@ def absent(name, poll=5, timeout=60, profile=None): return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Stack {} is set to be removed".format(name) + ret["comment"] = f"Stack {name} is set to be removed" return ret stack = __salt__["heat.delete_stack"]( diff --git a/salt/states/helm.py b/salt/states/helm.py index f80a766a956..95d1e393655 100644 --- a/salt/states/helm.py +++ b/salt/states/helm.py @@ -99,7 +99,7 @@ def repo_managed( except CommandExecutionError as err: ret["result"] = False - ret["comment"] = "Failed to add some repositories: {}.".format(err) + ret["comment"] = f"Failed to add some repositories: {err}." return ret @@ -154,7 +154,7 @@ def repo_updated(name, namespace=None, flags=None, kvflags=None): except CommandExecutionError as err: ret["result"] = False - ret["comment"] = "Failed to update some repositories: {}.".format(err) + ret["comment"] = f"Failed to update some repositories: {err}." return ret @@ -226,7 +226,7 @@ def release_present( "name": name, "changes": {}, "result": True, - "comment": "Helm release {} is present".format(name), + "comment": f"Helm release {name} is present", } if "helm.status" not in __salt__: @@ -332,7 +332,7 @@ def release_absent(name, namespace=None, flags=None, kvflags=None): "name": name, "changes": {}, "result": True, - "comment": "Helm release {} is absent.".format(name), + "comment": f"Helm release {name} is absent.", } if "helm.uninstall" not in __salt__: diff --git a/salt/states/hg.py b/salt/states/hg.py index c75e58435fb..f4045514e38 100644 --- a/salt/states/hg.py +++ b/salt/states/hg.py @@ -13,7 +13,6 @@ in ~/.ssh/known_hosts, and the remote host has this host's public key. - target: /tmp/example_repo """ - import logging import os import shutil @@ -33,7 +32,7 @@ def __virtual__(): """ if __salt__["cmd.has_exec"](HG_BINARY): return True - return (False, "Command {} not found".format(HG_BINARY)) + return (False, f"Command {HG_BINARY} not found") def latest( @@ -89,7 +88,7 @@ def latest( if not target: return _fail(ret, '"target option is required') - is_repository = os.path.isdir(target) and os.path.isdir("{}/.hg".format(target)) + is_repository = os.path.isdir(target) and os.path.isdir(f"{target}/.hg") if is_repository: ret = _update_repo( @@ -104,7 +103,7 @@ def latest( log.debug('target %s is not found, "hg clone" is required', target) if __opts__["test"]: return _neutral_test( - ret, "Repository {} is about to be cloned to {}".format(name, target) + ret, f"Repository {name} is about to be cloned to {target}" ) _clone_repo(ret, target, name, user, identity, rev, opts) return ret @@ -118,7 +117,7 @@ def _update_repo(ret, name, target, clean, user, identity, rev, opts, update_hea current_rev = __salt__["hg.revision"](target, user=user, rev=".") if not current_rev: - return _fail(ret, "Seems that {} is not a valid hg repo".format(target)) + return _fail(ret, f"Seems that {target} is not a valid hg repo") if __opts__["test"]: return _neutral_test( @@ -145,9 +144,9 @@ def _update_repo(ret, name, target, clean, user, identity, rev, opts, update_hea " updating." ) else: - ret[ - "comment" - ] = "No changes found and update_head=False so will skip updating." + ret["comment"] = ( + "No changes found and update_head=False so will skip updating." + ) return ret if rev: @@ -168,12 +167,12 @@ def _update_repo(ret, name, target, clean, user, identity, rev, opts, update_hea new_rev = __salt__["hg.revision"](cwd=target, user=user, rev=".") if current_rev != new_rev: - revision_text = "{} => {}".format(current_rev, new_rev) + revision_text = f"{current_rev} => {new_rev}" log.info("Repository %s updated: %s", target, revision_text) - ret["comment"] = "Repository {} updated.".format(target) + ret["comment"] = f"Repository {target} updated." ret["changes"]["revision"] = revision_text elif "error:" in pull_out: - return _fail(ret, "An error was thrown by hg:\n{}".format(pull_out)) + return _fail(ret, f"An error was thrown by hg:\n{pull_out}") return ret @@ -217,7 +216,7 @@ def _clone_repo(ret, target, name, user, identity, rev, opts): return ret new_rev = __salt__["hg.revision"](cwd=target, user=user) - message = "Repository {} cloned to {}".format(name, target) + message = f"Repository {name} cloned to {target}" log.info(message) ret["comment"] = message diff --git a/salt/states/highstate_doc.py b/salt/states/highstate_doc.py index ea7c27e0125..8af62692521 100644 --- a/salt/states/highstate_doc.py +++ b/salt/states/highstate_doc.py @@ -2,7 +2,6 @@ To be used with processors in module `highstate_doc`. """ - __virtualname__ = "highstate_doc" @@ -36,7 +35,7 @@ def note(name, source=None, contents=None, **kwargs): """ comment = "" if source: - comment += "include file: {}\n".format(source) + comment += f"include file: {source}\n" if contents and len(contents) < 200: comment += contents return {"name": name, "result": True, "comment": comment, "changes": {}} diff --git a/salt/states/host.py b/salt/states/host.py index c70f04d9ed7..078e4b9f0dc 100644 --- a/salt/states/host.py +++ b/salt/states/host.py @@ -70,7 +70,6 @@ You can also include comments: """ - import logging import salt.utils.validate.net @@ -145,7 +144,7 @@ def present(name, ip, comment="", clean=False): # pylint: disable=C0103 update_comment.add((addr, comment)) else: # No changes needed for this IP address and hostname - comments.append("Host {} ({}) already present".format(name, addr)) + comments.append(f"Host {name} ({addr}) already present") else: # IP address listed in hosts file, but hostname is not present. # We will need to add it. @@ -155,32 +154,30 @@ def present(name, ip, comment="", clean=False): # pylint: disable=C0103 update_comment.add((addr, comment)) else: ret["result"] = False - comments.append("Invalid IP Address for {} ({})".format(name, addr)) + comments.append(f"Invalid IP Address for {name} ({addr})") for addr, name in to_add: if __opts__["test"]: ret["result"] = None - comments.append("Host {} ({}) would be added".format(name, addr)) + comments.append(f"Host {name} ({addr}) would be added") else: if __salt__["hosts.add_host"](addr, name): - comments.append("Added host {} ({})".format(name, addr)) + comments.append(f"Added host {name} ({addr})") else: ret["result"] = False - comments.append("Failed to add host {} ({})".format(name, addr)) + comments.append(f"Failed to add host {name} ({addr})") continue ret["changes"].setdefault("added", {}).setdefault(addr, []).append(name) for addr, comment in update_comment: if __opts__["test"]: - comments.append("Comment for {} ({}) would be added".format(addr, comment)) + comments.append(f"Comment for {addr} ({comment}) would be added") else: if __salt__["hosts.set_comment"](addr, comment): - comments.append("Set comment for host {} ({})".format(addr, comment)) + comments.append(f"Set comment for host {addr} ({comment})") else: ret["result"] = False - comments.append( - "Failed to add comment for host {} ({})".format(addr, comment) - ) + comments.append(f"Failed to add comment for host {addr} ({comment})") continue ret["changes"].setdefault("comment_added", {}).setdefault(addr, []).append( comment @@ -189,13 +186,13 @@ def present(name, ip, comment="", clean=False): # pylint: disable=C0103 for addr, name in to_remove: if __opts__["test"]: ret["result"] = None - comments.append("Host {} ({}) would be removed".format(name, addr)) + comments.append(f"Host {name} ({addr}) would be removed") else: if __salt__["hosts.rm_host"](addr, name): - comments.append("Removed host {} ({})".format(name, addr)) + comments.append(f"Removed host {name} ({addr})") else: ret["result"] = False - comments.append("Failed to remove host {} ({})".format(name, addr)) + comments.append(f"Failed to remove host {name} ({addr})") continue ret["changes"].setdefault("removed", {}).setdefault(addr, []).append(name) @@ -222,15 +219,15 @@ def absent(name, ip): # pylint: disable=C0103 for _ip in ip: if not __salt__["hosts.has_pair"](_ip, name): ret["result"] = True - comments.append("Host {} ({}) already absent".format(name, _ip)) + comments.append(f"Host {name} ({_ip}) already absent") else: if __opts__["test"]: - comments.append("Host {} ({}) needs to be removed".format(name, _ip)) + comments.append(f"Host {name} ({_ip}) needs to be removed") else: if __salt__["hosts.rm_host"](_ip, name): ret["changes"] = {"host": name} ret["result"] = True - comments.append("Removed host {} ({})".format(name, _ip)) + comments.append(f"Removed host {name} ({_ip})") else: ret["result"] = False comments.append("Failed to remove host") @@ -264,12 +261,12 @@ def only(name, hostnames): new = " ".join(x.strip() for x in hostnames) if old == new: - ret["comment"] = 'IP address {} already set to "{}"'.format(name, new) + ret["comment"] = f'IP address {name} already set to "{new}"' ret["result"] = True return ret if __opts__["test"]: - ret["comment"] = 'Would change {} from "{}" to "{}"'.format(name, old, new) + ret["comment"] = f'Would change {name} from "{old}" to "{new}"' return ret ret["result"] = __salt__["hosts.set_host"](name, new) @@ -279,6 +276,6 @@ def only(name, hostnames): ) return ret - ret["comment"] = 'successfully changed {} from "{}" to "{}"'.format(name, old, new) + ret["comment"] = f'successfully changed {name} from "{old}" to "{new}"' ret["changes"] = {name: {"old": old, "new": new}} return ret diff --git a/salt/states/http.py b/salt/states/http.py index 271f06fece1..3cb5485e0c3 100644 --- a/salt/states/http.py +++ b/salt/states/http.py @@ -6,7 +6,6 @@ Perform an HTTP query and statefully return the result .. versionadded:: 2015.5.0 """ - import logging import re import sys @@ -26,7 +25,7 @@ def query( status=None, status_type="string", wait_for=None, - **kwargs + **kwargs, ): """ Perform an HTTP query and statefully return the result @@ -130,48 +129,48 @@ def query( if match_type == "string": if str(match) in data.get("text", ""): ret["result"] = True - ret["comment"] += ' Match text "{}" was found.'.format(match) + ret["comment"] += f' Match text "{match}" was found.' else: ret["result"] = False - ret["comment"] += ' Match text "{}" was not found.'.format(match) + ret["comment"] += f' Match text "{match}" was not found.' elif match_type == "pcre": if re.search(str(match), str(data.get("text", ""))): ret["result"] = True - ret["comment"] += ' Match pattern "{}" was found.'.format(match) + ret["comment"] += f' Match pattern "{match}" was found.' else: ret["result"] = False - ret["comment"] += ' Match pattern "{}" was not found.'.format(match) + ret["comment"] += f' Match pattern "{match}" was not found.' if status is not None: # Deals with case of status_type as a list of strings representing statuses if status_type == "list": for stat in status: if str(data.get("status", "")) == str(stat): - ret["comment"] += " Status {} was found.".format(stat) + ret["comment"] += f" Status {stat} was found." if ret["result"] is None: ret["result"] = True if ret["result"] is not True: - ret["comment"] += " Statuses {} were not found.".format(status) + ret["comment"] += f" Statuses {status} were not found." ret["result"] = False # Deals with the case of status_type representing a regex elif status_type == "pcre": if re.search(str(status), str(data.get("status", ""))): - ret["comment"] += ' Status pattern "{}" was found.'.format(status) + ret["comment"] += f' Status pattern "{status}" was found.' if ret["result"] is None: ret["result"] = True else: - ret["comment"] += ' Status pattern "{}" was not found.'.format(status) + ret["comment"] += f' Status pattern "{status}" was not found.' ret["result"] = False # Deals with the case of status_type as a single string representing a status elif status_type == "string": if str(data.get("status", "")) == str(status): - ret["comment"] += " Status {} was found.".format(status) + ret["comment"] += f" Status {status} was found." if ret["result"] is None: ret["result"] = True else: - ret["comment"] += " Status {} was not found.".format(status) + ret["comment"] += f" Status {status} was not found." ret["result"] = False # cleanup spaces in comment diff --git a/salt/states/icinga2.py b/salt/states/icinga2.py index c67e58b3451..a764cc4f7f6 100644 --- a/salt/states/icinga2.py +++ b/salt/states/icinga2.py @@ -18,7 +18,6 @@ Its output may be stored in a file or in a grain. - output: "/tmp/query_id.txt" """ - import os.path import salt.utils.files @@ -69,10 +68,10 @@ def generate_ticket(name, output=None, grain=None, key=None, overwrite=True): return ret elif __opts__["test"]: ret["result"] = None - ret[ - "comment" - ] = "Ticket generation would be executed, storing result in grain: {}".format( - grain + ret["comment"] = ( + "Ticket generation would be executed, storing result in grain: {}".format( + grain + ) ) return ret elif grain: @@ -98,14 +97,14 @@ def generate_ticket(name, output=None, grain=None, key=None, overwrite=True): return ret elif output: if not overwrite and os.path.isfile(output): - ret["comment"] = "No execution needed. File {} already set".format(output) + ret["comment"] = f"No execution needed. File {output} already set" return ret elif __opts__["test"]: ret["result"] = None - ret[ - "comment" - ] = "Ticket generation would be executed, storing result in file: {}".format( - output + ret["comment"] = ( + "Ticket generation would be executed, storing result in file: {}".format( + output + ) ) return ret elif __opts__["test"]: @@ -122,7 +121,7 @@ def generate_ticket(name, output=None, grain=None, key=None, overwrite=True): if output == "grain": if grain and not key: __salt__["grains.setval"](grain, ticket) - ret["changes"]["ticket"] = "Executed. Output into grain: {}".format(grain) + ret["changes"]["ticket"] = f"Executed. Output into grain: {grain}" elif grain: if grain in __salt__["grains.ls"](): grain_value = __salt__["grains.get"](grain) @@ -134,7 +133,7 @@ def generate_ticket(name, output=None, grain=None, key=None, overwrite=True): grain, key ) elif output: - ret["changes"]["ticket"] = "Executed. Output into {}".format(output) + ret["changes"]["ticket"] = f"Executed. Output into {output}" with salt.utils.files.fopen(output, "w") as output_file: output_file.write(salt.utils.stringutils.to_str(ticket)) else: @@ -151,15 +150,15 @@ def generate_cert(name): The domain name for which this certificate and key will be generated """ ret = {"name": name, "changes": {}, "result": True, "comment": ""} - cert = "{}{}.crt".format(get_certs_path(), name) - key = "{}{}.key".format(get_certs_path(), name) + cert = f"{get_certs_path()}{name}.crt" + key = f"{get_certs_path()}{name}.key" # Checking if execution is needed. if os.path.isfile(cert) and os.path.isfile(key): - ret[ - "comment" - ] = "No execution needed. Cert: {} and key: {} already generated.".format( - cert, key + ret["comment"] = ( + "No execution needed. Cert: {} and key: {} already generated.".format( + cert, key + ) ) return ret if __opts__["test"]: @@ -171,8 +170,8 @@ def generate_cert(name): cert_save = __salt__["icinga2.generate_cert"](name) if not cert_save["retcode"]: ret["comment"] = "Certificate and key generated" - ret["changes"]["cert"] = "Executed. Certificate saved: {}".format(cert) - ret["changes"]["key"] = "Executed. Key saved: {}".format(key) + ret["changes"]["cert"] = f"Executed. Certificate saved: {cert}" + ret["changes"]["key"] = f"Executed. Key saved: {key}" return ret @@ -187,11 +186,11 @@ def save_cert(name, master): Icinga2 master node for which this certificate will be saved """ ret = {"name": name, "changes": {}, "result": True, "comment": ""} - cert = "{}trusted-master.crt".format(get_certs_path()) + cert = f"{get_certs_path()}trusted-master.crt" # Checking if execution is needed. if os.path.isfile(cert): - ret["comment"] = "No execution needed. Cert: {} already saved.".format(cert) + ret["comment"] = f"No execution needed. Cert: {cert} already saved." return ret if __opts__["test"]: ret["result"] = None @@ -202,7 +201,7 @@ def save_cert(name, master): cert_save = __salt__["icinga2.save_cert"](name, master) if not cert_save["retcode"]: ret["comment"] = "Certificate for icinga2 master saved" - ret["changes"]["cert"] = "Executed. Certificate saved: {}".format(cert) + ret["changes"]["cert"] = f"Executed. Certificate saved: {cert}" return ret @@ -223,11 +222,11 @@ def request_cert(name, master, ticket, port="5665"): Icinga2 port, defaults to 5665 """ ret = {"name": name, "changes": {}, "result": True, "comment": ""} - cert = "{}ca.crt".format(get_certs_path()) + cert = f"{get_certs_path()}ca.crt" # Checking if execution is needed. if os.path.isfile(cert): - ret["comment"] = "No execution needed. Cert: {} already exists.".format(cert) + ret["comment"] = f"No execution needed. Cert: {cert} already exists." return ret if __opts__["test"]: ret["result"] = None @@ -238,7 +237,7 @@ def request_cert(name, master, ticket, port="5665"): cert_request = __salt__["icinga2.request_cert"](name, master, ticket, port) if not cert_request["retcode"]: ret["comment"] = "Certificate request from icinga2 master executed" - ret["changes"]["cert"] = "Executed. Certificate requested: {}".format(cert) + ret["changes"]["cert"] = f"Executed. Certificate requested: {cert}" return ret ret["comment"] = "FAILED. Certificate requested failed with output: {}".format( @@ -262,8 +261,8 @@ def node_setup(name, master, ticket): Authentication ticket generated on icinga2 master """ ret = {"name": name, "changes": {}, "result": True, "comment": ""} - cert = "{}{}.crt.orig".format(get_certs_path(), name) - key = "{}{}.key.orig".format(get_certs_path(), name) + cert = f"{get_certs_path()}{name}.crt.orig" + key = f"{get_certs_path()}{name}.key.orig" # Checking if execution is needed. if os.path.isfile(cert) and os.path.isfile(cert): diff --git a/salt/states/idem.py b/salt/states/idem.py index a7caba30ecd..b324f885671 100644 --- a/salt/states/idem.py +++ b/salt/states/idem.py @@ -30,13 +30,13 @@ def _get_refs(sources, tree): sls_sources = [] SLSs = [] if tree: - sls_sources.append("file://{}".format(tree)) + sls_sources.append(f"file://{tree}") for sls in sources: path = pathlib.Path(sls) if path.is_file(): ref = str(path.stem if path.suffix == ".sls" else path.name) SLSs.append(ref) - implied = "file://{}".format(path.parent) + implied = f"file://{path.parent}" if implied not in sls_sources: sls_sources.append(implied) else: @@ -152,7 +152,7 @@ def state( return { "name": name, "result": success, - "comment": "Ran {} idem states".format(len(running)) if success else errors, + "comment": f"Ran {len(running)} idem states" if success else errors, "changes": {}, "sub_state_run": running, } diff --git a/salt/states/ifttt.py b/salt/states/ifttt.py index f7378576783..4ab7f68df02 100644 --- a/salt/states/ifttt.py +++ b/salt/states/ifttt.py @@ -80,8 +80,8 @@ def trigger_event(name, event, value1=None, value2=None, value3=None): if ret and ret["result"]: ret["result"] = True - ret["comment"] = "Triggered Event: {}".format(name) + ret["comment"] = f"Triggered Event: {name}" else: - ret["comment"] = "Failed to trigger event: {}".format(name) + ret["comment"] = f"Failed to trigger event: {name}" return ret diff --git a/salt/states/incron.py b/salt/states/incron.py index 6baad30808f..d290ca7b681 100644 --- a/salt/states/incron.py +++ b/salt/states/incron.py @@ -119,26 +119,26 @@ def present(name, path, mask, cmd, user="root"): status = _check_cron(user, path, mask, cmd) ret["result"] = None if status == "absent": - ret["comment"] = "Incron {} is set to be added".format(name) + ret["comment"] = f"Incron {name} is set to be added" elif status == "present": ret["result"] = True - ret["comment"] = "Incron {} already present".format(name) + ret["comment"] = f"Incron {name} already present" elif status == "update": - ret["comment"] = "Incron {} is set to be updated".format(name) + ret["comment"] = f"Incron {name} is set to be updated" return ret data = __salt__["incron.set_job"](user=user, path=path, mask=mask, cmd=cmd) if data == "present": - ret["comment"] = "Incron {} already present".format(name) + ret["comment"] = f"Incron {name} already present" return ret if data == "new": - ret["comment"] = "Incron {} added to {}'s incrontab".format(name, user) + ret["comment"] = f"Incron {name} added to {user}'s incrontab" ret["changes"] = {user: name} return ret if data == "updated": - ret["comment"] = "Incron {} updated".format(name) + ret["comment"] = f"Incron {name} updated" ret["changes"] = {user: name} return ret ret["comment"] = "Incron {} for user {} failed to commit with error \n{}".format( @@ -180,17 +180,17 @@ def absent(name, path, mask, cmd, user="root"): ret["result"] = None if status == "absent": ret["result"] = True - ret["comment"] = "Incron {} is absent".format(name) + ret["comment"] = f"Incron {name} is absent" elif status == "present" or status == "update": - ret["comment"] = "Incron {} is set to be removed".format(name) + ret["comment"] = f"Incron {name} is set to be removed" return ret data = __salt__["incron.rm_job"](user=user, path=path, mask=mask, cmd=cmd) if data == "absent": - ret["comment"] = "Incron {} already absent".format(name) + ret["comment"] = f"Incron {name} already absent" return ret if data == "removed": - ret["comment"] = "Incron {} removed from {}'s crontab".format(name, user) + ret["comment"] = f"Incron {name} removed from {user}'s crontab" ret["changes"] = {user: name} return ret ret["comment"] = "Incron {} for user {} failed to commit with error {}".format( diff --git a/salt/states/influxdb08_database.py b/salt/states/influxdb08_database.py index fac790a0824..e2bfe5989d0 100644 --- a/salt/states/influxdb08_database.py +++ b/salt/states/influxdb08_database.py @@ -49,16 +49,16 @@ def present(name, user=None, password=None, host=None, port=None): ) return ret if __salt__["influxdb08.db_create"](name, user, password, host, port): - ret["comment"] = "Database {} has been created".format(name) + ret["comment"] = f"Database {name} has been created" ret["changes"][name] = "Present" return ret else: - ret["comment"] = "Failed to create database {}".format(name) + ret["comment"] = f"Failed to create database {name}" ret["result"] = False return ret # fallback - ret["comment"] = "Database {} is already present, so cannot be created".format(name) + ret["comment"] = f"Database {name} is already present, so cannot be created" return ret @@ -93,14 +93,14 @@ def absent(name, user=None, password=None, host=None, port=None): ) return ret if __salt__["influxdb08.db_remove"](name, user, password, host, port): - ret["comment"] = "Database {} has been removed".format(name) + ret["comment"] = f"Database {name} has been removed" ret["changes"][name] = "Absent" return ret else: - ret["comment"] = "Failed to remove database {}".format(name) + ret["comment"] = f"Failed to remove database {name}" ret["result"] = False return ret # fallback - ret["comment"] = "Database {} is not present, so it cannot be removed".format(name) + ret["comment"] = f"Database {name} is not present, so it cannot be removed" return ret diff --git a/salt/states/influxdb08_user.py b/salt/states/influxdb08_user.py index 19865232692..e482287e6dc 100644 --- a/salt/states/influxdb08_user.py +++ b/salt/states/influxdb08_user.py @@ -53,7 +53,7 @@ def present( database, user, password, host, port ): ret["result"] = False - ret["comment"] = "Database {} does not exist".format(database) + ret["comment"] = f"Database {database} does not exist" return ret # check if user exists @@ -70,16 +70,16 @@ def present( if __salt__["influxdb08.user_create"]( name, passwd, database, user, password, host, port ): - ret["comment"] = "User {} has been created".format(name) + ret["comment"] = f"User {name} has been created" ret["changes"][name] = "Present" return ret else: - ret["comment"] = "Failed to create user {}".format(name) + ret["comment"] = f"Failed to create user {name}" ret["result"] = False return ret # fallback - ret["comment"] = "User {} is already present".format(name) + ret["comment"] = f"User {name} is already present" return ret @@ -112,19 +112,19 @@ def absent(name, database=None, user=None, password=None, host=None, port=None): if __salt__["influxdb08.user_exists"](name, database, user, password, host, port): if __opts__["test"]: ret["result"] = None - ret["comment"] = "User {} is present and needs to be removed".format(name) + ret["comment"] = f"User {name} is present and needs to be removed" return ret if __salt__["influxdb08.user_remove"]( name, database, user, password, host, port ): - ret["comment"] = "User {} has been removed".format(name) + ret["comment"] = f"User {name} has been removed" ret["changes"][name] = "Absent" return ret else: - ret["comment"] = "Failed to remove user {}".format(name) + ret["comment"] = f"Failed to remove user {name}" ret["result"] = False return ret # fallback - ret["comment"] = "User {} is not present, so it cannot be removed".format(name) + ret["comment"] = f"User {name} is not present, so it cannot be removed" return ret diff --git a/salt/states/influxdb_continuous_query.py b/salt/states/influxdb_continuous_query.py index 8c402dc1b09..c21dde4e5e0 100644 --- a/salt/states/influxdb_continuous_query.py +++ b/salt/states/influxdb_continuous_query.py @@ -42,7 +42,7 @@ def present( "name": name, "changes": {}, "result": True, - "comment": "continuous query {} is already present".format(name), + "comment": f"continuous query {name} is already present", } if not __salt__["influxdb.continuous_query_exists"]( @@ -50,16 +50,16 @@ def present( ): if __opts__["test"]: ret["result"] = None - ret["comment"] = " {} is absent and will be created".format(name) + ret["comment"] = f" {name} is absent and will be created" return ret if __salt__["influxdb.create_continuous_query"]( database, name, query, resample_time, coverage_period, **client_args ): - ret["comment"] = "continuous query {} has been created".format(name) + ret["comment"] = f"continuous query {name} has been created" ret["changes"][name] = "Present" return ret else: - ret["comment"] = "Failed to create continuous query {}".format(name) + ret["comment"] = f"Failed to create continuous query {name}" ret["result"] = False return ret @@ -80,22 +80,22 @@ def absent(name, database, **client_args): "name": name, "changes": {}, "result": True, - "comment": "continuous query {} is not present".format(name), + "comment": f"continuous query {name} is not present", } if __salt__["influxdb.continuous_query_exists"](database, name, **client_args): if __opts__["test"]: ret["result"] = None - ret[ - "comment" - ] = "continuous query {} is present and needs to be removed".format(name) + ret["comment"] = ( + f"continuous query {name} is present and needs to be removed" + ) return ret if __salt__["influxdb.drop_continuous_query"](database, name, **client_args): - ret["comment"] = "continuous query {} has been removed".format(name) + ret["comment"] = f"continuous query {name} has been removed" ret["changes"][name] = "Absent" return ret else: - ret["comment"] = "Failed to remove continuous query {}".format(name) + ret["comment"] = f"Failed to remove continuous query {name}" ret["result"] = False return ret diff --git a/salt/states/influxdb_database.py b/salt/states/influxdb_database.py index cfa2a1c9d47..1a99df01801 100644 --- a/salt/states/influxdb_database.py +++ b/salt/states/influxdb_database.py @@ -26,20 +26,20 @@ def present(name, **client_args): "name": name, "changes": {}, "result": True, - "comment": "Database {} is already present".format(name), + "comment": f"Database {name} is already present", } if not __salt__["influxdb.db_exists"](name, **client_args): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Database {} is absent and will be created".format(name) + ret["comment"] = f"Database {name} is absent and will be created" return ret if __salt__["influxdb.create_db"](name, **client_args): - ret["comment"] = "Database {} has been created".format(name) + ret["comment"] = f"Database {name} has been created" ret["changes"][name] = "Present" return ret else: - ret["comment"] = "Failed to create database {}".format(name) + ret["comment"] = f"Failed to create database {name}" ret["result"] = False return ret @@ -57,7 +57,7 @@ def absent(name, **client_args): "name": name, "changes": {}, "result": True, - "comment": "Database {} is not present".format(name), + "comment": f"Database {name} is not present", } if __salt__["influxdb.db_exists"](name, **client_args): @@ -68,11 +68,11 @@ def absent(name, **client_args): ) return ret if __salt__["influxdb.drop_db"](name, **client_args): - ret["comment"] = "Database {} has been removed".format(name) + ret["comment"] = f"Database {name} has been removed" ret["changes"][name] = "Absent" return ret else: - ret["comment"] = "Failed to remove database {}".format(name) + ret["comment"] = f"Failed to remove database {name}" ret["result"] = False return ret diff --git a/salt/states/influxdb_retention_policy.py b/salt/states/influxdb_retention_policy.py index e729269a605..f63ffd24c21 100644 --- a/salt/states/influxdb_retention_policy.py +++ b/salt/states/influxdb_retention_policy.py @@ -59,7 +59,7 @@ def present(name, database, duration="7d", replication=1, default=False, **clien "name": name, "changes": {}, "result": True, - "comment": "retention policy {} is already present".format(name), + "comment": f"retention policy {name} is already present", } if not __salt__["influxdb.retention_policy_exists"]( @@ -67,16 +67,16 @@ def present(name, database, duration="7d", replication=1, default=False, **clien ): if __opts__["test"]: ret["result"] = None - ret["comment"] = " {} is absent and will be created".format(name) + ret["comment"] = f" {name} is absent and will be created" return ret if __salt__["influxdb.create_retention_policy"]( database, name, duration, replication, default, **client_args ): - ret["comment"] = "retention policy {} has been created".format(name) + ret["comment"] = f"retention policy {name} has been created" ret["changes"][name] = "Present" return ret else: - ret["comment"] = "Failed to create retention policy {}".format(name) + ret["comment"] = f"Failed to create retention policy {name}" ret["result"] = False return ret @@ -106,16 +106,16 @@ def present(name, database, duration="7d", replication=1, default=False, **clien if update_policy: if __opts__["test"]: ret["result"] = None - ret["comment"] = " {} is present and set to be changed".format(name) + ret["comment"] = f" {name} is present and set to be changed" return ret else: if __salt__["influxdb.alter_retention_policy"]( database, name, duration, replication, default, **client_args ): - ret["comment"] = "retention policy {} has been changed".format(name) + ret["comment"] = f"retention policy {name} has been changed" return ret else: - ret["comment"] = "Failed to update retention policy {}".format(name) + ret["comment"] = f"Failed to update retention policy {name}" ret["result"] = False return ret @@ -136,22 +136,22 @@ def absent(name, database, **client_args): "name": name, "changes": {}, "result": True, - "comment": "retention policy {} is not present".format(name), + "comment": f"retention policy {name} is not present", } if __salt__["influxdb.retention_policy_exists"](database, name, **client_args): if __opts__["test"]: ret["result"] = None - ret[ - "comment" - ] = "retention policy {} is present and needs to be removed".format(name) + ret["comment"] = ( + f"retention policy {name} is present and needs to be removed" + ) return ret if __salt__["influxdb.drop_retention_policy"](database, name, **client_args): - ret["comment"] = "retention policy {} has been removed".format(name) + ret["comment"] = f"retention policy {name} has been removed" ret["changes"][name] = "Absent" return ret else: - ret["comment"] = "Failed to remove retention policy {}".format(name) + ret["comment"] = f"Failed to remove retention policy {name}" ret["result"] = False return ret diff --git a/salt/states/influxdb_user.py b/salt/states/influxdb_user.py index 52f153ccc53..ea48c6854d4 100644 --- a/salt/states/influxdb_user.py +++ b/salt/states/influxdb_user.py @@ -55,20 +55,20 @@ def present(name, passwd, admin=False, grants=None, **client_args): "name": name, "changes": {}, "result": True, - "comment": "User {} is present and up to date".format(name), + "comment": f"User {name} is present and up to date", } if not __salt__["influxdb.user_exists"](name, **client_args): create = True if __opts__["test"]: - ret["comment"] = "User {} will be created".format(name) + ret["comment"] = f"User {name} will be created" ret["result"] = None return ret else: if not __salt__["influxdb.create_user"]( name, passwd, admin=admin, **client_args ): - ret["comment"] = "Failed to create user {}".format(name) + ret["comment"] = f"Failed to create user {name}" ret["result"] = False return ret else: @@ -104,7 +104,7 @@ def present(name, passwd, admin=False, grants=None, **client_args): del db_privileges[database] if database not in db_privileges: ret["changes"][ - "Grant on database {} to user {}".format(database, name) + f"Grant on database {database} to user {name}" ] = privilege if not __opts__["test"]: __salt__["influxdb.grant_privilege"]( @@ -113,19 +113,19 @@ def present(name, passwd, admin=False, grants=None, **client_args): if ret["changes"]: if create: - ret["comment"] = "Created user {}".format(name) + ret["comment"] = f"Created user {name}" ret["changes"][name] = "User created" else: if __opts__["test"]: ret["result"] = None - ret[ - "comment" - ] = "User {} will be updated with the following changes:".format(name) + ret["comment"] = ( + f"User {name} will be updated with the following changes:" + ) for k, v in ret["changes"].items(): - ret["comment"] += "\n{} => {}".format(k, v) + ret["comment"] += f"\n{k} => {v}" ret["changes"] = {} else: - ret["comment"] = "Updated user {}".format(name) + ret["comment"] = f"Updated user {name}" return ret @@ -141,21 +141,21 @@ def absent(name, **client_args): "name": name, "changes": {}, "result": True, - "comment": "User {} is not present".format(name), + "comment": f"User {name} is not present", } if __salt__["influxdb.user_exists"](name, **client_args): if __opts__["test"]: ret["result"] = None - ret["comment"] = "User {} will be removed".format(name) + ret["comment"] = f"User {name} will be removed" return ret else: if __salt__["influxdb.remove_user"](name, **client_args): - ret["comment"] = "Removed user {}".format(name) + ret["comment"] = f"Removed user {name}" ret["changes"][name] = "removed" return ret else: - ret["comment"] = "Failed to remove user {}".format(name) + ret["comment"] = f"Failed to remove user {name}" ret["result"] = False return ret return ret diff --git a/salt/states/infoblox_a.py b/salt/states/infoblox_a.py index 35f3d716aa5..c2b43599c64 100644 --- a/salt/states/infoblox_a.py +++ b/salt/states/infoblox_a.py @@ -48,10 +48,10 @@ def present(name=None, ipv4addr=None, data=None, ensure_data=True, **api_opts): if obj: # warn user that the data was updated and does not match ret["result"] = False - ret[ - "comment" - ] = "** please update the name: {} to equal the updated data name {}".format( - name, data["name"] + ret["comment"] = ( + "** please update the name: {} to equal the updated data name {}".format( + name, data["name"] + ) ) return ret @@ -59,9 +59,9 @@ def present(name=None, ipv4addr=None, data=None, ensure_data=True, **api_opts): obj = obj[0] if not ensure_data: ret["result"] = True - ret[ - "comment" - ] = "infoblox record already created (supplied fields not ensured to match)" + ret["comment"] = ( + "infoblox record already created (supplied fields not ensured to match)" + ) return ret diff = __salt__["infoblox.diff_objects"](data, obj) diff --git a/salt/states/infoblox_cname.py b/salt/states/infoblox_cname.py index 99c42a6d9f8..f02470261d9 100644 --- a/salt/states/infoblox_cname.py +++ b/salt/states/infoblox_cname.py @@ -57,19 +57,19 @@ def present(name=None, data=None, ensure_data=True, **api_opts): if obj: # warn user that the data was updated and does not match ret["result"] = False - ret[ - "comment" - ] = "** please update the name: {} to equal the updated data name {}".format( - name, data["name"] + ret["comment"] = ( + "** please update the name: {} to equal the updated data name {}".format( + name, data["name"] + ) ) return ret if obj: if not ensure_data: ret["result"] = True - ret[ - "comment" - ] = "infoblox record already created (supplied fields not ensured to match)" + ret["comment"] = ( + "infoblox record already created (supplied fields not ensured to match)" + ) return ret diff = __salt__["infoblox.diff_objects"](data, obj) diff --git a/salt/states/infoblox_host_record.py b/salt/states/infoblox_host_record.py index e5c5ecb9529..3b1cace0ed3 100644 --- a/salt/states/infoblox_host_record.py +++ b/salt/states/infoblox_host_record.py @@ -53,19 +53,19 @@ def present(name=None, data=None, ensure_data=True, **api_opts): if obj: # warn user that the host name was updated and does not match ret["result"] = False - ret[ - "comment" - ] = "please update the name: {} to equal the updated data name {}".format( - name, data["name"] + ret["comment"] = ( + "please update the name: {} to equal the updated data name {}".format( + name, data["name"] + ) ) return ret if obj: if not ensure_data: ret["result"] = True - ret[ - "comment" - ] = "infoblox record already created (supplied fields not ensured to match)" + ret["comment"] = ( + "infoblox record already created (supplied fields not ensured to match)" + ) return ret obj = __salt__["infoblox.get_host_advanced"](name=name, **api_opts) @@ -131,7 +131,7 @@ def present(name=None, data=None, ensure_data=True, **api_opts): if __opts__["test"]: ret["result"] = None - ret["comment"] = "would attempt to create infoblox record {}".format(name) + ret["comment"] = f"would attempt to create infoblox record {name}" return ret new_obj_ref = __salt__["infoblox.create_host"](data=data, **api_opts) diff --git a/salt/states/infoblox_range.py b/salt/states/infoblox_range.py index 6eb0d193ebd..20783323420 100644 --- a/salt/states/infoblox_range.py +++ b/salt/states/infoblox_range.py @@ -132,7 +132,7 @@ def present(name=None, start_addr=None, end_addr=None, data=None, **api_opts): if __opts__["test"]: ret["result"] = None - ret["comment"] = "would attempt to create record {}".format(name) + ret["comment"] = f"would attempt to create record {name}" return ret new_obj_ref = __salt__["infoblox.create_ipv4_range"](data, **api_opts) @@ -199,7 +199,7 @@ def absent(name=None, start_addr=None, end_addr=None, data=None, **api_opts): if __salt__["infoblox.delete_object"](objref=obj["_ref"]): ret["result"] = True ret["changes"] = { - "old": "Found {} - {}".format(start_addr, end_addr), + "old": f"Found {start_addr} - {end_addr}", "new": "Removed", } return ret diff --git a/salt/states/ini_manage.py b/salt/states/ini_manage.py index 9d3989769c7..9851d792734 100644 --- a/salt/states/ini_manage.py +++ b/salt/states/ini_manage.py @@ -9,7 +9,6 @@ Manage ini files """ - from salt.utils.odict import OrderedDict __virtualname__ = "ini" @@ -71,12 +70,12 @@ def options_present(name, sections=None, separator="=", strict=False): for option in options: if option in original_top_level_opts: if str(original_top_level_opts[option]) == str(options[option]): - ret["comment"] += "Unchanged key {}.\n".format(option) + ret["comment"] += f"Unchanged key {option}.\n" else: - ret["comment"] += "Changed key {}.\n".format(option) + ret["comment"] += f"Changed key {option}.\n" ret["result"] = None else: - ret["comment"] += "Changed key {}.\n".format(option) + ret["comment"] += f"Changed key {option}.\n" ret["result"] = None else: options_updated = __salt__["ini.set_option"](name, options, separator) @@ -84,7 +83,7 @@ def options_present(name, sections=None, separator="=", strict=False): if strict: for opt_to_remove in set(original_top_level_opts).difference(options): if __opts__["test"]: - ret["comment"] += "Removed key {}.\n".format(opt_to_remove) + ret["comment"] += f"Removed key {opt_to_remove}.\n" ret["result"] = None else: __salt__["ini.remove_option"]( @@ -151,7 +150,7 @@ def options_present(name, sections=None, separator="=", strict=False): if not __opts__["test"]: changes = __salt__["ini.set_option"](name, sections, separator) except (OSError, KeyError) as err: - ret["comment"] = "{}".format(err) + ret["comment"] = f"{err}" ret["result"] = False return ret if "error" in changes: @@ -199,7 +198,7 @@ def options_absent(name, sections=None, separator="="): try: cur_section = __salt__["ini.get_section"](name, section, separator) except OSError as err: - ret["comment"] = "{}".format(err) + ret["comment"] = f"{err}" ret["result"] = False return ret except AttributeError: @@ -212,14 +211,14 @@ def options_absent(name, sections=None, separator="="): key, section_name ) continue - ret["comment"] += "Deleted key {}{}.\n".format(key, section_name) + ret["comment"] += f"Deleted key {key}{section_name}.\n" ret["result"] = None else: option = section if not __salt__["ini.get_option"](name, None, option, separator): - ret["comment"] += "Key {} does not exist.\n".format(option) + ret["comment"] += f"Key {option} does not exist.\n" continue - ret["comment"] += "Deleted key {}.\n".format(option) + ret["comment"] += f"Deleted key {option}.\n" ret["result"] = None if ret["comment"] == "": @@ -233,7 +232,7 @@ def options_absent(name, sections=None, separator="="): name, section, key, separator ) except OSError as err: - ret["comment"] = "{}".format(err) + ret["comment"] = f"{err}" ret["result"] = False return ret if not current_value: @@ -278,14 +277,14 @@ def sections_present(name, sections=None, separator="="): cur_ini = __salt__["ini.get_ini"](name, separator) except OSError as err: ret["result"] = False - ret["comment"] = "{}".format(err) + ret["comment"] = f"{err}" return ret for section in sections or {}: if section in cur_ini: - ret["comment"] += "Section unchanged {}.\n".format(section) + ret["comment"] += f"Section unchanged {section}.\n" continue else: - ret["comment"] += "Created new section {}.\n".format(section) + ret["comment"] += f"Created new section {section}.\n" ret["result"] = None if ret["comment"] == "": ret["comment"] = "No changes detected." @@ -297,7 +296,7 @@ def sections_present(name, sections=None, separator="="): changes = __salt__["ini.set_option"](name, section_to_update, separator) except OSError as err: ret["result"] = False - ret["comment"] = "{}".format(err) + ret["comment"] = f"{err}" return ret if "error" in changes: ret["result"] = False @@ -335,13 +334,13 @@ def sections_absent(name, sections=None, separator="="): cur_ini = __salt__["ini.get_ini"](name, separator) except OSError as err: ret["result"] = False - ret["comment"] = "{}".format(err) + ret["comment"] = f"{err}" return ret for section in sections or []: if section not in cur_ini: - ret["comment"] += "Section {} does not exist.\n".format(section) + ret["comment"] += f"Section {section} does not exist.\n" continue - ret["comment"] += "Deleted section {}.\n".format(section) + ret["comment"] += f"Deleted section {section}.\n" ret["result"] = None if ret["comment"] == "": ret["comment"] = "No changes detected." @@ -351,7 +350,7 @@ def sections_absent(name, sections=None, separator="="): cur_section = __salt__["ini.remove_section"](name, section, separator) except OSError as err: ret["result"] = False - ret["comment"] = "{}".format(err) + ret["comment"] = f"{err}" return ret if not cur_section: continue diff --git a/salt/states/ipmi.py b/salt/states/ipmi.py index 3f408590b49..51448b66329 100644 --- a/salt/states/ipmi.py +++ b/salt/states/ipmi.py @@ -131,7 +131,7 @@ def power(name="power_on", wait=300, **kwargs): return ret if __opts__["test"]: - ret["comment"] = "would power: {} system".format(name) + ret["comment"] = f"would power: {name} system" ret["result"] = None ret["changes"] = {"old": org, "new": name} return ret @@ -152,7 +152,7 @@ def user_present( link_auth=True, ipmi_msg=True, privilege_level="administrator", - **kwargs + **kwargs, ): """ Ensure IPMI user and user privileges. @@ -259,7 +259,7 @@ def user_present( link_auth, ipmi_msg, privilege_level, - **kwargs + **kwargs, ) current_user = __salt__["ipmi.get_user"](uid=uid, channel=channel, **kwargs) ret["comment"] = "(re)created user" diff --git a/salt/states/ipset.py b/salt/states/ipset.py index f59e01f80c9..8132e0b5f19 100644 --- a/salt/states/ipset.py +++ b/salt/states/ipset.py @@ -87,17 +87,17 @@ def set_present(name, set_type, family="ipv4", **kwargs): set_check = __salt__["ipset.check_set"](name) if set_check is True: ret["result"] = True - ret["comment"] = "ipset set {} already exists for {}".format(name, family) + ret["comment"] = f"ipset set {name} already exists for {family}" return ret if __opts__["test"]: - ret["comment"] = "ipset set {} would be added for {}".format(name, family) + ret["comment"] = f"ipset set {name} would be added for {family}" return ret command = __salt__["ipset.new_set"](name, set_type, family, **kwargs) if command is True: ret["changes"] = {"locale": name} ret["result"] = True - ret["comment"] = "ipset set {} created successfully for {}".format(name, family) + ret["comment"] = f"ipset set {name} created successfully for {family}" return ret else: ret["result"] = False @@ -122,10 +122,10 @@ def set_absent(name, family="ipv4", **kwargs): set_check = __salt__["ipset.check_set"](name, family) if not set_check: ret["result"] = True - ret["comment"] = "ipset set {} for {} is already absent".format(name, family) + ret["comment"] = f"ipset set {name} for {family} is already absent" return ret if __opts__["test"]: - ret["comment"] = "ipset set {} for {} would be removed".format(name, family) + ret["comment"] = f"ipset set {name} for {family} would be removed" return ret flush_set = __salt__["ipset.flush"](name, family) if flush_set: @@ -212,10 +212,10 @@ def present(name, entry=None, family="ipv4", **kwargs): ) else: ret["result"] = False - ret[ - "comment" - ] = "Failed to add to entry {1} to set {0} for family {2}.\n{3}".format( - kwargs["set_name"], _entry, family, command + ret["comment"] = ( + "Failed to add to entry {1} to set {0} for family {2}.\n{3}".format( + kwargs["set_name"], _entry, family, command + ) ) return ret @@ -310,7 +310,7 @@ def flush(name, family="ipv4", **kwargs): set_check = __salt__["ipset.check_set"](name) if set_check is False: ret["result"] = False - ret["comment"] = "ipset set {} does not exist for {}".format(name, family) + ret["comment"] = f"ipset set {name} does not exist for {family}" return ret if __opts__["test"]: @@ -321,7 +321,7 @@ def flush(name, family="ipv4", **kwargs): if __salt__["ipset.flush"](name, family): ret["changes"] = {"locale": name} ret["result"] = True - ret["comment"] = "Flushed ipset entries from set {} for {}".format(name, family) + ret["comment"] = f"Flushed ipset entries from set {name} for {family}" return ret else: ret["result"] = False diff --git a/salt/states/iptables.py b/salt/states/iptables.py index 79edd60b8ff..57c8b287cb0 100644 --- a/salt/states/iptables.py +++ b/salt/states/iptables.py @@ -245,6 +245,7 @@ Example rules for IPSec policy: output of iptables-save. This may have unintended consequences on legacy releases of ``iptables``. """ + import copy from salt.state import STATE_INTERNAL_KEYWORDS as _STATE_INTERNAL_KEYWORDS @@ -324,10 +325,10 @@ def chain_absent(name, table="filter", family="ipv4"): chain_check = __salt__["iptables.check_chain"](table, name, family) if not chain_check: ret["result"] = True - ret[ - "comment" - ] = "iptables {} chain is already absent in {} table for {}".format( - name, table, family + ret["comment"] = ( + "iptables {} chain is already absent in {} table for {}".format( + name, table, family + ) ) return ret if __opts__["test"]: @@ -341,10 +342,10 @@ def chain_absent(name, table="filter", family="ipv4"): if command is True: ret["changes"] = {"locale": name} ret["result"] = True - ret[ - "comment" - ] = "iptables {} chain in {} table delete success for {}".format( - name, table, family + ret["comment"] = ( + "iptables {} chain in {} table delete success for {}".format( + name, table, family + ) ) else: ret["result"] = False @@ -497,10 +498,10 @@ def append(name, table="filter", family="ipv4", **kwargs): return ret else: ret["result"] = False - ret[ - "comment" - ] = "Failed to set iptables rule for {}.\nAttempted rule was {} for {}".format( - name, command.strip(), family + ret["comment"] = ( + "Failed to set iptables rule for {}.\nAttempted rule was {} for {}".format( + name, command.strip(), family + ) ) return ret @@ -633,10 +634,10 @@ def insert(name, table="filter", family="ipv4", **kwargs): return ret else: ret["result"] = False - ret[ - "comment" - ] = "Failed to set iptables rule for {}.\nAttempted rule was {}".format( - name, command.strip() + ret["comment"] = ( + "Failed to set iptables rule for {}.\nAttempted rule was {}".format( + name, command.strip() + ) ) return ret @@ -736,7 +737,7 @@ def delete(name, table="filter", family="ipv4", **kwargs): if not result: ret["changes"] = {"locale": name} ret["result"] = True - ret["comment"] = "Delete iptables rule for {} {}".format(name, command.strip()) + ret["comment"] = f"Delete iptables rule for {name} {command.strip()}" if "save" in kwargs and kwargs["save"]: if kwargs["save"] is not True: filename = kwargs["save"] @@ -749,10 +750,10 @@ def delete(name, table="filter", family="ipv4", **kwargs): return ret else: ret["result"] = False - ret[ - "comment" - ] = "Failed to delete iptables rule for {}.\nAttempted rule was {}".format( - name, command.strip() + ret["comment"] = ( + "Failed to delete iptables rule for {}.\nAttempted rule was {}".format( + name, command.strip() + ) ) return ret @@ -788,10 +789,10 @@ def set_policy(name, table="filter", family="ipv4", **kwargs): == kwargs["policy"] ): ret["result"] = True - ret[ - "comment" - ] = "iptables default policy for chain {} on table {} for {} already set to {}".format( - kwargs["chain"], table, family, kwargs["policy"] + ret["comment"] = ( + "iptables default policy for chain {} on table {} for {} already set to {}".format( + kwargs["chain"], table, family, kwargs["policy"] + ) ) return ret if __opts__["test"]: @@ -814,10 +815,10 @@ def set_policy(name, table="filter", family="ipv4", **kwargs): else: filename = None __salt__["iptables.save"](filename=filename, family=family) - ret[ - "comment" - ] = "Set and saved default policy for {} to {} family {}".format( - kwargs["chain"], kwargs["policy"], family + ret["comment"] = ( + "Set and saved default policy for {} to {} family {}".format( + kwargs["chain"], kwargs["policy"], family + ) ) return ret else: @@ -852,10 +853,10 @@ def flush(name, table="filter", family="ipv4", **kwargs): if "chain" not in kwargs: kwargs["chain"] = "" if __opts__["test"]: - ret[ - "comment" - ] = "iptables rules in {} table {} chain {} family needs to be flushed".format( - name, table, family + ret["comment"] = ( + "iptables rules in {} table {} chain {} family needs to be flushed".format( + name, table, family + ) ) return ret if not __salt__["iptables.flush"](table, kwargs["chain"], family): diff --git a/salt/states/jboss7.py b/salt/states/jboss7.py index 8d3438d9940..9f1dfdb4c30 100644 --- a/salt/states/jboss7.py +++ b/salt/states/jboss7.py @@ -35,7 +35,6 @@ For the sake of brevity, examples for each state assume that jboss_config is con """ - import logging import re import time @@ -579,7 +578,7 @@ def __get_artifact(salt_source): except Exception as e: # pylint: disable=broad-except log.debug(traceback.format_exc()) - comment = "Unable to manage file: {}".format(e) + comment = f"Unable to manage file: {e}" else: resolved_source = salt_source["target_file"] @@ -649,10 +648,10 @@ def reloaded(name, jboss_config, timeout=60, interval=5): ret["changes"]["reloaded"] = "configuration" else: ret["result"] = False - ret[ - "comment" - ] = "Could not reload the configuration. Timeout ({} s) exceeded. ".format( - timeout + ret["comment"] = ( + "Could not reload the configuration. Timeout ({} s) exceeded. ".format( + timeout + ) ) if not status["success"]: ret["comment"] = __append_comment( @@ -675,9 +674,7 @@ def __check_dict_contains(dct, dict_name, keys, comment="", result=True): for key in keys: if key not in dct.keys(): result = False - comment = __append_comment( - "Missing {} in {}".format(key, dict_name), comment - ) + comment = __append_comment(f"Missing {key} in {dict_name}", comment) return result, comment diff --git a/salt/states/jenkins.py b/salt/states/jenkins.py index 3b04caf3b0c..b55b05a3716 100644 --- a/salt/states/jenkins.py +++ b/salt/states/jenkins.py @@ -6,7 +6,6 @@ Management of Jenkins """ - import difflib import io import logging @@ -56,7 +55,7 @@ def present(name, config=None, **kwargs): "name": name, "result": True, "changes": {}, - "comment": ["Job {} is up to date.".format(name)], + "comment": [f"Job {name} is up to date."], } if __salt__["jenkins.job_exists"](name): @@ -79,7 +78,7 @@ def present(name, config=None, **kwargs): return _fail(ret, exc.strerror) else: ret["changes"] = "".join(diff) - ret["comment"].append("Job '{}' updated.".format(name)) + ret["comment"].append(f"Job '{name}' updated.") else: cached_source_path = __salt__["cp.cache_file"](config, __env__) @@ -94,7 +93,7 @@ def present(name, config=None, **kwargs): buf = io.StringIO(new_config_xml) diff = difflib.unified_diff("", buf.readlines(), lineterm="") ret["changes"][name] = "".join(diff) - ret["comment"].append("Job '{}' added.".format(name)) + ret["comment"].append(f"Job '{name}' added.") ret["comment"] = "\n".join(ret["comment"]) return ret @@ -115,7 +114,7 @@ def absent(name, **kwargs): except CommandExecutionError as exc: return _fail(ret, exc.strerror) else: - ret["comment"] = "Job '{}' deleted.".format(name) + ret["comment"] = f"Job '{name}' deleted." else: - ret["comment"] = "Job '{}' already absent.".format(name) + ret["comment"] = f"Job '{name}' already absent." return ret diff --git a/salt/states/kapacitor.py b/salt/states/kapacitor.py index 23f99ff2e8a..94dc7477c49 100644 --- a/salt/states/kapacitor.py +++ b/salt/states/kapacitor.py @@ -15,6 +15,7 @@ Kapacitor state module. .. versionadded:: 2016.11.0 """ + import difflib import salt.utils.files @@ -74,7 +75,7 @@ def task_present( if not dbrps: dbrps = [] if database and retention_policy: - dbrp = "{}.{}".format(database, retention_policy) + dbrp = f"{database}.{retention_policy}" dbrps.append(dbrp) task_dbrps = [ {"db": dbrp[0], "rp": dbrp[1]} for dbrp in (dbrp.split(".") for dbrp in dbrps) diff --git a/salt/states/kernelpkg.py b/salt/states/kernelpkg.py index 0f535e74038..85476c071da 100644 --- a/salt/states/kernelpkg.py +++ b/salt/states/kernelpkg.py @@ -99,9 +99,9 @@ def latest_installed(name, **kwargs): # pylint: disable=unused-argument result = __salt__["kernelpkg.upgrade"]() ret["result"] = True ret["changes"] = result["upgrades"] - ret[ - "comment" - ] = "The latest kernel package has been installed, but not activated." + ret["comment"] = ( + "The latest kernel package has been installed, but not activated." + ) return ret diff --git a/salt/states/keyboard.py b/salt/states/keyboard.py index 0670a431c08..d8c0ede0d61 100644 --- a/salt/states/keyboard.py +++ b/salt/states/keyboard.py @@ -37,15 +37,15 @@ def system(name): ret = {"name": name, "changes": {}, "result": None, "comment": ""} if __salt__["keyboard.get_sys"]() == name: ret["result"] = True - ret["comment"] = "System layout {} already set".format(name) + ret["comment"] = f"System layout {name} already set" return ret if __opts__["test"]: - ret["comment"] = "System layout {} needs to be set".format(name) + ret["comment"] = f"System layout {name} needs to be set" return ret if __salt__["keyboard.set_sys"](name): ret["changes"] = {"layout": name} ret["result"] = True - ret["comment"] = "Set system keyboard layout {}".format(name) + ret["comment"] = f"Set system keyboard layout {name}" return ret else: ret["result"] = False @@ -63,15 +63,15 @@ def xorg(name): ret = {"name": name, "changes": {}, "result": None, "comment": ""} if __salt__["keyboard.get_x"]() == name: ret["result"] = True - ret["comment"] = "XOrg layout {} already set".format(name) + ret["comment"] = f"XOrg layout {name} already set" return ret if __opts__["test"]: - ret["comment"] = "XOrg layout {} needs to be set".format(name) + ret["comment"] = f"XOrg layout {name} needs to be set" return ret if __salt__["keyboard.set_x"](name): ret["changes"] = {"layout": name} ret["result"] = True - ret["comment"] = "Set XOrg keyboard layout {}".format(name) + ret["comment"] = f"Set XOrg keyboard layout {name}" return ret else: ret["result"] = False diff --git a/salt/states/keystone.py b/salt/states/keystone.py index eeab1ce27c4..f3ea1f5ceaa 100644 --- a/salt/states/keystone.py +++ b/salt/states/keystone.py @@ -112,7 +112,7 @@ def user_present( profile=None, password_reset=True, project=None, - **connection_args + **connection_args, ): """ Ensure that the keystone user is present with the specified properties. @@ -162,7 +162,7 @@ def user_present( "name": name, "changes": {}, "result": True, - "comment": 'User "{}" will be updated'.format(name), + "comment": f'User "{name}" will be updated', } _api_version(profile=profile, **connection_args) @@ -177,7 +177,7 @@ def user_present( ) if "Error" in tenantdata: ret["result"] = False - ret["comment"] = 'Tenant / project "{}" does not exist'.format(tenant) + ret["comment"] = f'Tenant / project "{tenant}" does not exist' return ret tenant_id = tenantdata[tenant]["id"] else: @@ -213,52 +213,52 @@ def user_present( change_email or change_enabled or change_tenant or change_password ): ret["result"] = None - ret["comment"] = 'User "{}" will be updated'.format(name) + ret["comment"] = f'User "{name}" will be updated' if change_email is True: ret["changes"]["Email"] = "Will be updated" if change_enabled is True: ret["changes"]["Enabled"] = "Will be True" if change_tenant is True: - ret["changes"]["Tenant"] = 'Will be added to "{}" tenant'.format(tenant) + ret["changes"]["Tenant"] = f'Will be added to "{tenant}" tenant' if change_password is True: ret["changes"]["Password"] = "Will be updated" return ret - ret["comment"] = 'User "{}" is already present'.format(name) + ret["comment"] = f'User "{name}" is already present' if change_email: __salt__["keystone.user_update"]( name=name, email=email, profile=profile, **connection_args ) - ret["comment"] = 'User "{}" has been updated'.format(name) + ret["comment"] = f'User "{name}" has been updated' ret["changes"]["Email"] = "Updated" if change_enabled: __salt__["keystone.user_update"]( name=name, enabled=enabled, profile=profile, **connection_args ) - ret["comment"] = 'User "{}" has been updated'.format(name) - ret["changes"]["Enabled"] = "Now {}".format(enabled) + ret["comment"] = f'User "{name}" has been updated' + ret["changes"]["Enabled"] = f"Now {enabled}" if change_tenant: __salt__["keystone.user_update"]( name=name, tenant=tenant, profile=profile, **connection_args ) - ret["comment"] = 'User "{}" has been updated'.format(name) - ret["changes"]["Tenant"] = 'Added to "{}" tenant'.format(tenant) + ret["comment"] = f'User "{name}" has been updated' + ret["changes"]["Tenant"] = f'Added to "{tenant}" tenant' if change_password: __salt__["keystone.user_password_update"]( name=name, password=password, profile=profile, **connection_args ) - ret["comment"] = 'User "{}" has been updated'.format(name) + ret["comment"] = f'User "{name}" has been updated' ret["changes"]["Password"] = "Updated" if roles: for tenant in roles: args = dict( {"user_name": name, "tenant_name": tenant, "profile": profile}, - **connection_args + **connection_args, ) tenant_roles = __salt__["keystone.user_role_list"](**args) for role in roles[tenant]: @@ -276,7 +276,7 @@ def user_present( "tenant": tenant, "profile": profile, }, - **connection_args + **connection_args, ) newrole = __salt__["keystone.user_role_add"](**addargs) if "roles" in ret["changes"]: @@ -298,7 +298,7 @@ def user_present( "tenant": tenant, "profile": profile, }, - **connection_args + **connection_args, ) oldrole = __salt__["keystone.user_role_remove"](**addargs) if "roles" in ret["changes"]: @@ -309,7 +309,7 @@ def user_present( # Create that user! if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Keystone user "{}" will be added'.format(name) + ret["comment"] = f'Keystone user "{name}" will be added' ret["changes"]["User"] = "Will be created" return ret __salt__["keystone.user_create"]( @@ -319,7 +319,7 @@ def user_present( tenant_id=tenant_id, enabled=enabled, profile=profile, - **connection_args + **connection_args, ) if roles: for tenant in roles: @@ -329,9 +329,9 @@ def user_present( role=role, tenant=tenant, profile=profile, - **connection_args + **connection_args, ) - ret["comment"] = "Keystone user {} has been added".format(name) + ret["comment"] = f"Keystone user {name} has been added" ret["changes"]["User"] = "Created" return ret @@ -348,7 +348,7 @@ def user_absent(name, profile=None, **connection_args): "name": name, "changes": {}, "result": True, - "comment": 'User "{}" is already absent'.format(name), + "comment": f'User "{name}" is already absent', } # Check if user is present @@ -356,11 +356,11 @@ def user_absent(name, profile=None, **connection_args): if "Error" not in user: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'User "{}" will be deleted'.format(name) + ret["comment"] = f'User "{name}" will be deleted' return ret # Delete that user! __salt__["keystone.user_delete"](name=name, profile=profile, **connection_args) - ret["comment"] = 'User "{}" has been deleted'.format(name) + ret["comment"] = f'User "{name}" has been deleted' ret["changes"]["User"] = "Deleted" return ret @@ -385,7 +385,7 @@ def tenant_present( "name": name, "changes": {}, "result": True, - "comment": 'Tenant / project "{}" already exists'.format(name), + "comment": f'Tenant / project "{name}" already exists', } _api_version(profile=profile, **connection_args) @@ -399,7 +399,7 @@ def tenant_present( if tenant[name].get("description", None) != description: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Tenant / project "{}" will be updated'.format(name) + ret["comment"] = f'Tenant / project "{name}" will be updated' ret["changes"]["Description"] = "Will be updated" return ret __salt__["keystone.tenant_update"]( @@ -407,29 +407,29 @@ def tenant_present( description=description, enabled=enabled, profile=profile, - **connection_args + **connection_args, ) - ret["comment"] = 'Tenant / project "{}" has been updated'.format(name) + ret["comment"] = f'Tenant / project "{name}" has been updated' ret["changes"]["Description"] = "Updated" if tenant[name].get("enabled", None) != enabled: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Tenant / project "{}" will be updated'.format(name) - ret["changes"]["Enabled"] = "Will be {}".format(enabled) + ret["comment"] = f'Tenant / project "{name}" will be updated' + ret["changes"]["Enabled"] = f"Will be {enabled}" return ret __salt__["keystone.tenant_update"]( name=name, description=description, enabled=enabled, profile=profile, - **connection_args + **connection_args, ) - ret["comment"] = 'Tenant / project "{}" has been updated'.format(name) - ret["changes"]["Enabled"] = "Now {}".format(enabled) + ret["comment"] = f'Tenant / project "{name}" has been updated' + ret["changes"]["Enabled"] = f"Now {enabled}" else: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Tenant / project "{}" will be added'.format(name) + ret["comment"] = f'Tenant / project "{name}" will be added' ret["changes"]["Tenant"] = "Will be created" return ret # Create tenant @@ -440,7 +440,7 @@ def tenant_present( description=description, enabled=enabled, profile=profile, - **connection_args + **connection_args, ) else: created = __salt__["keystone.tenant_create"]( @@ -448,11 +448,11 @@ def tenant_present( description=description, enabled=enabled, profile=profile, - **connection_args + **connection_args, ) ret["changes"]["Tenant"] = "Created" if created is True else "Failed" ret["result"] = created - ret["comment"] = 'Tenant / project "{}" has been added'.format(name) + ret["comment"] = f'Tenant / project "{name}" has been added' return ret @@ -467,7 +467,7 @@ def tenant_absent(name, profile=None, **connection_args): "name": name, "changes": {}, "result": True, - "comment": 'Tenant / project "{}" is already absent'.format(name), + "comment": f'Tenant / project "{name}" is already absent', } # Check if tenant is present @@ -477,13 +477,13 @@ def tenant_absent(name, profile=None, **connection_args): if "Error" not in tenant: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Tenant / project "{}" will be deleted'.format(name) + ret["comment"] = f'Tenant / project "{name}" will be deleted' return ret # Delete tenant __salt__["keystone.tenant_delete"]( name=name, profile=profile, **connection_args ) - ret["comment"] = 'Tenant / project "{}" has been deleted'.format(name) + ret["comment"] = f'Tenant / project "{name}" has been deleted' ret["changes"]["Tenant/Project"] = "Deleted" return ret @@ -522,7 +522,7 @@ def project_present( description=description, enabled=enabled, profile=profile, - **connection_args + **connection_args, ) @@ -558,7 +558,7 @@ def role_present(name, profile=None, **connection_args): "name": name, "changes": {}, "result": True, - "comment": 'Role "{}" already exists'.format(name), + "comment": f'Role "{name}" already exists', } # Check if role is already present @@ -569,11 +569,11 @@ def role_present(name, profile=None, **connection_args): else: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Role "{}" will be added'.format(name) + ret["comment"] = f'Role "{name}" will be added' return ret # Create role __salt__["keystone.role_create"](name, profile=profile, **connection_args) - ret["comment"] = 'Role "{}" has been added'.format(name) + ret["comment"] = f'Role "{name}" has been added' ret["changes"]["Role"] = "Created" return ret @@ -589,7 +589,7 @@ def role_absent(name, profile=None, **connection_args): "name": name, "changes": {}, "result": True, - "comment": 'Role "{}" is already absent'.format(name), + "comment": f'Role "{name}" is already absent', } # Check if role is present @@ -597,11 +597,11 @@ def role_absent(name, profile=None, **connection_args): if "Error" not in role: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Role "{}" will be deleted'.format(name) + ret["comment"] = f'Role "{name}" will be deleted' return ret # Delete role __salt__["keystone.role_delete"](name=name, profile=profile, **connection_args) - ret["comment"] = 'Role "{}" has been deleted'.format(name) + ret["comment"] = f'Role "{name}" has been deleted' ret["changes"]["Role"] = "Deleted" return ret @@ -626,7 +626,7 @@ def service_present( "name": name, "changes": {}, "result": True, - "comment": 'Service "{}" already exists'.format(name), + "comment": f'Service "{name}" already exists', } # Check if service is already present @@ -639,13 +639,13 @@ def service_present( else: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Service "{}" will be added'.format(name) + ret["comment"] = f'Service "{name}" will be added' return ret # Create service __salt__["keystone.service_create"]( name, service_type, description, profile=profile, **connection_args ) - ret["comment"] = 'Service "{}" has been added'.format(name) + ret["comment"] = f'Service "{name}" has been added' ret["changes"]["Service"] = "Created" return ret @@ -662,7 +662,7 @@ def service_absent(name, profile=None, **connection_args): "name": name, "changes": {}, "result": True, - "comment": 'Service "{}" is already absent'.format(name), + "comment": f'Service "{name}" is already absent', } # Check if service is present @@ -672,13 +672,13 @@ def service_absent(name, profile=None, **connection_args): if "Error" not in role: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Service "{}" will be deleted'.format(name) + ret["comment"] = f'Service "{name}" will be deleted' return ret # Delete service __salt__["keystone.service_delete"]( name=name, profile=profile, **connection_args ) - ret["comment"] = 'Service "{}" has been deleted'.format(name) + ret["comment"] = f'Service "{name}" has been deleted' ret["changes"]["Service"] = "Deleted" return ret @@ -693,7 +693,7 @@ def endpoint_present( profile=None, url=None, interface=None, - **connection_args + **connection_args, ): """ Ensure the specified endpoints exists for service @@ -740,7 +740,7 @@ def endpoint_present( url=url, interface=interface, profile=profile, - **connection_args + **connection_args, ) else: ret["changes"] = __salt__["keystone.endpoint_create"]( @@ -750,7 +750,7 @@ def endpoint_present( adminurl=adminurl, internalurl=internalurl, profile=profile, - **connection_args + **connection_args, ) if endpoint and "Error" not in endpoint and endpoint.get("region") == region: @@ -844,20 +844,20 @@ def endpoint_present( name, region, profile=profile, interface=interface, **connection_args ) _create_endpoint() - ret["comment"] += 'Endpoint for service "{}" has been updated'.format(name) + ret["comment"] += f'Endpoint for service "{name}" has been updated' else: # Add new endpoint if __opts__.get("test"): ret["result"] = None ret["changes"]["Endpoint"] = "Will be created" - ret["comment"] = 'Endpoint for service "{}" will be added'.format(name) + ret["comment"] = f'Endpoint for service "{name}" will be added' return ret _create_endpoint() - ret["comment"] = 'Endpoint for service "{}" has been added'.format(name) + ret["comment"] = f'Endpoint for service "{name}" has been added' if ret["comment"] == "": # => no changes - ret["comment"] = 'Endpoint for service "{}" already exists'.format(name) + ret["comment"] = f'Endpoint for service "{name}" already exists' return ret @@ -881,7 +881,7 @@ def endpoint_absent(name, region=None, profile=None, interface=None, **connectio "result": True, "comment": 'Endpoint for service "{}"{} is already absent'.format( name, - ', interface "{}",'.format(interface) if interface is not None else "", + f', interface "{interface}",' if interface is not None else "", ), } @@ -894,7 +894,7 @@ def endpoint_absent(name, region=None, profile=None, interface=None, **connectio else: if __opts__.get("test"): ret["result"] = None - ret["comment"] = 'Endpoint for service "{}" will be deleted'.format(name) + ret["comment"] = f'Endpoint for service "{name}" will be deleted' return ret # Delete service __salt__["keystone.endpoint_delete"]( @@ -902,7 +902,7 @@ def endpoint_absent(name, region=None, profile=None, interface=None, **connectio ) ret["comment"] = 'Endpoint for service "{}"{} has been deleted'.format( name, - ', interface "{}",'.format(interface) if interface is not None else "", + f', interface "{interface}",' if interface is not None else "", ) ret["changes"]["endpoint"] = "Deleted" return ret diff --git a/salt/states/keystone_domain.py b/salt/states/keystone_domain.py index b8df63b9871..b722238ae73 100644 --- a/salt/states/keystone_domain.py +++ b/salt/states/keystone_domain.py @@ -26,7 +26,6 @@ Example States - name: domain1 """ - __virtualname__ = "keystone_domain" @@ -65,7 +64,7 @@ def present(name, auth=None, **kwargs): if __opts__["test"]: ret["result"] = None ret["changes"] = kwargs - ret["comment"] = "Domain {} will be created.".format(name) + ret["comment"] = f"Domain {name} will be created." return ret kwargs["name"] = name @@ -79,7 +78,7 @@ def present(name, auth=None, **kwargs): if __opts__["test"]: ret["result"] = None ret["changes"] = changes - ret["comment"] = "Domain {} will be updated.".format(name) + ret["comment"] = f"Domain {name} will be updated." return ret kwargs["domain_id"] = domain.id @@ -107,7 +106,7 @@ def absent(name, auth=None): if __opts__["test"] is True: ret["result"] = None ret["changes"] = {"name": name} - ret["comment"] = "Domain {} will be deleted.".format(name) + ret["comment"] = f"Domain {name} will be deleted." return ret __salt__["keystoneng.domain_delete"](name=domain) diff --git a/salt/states/keystone_endpoint.py b/salt/states/keystone_endpoint.py index 279c3be23f6..56b30d20d0a 100644 --- a/salt/states/keystone_endpoint.py +++ b/salt/states/keystone_endpoint.py @@ -36,7 +36,6 @@ Example States - service_name: glance """ - __virtualname__ = "keystone_endpoint" diff --git a/salt/states/keystone_group.py b/salt/states/keystone_group.py index ac6077a3f9a..678b5ebce83 100644 --- a/salt/states/keystone_group.py +++ b/salt/states/keystone_group.py @@ -26,7 +26,6 @@ Example States - description: 'my group' """ - __virtualname__ = "keystone_group" diff --git a/salt/states/keystone_project.py b/salt/states/keystone_project.py index b6db7cc2033..49d0b80f61f 100644 --- a/salt/states/keystone_project.py +++ b/salt/states/keystone_project.py @@ -27,7 +27,6 @@ Example States - description: 'my project' """ - __virtualname__ = "keystone_project" diff --git a/salt/states/keystone_role.py b/salt/states/keystone_role.py index 1cb938a4a51..3ca384bdbf4 100644 --- a/salt/states/keystone_role.py +++ b/salt/states/keystone_role.py @@ -25,7 +25,6 @@ Example States - description: 'my group' """ - __virtualname__ = "keystone_role" diff --git a/salt/states/keystone_role_grant.py b/salt/states/keystone_role_grant.py index edc17a1148c..d908cf93af5 100644 --- a/salt/states/keystone_role_grant.py +++ b/salt/states/keystone_role_grant.py @@ -26,7 +26,6 @@ Example States - description: 'my group' """ - __virtualname__ = "keystone_role_grant" diff --git a/salt/states/keystone_service.py b/salt/states/keystone_service.py index 988eae706e6..4a62e711465 100644 --- a/salt/states/keystone_service.py +++ b/salt/states/keystone_service.py @@ -28,7 +28,6 @@ Example States - description: 'OpenStack Image' """ - __virtualname__ = "keystone_service" diff --git a/salt/states/keystone_user.py b/salt/states/keystone_user.py index 8f9ec9f8c8d..527d71916ad 100644 --- a/salt/states/keystone_user.py +++ b/salt/states/keystone_user.py @@ -29,7 +29,6 @@ Example States - description: 'my user' """ - __virtualname__ = "keystone_user" diff --git a/salt/states/keystore.py b/salt/states/keystore.py index 5990c9d1e0c..9e6abb72769 100644 --- a/salt/states/keystore.py +++ b/salt/states/keystore.py @@ -2,7 +2,6 @@ State management of a java keystore """ - import logging import os @@ -147,12 +146,12 @@ def managed(name, passphrase, entries, force_remove=False): log.debug("Will remove: %s", remove_list) for alias_name in remove_list: if __opts__["test"]: - ret["comment"] += "Alias {} would have been removed".format(alias_name) + ret["comment"] += f"Alias {alias_name} would have been removed" ret["result"] = None else: __salt__["keystore.remove"](alias_name, name, passphrase) ret["changes"][alias_name] = "Removed" - ret["comment"] += "Alias {} removed.\n".format(alias_name) + ret["comment"] += f"Alias {alias_name} removed.\n" if not ret["changes"] and not ret["comment"]: ret["comment"] = "No changes made.\n" diff --git a/salt/states/kmod.py b/salt/states/kmod.py index 0bb257412f3..92b8cb8e7b7 100644 --- a/salt/states/kmod.py +++ b/salt/states/kmod.py @@ -84,7 +84,7 @@ def present(name, persist=False, mods=None): # Intersection of loaded and proposed modules already_loaded = list(set(loaded_mods) & set(mods)) if len(already_loaded) == 1: - comment = "Kernel module {} is already present".format(already_loaded[0]) + comment = f"Kernel module {already_loaded[0]} is already present" _append_comment(ret, comment) elif len(already_loaded) > 1: comment = "Kernel modules {} are already present".format( @@ -103,7 +103,7 @@ def present(name, persist=False, mods=None): if ret["comment"]: ret["comment"] += "\n" if len(not_loaded) == 1: - comment = "Kernel module {} is set to be loaded".format(not_loaded[0]) + comment = f"Kernel module {not_loaded[0]} is set to be loaded" else: comment = "Kernel modules {} are set to be loaded".format( ", ".join(not_loaded) @@ -115,7 +115,7 @@ def present(name, persist=False, mods=None): unavailable = list(set(not_loaded) - set(__salt__["kmod.available"]())) if unavailable: if len(unavailable) == 1: - comment = "Kernel module {} is unavailable".format(unavailable[0]) + comment = f"Kernel module {unavailable[0]} is unavailable" else: comment = "Kernel modules {} are unavailable".format(", ".join(unavailable)) _append_comment(ret, comment) @@ -161,7 +161,7 @@ def present(name, persist=False, mods=None): if loaded["failed"]: for mod, msg in loaded["failed"]: - _append_comment(ret, "Failed to load kernel module {}: {}".format(mod, msg)) + _append_comment(ret, f"Failed to load kernel module {mod}: {msg}") return ret @@ -205,7 +205,7 @@ def absent(name, persist=False, comment=True, mods=None): ret["result"] = None if len(to_unload) == 1: _append_comment( - ret, "Kernel module {} is set to be removed".format(to_unload[0]) + ret, f"Kernel module {to_unload[0]} is set to be removed" ) elif len(to_unload) > 1: _append_comment( @@ -252,15 +252,13 @@ def absent(name, persist=False, comment=True, mods=None): if unloaded["failed"]: for mod, msg in unloaded["failed"]: - _append_comment( - ret, "Failed to remove kernel module {}: {}".format(mod, msg) - ) + _append_comment(ret, f"Failed to remove kernel module {mod}: {msg}") return ret else: if len(mods) == 1: - ret["comment"] = "Kernel module {} is already removed".format(mods[0]) + ret["comment"] = f"Kernel module {mods[0]} is already removed" else: ret["comment"] = "Kernel modules {} are already removed".format( ", ".join(mods) diff --git a/salt/states/layman.py b/salt/states/layman.py index 00d65c458be..6a7a552f12a 100644 --- a/salt/states/layman.py +++ b/salt/states/layman.py @@ -31,15 +31,15 @@ def present(name): # Overlay already present if name in __salt__["layman.list_local"](): - ret["comment"] = "Overlay {} already present".format(name) + ret["comment"] = f"Overlay {name} already present" elif __opts__["test"]: - ret["comment"] = "Overlay {} is set to be added".format(name) + ret["comment"] = f"Overlay {name} is set to be added" ret["result"] = None return ret else: # Does the overlay exist? if name not in __salt__["layman.list_all"](): - ret["comment"] = "Overlay {} not found".format(name) + ret["comment"] = f"Overlay {name} not found" ret["result"] = False else: # Attempt to add the overlay @@ -47,12 +47,12 @@ def present(name): # The overlay failed to add if len(changes) < 1: - ret["comment"] = "Overlay {} failed to add".format(name) + ret["comment"] = f"Overlay {name} failed to add" ret["result"] = False # Success else: ret["changes"]["added"] = changes - ret["comment"] = "Overlay {} added.".format(name) + ret["comment"] = f"Overlay {name} added." return ret @@ -68,9 +68,9 @@ def absent(name): # Overlay is already absent if name not in __salt__["layman.list_local"](): - ret["comment"] = "Overlay {} already absent".format(name) + ret["comment"] = f"Overlay {name} already absent" elif __opts__["test"]: - ret["comment"] = "Overlay {} is set to be deleted".format(name) + ret["comment"] = f"Overlay {name} is set to be deleted" ret["result"] = None return ret else: @@ -79,11 +79,11 @@ def absent(name): # The overlay failed to delete if len(changes) < 1: - ret["comment"] = "Overlay {} failed to delete".format(name) + ret["comment"] = f"Overlay {name} failed to delete" ret["result"] = False # Success else: ret["changes"]["deleted"] = changes - ret["comment"] = "Overlay {} deleted.".format(name) + ret["comment"] = f"Overlay {name} deleted." return ret diff --git a/salt/states/libcloud_dns.py b/salt/states/libcloud_dns.py index a78a5d17dde..d9d6c41ff08 100644 --- a/salt/states/libcloud_dns.py +++ b/salt/states/libcloud_dns.py @@ -185,6 +185,6 @@ def record_absent(name, zone, type, data, profile): matching_zone["id"], record["id"], profile ) ) - return state_result(all(result), "Removed {} records".format(len(result)), name) + return state_result(all(result), f"Removed {len(result)} records", name) else: return state_result(True, "Records already absent", name) diff --git a/salt/states/libcloud_loadbalancer.py b/salt/states/libcloud_loadbalancer.py index c49ea093c1f..b10bb0b854c 100644 --- a/salt/states/libcloud_loadbalancer.py +++ b/salt/states/libcloud_loadbalancer.py @@ -45,7 +45,6 @@ Using States to deploy a load balancer with extended arguments to specify region :depends: apache-libcloud """ - import logging log = logging.getLogger(__name__) diff --git a/salt/states/libcloud_storage.py b/salt/states/libcloud_storage.py index a2a70f44389..641155f4cea 100644 --- a/salt/states/libcloud_storage.py +++ b/salt/states/libcloud_storage.py @@ -63,7 +63,6 @@ This example will download the file from the remote cloud and keep it locally :depends: apache-libcloud """ - import logging log = logging.getLogger(__name__) diff --git a/salt/states/linux_acl.py b/salt/states/linux_acl.py index 016af32a3e6..61429b592cf 100644 --- a/salt/states/linux_acl.py +++ b/salt/states/linux_acl.py @@ -81,7 +81,6 @@ Ensure a Linux ACL list does not exist """ - import logging import os diff --git a/salt/states/locale.py b/salt/states/locale.py index 23a8c8684f7..2fd35a4a29f 100644 --- a/salt/states/locale.py +++ b/salt/states/locale.py @@ -17,7 +17,6 @@ Manage the available locales and the system default: - locale: us_locale """ - from salt.exceptions import CommandExecutionError @@ -41,23 +40,23 @@ def system(name): try: if __salt__["locale.get_locale"]() == name: ret["result"] = True - ret["comment"] = "System locale {} already set".format(name) + ret["comment"] = f"System locale {name} already set" return ret if __opts__["test"]: - ret["comment"] = "System locale {} needs to be set".format(name) + ret["comment"] = f"System locale {name} needs to be set" return ret if __salt__["locale.set_locale"](name): ret["changes"] = {"locale": name} ret["result"] = True - ret["comment"] = "Set system locale {}".format(name) + ret["comment"] = f"Set system locale {name}" return ret else: ret["result"] = False - ret["comment"] = "Failed to set system locale to {}".format(name) + ret["comment"] = f"Failed to set system locale to {name}" return ret except CommandExecutionError as err: ret["result"] = False - ret["comment"] = "Failed to set system locale: {}".format(err) + ret["comment"] = f"Failed to set system locale: {err}" return ret @@ -74,17 +73,17 @@ def present(name): ret = {"name": name, "changes": {}, "result": None, "comment": ""} if __salt__["locale.avail"](name): ret["result"] = True - ret["comment"] = "Locale {} is already present".format(name) + ret["comment"] = f"Locale {name} is already present" return ret if __opts__["test"]: - ret["comment"] = "Locale {} needs to be generated".format(name) + ret["comment"] = f"Locale {name} needs to be generated" return ret if __salt__["locale.gen_locale"](name): ret["changes"] = {"locale": name} ret["result"] = True - ret["comment"] = "Generated locale {}".format(name) + ret["comment"] = f"Generated locale {name}" return ret else: ret["result"] = False - ret["comment"] = "Failed to generate locale {}".format(name) + ret["comment"] = f"Failed to generate locale {name}" return ret diff --git a/salt/states/logrotate.py b/salt/states/logrotate.py index fcac9f20ff3..d65d2ce28ac 100644 --- a/salt/states/logrotate.py +++ b/salt/states/logrotate.py @@ -5,7 +5,6 @@ Module for managing logrotate. """ - _DEFAULT_CONF = "/etc/logrotate.conf" # Define the module's virtual name @@ -85,10 +84,10 @@ def set_(name, key, value, setting=None, conf_file=_DEFAULT_CONF): value = _convert_if_int(value) if current_value == value: - ret["comment"] = "Command '{}' already has value: {}".format(key, value) + ret["comment"] = f"Command '{key}' already has value: {value}" ret["result"] = True elif __opts__["test"]: - ret["comment"] = "Command '{}' will be set to value: {}".format(key, value) + ret["comment"] = f"Command '{key}' will be set to value: {value}" ret["changes"] = {"old": current_value, "new": value} else: ret["changes"] = {"old": current_value, "new": value} @@ -96,7 +95,7 @@ def set_(name, key, value, setting=None, conf_file=_DEFAULT_CONF): key=key, value=value, conf_file=conf_file ) if ret["result"]: - ret["comment"] = "Set command '{}' value: {}".format(key, value) + ret["comment"] = f"Set command '{key}' value: {value}" else: ret["comment"] = "Unable to set command '{}' value: {}".format( key, value diff --git a/salt/states/loop.py b/salt/states/loop.py index 6b787393858..a2434daeff2 100644 --- a/salt/states/loop.py +++ b/salt/states/loop.py @@ -57,7 +57,6 @@ The function :py:func:`data.subdict_match ` check instances: "{{ instance }}" """ - import logging import operator import sys @@ -96,7 +95,7 @@ def until(name, m_args=None, m_kwargs=None, condition=None, period=1, timeout=60 m_kwargs = {} if name not in __salt__: - ret["comment"] = "Cannot find module {}".format(name) + ret["comment"] = f"Cannot find module {name}" elif condition is None: ret["comment"] = "An exit condition must be specified" elif not isinstance(period, (int, float)): @@ -104,7 +103,7 @@ def until(name, m_args=None, m_kwargs=None, condition=None, period=1, timeout=60 elif not isinstance(timeout, (int, float)): ret["comment"] = "Timeout must be specified as a float in seconds" elif __opts__["test"]: - ret["comment"] = "The execution module {} will be run".format(name) + ret["comment"] = f"The execution module {name} will be run" ret["result"] = None else: if m_args is None: @@ -117,7 +116,7 @@ def until(name, m_args=None, m_kwargs=None, condition=None, period=1, timeout=60 m_ret = __salt__[name](*m_args, **m_kwargs) if eval(condition): # pylint: disable=W0123 ret["result"] = True - ret["comment"] = "Condition {} was met".format(condition) + ret["comment"] = f"Condition {condition} was met" break time.sleep(period) else: @@ -162,7 +161,7 @@ def until_no_eval( """ ret = {"name": name, "comment": "", "changes": {}, "result": False} if name not in __salt__: - ret["comment"] = 'Module.function "{}" is unavailable.'.format(name) + ret["comment"] = f'Module.function "{name}" is unavailable.' elif not isinstance(period, (int, float)): ret["comment"] = "Period must be specified as a float in seconds" elif not isinstance(timeout, (int, float)): @@ -172,7 +171,7 @@ def until_no_eval( elif compare_operator in __utils__: comparator = __utils__[compare_operator] elif not hasattr(operator, compare_operator): - ret["comment"] = 'Invalid operator "{}" supplied.'.format(compare_operator) + ret["comment"] = f'Invalid operator "{compare_operator}" supplied.' else: comparator = getattr(operator, compare_operator) if __opts__["test"]: @@ -222,10 +221,10 @@ def until_no_eval( 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/lvm.py b/salt/states/lvm.py index 82c9fa6015b..5b4bdad8696 100644 --- a/salt/states/lvm.py +++ b/salt/states/lvm.py @@ -342,18 +342,18 @@ def lv_present( else: # ignore percentage "extents" if the logical volume already exists if "%" in str(extents): - ret[ - "comment" - ] = "Logical Volume {} already present, {} won't be resized.".format( - name, extents + ret["comment"] = ( + "Logical Volume {} already present, {} won't be resized.".format( + name, extents + ) ) extents = old_extents size_mb = old_size_mb if force is False and (size_mb < old_size_mb or extents < old_extents): - ret[ - "comment" - ] = "To reduce a Logical Volume option 'force' must be True." + ret["comment"] = ( + "To reduce a Logical Volume option 'force' must be True." + ) ret["result"] = False return ret @@ -378,9 +378,9 @@ def lv_present( ) if not changes: - ret[ - "comment" - ] = "Failed to resize Logical Volume. Unknown Error." + ret["comment"] = ( + "Failed to resize Logical Volume. Unknown Error." + ) ret["result"] = False lv_info = __salt__["lvm.lvdisplay"](lvpath, quiet=True)[lvpath] @@ -389,10 +389,10 @@ def lv_present( ret["comment"] = f"Resized Logical Volume {name}" ret["changes"]["resized"] = changes else: - ret[ - "comment" - ] = "Failed to resize Logical Volume {}.\nError: {}".format( - name, changes["Output from lvresize"] + ret["comment"] = ( + "Failed to resize Logical Volume {}.\nError: {}".format( + name, changes["Output from lvresize"] + ) ) ret["result"] = False return ret diff --git a/salt/states/lvs_server.py b/salt/states/lvs_server.py index 1c0eb81fb69..4d86848b9de 100644 --- a/salt/states/lvs_server.py +++ b/salt/states/lvs_server.py @@ -91,27 +91,27 @@ def present( weight=weight, ) if server_edit is True: - ret[ - "comment" - ] = "LVS Server {} in service {}({}) has been updated".format( - name, service_address, protocol + ret["comment"] = ( + "LVS Server {} in service {}({}) has been updated".format( + name, service_address, protocol + ) ) ret["changes"][name] = "Update" return ret else: ret["result"] = False - ret[ - "comment" - ] = "LVS Server {} in service {}({}) update failed({})".format( - name, service_address, protocol, server_edit + ret["comment"] = ( + "LVS Server {} in service {}({}) update failed({})".format( + name, service_address, protocol, server_edit + ) ) return ret else: if __opts__["test"]: - ret[ - "comment" - ] = "LVS Server {} in service {}({}) is not present and needs to be created".format( - name, service_address, protocol + ret["comment"] = ( + "LVS Server {} in service {}({}) is not present and needs to be created".format( + name, service_address, protocol + ) ) ret["result"] = None return ret @@ -124,18 +124,18 @@ def present( weight=weight, ) if server_add is True: - ret[ - "comment" - ] = "LVS Server {} in service {}({}) has been created".format( - name, service_address, protocol + ret["comment"] = ( + "LVS Server {} in service {}({}) has been created".format( + name, service_address, protocol + ) ) ret["changes"][name] = "Present" return ret else: - ret[ - "comment" - ] = "LVS Service {} in service {}({}) create failed({})".format( - name, service_address, protocol, server_add + ret["comment"] = ( + "LVS Service {} in service {}({}) create failed({})".format( + name, service_address, protocol, server_add + ) ) ret["result"] = False return ret @@ -168,10 +168,10 @@ def absent(name, protocol=None, service_address=None, server_address=None): if server_check is True: if __opts__["test"]: ret["result"] = None - ret[ - "comment" - ] = "LVS Server {} in service {}({}) is present and needs to be removed".format( - name, service_address, protocol + ret["comment"] = ( + "LVS Server {} in service {}({}) is present and needs to be removed".format( + name, service_address, protocol + ) ) return ret server_delete = __salt__["lvs.delete_server"]( @@ -186,18 +186,18 @@ def absent(name, protocol=None, service_address=None, server_address=None): ret["changes"][name] = "Absent" return ret else: - ret[ - "comment" - ] = "LVS Server {} in service {}({}) removed failed({})".format( - name, service_address, protocol, server_delete + ret["comment"] = ( + "LVS Server {} in service {}({}) removed failed({})".format( + name, service_address, protocol, server_delete + ) ) ret["result"] = False return ret else: - ret[ - "comment" - ] = "LVS Server {} in service {}({}) is not present, so it cannot be removed".format( - name, service_address, protocol + ret["comment"] = ( + "LVS Server {} in service {}({}) is not present, so it cannot be removed".format( + name, service_address, protocol + ) ) return ret diff --git a/salt/states/lvs_service.py b/salt/states/lvs_service.py index 4e12c321773..5a1981d4426 100644 --- a/salt/states/lvs_service.py +++ b/salt/states/lvs_service.py @@ -53,15 +53,15 @@ def present( protocol=protocol, service_address=service_address, scheduler=scheduler ) if service_rule_check is True: - ret["comment"] = "LVS Service {} is present".format(name) + ret["comment"] = f"LVS Service {name} is present" return ret else: if __opts__["test"]: ret["result"] = None - ret[ - "comment" - ] = "LVS Service {} is present but some options should update".format( - name + ret["comment"] = ( + "LVS Service {} is present but some options should update".format( + name + ) ) return ret else: @@ -71,18 +71,18 @@ def present( scheduler=scheduler, ) if service_edit is True: - ret["comment"] = "LVS Service {} has been updated".format(name) + ret["comment"] = f"LVS Service {name} has been updated" ret["changes"][name] = "Update" return ret else: ret["result"] = False - ret["comment"] = "LVS Service {} update failed".format(name) + ret["comment"] = f"LVS Service {name} update failed" return ret else: if __opts__["test"]: - ret[ - "comment" - ] = "LVS Service {} is not present and needs to be created".format(name) + ret["comment"] = ( + f"LVS Service {name} is not present and needs to be created" + ) ret["result"] = None return ret else: @@ -90,7 +90,7 @@ def present( protocol=protocol, service_address=service_address, scheduler=scheduler ) if service_add is True: - ret["comment"] = "LVS Service {} has been created".format(name) + ret["comment"] = f"LVS Service {name} has been created" ret["changes"][name] = "Present" return ret else: @@ -131,7 +131,7 @@ def absent(name, protocol=None, service_address=None): protocol=protocol, service_address=service_address ) if service_delete is True: - ret["comment"] = "LVS Service {} has been removed".format(name) + ret["comment"] = f"LVS Service {name} has been removed" ret["changes"][name] = "Absent" return ret else: @@ -141,8 +141,6 @@ def absent(name, protocol=None, service_address=None): ret["result"] = False return ret else: - ret[ - "comment" - ] = "LVS Service {} is not present, so it cannot be removed".format(name) + ret["comment"] = f"LVS Service {name} is not present, so it cannot be removed" return ret diff --git a/salt/states/lxc.py b/salt/states/lxc.py index 51dae0b92c6..05b7081d122 100644 --- a/salt/states/lxc.py +++ b/salt/states/lxc.py @@ -3,7 +3,6 @@ Manage Linux Containers ======================= """ - from salt.exceptions import CommandExecutionError, SaltInvocationError __docformat__ = "restructuredtext en" @@ -151,7 +150,7 @@ def present( ret = { "name": name, "result": True, - "comment": "Container '{}' already exists".format(name), + "comment": f"Container '{name}' already exists", "changes": {}, } @@ -179,17 +178,17 @@ def present( # Sanity check(s) if clone_from and not __salt__["lxc.exists"](clone_from, path=path): ret["result"] = False - ret["comment"] = "Clone source '{}' does not exist".format(clone_from) + ret["comment"] = f"Clone source '{clone_from}' does not exist" if not ret["result"]: return ret - action = "cloned from {}".format(clone_from) if clone_from else "created" + action = f"cloned from {clone_from}" if clone_from else "created" state = {"old": __salt__["lxc.state"](name, path=path)} if __opts__["test"]: if state["old"] is None: ret["comment"] = "Container '{}' will be {}".format( - name, "cloned from {}".format(clone_from) if clone_from else "created" + name, f"cloned from {clone_from}" if clone_from else "created" ) ret["result"] = None return ret @@ -210,7 +209,7 @@ def present( return ret else: if state["old"] in ("frozen", "running"): - ret["comment"] = "Container '{}' would be stopped".format(name) + ret["comment"] = f"Container '{name}' would be stopped" ret["result"] = None return ret else: @@ -257,7 +256,7 @@ def present( clone_from, name ) else: - ret["comment"] = "Created container '{}'".format(name) + ret["comment"] = f"Created container '{name}'" state["new"] = result["state"]["new"] if ret["result"] is True: @@ -279,7 +278,7 @@ def present( ret["comment"] += error except (SaltInvocationError, CommandExecutionError) as exc: ret["result"] = False - ret["comment"] += "{}: {}".format(error, exc) + ret["comment"] += f"{error}: {exc}" else: if state["old"] is None: ret["comment"] += ", and the container was started" @@ -302,12 +301,12 @@ def present( ret["comment"] += error except (SaltInvocationError, CommandExecutionError) as exc: ret["result"] = False - ret["comment"] += "{}: {}".format(error, exc) + ret["comment"] += f"{error}: {exc}" else: if state["old"] is None: ret["comment"] += ", and the container was stopped" else: - ret["comment"] = "Container '{}' was stopped".format(name) + ret["comment"] = f"Container '{name}' was stopped" if "new" not in state: # Make sure we know the final state of the container before we return @@ -346,7 +345,7 @@ def absent(name, stop=False, path=None): "name": name, "changes": {}, "result": True, - "comment": "Container '{}' does not exist".format(name), + "comment": f"Container '{name}' does not exist", } if not __salt__["lxc.exists"](name, path=path): @@ -354,17 +353,17 @@ def absent(name, stop=False, path=None): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Container '{}' would be destroyed".format(name) + ret["comment"] = f"Container '{name}' would be destroyed" return ret try: result = __salt__["lxc.destroy"](name, stop=stop, path=path) except (SaltInvocationError, CommandExecutionError) as exc: ret["result"] = False - ret["comment"] = "Failed to destroy container: {}".format(exc) + ret["comment"] = f"Failed to destroy container: {exc}" else: ret["changes"]["state"] = result["state"] - ret["comment"] = "Container '{}' was destroyed".format(name) + ret["comment"] = f"Container '{name}' was destroyed" return ret @@ -408,14 +407,14 @@ def running(name, restart=False, path=None): ret = { "name": name, "result": True, - "comment": "Container '{}' is already running".format(name), + "comment": f"Container '{name}' is already running", "changes": {}, } state = {"old": __salt__["lxc.state"](name, path=path)} if state["old"] is None: ret["result"] = False - ret["comment"] = "Container '{}' does not exist".format(name) + ret["comment"] = f"Container '{name}' does not exist" return ret elif state["old"] == "running" and not restart: return ret @@ -436,7 +435,7 @@ def running(name, restart=False, path=None): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Container '{}' would be {}".format(name, action[1]) + ret["comment"] = f"Container '{name}' would be {action[1]}" return ret try: @@ -455,7 +454,7 @@ def running(name, restart=False, path=None): state["new"] = result["state"]["new"] if state["new"] != "running": ret["result"] = False - ret["comment"] = "Unable to {} container '{}'".format(action[0], name) + ret["comment"] = f"Unable to {action[0]} container '{name}'" else: ret["comment"] = "Container '{}' was successfully {}".format( name, action[1] @@ -508,17 +507,17 @@ def frozen(name, start=True, path=None): ret = { "name": name, "result": True, - "comment": "Container '{}' is already frozen".format(name), + "comment": f"Container '{name}' is already frozen", "changes": {}, } state = {"old": __salt__["lxc.state"](name, path=path)} if state["old"] is None: ret["result"] = False - ret["comment"] = "Container '{}' does not exist".format(name) + ret["comment"] = f"Container '{name}' does not exist" elif state["old"] == "stopped" and not start: ret["result"] = False - ret["comment"] = "Container '{}' is stopped".format(name) + ret["comment"] = f"Container '{name}' is stopped" if ret["result"] is False or state["old"] == "frozen": return ret @@ -530,7 +529,7 @@ def frozen(name, start=True, path=None): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Container '{}' would be {}".format(name, action[1]) + ret["comment"] = f"Container '{name}' would be {action[1]}" return ret try: @@ -543,7 +542,7 @@ def frozen(name, start=True, path=None): state["new"] = result["state"]["new"] if state["new"] != "frozen": ret["result"] = False - ret["comment"] = "Unable to {} container '{}'".format(action[0], name) + ret["comment"] = f"Unable to {action[0]} container '{name}'" else: ret["comment"] = "Container '{}' was successfully {}".format( name, action[1] @@ -595,14 +594,14 @@ def stopped(name, kill=False, path=None): ret = { "name": name, "result": True, - "comment": "Container '{}' is already stopped".format(name), + "comment": f"Container '{name}' is already stopped", "changes": {}, } state = {"old": __salt__["lxc.state"](name, path=path)} if state["old"] is None: ret["result"] = False - ret["comment"] = "Container '{}' does not exist".format(name) + ret["comment"] = f"Container '{name}' does not exist" return ret elif state["old"] == "stopped": return ret @@ -614,7 +613,7 @@ def stopped(name, kill=False, path=None): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Container '{}' would be {}".format(name, action[1]) + ret["comment"] = f"Container '{name}' would be {action[1]}" return ret try: @@ -627,7 +626,7 @@ def stopped(name, kill=False, path=None): state["new"] = result["state"]["new"] if state["new"] != "stopped": ret["result"] = False - ret["comment"] = "Unable to {} container '{}'".format(action[0], name) + ret["comment"] = f"Unable to {action[0]} container '{name}'" else: ret["comment"] = "Container '{}' was successfully {}".format( name, action[1] @@ -708,7 +707,7 @@ def edited_conf(name, lxc_conf=None, lxc_conf_unset=None): if __opts__["test"]: return { "name": name, - "comment": "{} lxc.conf will be edited".format(name), + "comment": f"{name} lxc.conf will be edited", "result": True, "changes": {}, } diff --git a/salt/states/lxd.py b/salt/states/lxd.py index e5ddbf382af..35b87ea8371 100644 --- a/salt/states/lxd.py +++ b/salt/states/lxd.py @@ -27,7 +27,6 @@ Manage LXD profiles. :platform: Linux """ - import os.path from salt.exceptions import CommandExecutionError, SaltInvocationError @@ -173,7 +172,7 @@ def config_managed(name, value, force_password=False): ) elif str(value) == current_value: - return _success(ret, '"{}" is already set to "{}"'.format(name, value)) + return _success(ret, f'"{name}" is already set to "{value}"') if __opts__["test"]: if name == _password_config_key: @@ -181,7 +180,7 @@ def config_managed(name, value, force_password=False): ret["changes"] = {"password": msg} return _unchanged(ret, msg) else: - msg = 'Would set the "{}" to "{}"'.format(name, value) + msg = f'Would set the "{name}" to "{value}"' ret["changes"] = {name: msg} return _unchanged(ret, msg) @@ -191,9 +190,7 @@ def config_managed(name, value, force_password=False): if name == _password_config_key: ret["changes"] = {name: "Changed the password"} else: - ret["changes"] = { - name: 'Changed from "{}" to {}"'.format(current_value, value) - } + ret["changes"] = {name: f'Changed from "{current_value}" to {value}"'} except CommandExecutionError as e: return _error(ret, str(e)) @@ -266,9 +263,9 @@ def authenticate(name, remote_addr, password, cert, key, verify_cert=True): return _error(ret, str(e)) if result is not True: - return _error(ret, "Failed to authenticate with peer: {}".format(remote_addr)) + return _error(ret, f"Failed to authenticate with peer: {remote_addr}") - msg = "Successfully authenticated with peer: {}".format(remote_addr) + msg = f"Successfully authenticated with peer: {remote_addr}" ret["changes"] = msg return _success(ret, msg) diff --git a/salt/states/lxd_container.py b/salt/states/lxd_container.py index 014c0265522..a1f894c6ac5 100644 --- a/salt/states/lxd_container.py +++ b/salt/states/lxd_container.py @@ -27,7 +27,6 @@ Manage LXD containers. :platform: Linux """ - from salt.exceptions import CommandExecutionError, SaltInvocationError __docformat__ = "restructuredtext en" @@ -219,7 +218,7 @@ def present( if container is None: if __opts__["test"]: # Test is on, just return that we would create the container - msg = 'Would create the container "{}"'.format(name) + msg = f'Would create the container "{name}"' ret["changes"] = {"created": msg} if running is True: msg = msg + " and start it." @@ -249,7 +248,7 @@ def present( except CommandExecutionError as e: return _error(ret, str(e)) - msg = 'Created the container "{}"'.format(name) + msg = f'Created the container "{name}"' ret["changes"] = {"created": msg} if running is True: @@ -261,7 +260,7 @@ def present( return _error(ret, str(e)) msg = msg + " and started it." - ret["changes"] = {"started": 'Started the container "{}"'.format(name)} + ret["changes"] = {"started": f'Started the container "{name}"'} return _success(ret, msg) @@ -275,18 +274,18 @@ def present( # Removed profiles for k in old_profiles.difference(new_profiles): if not __opts__["test"]: - profile_changes.append('Removed profile "{}"'.format(k)) + profile_changes.append(f'Removed profile "{k}"') old_profiles.discard(k) else: - profile_changes.append('Would remove profile "{}"'.format(k)) + profile_changes.append(f'Would remove profile "{k}"') # Added profiles for k in new_profiles.difference(old_profiles): if not __opts__["test"]: - profile_changes.append('Added profile "{}"'.format(k)) + profile_changes.append(f'Added profile "{k}"') old_profiles.add(k) else: - profile_changes.append('Would add profile "{}"'.format(k)) + profile_changes.append(f'Would add profile "{k}"') if profile_changes: container_changed = True @@ -316,7 +315,7 @@ def present( changes["running"] = "Would start the container" return _unchanged( ret, - 'Container "{}" would get changed and started.'.format(name), + f'Container "{name}" would get changed and started.', ) else: container.start(wait=True) @@ -327,7 +326,7 @@ def present( changes["stopped"] = "Would stopped the container" return _unchanged( ret, - 'Container "{}" would get changed and stopped.'.format(name), + f'Container "{name}" would get changed and stopped.', ) else: container.stop(wait=True) @@ -342,17 +341,17 @@ def present( if __opts__["test"]: changes["restarted"] = "Would restart the container" - return _unchanged(ret, 'Would restart the container "{}"'.format(name)) + return _unchanged(ret, f'Would restart the container "{name}"') else: container.restart(wait=True) - changes["restarted"] = 'Container "{}" has been restarted'.format(name) - return _success(ret, 'Container "{}" has been restarted'.format(name)) + changes["restarted"] = f'Container "{name}" has been restarted' + return _success(ret, f'Container "{name}" has been restarted') if not container_changed: return _success(ret, "No changes") if __opts__["test"]: - return _unchanged(ret, 'Container "{}" would get changed.'.format(name)) + return _unchanged(ret, f'Container "{name}" would get changed.') return _success(ret, "{} changes".format(len(ret["changes"].keys()))) @@ -411,10 +410,10 @@ def absent(name, stop=False, remote_addr=None, cert=None, key=None, verify_cert= return _error(ret, str(e)) except SaltInvocationError as e: # Container not found - return _success(ret, 'Container "{}" not found.'.format(name)) + return _success(ret, f'Container "{name}" not found.') if __opts__["test"]: - ret["changes"] = {"removed": 'Container "{}" would get deleted.'.format(name)} + ret["changes"] = {"removed": f'Container "{name}" would get deleted.'} return _unchanged(ret, ret["changes"]["removed"]) if stop and container.status_code == CONTAINER_STATUS_RUNNING: @@ -422,7 +421,7 @@ def absent(name, stop=False, remote_addr=None, cert=None, key=None, verify_cert= container.delete(wait=True) - ret["changes"]["deleted"] = 'Container "{}" has been deleted.'.format(name) + ret["changes"]["deleted"] = f'Container "{name}" has been deleted.' return _success(ret, ret["changes"]["deleted"]) @@ -481,13 +480,13 @@ def running( return _error(ret, str(e)) except SaltInvocationError as e: # Container not found - return _error(ret, 'Container "{}" not found'.format(name)) + return _error(ret, f'Container "{name}" not found') is_running = container.status_code == CONTAINER_STATUS_RUNNING if is_running: if not restart: - return _success(ret, 'The container "{}" is already running'.format(name)) + return _success(ret, f'The container "{name}" is already running') else: if __opts__["test"]: ret["changes"]["restarted"] = 'Would restart the container "{}"'.format( @@ -502,11 +501,11 @@ def running( return _success(ret, ret["changes"]["restarted"]) if __opts__["test"]: - ret["changes"]["started"] = 'Would start the container "{}"'.format(name) + ret["changes"]["started"] = f'Would start the container "{name}"' return _unchanged(ret, ret["changes"]["started"]) container.start(wait=True) - ret["changes"]["started"] = 'Started the container "{}"'.format(name) + ret["changes"]["started"] = f'Started the container "{name}"' return _success(ret, ret["changes"]["started"]) @@ -563,10 +562,10 @@ def frozen(name, start=True, remote_addr=None, cert=None, key=None, verify_cert= return _error(ret, str(e)) except SaltInvocationError as e: # Container not found - return _error(ret, 'Container "{}" not found'.format(name)) + return _error(ret, f'Container "{name}" not found') if container.status_code == CONTAINER_STATUS_FROZEN: - return _success(ret, 'Container "{}" is alredy frozen'.format(name)) + return _success(ret, f'Container "{name}" is alredy frozen') is_running = container.status_code == CONTAINER_STATUS_RUNNING @@ -582,18 +581,18 @@ def frozen(name, start=True, remote_addr=None, cert=None, key=None, verify_cert= if __opts__["test"]: ret["changes"][ "started" - ] = 'Would start the container "{}" and freeze it after'.format(name) + ] = f'Would start the container "{name}" and freeze it after' return _unchanged(ret, ret["changes"]["started"]) else: container.start(wait=True) - ret["changes"]["started"] = 'Start the container "{}"'.format(name) + ret["changes"]["started"] = f'Start the container "{name}"' if __opts__["test"]: - ret["changes"]["frozen"] = 'Would freeze the container "{}"'.format(name) + ret["changes"]["frozen"] = f'Would freeze the container "{name}"' return _unchanged(ret, ret["changes"]["frozen"]) container.freeze(wait=True) - ret["changes"]["frozen"] = 'Froze the container "{}"'.format(name) + ret["changes"]["frozen"] = f'Froze the container "{name}"' return _success(ret, ret["changes"]["frozen"]) @@ -651,17 +650,17 @@ def stopped(name, kill=False, remote_addr=None, cert=None, key=None, verify_cert return _error(ret, str(e)) except SaltInvocationError as e: # Container not found - return _error(ret, 'Container "{}" not found'.format(name)) + return _error(ret, f'Container "{name}" not found') if container.status_code == CONTAINER_STATUS_STOPPED: - return _success(ret, 'Container "{}" is already stopped'.format(name)) + return _success(ret, f'Container "{name}" is already stopped') if __opts__["test"]: - ret["changes"]["stopped"] = 'Would stop the container "{}"'.format(name) + ret["changes"]["stopped"] = f'Would stop the container "{name}"' return _unchanged(ret, ret["changes"]["stopped"]) container.stop(force=kill, wait=True) - ret["changes"]["stopped"] = 'Stopped the container "{}"'.format(name) + ret["changes"]["stopped"] = f'Stopped the container "{name}"' return _success(ret, ret["changes"]["stopped"]) @@ -764,7 +763,7 @@ def migrated( pass if dest_container is not None: - return _success(ret, 'Container "{}" exists on the destination'.format(name)) + return _success(ret, f'Container "{name}" exists on the destination') if src_verify_cert is None: src_verify_cert = verify_cert @@ -777,13 +776,13 @@ def migrated( return _error(ret, str(e)) except SaltInvocationError as e: # Container not found - return _error(ret, 'Source Container "{}" not found'.format(name)) + return _error(ret, f'Source Container "{name}" not found') if __opts__["test"]: - ret["changes"][ - "migrated" - ] = 'Would migrate the container "{}" from "{}" to "{}"'.format( - name, src_remote_addr, remote_addr + ret["changes"]["migrated"] = ( + 'Would migrate the container "{}" from "{}" to "{}"'.format( + name, src_remote_addr, remote_addr + ) ) return _unchanged(ret, ret["changes"]["migrated"]) diff --git a/salt/states/lxd_image.py b/salt/states/lxd_image.py index c6d554ee284..923726e7b26 100644 --- a/salt/states/lxd_image.py +++ b/salt/states/lxd_image.py @@ -28,7 +28,6 @@ Manage LXD images. :platform: Linux """ - from salt.exceptions import CommandExecutionError, SaltInvocationError __docformat__ = "restructuredtext en" @@ -181,7 +180,7 @@ def present( if image is None: if __opts__["test"]: # Test is on, just return that we would create the image - msg = 'Would create the image "{}"'.format(name) + msg = f'Would create the image "{name}"' ret["changes"] = {"created": msg} return _unchanged(ret, msg) @@ -259,17 +258,17 @@ def present( for k in old_aliases.difference(new_aliases): if not __opts__["test"]: __salt__["lxd.image_alias_delete"](image, k) - alias_changes.append('Removed alias "{}"'.format(k)) + alias_changes.append(f'Removed alias "{k}"') else: - alias_changes.append('Would remove alias "{}"'.format(k)) + alias_changes.append(f'Would remove alias "{k}"') # New aliases for k in new_aliases.difference(old_aliases): if not __opts__["test"]: __salt__["lxd.image_alias_add"](image, k, "") - alias_changes.append('Added alias "{}"'.format(k)) + alias_changes.append(f'Added alias "{k}"') else: - alias_changes.append('Would add alias "{}"'.format(k)) + alias_changes.append(f'Would add alias "{k}"') if alias_changes: ret["changes"]["aliases"] = alias_changes @@ -277,11 +276,11 @@ def present( # Set public if public is not None and image.public != public: if not __opts__["test"]: - ret["changes"]["public"] = "Setting the image public to {!s}".format(public) + ret["changes"]["public"] = f"Setting the image public to {public!s}" image.public = public __salt__["lxd.pylxd_save_object"](image) else: - ret["changes"]["public"] = "Would set public to {!s}".format(public) + ret["changes"]["public"] = f"Would set public to {public!s}" if __opts__["test"] and ret["changes"]: return _unchanged(ret, "Would do {} changes".format(len(ret["changes"].keys()))) @@ -342,15 +341,15 @@ def absent(name, remote_addr=None, cert=None, key=None, verify_cert=True): except CommandExecutionError as e: return _error(ret, str(e)) except SaltInvocationError as e: - return _success(ret, 'Image "{}" not found.'.format(name)) + return _success(ret, f'Image "{name}" not found.') if __opts__["test"]: - ret["changes"] = {"removed": 'Image "{}" would get deleted.'.format(name)} + ret["changes"] = {"removed": f'Image "{name}" would get deleted.'} return _success(ret, ret["changes"]["removed"]) __salt__["lxd.image_delete"](image) - ret["changes"] = {"removed": 'Image "{}" has been deleted.'.format(name)} + ret["changes"] = {"removed": f'Image "{name}" has been deleted.'} return _success(ret, ret["changes"]["removed"]) diff --git a/salt/states/lxd_profile.py b/salt/states/lxd_profile.py index a4a0176ad39..a699252b4d7 100644 --- a/salt/states/lxd_profile.py +++ b/salt/states/lxd_profile.py @@ -27,7 +27,6 @@ Manage LXD profiles. :platform: Linux """ - from salt.exceptions import CommandExecutionError, SaltInvocationError __docformat__ = "restructuredtext en" @@ -133,7 +132,7 @@ def present( if profile is None: if __opts__["test"]: # Test is on, just return that we would create the profile - msg = 'Would create the profile "{}"'.format(name) + msg = f'Would create the profile "{name}"' ret["changes"] = {"created": msg} return _unchanged(ret, msg) @@ -146,7 +145,7 @@ def present( except CommandExecutionError as e: return _error(ret, str(e)) - msg = 'Profile "{}" has been created'.format(name) + msg = f'Profile "{name}" has been created' ret["changes"] = {"created": msg} return _success(ret, msg) @@ -156,10 +155,10 @@ def present( # Description change # if str(profile.description) != str(description): - ret["changes"][ - "description" - ] = 'Description changed, from "{}" to "{}".'.format( - profile.description, description + ret["changes"]["description"] = ( + 'Description changed, from "{}" to "{}".'.format( + profile.description, description + ) ) profile.description = description @@ -173,7 +172,7 @@ def present( return _success(ret, "No changes") if __opts__["test"]: - return _unchanged(ret, 'Profile "{}" would get changed.'.format(name)) + return _unchanged(ret, f'Profile "{name}" would get changed.') try: __salt__["lxd.pylxd_save_object"](profile) @@ -234,9 +233,9 @@ def absent(name, remote_addr=None, cert=None, key=None, verify_cert=True): return _error(ret, str(e)) except SaltInvocationError as e: # Profile not found - return _success(ret, 'Profile "{}" not found.'.format(name)) + return _success(ret, f'Profile "{name}" not found.') - ret["changes"] = {"removed": 'Profile "{}" would get deleted.'.format(name)} + ret["changes"] = {"removed": f'Profile "{name}" would get deleted.'} return _success(ret, ret["changes"]["removed"]) try: @@ -245,9 +244,9 @@ def absent(name, remote_addr=None, cert=None, key=None, verify_cert=True): return _error(ret, str(e)) except SaltInvocationError as e: # Profile not found - return _success(ret, 'Profile "{}" not found.'.format(name)) + return _success(ret, f'Profile "{name}" not found.') - ret["changes"] = {"removed": 'Profile "{}" has been deleted.'.format(name)} + ret["changes"] = {"removed": f'Profile "{name}" has been deleted.'} return _success(ret, ret["changes"]["removed"]) diff --git a/salt/states/mac_assistive.py b/salt/states/mac_assistive.py index 8aee4ccffec..ad0de154452 100644 --- a/salt/states/mac_assistive.py +++ b/salt/states/mac_assistive.py @@ -53,12 +53,12 @@ def installed(name, enabled=True): if enabled != is_enabled: __salt__["assistive.enable"](name, enabled) - ret["comment"] = "Updated enable to {}".format(enabled) + ret["comment"] = f"Updated enable to {enabled}" else: ret["comment"] = "Already in the correct state" else: __salt__["assistive.install"](name, enabled) - ret["comment"] = "Installed {} into the assistive access panel".format(name) + ret["comment"] = f"Installed {name} into the assistive access panel" return ret diff --git a/salt/states/mac_keychain.py b/salt/states/mac_keychain.py index 7126a95b01c..fd1af09623b 100644 --- a/salt/states/mac_keychain.py +++ b/salt/states/mac_keychain.py @@ -95,9 +95,9 @@ def installed(name, password, keychain="/Library/Keychains/System.keychain", **k ret["changes"]["installed"] = friendly_name else: ret["result"] = False - ret["comment"] += "Failed to install {}".format(friendly_name) + ret["comment"] += f"Failed to install {friendly_name}" else: - ret["comment"] += "{} already installed.".format(friendly_name) + ret["comment"] += f"{friendly_name} already installed." return ret @@ -150,9 +150,9 @@ def uninstalled( ret["changes"]["uninstalled"] = friendly_name else: ret["result"] = False - ret["comment"] += "Failed to uninstall {}".format(friendly_name) + ret["comment"] += f"Failed to uninstall {friendly_name}" else: - ret["comment"] += "{} already uninstalled.".format(friendly_name) + ret["comment"] += f"{friendly_name} already uninstalled." return ret @@ -175,18 +175,18 @@ def default_keychain(name, domain="user", user=None): if not os.path.exists(name): ret["result"] = False - ret["comment"] += "Keychain not found at {}".format(name) + ret["comment"] += f"Keychain not found at {name}" else: out = __salt__["keychain.get_default_keychain"](user, domain) if name in out: - ret["comment"] += "{} was already the default keychain.".format(name) + ret["comment"] += f"{name} was already the default keychain." else: out = __salt__["keychain.set_default_keychain"](name, domain, user) if len(out) == 0: ret["changes"]["default"] = name else: ret["result"] = False - ret["comment"] = "Failed to install keychain. {}".format(out) + ret["comment"] = f"Failed to install keychain. {out}" return ret diff --git a/salt/states/macdefaults.py b/salt/states/macdefaults.py index 67383eaffcd..05e83c2a4d6 100644 --- a/salt/states/macdefaults.py +++ b/salt/states/macdefaults.py @@ -58,20 +58,20 @@ def write(name, domain, value, vtype="string", user=None): (value in [True, "TRUE", "YES"] and current_value == "1") or (value in [False, "FALSE", "NO"] and current_value == "0") ): - ret["comment"] += "{} {} is already set to {}".format(domain, name, value) + ret["comment"] += f"{domain} {name} is already set to {value}" elif vtype in ["int", "integer"] and safe_cast(current_value, int) == safe_cast( value, int ): - ret["comment"] += "{} {} is already set to {}".format(domain, name, value) + ret["comment"] += f"{domain} {name} is already set to {value}" elif current_value == value: - ret["comment"] += "{} {} is already set to {}".format(domain, name, value) + ret["comment"] += f"{domain} {name} is already set to {value}" else: out = __salt__["macdefaults.write"](domain, name, value, vtype, user) if out["retcode"] != 0: ret["result"] = False ret["comment"] = "Failed to write default. {}".format(out["stdout"]) else: - ret["changes"]["written"] = "{} {} is set to {}".format(domain, name, value) + ret["changes"]["written"] = f"{domain} {name} is set to {value}" return ret @@ -96,8 +96,8 @@ def absent(name, domain, user=None): out = __salt__["macdefaults.delete"](domain, name, user) if out["retcode"] != 0: - ret["comment"] += "{} {} is already absent".format(domain, name) + ret["comment"] += f"{domain} {name} is already absent" else: - ret["changes"]["absent"] = "{} {} is now absent".format(domain, name) + ret["changes"]["absent"] = f"{domain} {name} is now absent" return ret diff --git a/salt/states/macpackage.py b/salt/states/macpackage.py index 17a03fb1140..2d64d3b6955 100644 --- a/salt/states/macpackage.py +++ b/salt/states/macpackage.py @@ -114,7 +114,7 @@ def installed( version_out = "" if re.match(expected_version, version_out) is not None: - ret["comment"] += "Version already matches {}".format(expected_version) + ret["comment"] += f"Version already matches {expected_version}" return ret else: ret["comment"] += "Version {} doesn't match {}. ".format( @@ -130,7 +130,7 @@ def installed( out, mount_point = __salt__["macpackage.mount"](name) if "attach failed" in out: ret["result"] = False - ret["comment"] += "Unable to mount {}".format(name) + ret["comment"] += f"Unable to mount {name}" return ret if app: @@ -150,7 +150,7 @@ def installed( if ".app" not in out: ret["result"] = False - ret["comment"] += "Unable to find .app in {}".format(mount_point) + ret["comment"] += f"Unable to find .app in {mount_point}" return ret else: pkg_ids = out.split("\n") @@ -191,7 +191,7 @@ def installed( def failed_pkg(f_pkg): ret["result"] = False - ret["comment"] += "{} failed to install: {}".format(name, out) + ret["comment"] += f"{name} failed to install: {out}" if "failed" in ret["changes"]: ret["changes"]["failed"].append(f_pkg) @@ -209,7 +209,7 @@ def installed( if len(out) != 0: failed_pkg(app) else: - ret["comment"] += "{} installed".format(app) + ret["comment"] += f"{app} installed" if "installed" in ret["changes"]: ret["changes"]["installed"].append(app) else: @@ -224,9 +224,9 @@ def installed( if out["retcode"] != 0: ret["result"] = False - ret["comment"] += ". {} failed to install: {}".format(name, out) + ret["comment"] += f". {name} failed to install: {out}" else: - ret["comment"] += "{} installed".format(name) + ret["comment"] += f"{name} installed" ret["changes"]["installed"] = installing finally: diff --git a/salt/states/makeconf.py b/salt/states/makeconf.py index 632a11b2c43..9e5a19261c1 100644 --- a/salt/states/makeconf.py +++ b/salt/states/makeconf.py @@ -131,11 +131,11 @@ def present(name, value=None, contains=None, excludes=None): ret["comment"] = msg.format(name) else: if __opts__["test"]: - msg = "Variable {} is set to".format(name) + msg = f"Variable {name} is set to" if len(to_append) > 0: - msg += ' append "{}"'.format(list(to_append)) + msg += f' append "{list(to_append)}"' if len(to_trim) > 0: - msg += ' trim "{}"'.format(list(to_trim)) + msg += f' trim "{list(to_trim)}"' msg += " in make.conf" ret["comment"] = msg ret["result"] = None diff --git a/salt/states/marathon_app.py b/salt/states/marathon_app.py index 3d44503db61..95339b1d148 100644 --- a/salt/states/marathon_app.py +++ b/salt/states/marathon_app.py @@ -66,7 +66,7 @@ def config(name, config): # if test, report there will be an update if __opts__["test"]: ret["result"] = None - ret["comment"] = "Marathon app {} is set to be updated".format(name) + ret["comment"] = f"Marathon app {name} is set to be updated" return ret update_result = __salt__["marathon.update_app"](name, update_config) @@ -79,10 +79,10 @@ def config(name, config): return ret else: ret["result"] = True - ret["comment"] = "Updated app config for {}".format(name) + ret["comment"] = f"Updated app config for {name}" return ret ret["result"] = True - ret["comment"] = "Marathon app {} configured correctly".format(name) + ret["comment"] = f"Marathon app {name} configured correctly" return ret @@ -96,20 +96,20 @@ def absent(name): ret = {"name": name, "changes": {}, "result": False, "comment": ""} if not __salt__["marathon.has_app"](name): ret["result"] = True - ret["comment"] = "App {} already absent".format(name) + ret["comment"] = f"App {name} already absent" return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "App {} is set to be removed".format(name) + ret["comment"] = f"App {name} is set to be removed" return ret if __salt__["marathon.rm_app"](name): ret["changes"] = {"app": name} ret["result"] = True - ret["comment"] = "Removed app {}".format(name) + ret["comment"] = f"Removed app {name}" return ret else: ret["result"] = False - ret["comment"] = "Failed to remove app {}".format(name) + ret["comment"] = f"Failed to remove app {name}" return ret @@ -125,12 +125,12 @@ def running(name, restart=False, force=True): ret = {"name": name, "changes": {}, "result": False, "comment": ""} if not __salt__["marathon.has_app"](name): ret["result"] = False - ret["comment"] = "App {} cannot be restarted because it is absent".format(name) + ret["comment"] = f"App {name} cannot be restarted because it is absent" return ret if __opts__["test"]: ret["result"] = None qualifier = "is" if restart else "is not" - ret["comment"] = "App {} {} set to be restarted".format(name, qualifier) + ret["comment"] = f"App {name} {qualifier} set to be restarted" return ret restart_result = __salt__["marathon.restart_app"](name, restart, force) if "exception" in restart_result: @@ -143,5 +143,5 @@ def running(name, restart=False, force=True): ret["changes"] = restart_result ret["result"] = True qualifier = "Restarted" if restart else "Did not restart" - ret["comment"] = "{} app {}".format(qualifier, name) + ret["comment"] = f"{qualifier} app {name}" return ret diff --git a/salt/states/mdadm_raid.py b/salt/states/mdadm_raid.py index 7f32f3bd991..76396d858dd 100644 --- a/salt/states/mdadm_raid.py +++ b/salt/states/mdadm_raid.py @@ -19,7 +19,6 @@ A state module for creating or destroying software RAID devices. - run: True """ - import logging import salt.utils.path @@ -100,20 +99,20 @@ def present(name, level, devices, **kwargs): new_devices.append(dev) if len(uuid_dict) > 1: - ret[ - "comment" - ] = "Devices are a mix of RAID constituents with multiple MD_UUIDs: {}.".format( - sorted(uuid_dict) + ret["comment"] = ( + "Devices are a mix of RAID constituents with multiple MD_UUIDs: {}.".format( + sorted(uuid_dict) + ) ) ret["result"] = False return ret elif len(uuid_dict) == 1: uuid = next(iter(uuid_dict)) if present and present["uuid"] != uuid: - ret[ - "comment" - ] = "Devices MD_UUIDs: {} differs from present RAID uuid {}.".format( - uuid, present["uuid"] + ret["comment"] = ( + "Devices MD_UUIDs: {} differs from present RAID uuid {}.".format( + uuid, present["uuid"] + ) ) ret["result"] = False return ret @@ -131,7 +130,7 @@ def present(name, level, devices, **kwargs): verb = "assembled" else: if len(new_devices) == 0: - ret["comment"] = "All devices are missing: {}.".format(missing) + ret["comment"] = f"All devices are missing: {missing}." ret["result"] = False return ret do_assemble = False @@ -150,22 +149,22 @@ def present(name, level, devices, **kwargs): level, new_devices + ["missing"] * len(missing), test_mode=True, - **kwargs + **kwargs, ) if present: - ret["comment"] = "Raid {} already present.".format(name) + ret["comment"] = f"Raid {name} already present." if do_assemble or do_create: - ret["comment"] = "Raid will be {} with: {}".format(verb, res) + ret["comment"] = f"Raid will be {verb} with: {res}" ret["result"] = None if (do_assemble or present) and len(new_devices) > 0: - ret["comment"] += " New devices will be added: {}".format(new_devices) + ret["comment"] += f" New devices will be added: {new_devices}" ret["result"] = None if len(missing) > 0: - ret["comment"] += " Missing devices: {}".format(missing) + ret["comment"] += f" Missing devices: {missing}" return ret @@ -181,29 +180,29 @@ def present(name, level, devices, **kwargs): raids = __salt__["raid.list"]() changes = raids.get(name) if changes: - ret["comment"] = "Raid {} {}.".format(name, verb) + ret["comment"] = f"Raid {name} {verb}." ret["changes"] = changes # Saving config __salt__["raid.save_config"]() else: - ret["comment"] = "Raid {} failed to be {}.".format(name, verb) + ret["comment"] = f"Raid {name} failed to be {verb}." ret["result"] = False else: - ret["comment"] = "Raid {} already present.".format(name) + ret["comment"] = f"Raid {name} already present." if (do_assemble or present) and len(new_devices) > 0 and ret["result"]: for d in new_devices: res = __salt__["raid.add"](name, d) if not res: - ret["comment"] += " Unable to add {} to {}.\n".format(d, name) + ret["comment"] += f" Unable to add {d} to {name}.\n" ret["result"] = False else: - ret["comment"] += " Added new device {} to {}.\n".format(d, name) + ret["comment"] += f" Added new device {d} to {name}.\n" if ret["result"]: ret["changes"]["added"] = new_devices if len(missing) > 0: - ret["comment"] += " Missing devices: {}".format(missing) + ret["comment"] += f" Missing devices: {missing}" return ret @@ -225,10 +224,10 @@ def absent(name): # Raid does not exist if name not in __salt__["raid.list"](): - ret["comment"] = "Raid {} already absent".format(name) + ret["comment"] = f"Raid {name} already absent" return ret elif __opts__["test"]: - ret["comment"] = "Raid {} is set to be destroyed".format(name) + ret["comment"] = f"Raid {name} is set to be destroyed" ret["result"] = None return ret else: @@ -236,7 +235,7 @@ def absent(name): ret["result"] = __salt__["raid.destroy"](name) if ret["result"]: - ret["comment"] = "Raid {} has been destroyed".format(name) + ret["comment"] = f"Raid {name} has been destroyed" else: - ret["comment"] = "Raid {} failed to be destroyed".format(name) + ret["comment"] = f"Raid {name} failed to be destroyed" return ret diff --git a/salt/states/memcached.py b/salt/states/memcached.py index 9f4a6d367dd..3499961671b 100644 --- a/salt/states/memcached.py +++ b/salt/states/memcached.py @@ -5,7 +5,6 @@ States for Management of Memcached Keys .. versionadded:: 2014.1.0 """ - from salt.exceptions import CommandExecutionError, SaltInvocationError from salt.modules.memcached import ( DEFAULT_HOST, @@ -21,7 +20,7 @@ def __virtual__(): """ Only load if memcache module is available """ - if "{}.status".format(__virtualname__) in __salt__: + if f"{__virtualname__}.status" in __salt__: return __virtualname__ return (False, "memcached module could not be loaded") @@ -66,15 +65,15 @@ def managed( if cur == value: ret["result"] = True - ret["comment"] = "Key '{}' does not need to be updated".format(name) + ret["comment"] = f"Key '{name}' does not need to be updated" return ret if __opts__["test"]: ret["result"] = None if cur is None: - ret["comment"] = "Key '{}' would be added".format(name) + ret["comment"] = f"Key '{name}' would be added" else: - ret["comment"] = "Value of key '{}' would be changed".format(name) + ret["comment"] = f"Value of key '{name}' would be changed" return ret try: @@ -85,13 +84,13 @@ def managed( ret["comment"] = str(exc) else: if ret["result"]: - ret["comment"] = "Successfully set key '{}'".format(name) + ret["comment"] = f"Successfully set key '{name}'" if cur is not None: ret["changes"] = {"old": cur, "new": value} else: ret["changes"] = {"key added": name, "value": value} else: - ret["comment"] = "Failed to set key '{}'".format(name) + ret["comment"] = f"Failed to set key '{name}'" return ret @@ -139,12 +138,12 @@ def absent(name, value=None, host=DEFAULT_HOST, port=DEFAULT_PORT, time=DEFAULT_ return ret if cur is None: ret["result"] = True - ret["comment"] = "Key '{}' does not exist".format(name) + ret["comment"] = f"Key '{name}' does not exist" return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Key '{}' would be deleted".format(name) + ret["comment"] = f"Key '{name}' would be deleted" return ret try: @@ -153,8 +152,8 @@ def absent(name, value=None, host=DEFAULT_HOST, port=DEFAULT_PORT, time=DEFAULT_ ret["comment"] = str(exc) else: if ret["result"]: - ret["comment"] = "Successfully deleted key '{}'".format(name) + ret["comment"] = f"Successfully deleted key '{name}'" ret["changes"] = {"key deleted": name, "value": cur} else: - ret["comment"] = "Failed to delete key '{}'".format(name) + ret["comment"] = f"Failed to delete key '{name}'" return ret diff --git a/salt/states/modjk.py b/salt/states/modjk.py index 0932715b129..f41a84010ab 100644 --- a/salt/states/modjk.py +++ b/salt/states/modjk.py @@ -26,7 +26,7 @@ def _bulk_state(saltfunc, lbn, workers, profile): if not isinstance(workers, list): ret["result"] = False - ret["comment"] = "workers should be a list not a {}".format(type(workers)) + ret["comment"] = f"workers should be a list not a {type(workers)}" return ret if __opts__["test"]: @@ -38,7 +38,7 @@ def _bulk_state(saltfunc, lbn, workers, profile): cmdret = __salt__[saltfunc](workers, lbn, profile=profile) except KeyError: ret["result"] = False - ret["comment"] = "unsupported function {}".format(saltfunc) + ret["comment"] = f"unsupported function {saltfunc}" return ret errors = [] @@ -49,7 +49,7 @@ def _bulk_state(saltfunc, lbn, workers, profile): ret["changes"] = {"status": cmdret} if errors: ret["result"] = False - ret["comment"] = "{} failed on some workers".format(saltfunc) + ret["comment"] = f"{saltfunc} failed on some workers" return ret diff --git a/salt/states/modjk_worker.py b/salt/states/modjk_worker.py index bcf745c03eb..5cefeac1d63 100644 --- a/salt/states/modjk_worker.py +++ b/salt/states/modjk_worker.py @@ -44,7 +44,7 @@ def _send_command(cmd, worker, lbn, target, profile="default", tgt_type="glob"): } # Send the command to target - func = "modjk.{}".format(cmd) + func = f"modjk.{cmd}" args = [worker, lbn, profile] response = __salt__["publish.publish"](target, func, args, tgt_type) @@ -58,7 +58,7 @@ def _send_command(cmd, worker, lbn, target, profile="default", tgt_type="glob"): # parse response if not response: - ret["msg"] = "no servers answered the published command {}".format(cmd) + ret["msg"] = f"no servers answered the published command {cmd}" return ret elif len(errors) > 0: ret["msg"] = "the following minions return False" @@ -127,16 +127,16 @@ 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"]: - ret[ - "comment" - ] = "the worker is in the desired activation state on all the balancers" + ret["comment"] = ( + "the worker is in the desired activation state on all the balancers" + ) return ret else: ret["comment"] = "the action {} will be sent to the balancers {}".format( diff --git a/salt/states/module.py b/salt/states/module.py index 5ad87b053d2..262e38b96d6 100644 --- a/salt/states/module.py +++ b/salt/states/module.py @@ -300,6 +300,7 @@ Windows system: .. _file_roots: https://docs.saltproject.io/en/latest/ref/configuration/master.html#file-roots """ + import logging import salt.loader @@ -459,19 +460,21 @@ def _run(**kwargs): ) ) if func_ret is False: - failures.append("'{}': {}".format(func, func_ret)) + failures.append(f"'{func}': {func_ret}") else: success.append( "{}: {}".format( func, - func_ret.get("comment", "Success") - if isinstance(func_ret, dict) - else func_ret, + ( + func_ret.get("comment", "Success") + if isinstance(func_ret, dict) + else func_ret + ), ) ) ret["changes"][func] = func_ret except (SaltInvocationError, TypeError) as ex: - failures.append("'{}' failed: {}".format(func, ex)) + failures.append(f"'{func}' failed: {ex}") ret["comment"] = ", ".join(failures + success) ret["result"] = not bool(failures) @@ -527,12 +530,12 @@ def _legacy_run(name, **kwargs): """ ret = {"name": name, "changes": {}, "comment": "", "result": None} if name not in __salt__: - ret["comment"] = "Module function {} is not available".format(name) + ret["comment"] = f"Module function {name} is not available" ret["result"] = False return ret if __opts__["test"]: - ret["comment"] = "Module function {} is set to execute".format(name) + ret["comment"] = f"Module function {name} is set to execute" return ret aspec = salt.utils.args.get_function_argspec(__salt__[name]) @@ -590,7 +593,7 @@ def _legacy_run(name, **kwargs): if missing: comment = "The following arguments are missing:" for arg in missing: - comment += " {}".format(arg) + comment += f" {arg}" ret["comment"] = comment ret["result"] = False return ret @@ -654,7 +657,7 @@ def _legacy_run(name, **kwargs): returners = salt.loader.returners(__opts__, __salt__) if kwargs["returner"] in returners: returners[kwargs["returner"]](ret_ret) - ret["comment"] = "Module function {} executed".format(name) + ret["comment"] = f"Module function {name} executed" ret["result"] = _get_result(mret, ret["changes"]) return ret diff --git a/salt/states/mongodb_database.py b/salt/states/mongodb_database.py index 4df6c4297ed..5445b3b880d 100644 --- a/salt/states/mongodb_database.py +++ b/salt/states/mongodb_database.py @@ -53,9 +53,9 @@ def absent(name, user=None, password=None, host=None, port=None, authdb=None): if __salt__["mongodb.db_remove"]( name, user, password, host, port, authdb=authdb ): - ret["comment"] = "Database {} has been removed".format(name) + ret["comment"] = f"Database {name} has been removed" ret["changes"][name] = "Absent" return ret - ret["comment"] = "Database {} is not present".format(name) + ret["comment"] = f"Database {name} is not present" return ret diff --git a/salt/states/mongodb_user.py b/salt/states/mongodb_user.py index a83cd9b5686..6494b0018a9 100644 --- a/salt/states/mongodb_user.py +++ b/salt/states/mongodb_user.py @@ -81,7 +81,7 @@ def present( "name": name, "changes": {}, "result": True, - "comment": "User {} is already present".format(name), + "comment": f"User {name} is already present", } # setup default empty roles if not provided to preserve previous API interface @@ -93,7 +93,7 @@ def present( port = int(port) except TypeError: ret["result"] = False - ret["comment"] = "Port ({}) is not an integer.".format(port) + ret["comment"] = f"Port ({port}) is not an integer." return ret # check if user exists @@ -106,7 +106,7 @@ def present( # users= (False, 'not authorized on admin to execute command { usersInfo: "root" }') if not users[0]: ret["result"] = False - ret["comment"] = "Mongo Err: {}".format(users[1]) + ret["comment"] = f"Mongo Err: {users[1]}" return ret # check each user occurrence @@ -152,7 +152,7 @@ def present( if __opts__["test"]: ret["result"] = None - ret["comment"] = "User {} is not present and needs to be created".format(name) + ret["comment"] = f"User {name} is not present and needs to be created" return ret # The user is not present, make it! if __salt__["mongodb.user_create"]( @@ -166,10 +166,10 @@ def present( authdb=authdb, roles=roles, ): - ret["comment"] = "User {} has been created".format(name) + ret["comment"] = f"User {name} has been created" ret["changes"][name] = "Present" else: - ret["comment"] = "Failed to create database {}".format(name) + ret["comment"] = f"Failed to create database {name}" ret["result"] = False return ret @@ -212,12 +212,12 @@ def absent( if user_exists is True: if __opts__["test"]: ret["result"] = None - ret["comment"] = "User {} is present and needs to be removed".format(name) + ret["comment"] = f"User {name} is present and needs to be removed" return ret if __salt__["mongodb.user_remove"]( name, user, password, host, port, database=database, authdb=authdb ): - ret["comment"] = "User {} has been removed".format(name) + ret["comment"] = f"User {name} has been removed" ret["changes"][name] = "Absent" return ret @@ -229,5 +229,5 @@ def absent( return ret # fallback - ret["comment"] = "User {} is not present".format(name) + ret["comment"] = f"User {name} is not present" return ret diff --git a/salt/states/monit.py b/salt/states/monit.py index b6de50d307f..4e1cd7dd514 100644 --- a/salt/states/monit.py +++ b/salt/states/monit.py @@ -40,20 +40,20 @@ def monitor(name): try: for key, value in result.items(): if "Running" in value[name]: - ret["comment"] = "{} is being being monitored.".format(name) + ret["comment"] = f"{name} is being being monitored." ret["result"] = True else: if __opts__["test"]: - ret["comment"] = "Service {} is set to be monitored.".format(name) + ret["comment"] = f"Service {name} is set to be monitored." ret["result"] = None return ret __salt__["monit.monitor"](name) - ret["comment"] = "{} started to be monitored.".format(name) + ret["comment"] = f"{name} started to be monitored." ret["changes"][name] = "Running" ret["result"] = True break except KeyError: - ret["comment"] = "{} not found in configuration.".format(name) + ret["comment"] = f"{name} not found in configuration." ret["result"] = False return ret @@ -70,20 +70,20 @@ def unmonitor(name): try: for key, value in result.items(): if "Not monitored" in value[name]: - ret["comment"] = "{} is not being monitored.".format(name) + ret["comment"] = f"{name} is not being monitored." ret["result"] = True else: if __opts__["test"]: - ret["comment"] = "Service {} is set to be unmonitored.".format(name) + ret["comment"] = f"Service {name} is set to be unmonitored." ret["result"] = None return ret __salt__["monit.unmonitor"](name) - ret["comment"] = "{} stopped being monitored.".format(name) + ret["comment"] = f"{name} stopped being monitored." ret["changes"][name] = "Not monitored" ret["result"] = True break except KeyError: - ret["comment"] = "{} not found in configuration.".format(name) + ret["comment"] = f"{name} not found in configuration." ret["result"] = False return ret diff --git a/salt/states/mount.py b/salt/states/mount.py index 8f608bf265b..560ccc39ae6 100644 --- a/salt/states/mount.py +++ b/salt/states/mount.py @@ -477,10 +477,10 @@ def mounted( if trigger_remount: if __opts__["test"]: ret["result"] = None - ret[ - "comment" - ] = "Remount would be forced because options ({}) changed".format( - ",".join(sorted(trigger_remount)) + ret["comment"] = ( + "Remount would be forced because options ({}) changed".format( + ",".join(sorted(trigger_remount)) + ) ) return ret else: @@ -603,10 +603,10 @@ def mounted( ret["result"] = mount_result else: ret["result"] = False - ret[ - "comment" - ] = "Unable to unmount {}: {}.".format( - real_name, unmount_result + ret["comment"] = ( + "Unable to unmount {}: {}.".format( + real_name, unmount_result + ) ) return ret else: @@ -708,10 +708,10 @@ def mounted( if mkmnt: ret["comment"] = f"{name} would be created, but not mounted" else: - ret[ - "comment" - ] = "{} does not exist and would neither be created nor mounted".format( - name + ret["comment"] = ( + "{} does not exist and would neither be created nor mounted".format( + name + ) ) elif mkmnt: __salt__["file.mkdir"](name, user=user) @@ -899,10 +899,10 @@ def swap(name, persist=True, config="/etc/fstab"): ]: ret["result"] = None if name in on_: - ret[ - "comment" - ] = "Swap {} is set to be added to the fstab and to be activated".format( - name + ret["comment"] = ( + "Swap {} is set to be added to the fstab and to be activated".format( + name + ) ) return ret diff --git a/salt/states/mssql_database.py b/salt/states/mssql_database.py index e5c4c3cc67f..f3f44f0bd64 100644 --- a/salt/states/mssql_database.py +++ b/salt/states/mssql_database.py @@ -25,7 +25,7 @@ def __virtual__(): def _normalize_options(options): if type(options) in [dict, collections.OrderedDict]: - return ["{}={}".format(k, v) for k, v in options.items()] + return [f"{k}={v}" for k, v in options.items()] if type(options) is list and (not options or type(options[0]) is str): return options # Invalid options @@ -51,22 +51,22 @@ def present(name, containment="NONE", options=None, **kwargs): ret = {"name": name, "changes": {}, "result": True, "comment": ""} if __salt__["mssql.db_exists"](name, **kwargs): - ret[ - "comment" - ] = "Database {} is already present (Not going to try to set its options)".format( - name + ret["comment"] = ( + "Database {} is already present (Not going to try to set its options)".format( + name + ) ) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Database {} is set to be added".format(name) + ret["comment"] = f"Database {name} is set to be added" return ret db_created = __salt__["mssql.db_create"]( name, containment=containment, new_database_options=_normalize_options(options), - **kwargs + **kwargs, ) if ( db_created is not True @@ -76,7 +76,7 @@ def present(name, containment="NONE", options=None, **kwargs): name, db_created ) return ret - ret["comment"] += "Database {} has been added".format(name) + ret["comment"] += f"Database {name} has been added" ret["changes"][name] = "Present" return ret @@ -91,17 +91,17 @@ def absent(name, **kwargs): ret = {"name": name, "changes": {}, "result": True, "comment": ""} if not __salt__["mssql.db_exists"](name): - ret["comment"] = "Database {} is not present".format(name) + ret["comment"] = f"Database {name} is not present" return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Database {} is set to be removed".format(name) + ret["comment"] = f"Database {name} is set to be removed" return ret if __salt__["mssql.db_remove"](name, **kwargs): - ret["comment"] = "Database {} has been removed".format(name) + ret["comment"] = f"Database {name} has been removed" ret["changes"][name] = "Absent" return ret # else: ret["result"] = False - ret["comment"] = "Database {} failed to be removed".format(name) + ret["comment"] = f"Database {name} failed to be removed" return ret diff --git a/salt/states/mssql_login.py b/salt/states/mssql_login.py index 89ace89bcaf..56316db60f4 100644 --- a/salt/states/mssql_login.py +++ b/salt/states/mssql_login.py @@ -26,7 +26,7 @@ def __virtual__(): def _normalize_options(options): if type(options) in [dict, collections.OrderedDict]: - return ["{}={}".format(k, v) for k, v in options.items()] + return [f"{k}={v}" for k, v in options.items()] if type(options) is list and (not options or type(options[0]) is str): return options # Invalid options @@ -67,15 +67,15 @@ def present( ret["comment"] = "One and only one of password and domain should be specifies" return ret if __salt__["mssql.login_exists"](name, domain=domain, **kwargs): - ret[ - "comment" - ] = "Login {} is already present (Not going to try to set its password)".format( - name + ret["comment"] = ( + "Login {} is already present (Not going to try to set its password)".format( + name + ) ) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Login {} is set to be added".format(name) + ret["comment"] = f"Login {name} is set to be added" return ret login_created = __salt__["mssql.login_create"]( @@ -84,14 +84,14 @@ def present( new_login_domain=domain, new_login_roles=server_roles, new_login_options=_normalize_options(options), - **kwargs + **kwargs, ) # Non-empty strings are also evaluated to True, so we cannot use if not login_created: if login_created is not True: ret["result"] = False - ret["comment"] = "Login {} failed to be added: {}".format(name, login_created) + ret["comment"] = f"Login {name} failed to be added: {login_created}" return ret - ret["comment"] = "Login {} has been added. ".format(name) + ret["comment"] = f"Login {name} has been added. " ret["changes"][name] = "Present" return ret @@ -106,17 +106,17 @@ def absent(name, **kwargs): ret = {"name": name, "changes": {}, "result": True, "comment": ""} if not __salt__["mssql.login_exists"](name): - ret["comment"] = "Login {} is not present".format(name) + ret["comment"] = f"Login {name} is not present" return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Login {} is set to be removed".format(name) + ret["comment"] = f"Login {name} is set to be removed" return ret if __salt__["mssql.login_remove"](name, **kwargs): - ret["comment"] = "Login {} has been removed".format(name) + ret["comment"] = f"Login {name} has been removed" ret["changes"][name] = "Absent" return ret # else: ret["result"] = False - ret["comment"] = "Login {} failed to be removed".format(name) + ret["comment"] = f"Login {name} failed to be removed" return ret diff --git a/salt/states/mssql_role.py b/salt/states/mssql_role.py index 2fbdfe172a7..2bd540233f0 100644 --- a/salt/states/mssql_role.py +++ b/salt/states/mssql_role.py @@ -35,15 +35,15 @@ def present(name, owner=None, grants=None, **kwargs): ret = {"name": name, "changes": {}, "result": True, "comment": ""} if __salt__["mssql.role_exists"](name, **kwargs): - ret[ - "comment" - ] = "Role {} is already present (Not going to try to set its grants)".format( - name + ret["comment"] = ( + "Role {} is already present (Not going to try to set its grants)".format( + name + ) ) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Role {} is set to be added".format(name) + ret["comment"] = f"Role {name} is set to be added" return ret role_created = __salt__["mssql.role_create"]( @@ -53,9 +53,9 @@ def present(name, owner=None, grants=None, **kwargs): role_created is not True ): # Non-empty strings are also evaluated to True, so we cannot use if not role_created: ret["result"] = False - ret["comment"] += "Role {} failed to be created: {}".format(name, role_created) + ret["comment"] += f"Role {name} failed to be created: {role_created}" return ret - ret["comment"] += "Role {} has been added".format(name) + ret["comment"] += f"Role {name} has been added" ret["changes"][name] = "Present" return ret @@ -70,17 +70,17 @@ def absent(name, **kwargs): ret = {"name": name, "changes": {}, "result": True, "comment": ""} if not __salt__["mssql.role_exists"](name): - ret["comment"] = "Role {} is not present".format(name) + ret["comment"] = f"Role {name} is not present" return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Role {} is set to be removed".format(name) + ret["comment"] = f"Role {name} is set to be removed" return ret if __salt__["mssql.role_remove"](name, **kwargs): - ret["comment"] = "Role {} has been removed".format(name) + ret["comment"] = f"Role {name} has been removed" ret["changes"][name] = "Absent" return ret # else: ret["result"] = False - ret["comment"] = "Role {} failed to be removed".format(name) + ret["comment"] = f"Role {name} failed to be removed" return ret diff --git a/salt/states/mssql_user.py b/salt/states/mssql_user.py index d07c0d56cca..60f8987d518 100644 --- a/salt/states/mssql_user.py +++ b/salt/states/mssql_user.py @@ -26,7 +26,7 @@ def __virtual__(): def _normalize_options(options): if type(options) in [dict, collections.OrderedDict]: - return ["{}={}".format(k, v) for k, v in options.items()] + return [f"{k}={v}" for k, v in options.items()] if type(options) is list and (not options or type(options[0]) is str): return options # Invalid options @@ -66,15 +66,15 @@ def present( ret["comment"] = "domain cannot be set without login" return ret if __salt__["mssql.user_exists"](name, domain=domain, database=database, **kwargs): - ret[ - "comment" - ] = "User {} is already present (Not going to try to set its roles or options)".format( - name + ret["comment"] = ( + "User {} is already present (Not going to try to set its roles or options)".format( + name + ) ) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "User {} is set to be added".format(name) + ret["comment"] = f"User {name} is set to be added" return ret user_created = __salt__["mssql.user_create"]( @@ -84,15 +84,15 @@ def present( database=database, roles=roles, options=_normalize_options(options), - **kwargs + **kwargs, ) if ( user_created is not True ): # Non-empty strings are also evaluated to True, so we cannot use if not user_created: ret["result"] = False - ret["comment"] += "User {} failed to be added: {}".format(name, user_created) + ret["comment"] += f"User {name} failed to be added: {user_created}" return ret - ret["comment"] += "User {} has been added".format(name) + ret["comment"] += f"User {name} has been added" ret["changes"][name] = "Present" return ret @@ -107,17 +107,17 @@ def absent(name, **kwargs): ret = {"name": name, "changes": {}, "result": True, "comment": ""} if not __salt__["mssql.user_exists"](name): - ret["comment"] = "User {} is not present".format(name) + ret["comment"] = f"User {name} is not present" return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "User {} is set to be removed".format(name) + ret["comment"] = f"User {name} is set to be removed" return ret if __salt__["mssql.user_remove"](name, **kwargs): - ret["comment"] = "User {} has been removed".format(name) + ret["comment"] = f"User {name} has been removed" ret["changes"][name] = "Absent" return ret # else: ret["result"] = False - ret["comment"] = "User {} failed to be removed".format(name) + ret["comment"] = f"User {name} failed to be removed" return ret diff --git a/salt/states/msteams.py b/salt/states/msteams.py index d84387c7d68..a4438825797 100644 --- a/salt/states/msteams.py +++ b/salt/states/msteams.py @@ -21,7 +21,6 @@ The hook_url can be specified in the master or minion configuration like below: hook_url: https://outlook.office.com/webhook/837 """ - from salt.exceptions import SaltInvocationError @@ -70,7 +69,7 @@ def post_card(name, message, hook_url=None, title=None, theme_color=None): return ret if not message: - ret["comment"] = "Teams message is missing: {}".format(message) + ret["comment"] = f"Teams message is missing: {message}" return ret try: @@ -81,11 +80,11 @@ def post_card(name, message, hook_url=None, title=None, theme_color=None): theme_color=theme_color, ) except SaltInvocationError as sie: - ret["comment"] = "Failed to send message ({}): {}".format(sie, name) + ret["comment"] = f"Failed to send message ({sie}): {name}" else: if isinstance(result, bool) and result: ret["result"] = True - ret["comment"] = "Sent message: {}".format(name) + ret["comment"] = f"Sent message: {name}" else: ret["comment"] = "Failed to send message ({}): {}".format( result["message"], name diff --git a/salt/states/mysql_database.py b/salt/states/mysql_database.py index c7561cf14db..0c0ce030ff4 100644 --- a/salt/states/mysql_database.py +++ b/salt/states/mysql_database.py @@ -52,7 +52,7 @@ def present(name, character_set=None, collate=None, **connection_args): "name": name, "changes": {}, "result": True, - "comment": "Database {} is already present".format(name), + "comment": f"Database {name} is already present", } # check if database exists existing = __salt__["mysql.db_get"](name, **connection_args) @@ -91,20 +91,20 @@ def present(name, character_set=None, collate=None, **connection_args): ) if __opts__.get("test", False): ret["result"] = None - ret["comment"] += "\n{}".format(comment) + ret["comment"] += f"\n{comment}" return ret else: - ret["comment"] += "\n{}".format(comment) + ret["comment"] += f"\n{comment}" if alter_charset or alter_collate: if __opts__.get("test", False): - ret["comment"] += "\nDatabase {} is going to be updated".format(name) + ret["comment"] += f"\nDatabase {name} is going to be updated" else: __salt__["mysql.alter_db"]( name, character_set=character_set, collate=collate, - **connection_args + **connection_args, ) current = __salt__["mysql.db_get"](name, **connection_args) @@ -145,13 +145,13 @@ def present(name, character_set=None, collate=None, **connection_args): if __salt__["mysql.db_create"]( name, character_set=character_set, collate=collate, **connection_args ): - ret["comment"] = "The database {} has been created".format(name) + ret["comment"] = f"The database {name} has been created" ret["changes"][name] = "Present" else: - ret["comment"] = "Failed to create database {}".format(name) + ret["comment"] = f"Failed to create database {name}" err = _get_mysql_error() if err is not None: - ret["comment"] += " ({})".format(err) + ret["comment"] += f" ({err})" ret["result"] = False return ret @@ -175,13 +175,13 @@ def absent(name, **connection_args): ) return ret if __salt__["mysql.db_remove"](name, **connection_args): - ret["comment"] = "Database {} has been removed".format(name) + ret["comment"] = f"Database {name} has been removed" ret["changes"][name] = "Absent" return ret else: err = _get_mysql_error() if err is not None: - ret["comment"] = "Unable to remove database {} ({})".format(name, err) + ret["comment"] = f"Unable to remove database {name} ({err})" ret["result"] = False return ret else: @@ -192,5 +192,5 @@ def absent(name, **connection_args): return ret # fallback - ret["comment"] = "Database {} is not present, so it cannot be removed".format(name) + ret["comment"] = f"Database {name} is not present, so it cannot be removed" return ret diff --git a/salt/states/mysql_grants.py b/salt/states/mysql_grants.py index acc9856a1f4..74e1c8346b5 100644 --- a/salt/states/mysql_grants.py +++ b/salt/states/mysql_grants.py @@ -77,7 +77,7 @@ def present( escape=True, revoke_first=False, ssl_option=False, - **connection_args + **connection_args, ): """ Ensure that the grant is present with the specified properties @@ -182,14 +182,14 @@ def present( host=host, grant_option=grant_option, escape=escape, - **connection_args + **connection_args, ) # The grant is not present, make it! if __opts__["test"]: # there is probably better things to make in test mode ret["result"] = None - ret["comment"] = "MySQL grant {} is set to be created".format(name) + ret["comment"] = f"MySQL grant {name} is set to be created" return ret if __salt__["mysql.grant_add"]( grant, database, user, host, grant_option, escape, ssl_option, **connection_args @@ -202,7 +202,7 @@ def present( ret["comment"] = ret["comment"].format(grant, database, user, host) err = _get_mysql_error() if err is not None: - ret["comment"] += " ({})".format(err) + ret["comment"] += f" ({err})" ret["result"] = False return ret @@ -215,7 +215,7 @@ def absent( host="localhost", grant_option=False, escape=True, - **connection_args + **connection_args, ): """ Ensure that the grant is absent @@ -244,7 +244,7 @@ def absent( if __opts__["test"]: ret["result"] = None - ret["comment"] = "MySQL grant {} is set to be revoked".format(name) + ret["comment"] = f"MySQL grant {name} is set to be revoked" return ret if __salt__["mysql.grant_revoke"]( grant, database, user, host, grant_option, **connection_args @@ -257,28 +257,28 @@ 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 # fallback - ret[ - "comment" - ] = "Grant {} on {} to {}@{} is not present, so it cannot be revoked".format( - grant, database, user, host + ret["comment"] = ( + "Grant {} on {} to {}@{} is not present, so it cannot be revoked".format( + grant, database, user, host + ) ) return ret diff --git a/salt/states/mysql_query.py b/salt/states/mysql_query.py index be4ee5169a6..d0bc6bedfc9 100644 --- a/salt/states/mysql_query.py +++ b/salt/states/mysql_query.py @@ -19,7 +19,6 @@ Its output may be stored in a file or in a grain. - output: "/tmp/query_id.txt" """ - import os.path import sys @@ -57,7 +56,7 @@ def run_file( saltenv=None, check_db_exists=True, client_flags=None, - **connection_args + **connection_args, ): """ Execute an arbitrary query on the specified database @@ -104,7 +103,7 @@ def run_file( "name": name, "changes": {}, "result": True, - "comment": "Database {} is already present".format(database), + "comment": f"Database {database} is already present", } if client_flags is None: @@ -125,7 +124,7 @@ def run_file( query_file = __salt__["cp.cache_file"](query_file, saltenv=saltenv or __env__) if not os.path.exists(query_file): - ret["comment"] = "File {} does not exist".format(query_file) + ret["comment"] = f"File {query_file} does not exist" ret["result"] = False return ret @@ -138,7 +137,7 @@ def run_file( return ret ret["result"] = None - ret["comment"] = "Database {} is not present".format(database) + ret["comment"] = f"Database {database} is not present" return ret # Check if execution needed @@ -253,7 +252,7 @@ def run( overwrite=True, check_db_exists=True, client_flags=None, - **connection_args + **connection_args, ): """ Execute an arbitrary query on the specified database @@ -295,7 +294,7 @@ def run( "name": name, "changes": {}, "result": True, - "comment": "Database {} is already present".format(database), + "comment": f"Database {database} is already present", } if client_flags is None: @@ -316,7 +315,7 @@ def run( return ret ret["result"] = None - ret["comment"] = "Database {} is not present".format(name) + ret["comment"] = f"Database {name} is not present" return ret # Check if execution needed @@ -414,7 +413,7 @@ def run( else: for col, val in query_result.items(): output_file.write( - salt.utils.stringutils.to_str("{}:{}\n".format(col, val)) + salt.utils.stringutils.to_str(f"{col}:{val}\n") ) else: ret["changes"]["query"] = "Executed" diff --git a/salt/states/mysql_user.py b/salt/states/mysql_user.py index 61f2caa936a..1c54de4ec5c 100644 --- a/salt/states/mysql_user.py +++ b/salt/states/mysql_user.py @@ -73,7 +73,7 @@ def present( unix_socket=False, password_column=None, auth_plugin="mysql_native_password", - **connection_args + **connection_args, ): """ Ensure that the named user is present with the specified properties. A @@ -117,7 +117,7 @@ def present( "name": name, "changes": {}, "result": True, - "comment": "User {}@{} is already present".format(name, host), + "comment": f"User {name}@{host} is already present", } passwordless = not any((password, password_hash)) @@ -138,7 +138,7 @@ def present( passwordless=True, unix_socket=unix_socket, password_column=password_column, - **connection_args + **connection_args, ): if allow_passwordless: ret["comment"] += " with passwordless login" @@ -157,7 +157,7 @@ def present( password_hash, unix_socket=unix_socket, password_column=password_column, - **connection_args + **connection_args, ): if auth_plugin == "mysql_native_password": ret["comment"] += " with the desired password" @@ -180,7 +180,7 @@ def present( # The user is present, change the password if __opts__["test"]: - ret["comment"] = "Password for user {}@{} is set to be ".format(name, host) + ret["comment"] = f"Password for user {name}@{host} is set to be " ret["result"] = None if passwordless: ret["comment"] += "cleared" @@ -198,7 +198,7 @@ def present( password_hash, allow_passwordless, unix_socket, - **connection_args + **connection_args, ): ret["comment"] = "Password for user {}@{} has been {}".format( name, host, "cleared" if passwordless else "changed" @@ -210,7 +210,7 @@ def present( ) err = _get_mysql_error() if err is not None: - ret["comment"] += " ({})".format(err) + ret["comment"] += f" ({err})" if passwordless and not salt.utils.data.is_true(allow_passwordless): ret["comment"] += ( ". Note: allow_passwordless must be True " @@ -227,7 +227,7 @@ def present( # The user is not present, make it! if __opts__["test"]: - ret["comment"] = "User {}@{} is set to be added".format(name, host) + ret["comment"] = f"User {name}@{host} is set to be added" ret["result"] = None if allow_passwordless: ret["comment"] += " with passwordless login" @@ -247,19 +247,19 @@ def present( unix_socket=unix_socket, password_column=password_column, auth_plugin=auth_plugin, - **connection_args + **connection_args, ): - ret["comment"] = "The user {}@{} has been added".format(name, host) + ret["comment"] = f"The user {name}@{host} has been added" if allow_passwordless: ret["comment"] += " with passwordless login" if unix_socket: ret["comment"] += " using unix_socket" ret["changes"][name] = "Present" else: - ret["comment"] = "Failed to create user {}@{}".format(name, host) + ret["comment"] = f"Failed to create user {name}@{host}" err = _get_mysql_error() if err is not None: - ret["comment"] += " ({})".format(err) + ret["comment"] += f" ({err})" ret["result"] = False return ret @@ -278,10 +278,10 @@ def absent(name, host="localhost", **connection_args): if __salt__["mysql.user_exists"](name, host, **connection_args): if __opts__["test"]: ret["result"] = None - ret["comment"] = "User {}@{} is set to be removed".format(name, host) + ret["comment"] = f"User {name}@{host} is set to be removed" return ret if __salt__["mysql.user_remove"](name, host, **connection_args): - ret["comment"] = "User {}@{} has been removed".format(name, host) + ret["comment"] = f"User {name}@{host} has been removed" ret["changes"][name] = "Absent" return ret else: diff --git a/salt/states/netconfig.py b/salt/states/netconfig.py index 2b050e8abee..17870ab4afd 100644 --- a/salt/states/netconfig.py +++ b/salt/states/netconfig.py @@ -67,7 +67,7 @@ def _update_config( commit=True, debug=False, replace=False, - **template_vars + **template_vars, ): """ Call the necessary functions in order to execute the state. @@ -92,7 +92,7 @@ def _update_config( commit=commit, debug=debug, replace=replace, - **template_vars + **template_vars, ) @@ -275,7 +275,7 @@ def saved( win_deny_perms=None, win_inheritance=True, win_perms_reset=False, - **kwargs + **kwargs, ): """ .. versionadded:: 2019.2.0 @@ -452,7 +452,7 @@ def saved( win_deny_perms=win_deny_perms, win_inheritance=win_inheritance, win_perms_reset=win_perms_reset, - **kwargs + **kwargs, ) @@ -475,7 +475,7 @@ def managed( commit_at=None, revert_in=None, revert_at=None, - **template_vars + **template_vars, ): """ Manages the configuration on network devices. @@ -851,7 +851,7 @@ def managed( revert_at=revert_at, debug=debug, replace=replace, - **template_vars + **template_vars, ) return salt.utils.napalm.loaded_ret(ret, config_update_ret, test, debug) @@ -877,7 +877,7 @@ def commit_cancelled(name): """ cancelled = {"name": name, "result": None, "changes": {}, "comment": ""} if __opts__["test"]: - cancelled["comment"] = "It would cancel commit #{}".format(name) + cancelled["comment"] = f"It would cancel commit #{name}" return cancelled ret = __salt__["net.cancel_commit"](name) cancelled.update(ret) @@ -904,7 +904,7 @@ def commit_confirmed(name): """ confirmed = {"name": name, "result": None, "changes": {}, "comment": ""} if __opts__["test"]: - confirmed["comment"] = "It would confirm commit #{}".format(name) + confirmed["comment"] = f"It would confirm commit #{name}" return confirmed ret = __salt__["net.confirm_commit"](name) confirmed.update(ret) diff --git a/salt/states/netntp.py b/salt/states/netntp.py index 27a8b09713f..561b5bbda12 100644 --- a/salt/states/netntp.py +++ b/salt/states/netntp.py @@ -80,21 +80,18 @@ def _default_ret(name): def _retrieve_ntp_peers(): - """Retrieves configured NTP peers""" return __salt__["ntp.peers"]() def _retrieve_ntp_servers(): - """Retrieves configured NTP servers""" return __salt__["ntp.servers"]() def _check(peers): - """Checks whether the input is a valid list of peers and transforms domain names into IP Addresses""" if not isinstance(peers, list): @@ -141,28 +138,24 @@ def _clean(lst): def _set_ntp_peers(peers): - """Calls ntp.set_peers.""" return __salt__["ntp.set_peers"](*peers, commit=False) def _set_ntp_servers(servers): - """Calls ntp.set_servers.""" return __salt__["ntp.set_servers"](*servers, commit=False) def _delete_ntp_peers(peers): - """Calls ntp.delete_peers.""" return __salt__["ntp.delete_peers"](*peers, commit=False) def _delete_ntp_servers(servers): - """Calls ntp.delete_servers.""" return __salt__["ntp.delete_servers"](*servers, commit=False) @@ -185,7 +178,7 @@ def _check_diff_and_configure(fun_name, peers_servers, name="peers"): if name not in _options: return _ret - _retrieve_fun = "_retrieve_ntp_{what}".format(what=name) + _retrieve_fun = f"_retrieve_ntp_{name}" ntp_list_output = _exec_fun( _retrieve_fun ) # contains only IP Addresses as dictionary keys @@ -202,7 +195,7 @@ def _check_diff_and_configure(fun_name, peers_servers, name="peers"): if configured_ntp_list == desired_ntp_list: _ret.update( { - "comment": "NTP {what} already configured as needed.".format(what=name), + "comment": f"NTP {name} already configured as needed.", "result": True, } ) @@ -238,7 +231,7 @@ def _check_diff_and_configure(fun_name, peers_servers, name="peers"): comment = "" if list_to_set: - _set_fun = "_set_ntp_{what}".format(what=name) + _set_fun = f"_set_ntp_{name}" _set = _exec_fun(_set_fun, list_to_set) if _set.get("result"): expected_config_change = True @@ -249,7 +242,7 @@ def _check_diff_and_configure(fun_name, peers_servers, name="peers"): ) if list_to_delete: - _delete_fun = "_delete_ntp_{what}".format(what=name) + _delete_fun = f"_delete_ntp_{name}" _removed = _exec_fun(_delete_fun, list_to_delete) if _removed.get("result"): expected_config_change = True @@ -276,7 +269,6 @@ def _check_diff_and_configure(fun_name, peers_servers, name="peers"): def managed(name, peers=None, servers=None): - """ Manages the configuration of NTP peers and servers on the device, as specified in the state SLS file. NTP entities not specified in these lists will be removed whilst entities not configured on the device will be set. @@ -334,15 +326,15 @@ def managed(name, peers=None, servers=None): return ret # just exit if isinstance(peers, list) and not _check(peers): # check and clean peers - ret[ - "comment" - ] = "NTP peers must be a list of valid IP Addresses or Domain Names" + ret["comment"] = ( + "NTP peers must be a list of valid IP Addresses or Domain Names" + ) return ret if isinstance(servers, list) and not _check(servers): # check and clean servers - ret[ - "comment" - ] = "NTP servers must be a list of valid IP Addresses or Domain Names" + ret["comment"] = ( + "NTP servers must be a list of valid IP Addresses or Domain Names" + ) return ret # ----- Retrieve existing NTP peers and determine peers to be added/removed ---------------------------------------> diff --git a/salt/states/netsnmp.py b/salt/states/netsnmp.py index 54dbf7887d3..be2c4ccec5d 100644 --- a/salt/states/netsnmp.py +++ b/salt/states/netsnmp.py @@ -60,7 +60,6 @@ def __virtual__(): def _ordered_dict_to_dict(config): - """ Forced the datatype to dict, in case OrderedDict is used. """ @@ -69,7 +68,6 @@ def _ordered_dict_to_dict(config): def _expand_config(config, defaults): - """ Completed the values of the expected config for the edge cases with the default values. """ @@ -79,7 +77,6 @@ def _expand_config(config, defaults): def _valid_dict(dic): - """ Valid dictionary? """ @@ -88,7 +85,6 @@ def _valid_dict(dic): def _valid_str(value): - """ Valid str? """ @@ -97,7 +93,6 @@ def _valid_str(value): def _community_defaults(): - """ Returns the default values of a community. """ @@ -106,7 +101,6 @@ def _community_defaults(): def _clear_community_details(community_details): - """ Clears community details. """ @@ -126,7 +120,6 @@ def _clear_community_details(community_details): def _str_elem(config, key): - """ Re-adds the value of a specific key in the dict, only in case of valid str value. """ @@ -137,7 +130,6 @@ def _str_elem(config, key): def _check_config(config): - """ Checks the desired config and clears interesting details. """ @@ -187,7 +179,6 @@ def _check_config(config): def _retrieve_device_config(): - """ Retrieves the SNMP config from the device. """ @@ -196,7 +187,6 @@ def _retrieve_device_config(): def _create_diff_action(diff, diff_key, key, value): - """ DRY to build diff parts (added, removed, updated). """ @@ -207,7 +197,6 @@ def _create_diff_action(diff, diff_key, key, value): def _create_diff(diff, fun, key, prev, curr): - """ Builds the diff dictionary. """ @@ -221,7 +210,6 @@ def _create_diff(diff, fun, key, prev, curr): def _compute_diff(existing, expected): - """ Computes the differences between the existing and the expected SNMP config. """ @@ -240,7 +228,6 @@ def _compute_diff(existing, expected): def _configure(changes): - """ Calls the configuration template to apply the configuration changes on the device. """ @@ -259,7 +246,7 @@ def _configure(changes): _chassis_id = _updated_changes.get("chassis_id", "") if key == "removed": fun = "remove_config" - _ret = __salt__["snmp.{fun}".format(fun=fun)]( + _ret = __salt__[f"snmp.{fun}"]( location=_location, contact=_contact, community=_community, @@ -279,7 +266,6 @@ def _configure(changes): def managed(name, config=None, defaults=None): - """ Configures the SNMP on the device as specified in the SLS file. diff --git a/salt/states/netusers.py b/salt/states/netusers.py index 9120ce358aa..350fe5b471c 100644 --- a/salt/states/netusers.py +++ b/salt/states/netusers.py @@ -54,21 +54,18 @@ def __virtual__(): def _retrieve_users(): - """Retrieves configured users""" return __salt__["users.config"]() def _ordered_dict_to_dict(probes): - """.""" return salt.utils.json.loads(salt.utils.json.dumps(probes)) def _expand_users(device_users, common_users): - """Creates a longer list of accepted users on the device.""" expected_users = copy.deepcopy(common_users) @@ -78,7 +75,6 @@ def _expand_users(device_users, common_users): def _check_users(users): - """Checks if the input dictionary of users is valid.""" messg = "" @@ -87,7 +83,7 @@ def _check_users(users): for user, user_details in users.items(): if not user_details: valid = False - messg += "Please provide details for username {user}.\n".format(user=user) + messg += f"Please provide details for username {user}.\n" continue if not ( isinstance(user_details.get("level"), int) @@ -103,7 +99,6 @@ def _check_users(users): def _compute_diff(configured, expected): - """Computes the differences between the actual config and the expected config""" diff = {"add": {}, "update": {}, "remove": {}} @@ -135,21 +130,18 @@ def _compute_diff(configured, expected): def _set_users(users): - """Calls users.set_users.""" return __salt__["users.set_users"](users, commit=False) def _update_users(users): - """Calls users.set_users.""" return __salt__["users.set_users"](users, commit=False) def _delete_users(users): - """Calls users.delete_users.""" return __salt__["users.delete_users"](users, commit=False) @@ -161,7 +153,6 @@ def _delete_users(users): def managed(name, users=None, defaults=None): - """ Manages the configuration of the users on the device, as specified in the state SLS file. Users not defined in that file will be removed whilst users not configured on the device, will be added. diff --git a/salt/states/network.py b/salt/states/network.py index b942a7e58d4..383b1b69243 100644 --- a/salt/states/network.py +++ b/salt/states/network.py @@ -482,7 +482,7 @@ def managed(name, enabled=True, **kwargs): "name": name, "changes": {}, "result": True, - "comment": "Interface {} is up to date.".format(name), + "comment": f"Interface {name} is up to date.", } if "test" not in kwargs: kwargs["test"] = __opts__.get("test", False) @@ -513,7 +513,7 @@ def managed(name, enabled=True, **kwargs): pass if not old and new: ret["result"] = None - ret["comment"] = "Interface {} is set to be added.".format(name) + ret["comment"] = f"Interface {name} is set to be added." elif old != new: diff = difflib.unified_diff(old, new, lineterm="") ret["result"] = None @@ -522,12 +522,12 @@ def managed(name, enabled=True, **kwargs): ) else: if not old and new: - ret["comment"] = "Interface {} added.".format(name) + ret["comment"] = f"Interface {name} added." ret["changes"]["interface"] = "Added network interface." apply_ranged_setting = True elif old != new: diff = difflib.unified_diff(old, new, lineterm="") - ret["comment"] = "Interface {} updated.".format(name) + ret["comment"] = f"Interface {name} updated." ret["changes"]["interface"] = "\n".join(diff) apply_ranged_setting = True except AttributeError as error: @@ -554,19 +554,19 @@ 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: - ret["comment"] = "Bond interface {} added.".format(name) - ret["changes"]["bond"] = "Added bond {}.".format(name) + ret["comment"] = f"Bond interface {name} added." + ret["changes"]["bond"] = f"Added bond {name}." apply_ranged_setting = True elif old != new: diff = difflib.unified_diff(old, new, lineterm="") - ret["comment"] = "Bond interface {} updated.".format(name) + ret["comment"] = f"Bond interface {name} updated." ret["changes"]["bond"] = "\n".join(diff) apply_ranged_setting = True except AttributeError as error: @@ -628,15 +628,15 @@ def managed(name, enabled=True, **kwargs): __salt__["ip.up"](name, iface_type) ret["changes"][ "status" - ] = "Interface {} restart to validate".format(name) + ] = f"Interface {name} restart to validate" else: __salt__["ip.up"](name, iface_type) - ret["changes"]["status"] = "Interface {} is up".format(name) + ret["changes"]["status"] = f"Interface {name} is up" else: if "noifupdown" not in kwargs: if interface_status: __salt__["ip.down"](name, iface_type) - ret["changes"]["status"] = "Interface {} down".format(name) + ret["changes"]["status"] = f"Interface {name} down" except Exception as error: # pylint: disable=broad-except ret["result"] = False ret["comment"] = str(error) @@ -648,7 +648,7 @@ def managed(name, enabled=True, **kwargs): if "slaves" in kwargs and kwargs["slaves"]: # Check that there are new slaves for this master present_slaves = __salt__["cmd.run"]( - ["cat", "/sys/class/net/{}/bonding/slaves".format(name)] + ["cat", f"/sys/class/net/{name}/bonding/slaves"] ).split() if isinstance(kwargs["slaves"], list): desired_slaves = kwargs["slaves"] @@ -670,10 +670,10 @@ def managed(name, enabled=True, **kwargs): __salt__["cmd.run"](cmd, python_shell=False) else: log.error("Command 'ifenslave' not found") - ret["changes"][ - "enslave" - ] = "Added slaves '{}' to master '{}'".format( - " ".join(missing_slaves), name + ret["changes"]["enslave"] = ( + "Added slaves '{}' to master '{}'".format( + " ".join(missing_slaves), name + ) ) else: log.info( @@ -706,7 +706,7 @@ def routes(name, **kwargs): "name": name, "changes": {}, "result": True, - "comment": "Interface {} routes are up to date.".format(name), + "comment": f"Interface {name} routes are up to date.", } apply_routes = False if "test" not in kwargs: @@ -721,25 +721,25 @@ def routes(name, **kwargs): return ret if not old and new: ret["result"] = None - ret["comment"] = "Interface {} routes are set to be added.".format(name) + ret["comment"] = f"Interface {name} routes are set to be added." return ret 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: apply_routes = True - ret["comment"] = "Interface {} routes added.".format(name) - ret["changes"]["network_routes"] = "Added interface {} routes.".format(name) + ret["comment"] = f"Interface {name} routes added." + ret["changes"]["network_routes"] = f"Added interface {name} routes." elif old != new: diff = difflib.unified_diff(old, new, lineterm="") apply_routes = True - ret["comment"] = "Interface {} routes updated.".format(name) + ret["comment"] = f"Interface {name} routes updated." ret["changes"]["network_routes"] = "\n".join(diff) except AttributeError as error: ret["result"] = False @@ -791,10 +791,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/neutron_network.py b/salt/states/neutron_network.py index 30e6cfb050f..2dc5bc0a3a0 100644 --- a/salt/states/neutron_network.py +++ b/salt/states/neutron_network.py @@ -28,7 +28,6 @@ Example States - project: project1 """ - __virtualname__ = "neutron_network" @@ -99,7 +98,7 @@ def present(name, auth=None, **kwargs): del kwargs["project"] else: ret["result"] = False - ret["comment"] = "Project:{} not found.".format(projectname) + ret["comment"] = f"Project:{projectname} not found." return ret network = __salt__["neutronng.network_create"](**kwargs) diff --git a/salt/states/neutron_secgroup.py b/salt/states/neutron_secgroup.py index 045f413c945..144178bbc2d 100644 --- a/salt/states/neutron_secgroup.py +++ b/salt/states/neutron_secgroup.py @@ -34,7 +34,6 @@ Example States - project_name: Project1 """ - __virtualname__ = "neutron_secgroup" diff --git a/salt/states/neutron_secgroup_rule.py b/salt/states/neutron_secgroup_rule.py index db4721fc79e..219455a8447 100644 --- a/salt/states/neutron_secgroup_rule.py +++ b/salt/states/neutron_secgroup_rule.py @@ -28,7 +28,6 @@ Example States - project_id: 1dcac318a83b4610b7a7f7ba01465548 """ - __virtualname__ = "neutron_secgroup_rule" @@ -96,7 +95,7 @@ def present(name, auth=None, **kwargs): if secgroup is None: ret["result"] = False ret["changes"] = ({},) - ret["comment"] = "Security Group does not exist {}".format(name) + ret["comment"] = f"Security Group does not exist {name}" return ret # we have to search through all secgroup rules for a possible match diff --git a/salt/states/neutron_subnet.py b/salt/states/neutron_subnet.py index 30c69992b58..60e241e69ef 100644 --- a/salt/states/neutron_subnet.py +++ b/salt/states/neutron_subnet.py @@ -46,7 +46,6 @@ Example States - ip_version: 6 """ - __virtualname__ = "neutron_subnet" diff --git a/salt/states/nexus.py b/salt/states/nexus.py index a823b0a47d0..10d71db4cd8 100644 --- a/salt/states/nexus.py +++ b/salt/states/nexus.py @@ -4,7 +4,6 @@ This state downloads artifacts from Nexus 3.x. .. versionadded:: 2018.3.0 """ - import logging log = logging.getLogger(__name__) diff --git a/salt/states/nfs_export.py b/salt/states/nfs_export.py index ad572739d7f..27d6b853d54 100644 --- a/salt/states/nfs_export.py +++ b/salt/states/nfs_export.py @@ -140,14 +140,14 @@ def present(name, clients=None, hosts=None, options=None, exports="/etc/exports" if path in old: if old[path] == clients: ret["result"] = True - ret["comment"] = "Export {} already configured".format(path) + ret["comment"] = f"Export {path} already configured" return ret ret["changes"]["new"] = clients ret["changes"]["old"] = old[path] if __opts__["test"]: ret["result"] = None - ret["comment"] = "Export {} would be changed".format(path) + ret["comment"] = f"Export {path} would be changed" return ret __salt__["nfs3.del_export"](exports, path) @@ -157,7 +157,7 @@ def present(name, clients=None, hosts=None, options=None, exports="/etc/exports" ret["changes"]["new"] = clients if __opts__["test"]: ret["result"] = None - ret["comment"] = "Export {} would be added".format(path) + ret["comment"] = f"Export {path} would be added" return ret add_export = __salt__["nfs3.add_export"] @@ -186,7 +186,7 @@ def absent(name, exports="/etc/exports"): old = __salt__["nfs3.list_exports"](exports) if path in old: if __opts__["test"]: - ret["comment"] = "Export {} would be removed".format(path) + ret["comment"] = f"Export {path} would be removed" ret["changes"][path] = old[path] ret["result"] = None return ret @@ -196,12 +196,12 @@ def absent(name, exports="/etc/exports"): if not try_reload["result"]: ret["comment"] = try_reload["stderr"] else: - ret["comment"] = "Export {} removed".format(path) + ret["comment"] = f"Export {path} removed" ret["result"] = try_reload["result"] ret["changes"][path] = old[path] else: - ret["comment"] = "Export {} already absent".format(path) + ret["comment"] = f"Export {path} already absent" ret["result"] = True return ret diff --git a/salt/states/nftables.py b/salt/states/nftables.py index 71c6e997eed..fa9a33fb929 100644 --- a/salt/states/nftables.py +++ b/salt/states/nftables.py @@ -157,10 +157,10 @@ def chain_present( return ret if __opts__["test"]: - ret[ - "comment" - ] = "nftables chain {} would be created in table {} for family {}".format( - name, table, family + ret["comment"] = ( + "nftables chain {} would be created in table {} for family {}".format( + name, table, family + ) ) return ret @@ -198,10 +198,10 @@ def chain_absent(name, table="filter", family="ipv4"): chain_check = __salt__["nftables.check_chain"](table, name, family) if not chain_check: ret["result"] = True - ret[ - "comment" - ] = "nftables {} chain is already absent in {} table for {}".format( - name, table, family + ret["comment"] = ( + "nftables {} chain is already absent in {} table for {}".format( + name, table, family + ) ) return ret @@ -211,10 +211,10 @@ def chain_absent(name, table="filter", family="ipv4"): if command is True: ret["changes"] = {"locale": name} ret["result"] = True - ret[ - "comment" - ] = "nftables {} chain in {} table delete success for {}".format( - name, table, family + ret["comment"] = ( + "nftables {} chain in {} table delete success for {}".format( + name, table, family + ) ) else: ret["result"] = False @@ -286,18 +286,18 @@ 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: ret["result"] = False - ret[ - "comment" - ] = "Failed to set nftables rule for {}.\nAttempted rule was {} for {}.\n{}".format( - name, command.strip(), family, res["comment"] + ret["comment"] = ( + "Failed to set nftables rule for {}.\nAttempted rule was {} for {}.\n{}".format( + name, command.strip(), family, res["comment"] + ) ) return ret @@ -361,18 +361,18 @@ 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: ret["result"] = False - ret[ - "comment" - ] = "Failed to set nftables rule for {}.\nAttempted rule was {}".format( - name, command.strip() + ret["comment"] = ( + "Failed to set nftables rule for {}.\nAttempted rule was {}".format( + name, command.strip() + ) ) return ret @@ -438,22 +438,22 @@ def delete(name, family="ipv4", **kwargs): if res["result"]: ret["changes"] = {"locale": name} ret["result"] = True - ret["comment"] = "Delete nftables rule for {} {}".format(name, command.strip()) + ret["comment"] = f"Delete nftables rule for {name} {command.strip()}" 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: ret["result"] = False - ret[ - "comment" - ] = "Failed to delete nftables rule for {}.\nAttempted rule was {}".format( - name, command.strip() + ret["comment"] = ( + "Failed to delete nftables rule for {}.\nAttempted rule was {}".format( + name, command.strip() + ) ) return ret @@ -492,10 +492,10 @@ def flush(name, family="ipv4", ignore_absence=False, **kwargs): check_table = __salt__["nftables.check_table"](kwargs["table"], family=family) if not ignore_absence and not check_table["result"]: ret["result"] = False - ret[ - "comment" - ] = "Failed to flush table {} in family {}, table does not exist.".format( - kwargs["table"], family + ret["comment"] = ( + "Failed to flush table {} in family {}, table does not exist.".format( + kwargs["table"], family + ) ) return ret @@ -562,10 +562,10 @@ def set_policy(name, table="filter", family="ipv4", **kwargs): if (policy or "").lower() == kwargs["policy"].lower(): ret["result"] = True - ret[ - "comment" - ] = "nftables default policy for chain {} on table {} for {} already set to {}".format( - kwargs["chain"], table, family, kwargs["policy"] + ret["comment"] = ( + "nftables default policy for chain {} on table {} for {} already set to {}".format( + kwargs["chain"], table, family, kwargs["policy"] + ) ) return ret @@ -590,10 +590,10 @@ def set_policy(name, table="filter", family="ipv4", **kwargs): __salt__["nftables.save"]( filename=kwargs.get("save_filename"), family=family ) - ret[ - "comment" - ] = "Set and saved default policy for {} to {} family {}".format( - kwargs["chain"], kwargs["policy"], family + ret["comment"] = ( + "Set and saved default policy for {} to {} family {}".format( + kwargs["chain"], kwargs["policy"], family + ) ) else: ret["result"] = False @@ -642,7 +642,7 @@ def table_present(name, family="ipv4", **kwargs): ) else: ret["result"] = False - ret["comment"] = "Failed to create table {} for family {}".format(name, family) + ret["comment"] = f"Failed to create table {name} for family {family}" return ret @@ -687,6 +687,6 @@ def table_absent(name, family="ipv4", **kwargs): ) else: ret["result"] = False - ret["comment"] = "Failed to delete table {} from family {}".format(name, family) + ret["comment"] = f"Failed to delete table {name} from family {family}" return ret diff --git a/salt/states/npm.py b/salt/states/npm.py index 535a516a1d4..1e8b942f90c 100644 --- a/salt/states/npm.py +++ b/salt/states/npm.py @@ -18,7 +18,6 @@ for the package which provides npm (simply ``npm`` in most cases). Example: - pkg: npm """ - import re from salt.exceptions import CommandExecutionError, CommandNotFoundError @@ -95,7 +94,7 @@ def installed( installed_pkgs = __salt__["npm.list"](dir=dir, runas=user, env=env, depth=0) except (CommandNotFoundError, CommandExecutionError) as err: ret["result"] = False - ret["comment"] = "Error looking up '{}': {}".format(name, err) + ret["comment"] = f"Error looking up '{name}': {err}" return ret else: installed_pkgs = {p: info for p, info in installed_pkgs.items()} @@ -239,26 +238,26 @@ def removed(name, dir=None, user=None): installed_pkgs = __salt__["npm.list"](dir=dir, depth=0) except (CommandExecutionError, CommandNotFoundError) as err: ret["result"] = False - ret["comment"] = "Error uninstalling '{}': {}".format(name, err) + ret["comment"] = f"Error uninstalling '{name}': {err}" return ret if name not in installed_pkgs: ret["result"] = True - ret["comment"] = "Package '{}' is not installed".format(name) + ret["comment"] = f"Package '{name}' is not installed" return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Package '{}' is set to be removed".format(name) + ret["comment"] = f"Package '{name}' is set to be removed" return ret if __salt__["npm.uninstall"](pkg=name, dir=dir, runas=user): ret["result"] = True ret["changes"][name] = "Removed" - ret["comment"] = "Package '{}' was successfully removed".format(name) + ret["comment"] = f"Package '{name}' was successfully removed" else: ret["result"] = False - ret["comment"] = "Error removing package '{}'".format(name) + ret["comment"] = f"Error removing package '{name}'" return ret @@ -284,20 +283,20 @@ def bootstrap(name, user=None, silent=True): if call: ret["result"] = None ret["changes"] = {"old": [], "new": call} - ret["comment"] = "{} is set to be bootstrapped".format(name) + ret["comment"] = f"{name} is set to be bootstrapped" else: ret["result"] = True - ret["comment"] = "{} is already bootstrapped".format(name) + ret["comment"] = f"{name} is already bootstrapped" except (CommandNotFoundError, CommandExecutionError) as err: ret["result"] = False - ret["comment"] = "Error Bootstrapping '{}': {}".format(name, err) + ret["comment"] = f"Error Bootstrapping '{name}': {err}" return ret try: call = __salt__["npm.install"](dir=name, runas=user, pkg=None, silent=silent) except (CommandNotFoundError, CommandExecutionError) as err: ret["result"] = False - ret["comment"] = "Error Bootstrapping '{}': {}".format(name, err) + ret["comment"] = f"Error Bootstrapping '{name}': {err}" return ret if not call: @@ -351,11 +350,11 @@ def cache_cleaned(name=None, user=None, force=False): all_cached_pkgs = __salt__["npm.cache_list"](path=None, runas=user) # The first package is always the cache path cache_root_path = all_cached_pkgs[0] - specific_pkg = "{}/{}/".format(cache_root_path, name) + specific_pkg = f"{cache_root_path}/{name}/" if specific_pkg not in cached_pkgs: ret["result"] = True - ret["comment"] = "Package {} is not in the cache".format(name) + ret["comment"] = f"Package {name} is not in the cache" return ret if __opts__["test"]: diff --git a/salt/states/nxos.py b/salt/states/nxos.py index 6888413e859..6d413d45548 100644 --- a/salt/states/nxos.py +++ b/salt/states/nxos.py @@ -352,7 +352,7 @@ def replace(name, repl, full_match=False): ret = {"name": name, "result": False, "changes": {}, "comment": ""} if full_match is False: - search = "^.*{}.*$".format(name) + search = f"^.*{name}.*$" else: search = name @@ -376,7 +376,7 @@ def replace(name, repl, full_match=False): if matches: ret["result"] = False - ret["comment"] = 'Failed to replace all instances of "{}"'.format(name) + ret["comment"] = f'Failed to replace all instances of "{name}"' else: ret["result"] = True ret["comment"] = 'Successfully replaced all instances of "{}" with "{}"'.format( diff --git a/salt/states/nxos_upgrade.py b/salt/states/nxos_upgrade.py index daa22f6fcfc..f4960b777be 100644 --- a/salt/states/nxos_upgrade.py +++ b/salt/states/nxos_upgrade.py @@ -90,7 +90,7 @@ def image_running(name, system_image, kickstart_image=None, issu=True, **kwargs) system_image=system_image, kickstart_image=kickstart_image, issu=issu, - **kwargs + **kwargs, ) if upgrade["upgrade_in_progress"]: @@ -99,7 +99,7 @@ def image_running(name, system_image, kickstart_image=None, issu=True, **kwargs) ret["comment"] = "NX-OS Device Now Being Upgraded - See Change Details Below" elif upgrade["succeeded"]: ret["result"] = upgrade["succeeded"] - ret["comment"] = "NX-OS Device Running Image: {}".format(_version_info()) + ret["comment"] = f"NX-OS Device Running Image: {_version_info()}" else: ret["comment"] = "Upgrade Failed: {}.".format(upgrade["error_data"]) diff --git a/salt/states/openstack_config.py b/salt/states/openstack_config.py index e9154d57a4f..bad221a802a 100644 --- a/salt/states/openstack_config.py +++ b/salt/states/openstack_config.py @@ -8,7 +8,6 @@ Manage OpenStack configuration file settings. """ - from salt.exceptions import CommandExecutionError @@ -113,7 +112,7 @@ def absent(name, filename, section, parameter=None): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Value '{}' is set to be deleted.".format(old_value) + ret["comment"] = f"Value '{old_value}' is set to be deleted." return ret __salt__["openstack_config.delete"]( diff --git a/salt/states/openvswitch_port.py b/salt/states/openvswitch_port.py index 3ca769b1e37..a4591c6da12 100644 --- a/salt/states/openvswitch_port.py +++ b/salt/states/openvswitch_port.py @@ -47,24 +47,24 @@ def present( comments = {} - comments["comment_bridge_notexists"] = "Bridge {} does not exist.".format(bridge) - comments["comment_port_exists"] = "Port {} already exists.".format(name) + comments["comment_bridge_notexists"] = f"Bridge {bridge} does not exist." + comments["comment_port_exists"] = f"Port {name} already exists." comments["comment_port_created"] = "Port {} created on bridge {}.".format( name, bridge ) - comments[ - "comment_port_notcreated" - ] = "Unable to create port {} on bridge {}.".format(name, bridge) + comments["comment_port_notcreated"] = ( + f"Unable to create port {name} on bridge {bridge}." + ) comments["changes_port_created"] = { name: { - "old": "No port named {} present.".format(name), - "new": "Created port {1} on bridge {0}.".format(bridge, name), + "old": f"No port named {name} present.", + "new": f"Created port {name} on bridge {bridge}.", } } - comments[ - "comment_port_internal" - ] = "Port {} already exists, but interface type has been changed to internal.".format( - name + comments["comment_port_internal"] = ( + "Port {} already exists, but interface type has been changed to internal.".format( + name + ) ) comments["changes_port_internal"] = {"internal": {"old": False, "new": True}} comments["comment_port_internal_not_changed"] = ( @@ -76,23 +76,23 @@ def present( comments["comment_invalid_ip"] = "Remote is not valid ip address." if tunnel_type == "vlan": comments["comment_vlan_invalid_id"] = "VLANs id must be between 0 and 4095." - comments[ - "comment_vlan_invalid_name" - ] = "Could not find network interface {}.".format(name) - comments[ - "comment_vlan_port_exists" - ] = "Port {} with access to VLAN {} already exists on bridge {}.".format( - name, id, bridge + comments["comment_vlan_invalid_name"] = ( + f"Could not find network interface {name}." ) - comments[ - "comment_vlan_created" - ] = "Created port {} with access to VLAN {} on bridge {}.".format( - name, id, bridge + comments["comment_vlan_port_exists"] = ( + "Port {} with access to VLAN {} already exists on bridge {}.".format( + name, id, bridge + ) ) - comments[ - "comment_vlan_notcreated" - ] = "Unable to create port {} with access to VLAN {} on bridge {}.".format( - name, id, bridge + comments["comment_vlan_created"] = ( + "Created port {} with access to VLAN {} on bridge {}.".format( + name, id, bridge + ) + ) + comments["comment_vlan_notcreated"] = ( + "Unable to create port {} with access to VLAN {} on bridge {}.".format( + name, id, bridge + ) ) comments["changes_vlan_created"] = { name: { @@ -108,9 +108,9 @@ def present( } elif tunnel_type == "gre": - comments[ - "comment_gre_invalid_id" - ] = "Id of GRE tunnel must be an unsigned 32-bit integer." + comments["comment_gre_invalid_id"] = ( + "Id of GRE tunnel must be an unsigned 32-bit integer." + ) comments["comment_gre_interface_exists"] = ( "GRE tunnel interface {} with rempte ip {} and key {} " "already exists on bridge {}.".format(name, remote, id, bridge) @@ -139,9 +139,9 @@ def present( comments["comment_dstport"] = ( " (dst_port" + str(dst_port) + ")" if 0 < dst_port <= 65535 else "" ) - comments[ - "comment_vxlan_invalid_id" - ] = "Id of VXLAN tunnel must be an unsigned 64-bit integer." + comments["comment_vxlan_invalid_id"] = ( + "Id of VXLAN tunnel must be an unsigned 64-bit integer." + ) comments["comment_vxlan_interface_exists"] = ( "VXLAN tunnel interface {} with rempte ip {} and key {} " "already exists on bridge {}{}.".format( @@ -234,11 +234,7 @@ def present( 'dst_port="' + str(dst_port) + '", ' if 0 < dst_port <= 65535 else "" ) interface_attroptions = ( - '{{{0}key="'.format(opt_port) - + str(id) - + '", remote_ip="' - + str(remote) - + '"}' + f'{{{opt_port}key="' + str(id) + '", remote_ip="' + str(remote) + '"}' ) try: if ( @@ -388,16 +384,16 @@ def absent(name, bridge=None): # Comment and change messages comments = {} - comments["comment_bridge_notexists"] = "Bridge {} does not exist.".format(bridge) + comments["comment_bridge_notexists"] = f"Bridge {bridge} does not exist." comments["comment_port_notexists"] = "Port {} does not exist on bridge {}.".format( name, bridge ) - comments["comment_port_deleted"] = "Port {} deleted.".format(name) - comments["comment_port_notdeleted"] = "Unable to delete port {}.".format(name) + comments["comment_port_deleted"] = f"Port {name} deleted." + comments["comment_port_notdeleted"] = f"Unable to delete port {name}." comments["changes_port_deleted"] = { name: { - "old": "Port named {} may exist.".format(name), - "new": "Deleted port {}.".format(name), + "old": f"Port named {name} may exist.", + "new": f"Deleted port {name}.", } } diff --git a/salt/states/opsgenie.py b/salt/states/opsgenie.py index 8e80bf2ef90..f7cafcccfd9 100644 --- a/salt/states/opsgenie.py +++ b/salt/states/opsgenie.py @@ -75,10 +75,10 @@ def create_alert(name=None, api_key=None, reason=None, action_type="Create"): raise salt.exceptions.SaltInvocationError("API Key or Reason cannot be None.") if __opts__["test"] is True: - ret[ - "comment" - ] = 'Test: {} alert request will be processed using the API Key="{}".'.format( - action_type, api_key + ret["comment"] = ( + 'Test: {} alert request will be processed using the API Key="{}".'.format( + action_type, api_key + ) ) # Return ``None`` when running with ``test=true``. @@ -96,10 +96,10 @@ def create_alert(name=None, api_key=None, reason=None, action_type="Create"): response_text, response_status_code, ) - ret[ - "comment" - ] = 'Test: {} alert request will be processed using the API Key="{}".'.format( - action_type, api_key + ret["comment"] = ( + 'Test: {} alert request will be processed using the API Key="{}".'.format( + action_type, api_key + ) ) ret["result"] = True else: diff --git a/salt/states/pagerduty.py b/salt/states/pagerduty.py index bfdd82f28ac..2be04eff915 100644 --- a/salt/states/pagerduty.py +++ b/salt/states/pagerduty.py @@ -57,7 +57,7 @@ def create_event(name, details, service_key, profile): """ ret = {"name": name, "changes": {}, "result": None, "comment": ""} if __opts__["test"]: - ret["comment"] = "Need to create event: {}".format(name) + ret["comment"] = f"Need to create event: {name}" return ret __salt__["pagerduty.create_event"]( description=name, @@ -66,5 +66,5 @@ def create_event(name, details, service_key, profile): profile=profile, ) ret["result"] = True - ret["comment"] = "Created event: {}".format(name) + ret["comment"] = f"Created event: {name}" return ret diff --git a/salt/states/pagerduty_escalation_policy.py b/salt/states/pagerduty_escalation_policy.py index 44e663e4ea3..3b3594587d4 100644 --- a/salt/states/pagerduty_escalation_policy.py +++ b/salt/states/pagerduty_escalation_policy.py @@ -96,7 +96,7 @@ def present(profile="pagerduty", subdomain=None, api_key=None, **kwargs): if schedule: target_id = schedule["schedule"]["id"] if target_id is None: - raise Exception("unidentified target: {}".format(target)) + raise Exception(f"unidentified target: {target}") target["id"] = target_id r = __salt__["pagerduty_util.resource_present"]( @@ -106,7 +106,7 @@ def present(profile="pagerduty", subdomain=None, api_key=None, **kwargs): profile, subdomain, api_key, - **kwargs + **kwargs, ) return r @@ -143,7 +143,7 @@ def _diff(state_data, resource_object): else: resource_value = resource_object[k] if v != resource_value: - objects_differ = "{} {} {}".format(k, v, resource_value) + objects_differ = f"{k} {v} {resource_value}" break if objects_differ: diff --git a/salt/states/pagerduty_schedule.py b/salt/states/pagerduty_schedule.py index 75f705f6086..5947dbc4b0a 100644 --- a/salt/states/pagerduty_schedule.py +++ b/salt/states/pagerduty_schedule.py @@ -65,7 +65,7 @@ def present(profile="pagerduty", subdomain=None, api_key=None, **kwargs): api_key=api_key, ) if u is None: - raise Exception("unknown user: {}".format(user)) + raise Exception(f"unknown user: {user}") user["user"]["id"] = u["id"] r = __salt__["pagerduty_util.resource_present"]( "schedules", ["name", "id"], _diff, profile, subdomain, api_key, **kwargs diff --git a/salt/states/pagerduty_service.py b/salt/states/pagerduty_service.py index f615aff7a7b..f17c7ef6087 100644 --- a/salt/states/pagerduty_service.py +++ b/salt/states/pagerduty_service.py @@ -110,7 +110,7 @@ def _diff(state_data, resource_object): else: resource_value = resource_object[k] if v != resource_value: - objects_differ = "{} {} {}".format(k, v, resource_value) + objects_differ = f"{k} {v} {resource_value}" break if objects_differ: diff --git a/salt/states/panos.py b/salt/states/panos.py index fb915bbdb78..5ea57dbf0dd 100644 --- a/salt/states/panos.py +++ b/salt/states/panos.py @@ -108,10 +108,10 @@ def _build_members(members, anycheck=False): return "any" response = "" for m in members: - response += "{}".format(m) + response += f"{m}" return response else: - return "{}".format(members) + return f"{members}" def _default_ret(name): @@ -354,19 +354,19 @@ def address_exists( # Verify the arguments if ipnetmask: - element = "{}".format(ipnetmask) + element = f"{ipnetmask}" elif iprange: - element = "{}".format(iprange) + element = f"{iprange}" elif fqdn: - element = "{}".format(fqdn) + element = f"{fqdn}" else: ret.update({"comment": "A valid address type must be specified."}) return ret if description: - element += "{}".format(description) + element += f"{description}" - full_element = "{}".format(addressname, element) + full_element = f"{element}" new_address = xml.to_dict(ET.fromstring(full_element), True) @@ -467,15 +467,15 @@ def address_group_exists( # Verify the arguments if members: - element = "{}".format(_build_members(members, True)) + element = f"{_build_members(members, True)}" else: ret.update({"comment": "The group members must be provided."}) return ret if description: - element += "{}".format(description) + element += f"{description}" - full_element = "{}".format(groupname, element) + full_element = f"{element}" new_group = xml.to_dict(ET.fromstring(full_element), True) @@ -1117,19 +1117,19 @@ def security_rule_exists( # Build the rule element element = "" if sourcezone: - element += "{}".format(_build_members(sourcezone, True)) + element += f"{_build_members(sourcezone, True)}" else: ret.update({"comment": "The sourcezone field must be provided."}) return ret if destinationzone: - element += "{}".format(_build_members(destinationzone, True)) + element += f"{_build_members(destinationzone, True)}" else: ret.update({"comment": "The destinationzone field must be provided."}) return ret if source: - element += "{}".format(_build_members(source, True)) + element += f"{_build_members(source, True)}" else: ret.update({"comment": "The source field must be provided."}) return @@ -1151,13 +1151,13 @@ def security_rule_exists( return ret if service: - element += "{}".format(_build_members(service, True)) + element += f"{_build_members(service, True)}" else: ret.update({"comment": "The service field must be provided."}) return ret if action: - element += "{}".format(action) + element += f"{action}" else: ret.update({"comment": "The action field must be provided."}) return ret @@ -1169,10 +1169,10 @@ def security_rule_exists( element += "no" if description: - element += "{}".format(description) + element += f"{description}" if logsetting: - element += "{}".format(logsetting) + element += f"{logsetting}" if logstart is not None: if logstart: @@ -1201,7 +1201,7 @@ def security_rule_exists( # Build the profile settings profile_string = None if profilegroup: - profile_string = "{}".format(profilegroup) + profile_string = f"{profilegroup}" else: member_string = "" if datafilter: @@ -1212,16 +1212,16 @@ def security_rule_exists( ) if fileblock: member_string += ( - "{}".format(fileblock) + f"{fileblock}" ) if spyware: - member_string += "{}".format(spyware) + member_string += f"{spyware}" if urlfilter: member_string += ( - "{}".format(urlfilter) + f"{urlfilter}" ) if virus: - member_string += "{}".format(virus) + member_string += f"{virus}" if vulnerability: member_string += ( "{}".format( @@ -1235,12 +1235,12 @@ def security_rule_exists( ) ) if member_string != "": - profile_string = "{}".format(member_string) + profile_string = f"{member_string}" if profile_string: - element += "{}".format(profile_string) + element += f"{profile_string}" - full_element = "{}".format(rulename, element) + full_element = f"{element}" new_rule = xml.to_dict(ET.fromstring(full_element), True) @@ -1380,9 +1380,9 @@ def service_exists( element = "<{0}>{1}".format(protocol, port) if description: - element += "{}".format(description) + element += f"{description}" - full_element = "{}".format(servicename, element) + full_element = f"{element}" new_service = xml.to_dict(ET.fromstring(full_element), True) @@ -1483,15 +1483,15 @@ def service_group_exists( # Verify the arguments if members: - element = "{}".format(_build_members(members, True)) + element = f"{_build_members(members, True)}" else: ret.update({"comment": "The group members must be provided."}) return ret if description: - element += "{}".format(description) + element += f"{description}" - full_element = "{}".format(groupname, element) + full_element = f"{element}" new_group = xml.to_dict(ET.fromstring(full_element), True) diff --git a/salt/states/pbm.py b/salt/states/pbm.py index ae21462ea47..8b2c3eb2a4b 100644 --- a/salt/states/pbm.py +++ b/salt/states/pbm.py @@ -90,7 +90,6 @@ PyVmomi can be installed via pip: information. """ - import copy import logging import sys @@ -153,7 +152,7 @@ def default_vsan_policy_configured(name, policy): # All allowed proxies have a shim execution module with the same # name which implementes a get_details function # All allowed proxies have a vcenter detail - vcenter = __salt__["{}.get_details".format(proxy_type)]()["vcenter"] + vcenter = __salt__[f"{proxy_type}.get_details"]()["vcenter"] log.info("Running %s on vCenter '%s'", name, vcenter) log.trace("policy = %s", policy) changes_required = False @@ -215,7 +214,7 @@ def default_vsan_policy_configured(name, policy): if subprofile_differ.diffs: str_changes.extend( [ - " {}".format(change) + f" {change}" for change in subprofile_differ.changes_str.split("\n") ] ) @@ -223,7 +222,7 @@ def default_vsan_policy_configured(name, policy): str_changes.append(" capabilities:") str_changes.extend( [ - " {}".format(change) + f" {change}" for change in capabilities_differ.changes_str2.split( "\n" ) @@ -241,7 +240,7 @@ def default_vsan_policy_configured(name, policy): service_instance=si, ) comments.append( - "Updated the default VSAN policy in vCenter '{}'".format(vcenter) + f"Updated the default VSAN policy in vCenter '{vcenter}'" ) log.info(comments[-1]) @@ -320,7 +319,7 @@ def storage_policies_configured(name, policies): # All allowed proxies have a shim execution module with the same # name which implementes a get_details function # All allowed proxies have a vcenter detail - vcenter = __salt__["{}.get_details".format(proxy_type)]()["vcenter"] + vcenter = __salt__[f"{proxy_type}.get_details"]()["vcenter"] log.info("Running state '%s' on vCenter '%s'", name, vcenter) si = __salt__["vsphere.get_service_instance_via_proxy"]() current_policies = __salt__["vsphere.list_storage_policies"]( @@ -402,7 +401,7 @@ def storage_policies_configured(name, policies): if subprofile_differ.diffs: str_changes.extend( [ - " {}".format(change) + f" {change}" for change in subprofile_differ.changes_str.split( "\n" ) @@ -412,7 +411,7 @@ def storage_policies_configured(name, policies): str_changes.append(" capabilities:") str_changes.extend( [ - " {}".format(change) + f" {change}" for change in capabilities_differ.changes_str2.split( "\n" ) diff --git a/salt/states/pecl.py b/salt/states/pecl.py index a69a2ca1cb1..e690b5a01e9 100644 --- a/salt/states/pecl.py +++ b/salt/states/pecl.py @@ -73,25 +73,25 @@ def installed( version is None or version in installed_pecls[package] ) and preferred_state in installed_pecls[package]: ret["result"] = True - ret["comment"] = "Pecl extension {} is already installed.".format(name) + ret["comment"] = f"Pecl extension {name} is already installed." return ret if version is not None: # Modify the name to include the version and proceed. - name = "{}-{}".format(name, version) + name = f"{name}-{version}" if __opts__["test"]: - ret["comment"] = "Pecl extension {} would have been installed".format(name) + ret["comment"] = f"Pecl extension {name} would have been installed" return ret if __salt__["pecl.install"]( name, defaults=defaults, force=force, preferred_state=preferred_state ): ret["result"] = True ret["changes"][name] = "Installed" - ret["comment"] = "Pecl extension {} was successfully installed".format(name) + ret["comment"] = f"Pecl extension {name} was successfully installed" else: ret["result"] = False - ret["comment"] = "Could not install pecl extension {}.".format(name) + ret["comment"] = f"Could not install pecl extension {name}." return ret @@ -106,17 +106,17 @@ def removed(name): ret = {"name": name, "result": None, "comment": "", "changes": {}} if name not in __salt__["pecl.list"](): ret["result"] = True - ret["comment"] = "Pecl extension {} is not installed.".format(name) + ret["comment"] = f"Pecl extension {name} is not installed." return ret if __opts__["test"]: - ret["comment"] = "Pecl extension {} would have been removed".format(name) + ret["comment"] = f"Pecl extension {name} would have been removed" return ret if __salt__["pecl.uninstall"](name): ret["result"] = True ret["changes"][name] = "Removed" - ret["comment"] = "Pecl extension {} was successfully removed.".format(name) + ret["comment"] = f"Pecl extension {name} was successfully removed." else: ret["result"] = False - ret["comment"] = "Could not remove pecl extension {}.".format(name) + ret["comment"] = f"Could not remove pecl extension {name}." return ret diff --git a/salt/states/pip_state.py b/salt/states/pip_state.py index bb23f715e83..a262e16261e 100644 --- a/salt/states/pip_state.py +++ b/salt/states/pip_state.py @@ -18,7 +18,6 @@ requisite to a pkg.installed state for the package which provides pip - pkg: python-pip """ - import logging import re import sys @@ -754,8 +753,8 @@ def installed( # prepro = lambda pkg: pkg if type(pkg) == str else \ # ' '.join((pkg.items()[0][0], pkg.items()[0][1].replace(',', ';'))) # pkgs = ','.join([prepro(pkg) for pkg in pkgs]) - prepro = ( - lambda pkg: pkg + prepro = lambda pkg: ( + pkg if isinstance(pkg, str) else " ".join((pkg.items()[0][0], pkg.items()[0][1])) ) diff --git a/salt/states/pkg.py b/salt/states/pkg.py index 13a9edd0fb4..1e7336749cd 100644 --- a/salt/states/pkg.py +++ b/salt/states/pkg.py @@ -67,6 +67,7 @@ state module Make sure the package name has the correct case for package managers which are case-sensitive (such as :mod:`pkgng `). """ + import fnmatch import logging import os @@ -1953,10 +1954,10 @@ def installed( ret["comment"] = exc.strerror_without_changes else: ret["changes"] = {} - ret[ - "comment" - ] = "An error was encountered while installing package(s): {}".format( - exc + ret["comment"] = ( + "An error was encountered while installing package(s): {}".format( + exc + ) ) if warnings: ret.setdefault("warnings", []).extend(warnings) @@ -2368,9 +2369,9 @@ def downloaded( ret["comment"] = exc.strerror_without_changes else: ret["changes"] = {} - ret[ - "comment" - ] = f"An error was encountered while downloading package(s): {exc}" + ret["comment"] = ( + f"An error was encountered while downloading package(s): {exc}" + ) return ret new_pkgs = __salt__["pkg.list_downloaded"](**kwargs) @@ -2425,9 +2426,9 @@ def patch_installed(name, advisory_ids=None, downloadonly=None, **kwargs): if "pkg.list_patches" not in __salt__: ret["result"] = False - ret[ - "comment" - ] = "The pkg.patch_installed state is not available on this platform" + ret["comment"] = ( + "The pkg.patch_installed state is not available on this platform" + ) return ret if isinstance(advisory_ids, list) and len(advisory_ids) == 0: @@ -2448,9 +2449,9 @@ def patch_installed(name, advisory_ids=None, downloadonly=None, **kwargs): if __opts__["test"]: summary = ", ".join(targets) - ret[ - "comment" - ] = f"The following advisory patches would be downloaded: {summary}" + ret["comment"] = ( + f"The following advisory patches would be downloaded: {summary}" + ) return ret try: @@ -2467,18 +2468,18 @@ def patch_installed(name, advisory_ids=None, downloadonly=None, **kwargs): ret["comment"] = exc.strerror_without_changes else: ret["changes"] = {} - ret[ - "comment" - ] = f"An error was encountered while downloading package(s): {exc}" + ret["comment"] = ( + f"An error was encountered while downloading package(s): {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 @@ -3164,9 +3165,9 @@ def removed(name, version=None, pkgs=None, normalize=True, ignore_epoch=None, ** ret["comment"] = exc.strerror_without_changes else: ret["changes"] = {} - ret[ - "comment" - ] = f"An error was encountered while removing package(s): {exc}" + ret["comment"] = ( + f"An error was encountered while removing package(s): {exc}" + ) return ret @@ -3491,19 +3492,19 @@ def group_installed(name, skip=None, include=None, **kwargs): if "unexpected keyword argument" in str(err): ret["comment"] = "Repo options are not supported on this platform" else: - ret[ - "comment" - ] = f"An error was encountered while installing/updating group '{name}': {err}." + ret["comment"] = ( + f"An error was encountered while installing/updating group '{name}': {err}." + ) return ret mandatory = diff["mandatory"]["installed"] + diff["mandatory"]["not installed"] invalid_skip = [x for x in mandatory if x in skip] if invalid_skip: - ret[ - "comment" - ] = "The following mandatory packages cannot be skipped: {}".format( - ", ".join(invalid_skip) + ret["comment"] = ( + "The following mandatory packages cannot be skipped: {}".format( + ", ".join(invalid_skip) + ) ) return ret @@ -3525,9 +3526,9 @@ def group_installed(name, skip=None, include=None, **kwargs): if __opts__["test"]: ret["result"] = None if partially_installed: - ret[ - "comment" - ] = f"Group '{name}' is partially installed and will be updated" + ret["comment"] = ( + f"Group '{name}' is partially installed and will be updated" + ) else: ret["comment"] = f"Group '{name}' will be installed" return ret diff --git a/salt/states/pkgbuild.py b/salt/states/pkgbuild.py index 68725fc362b..7888e97bb59 100644 --- a/salt/states/pkgbuild.py +++ b/salt/states/pkgbuild.py @@ -330,7 +330,7 @@ def repo( if __opts__["test"] is True: ret["result"] = None - ret["comment"] = "Package repo metadata at {} will be refreshed".format(name) + ret["comment"] = f"Package repo metadata at {name} will be refreshed" return ret # Need the check for None here, if env is not provided then it falls back diff --git a/salt/states/pkgrepo.py b/salt/states/pkgrepo.py index 25959da679c..35b8d3896b8 100644 --- a/salt/states/pkgrepo.py +++ b/salt/states/pkgrepo.py @@ -117,7 +117,6 @@ Using ``aptkey: False`` with ``keyserver`` and ``keyid``: - aptkey: False """ - import sys import salt.utils.data @@ -365,15 +364,15 @@ def managed(name, ppa=None, copr=None, aptkey=True, **kwargs): if "key_url" in kwargs and ("keyid" in kwargs or "keyserver" in kwargs): ret["result"] = False - ret[ - "comment" - ] = 'You may not use both "keyid"/"keyserver" and "key_url" argument.' + ret["comment"] = ( + 'You may not use both "keyid"/"keyserver" and "key_url" argument.' + ) if "key_text" in kwargs and ("keyid" in kwargs or "keyserver" in kwargs): ret["result"] = False - ret[ - "comment" - ] = 'You may not use both "keyid"/"keyserver" and "key_text" argument.' + ret["comment"] = ( + 'You may not use both "keyid"/"keyserver" and "key_text" argument.' + ) if "key_text" in kwargs and ("key_url" in kwargs): ret["result"] = False ret["comment"] = 'You may not use both "key_url" and "key_text" argument.' @@ -409,9 +408,9 @@ def managed(name, ppa=None, copr=None, aptkey=True, **kwargs): ) else: ret["result"] = False - ret[ - "comment" - ] = "Cannot have 'key_url' using http with 'allow_insecure_key' set to True" + ret["comment"] = ( + "Cannot have 'key_url' using http with 'allow_insecure_key' set to True" + ) return ret repo = name diff --git a/salt/states/ports.py b/salt/states/ports.py index b4e53c4a6a7..072bb7bf4f4 100644 --- a/salt/states/ports.py +++ b/salt/states/ports.py @@ -49,7 +49,7 @@ def _get_option_list(options): Returns the key/value pairs in the passed dict in a commaspace-delimited list in the format "key=value". """ - return ", ".join(["{}={}".format(x, y) for x, y in options.items()]) + return ", ".join([f"{x}={y}" for x, y in options.items()]) def _build_option_string(options): @@ -57,7 +57,7 @@ def _build_option_string(options): Common function to get a string to append to the end of the state comment """ if options: - return "with the following build options: {}".format(_get_option_list(options)) + return f"with the following build options: {_get_option_list(options)}" else: return "with the default build options" @@ -89,7 +89,7 @@ def installed(name, options=None): "name": name, "changes": {}, "result": True, - "comment": "{} is already installed".format(name), + "comment": f"{name} is already installed", } try: current_options = __salt__["ports.showconfig"]( @@ -128,44 +128,44 @@ def installed(name, options=None): if not default_options: if options: ret["result"] = False - ret[ - "comment" - ] = "{} does not have any build options, yet options were specified".format( - name + ret["comment"] = ( + "{} does not have any build options, yet options were specified".format( + name + ) ) return ret else: if __opts__["test"]: ret["result"] = None - ret["comment"] = "{} will be installed".format(name) + ret["comment"] = f"{name} will be installed" return ret else: 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 if __opts__["test"]: ret["result"] = None - ret["comment"] = "{} will be installed ".format(name) + ret["comment"] = f"{name} will be installed " ret["comment"] += _build_option_string(options) return ret if options: if not __salt__["ports.config"](name, reset=True, **options): ret["result"] = False - ret["comment"] = "Unable to set options for {}".format(name) + ret["comment"] = f"Unable to set options for {name}" return ret else: __salt__["ports.rmconfig"](name) if _options_file_exists(name): ret["result"] = False - ret["comment"] = "Unable to clear options for {}".format(name) + ret["comment"] = f"Unable to clear options for {name}" return ret ret["changes"] = __salt__["ports.install"](name) @@ -178,11 +178,11 @@ def installed(name, options=None): if err or name not in ports_post: ret["result"] = False if ret["result"]: - ret["comment"] = "Successfully installed {}".format(name) + ret["comment"] = f"Successfully installed {name}" if default_options: ret["comment"] += " " + _build_option_string(options) else: - ret["comment"] = "Failed to install {}".format(name) + ret["comment"] = f"Failed to install {name}" if err: - ret["comment"] += ". Error message:\n{}".format(err) + ret["comment"] += f". Error message:\n{err}" return ret diff --git a/salt/states/postgres_cluster.py b/salt/states/postgres_cluster.py index de98d5ab92f..bbcf42eb5ce 100644 --- a/salt/states/postgres_cluster.py +++ b/salt/states/postgres_cluster.py @@ -70,13 +70,13 @@ def present( .. versionadded:: 2016.3.0 """ - msg = "Cluster {}/{} is already present".format(version, name) + msg = f"Cluster {version}/{name} is already present" ret = {"name": name, "changes": {}, "result": True, "comment": msg} if __salt__["postgres.cluster_exists"](version, name): # check cluster config is correct infos = __salt__["postgres.cluster_list"](verbose=True) - info = infos["{}/{}".format(version, name)] + info = infos[f"{version}/{name}"] # TODO: check locale en encoding configs also if any( ( @@ -111,7 +111,7 @@ def present( if cluster: msg = "The cluster {0}/{1} has been created" ret["comment"] = msg.format(version, name) - ret["changes"]["{}/{}".format(version, name)] = "Present" + ret["changes"][f"{version}/{name}"] = "Present" else: msg = "Failed to create cluster {0}/{1}" ret["comment"] = msg.format(version, name) diff --git a/salt/states/postgres_database.py b/salt/states/postgres_database.py index eaeec035273..dfe2cfcd998 100644 --- a/salt/states/postgres_database.py +++ b/salt/states/postgres_database.py @@ -124,17 +124,19 @@ def present( return ret elif name in dbs and any( ( - db_params.get("Encoding").lower() != encoding.lower() - if encoding - else False, + ( + db_params.get("Encoding").lower() != encoding.lower() + if encoding + else False + ), db_params.get("Collate") != lc_collate if lc_collate else False, db_params.get("Ctype") != lc_ctype if lc_ctype else False, ) ): - ret[ - "comment" - ] = "Database {} has wrong parameters which couldn't be changed on fly.".format( - name + ret["comment"] = ( + "Database {} has wrong parameters which couldn't be changed on fly.".format( + name + ) ) ret["result"] = False return ret @@ -145,9 +147,9 @@ def present( if name not in dbs: ret["comment"] = f"Database {name} is set to be created" else: - ret[ - "comment" - ] = f"Database {name} exists, but parameters need to be changed" + ret["comment"] = ( + f"Database {name} exists, but parameters need to be changed" + ) return ret if name not in dbs and __salt__["postgres.db_create"]( name, diff --git a/salt/states/postgres_extension.py b/salt/states/postgres_extension.py index 963b9caa5ff..91726fbd58e 100644 --- a/salt/states/postgres_extension.py +++ b/salt/states/postgres_extension.py @@ -93,7 +93,7 @@ def present( "name": name, "changes": {}, "result": True, - "comment": "Extension {} is already present".format(name), + "comment": f"Extension {name} is already present", } db_args = { "maintenance_db": maintenance_db, @@ -135,17 +135,17 @@ def present( schema=schema, ext_version=ext_version, from_version=from_version, - **db_args + **db_args, ) if cret: if mode.endswith("e"): suffix = "d" else: suffix = "ed" - ret["comment"] = "The extension {} has been {}{}".format(name, mode, suffix) - ret["changes"][name] = "{}{}".format(mode.capitalize(), suffix) + ret["comment"] = f"The extension {name} has been {mode}{suffix}" + ret["changes"][name] = f"{mode.capitalize()}{suffix}" elif cret is not None: - ret["comment"] = "Failed to {1} extension {0}".format(name, mode) + ret["comment"] = f"Failed to {mode} extension {name}" ret["result"] = False return ret @@ -210,17 +210,17 @@ def absent( if exists: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Extension {} is set to be removed".format(name) + ret["comment"] = f"Extension {name} is set to be removed" return ret if __salt__["postgres.drop_extension"]( name, if_exists=if_exists, restrict=restrict, cascade=cascade, **db_args ): - ret["comment"] = "Extension {} has been removed".format(name) + ret["comment"] = f"Extension {name} has been removed" ret["changes"][name] = "Absent" return ret else: ret["result"] = False - ret["comment"] = "Extension {} failed to be removed".format(name) + ret["comment"] = f"Extension {name} failed to be removed" return ret else: ret["comment"] = "Extension {} is not present, so it cannot be removed".format( diff --git a/salt/states/postgres_group.py b/salt/states/postgres_group.py index 01209ddfd43..2668f01bc90 100644 --- a/salt/states/postgres_group.py +++ b/salt/states/postgres_group.py @@ -138,7 +138,7 @@ def present( "name": name, "changes": {}, "result": True, - "comment": "Group {} is already present".format(name), + "comment": f"Group {name} is already present", } # default to encrypted passwords @@ -210,9 +210,9 @@ def present( if update: ret["changes"][name] = update ret["result"] = None - ret["comment"] = "Group {} is set to be {}d".format(name, mode) + ret["comment"] = f"Group {name} is set to be {mode}d" return ret - cret = __salt__["postgres.group_{}".format(mode)]( + cret = __salt__[f"postgres.group_{mode}"]( groupname=name, createdb=createdb, createroles=createroles, @@ -223,19 +223,19 @@ def present( replication=replication, rolepassword=password, groups=groups, - **db_args + **db_args, ) else: cret = None if cret: - ret["comment"] = "The group {} has been {}d".format(name, mode) + ret["comment"] = f"The group {name} has been {mode}d" if update: ret["changes"][name] = update else: ret["changes"][name] = "Present" elif cret is not None: - ret["comment"] = "Failed to {} group {}".format(mode, name) + ret["comment"] = f"Failed to {mode} group {name}" ret["result"] = False else: ret["result"] = True @@ -289,17 +289,17 @@ def absent( if __salt__["postgres.user_exists"](name, **db_args): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Group {} is set to be removed".format(name) + ret["comment"] = f"Group {name} is set to be removed" return ret if __salt__["postgres.group_remove"](name, **db_args): - ret["comment"] = "Group {} has been removed".format(name) + ret["comment"] = f"Group {name} has been removed" ret["changes"][name] = "Absent" return ret else: ret["result"] = False - ret["comment"] = "Group {} failed to be removed".format(name) + ret["comment"] = f"Group {name} failed to be removed" return ret else: - ret["comment"] = "Group {} is not present, so it cannot be removed".format(name) + ret["comment"] = f"Group {name} is not present, so it cannot be removed" return ret diff --git a/salt/states/postgres_initdb.py b/salt/states/postgres_initdb.py index bde59f925eb..bb1a85474e4 100644 --- a/salt/states/postgres_initdb.py +++ b/salt/states/postgres_initdb.py @@ -83,13 +83,13 @@ def present( runas The system user the operation should be performed on behalf of """ - _cmt = "Postgres data directory {} is already present".format(name) + _cmt = f"Postgres data directory {name} is already present" ret = {"name": name, "changes": {}, "result": True, "comment": _cmt} if not __salt__["postgres.datadir_exists"](name=name): if __opts__["test"]: ret["result"] = None - _cmt = "Postgres data directory {} is set to be initialized".format(name) + _cmt = f"Postgres data directory {name} is set to be initialized" ret["comment"] = _cmt return ret @@ -105,11 +105,11 @@ def present( ) if __salt__["postgres.datadir_init"](name, **kwargs): - _cmt = "Postgres data directory {} has been initialized".format(name) + _cmt = f"Postgres data directory {name} has been initialized" ret["comment"] = _cmt ret["changes"][name] = "Present" else: - _cmt = "Postgres data directory {} initialization failed".format(name) + _cmt = f"Postgres data directory {name} initialization failed" ret["result"] = False ret["comment"] = _cmt diff --git a/salt/states/postgres_language.py b/salt/states/postgres_language.py index 3a06476c975..d8c5665ddf4 100644 --- a/salt/states/postgres_language.py +++ b/salt/states/postgres_language.py @@ -72,7 +72,7 @@ def present( "name": name, "changes": {}, "result": True, - "comment": "Language {} is already installed".format(name), + "comment": f"Language {name} is already installed", } dbargs = { @@ -88,14 +88,14 @@ def present( if name not in languages: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Language {} is set to be installed".format(name) + ret["comment"] = f"Language {name} is set to be installed" return ret if __salt__["postgres.language_create"](name, maintenance_db, **dbargs): - ret["comment"] = "Language {} has been installed".format(name) + ret["comment"] = f"Language {name} has been installed" ret["changes"][name] = "Present" else: - ret["comment"] = "Failed to install language {}".format(name) + ret["comment"] = f"Failed to install language {name}" ret["result"] = False return ret @@ -148,15 +148,15 @@ def absent( if __salt__["postgres.language_exists"](name, maintenance_db, **dbargs): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Language {} is set to be removed".format(name) + ret["comment"] = f"Language {name} is set to be removed" return ret if __salt__["postgres.language_remove"](name, **dbargs): - ret["comment"] = "Language {} has been removed".format(name) + ret["comment"] = f"Language {name} has been removed" ret["changes"][name] = "Absent" return ret else: - ret["comment"] = "Failed to remove language {}".format(name) + ret["comment"] = f"Failed to remove language {name}" ret["result"] = False - ret["comment"] = "Language {} is not present so it cannot be removed".format(name) + ret["comment"] = f"Language {name} is not present so it cannot be removed" return ret diff --git a/salt/states/postgres_privileges.py b/salt/states/postgres_privileges.py index 9241c2de6e4..9829e583441 100644 --- a/salt/states/postgres_privileges.py +++ b/salt/states/postgres_privileges.py @@ -311,10 +311,10 @@ def absent( if __opts__["test"]: ret["result"] = None - ret[ - "comment" - ] = "The privilege(s): {} are set to be revoked from {}".format( - _privs, name + ret["comment"] = ( + "The privilege(s): {} are set to be revoked from {}".format( + _privs, name + ) ) return ret diff --git a/salt/states/postgres_schema.py b/salt/states/postgres_schema.py index 0f58db1afe8..0052f4da1d7 100644 --- a/salt/states/postgres_schema.py +++ b/salt/states/postgres_schema.py @@ -66,7 +66,7 @@ def present( "name": name, "changes": {}, "result": True, - "comment": "Schema {} is already present in database {}".format(name, dbname), + "comment": f"Schema {name} is already present in database {dbname}", } db_args = { @@ -163,13 +163,13 @@ def absent( return ret else: ret["result"] = False - ret["comment"] = "Schema {} failed to be removed".format(name) + ret["comment"] = f"Schema {name} failed to be removed" return ret else: - ret[ - "comment" - ] = "Schema {} is not present in database {}, so it cannot be removed".format( - name, dbname + ret["comment"] = ( + "Schema {} is not present in database {}, so it cannot be removed".format( + name, dbname + ) ) return ret diff --git a/salt/states/postgres_tablespace.py b/salt/states/postgres_tablespace.py index fcb28d68774..84da41f99ec 100644 --- a/salt/states/postgres_tablespace.py +++ b/salt/states/postgres_tablespace.py @@ -15,7 +15,6 @@ A module used to create and manage PostgreSQL tablespaces. """ - import salt.utils.dictupdate as dictupdate @@ -94,7 +93,7 @@ def present( "name": name, "changes": {}, "result": True, - "comment": "Tablespace {} is already present".format(name), + "comment": f"Tablespace {name} is already present", } dbargs = { "maintenance_db": maintenance_db, @@ -109,22 +108,22 @@ def present( # not there, create it if __opts__["test"]: ret["result"] = None - ret["comment"] = "Tablespace {} is set to be created".format(name) + ret["comment"] = f"Tablespace {name} is set to be created" return ret if __salt__["postgres.tablespace_create"]( name, directory, options, owner, **dbargs ): - ret["comment"] = "The tablespace {} has been created".format(name) + ret["comment"] = f"The tablespace {name} has been created" ret["changes"][name] = "Present" return ret # already exists, make sure it's got the right config if tblspaces[name]["Location"] != directory and not __opts__["test"]: - ret[ - "comment" - ] = """Tablespace {} is not at the right location. This is + ret["comment"] = ( + """Tablespace {} is not at the right location. This is unfixable without dropping and recreating the tablespace.""".format( - name + name + ) ) ret["result"] = False return ret @@ -132,12 +131,12 @@ def present( if owner and not tblspaces[name]["Owner"] == owner: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Tablespace {} owner to be altered".format(name) + ret["comment"] = f"Tablespace {name} owner to be altered" if ( __salt__["postgres.tablespace_alter"](name, new_owner=owner) and not __opts__["test"] ): - ret["comment"] = "Tablespace {} owner changed".format(name) + ret["comment"] = f"Tablespace {name} owner changed" ret["changes"][name] = {"owner": owner} ret["result"] = True @@ -149,18 +148,18 @@ def present( # TODO remove options that exist if possible for k, v in options.items(): # if 'seq_page_cost=1.1' not in '{seq_page_cost=1.1,...}' - if "{}={}".format(k, v) not in tblspaces[name]["Opts"]: + if f"{k}={v}" not in tblspaces[name]["Opts"]: if __opts__["test"]: ret["result"] = None - ret[ - "comment" - ] = """Tablespace {} options to be + ret["comment"] = ( + """Tablespace {} options to be altered""".format( - name + name + ) ) break # we know it's going to be altered, no reason to cont if __salt__["postgres.tablespace_alter"](name, set_option={k: v}): - ret["comment"] = "Tablespace {} opts changed".format(name) + ret["comment"] = f"Tablespace {name} opts changed" dictupdate.update(ret["changes"], {name: {"options": {k: v}}}) ret["result"] = True @@ -214,10 +213,10 @@ def absent( if __salt__["postgres.tablespace_exists"](name, **db_args): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Tablespace {} is set to be removed".format(name) + ret["comment"] = f"Tablespace {name} is set to be removed" return ret if __salt__["postgres.tablespace_remove"](name, **db_args): - ret["comment"] = "Tablespace {} has been removed".format(name) + ret["comment"] = f"Tablespace {name} has been removed" ret["changes"][name] = "Absent" return ret diff --git a/salt/states/postgres_user.py b/salt/states/postgres_user.py index f76e5e38403..fa5f5f9ecbf 100644 --- a/salt/states/postgres_user.py +++ b/salt/states/postgres_user.py @@ -149,7 +149,7 @@ def present( "name": name, "changes": {}, "result": True, - "comment": "User {} is already present".format(name), + "comment": f"User {name} is already present", } db_args = { @@ -214,7 +214,7 @@ def present( "SELECT '{}'::timestamp(0) as dt;".format( valid_until.replace("'", "''") ), - **db_args + **db_args, )[0]["dt"] try: valid_until_dt = datetime.datetime.strptime( @@ -238,9 +238,9 @@ def present( if update: ret["changes"][name] = update ret["result"] = None - ret["comment"] = "User {} is set to be {}d".format(name, mode) + ret["comment"] = f"User {name} is set to be {mode}d" return ret - cret = __salt__["postgres.user_{}".format(mode)]( + cret = __salt__[f"postgres.user_{mode}"]( username=name, createdb=createdb, createroles=createroles, @@ -252,19 +252,19 @@ def present( rolepassword=password, valid_until=valid_until, groups=groups, - **db_args + **db_args, ) else: cret = None if cret: - ret["comment"] = "The user {} has been {}d".format(name, mode) + ret["comment"] = f"The user {name} has been {mode}d" if update: ret["changes"][name] = update else: ret["changes"][name] = "Present" elif cret is not None: - ret["comment"] = "Failed to {} user {}".format(mode, name) + ret["comment"] = f"Failed to {mode} user {name}" ret["result"] = False else: ret["result"] = True @@ -318,17 +318,17 @@ def absent( if __salt__["postgres.user_exists"](name, **db_args): if __opts__["test"]: ret["result"] = None - ret["comment"] = "User {} is set to be removed".format(name) + ret["comment"] = f"User {name} is set to be removed" return ret if __salt__["postgres.user_remove"](name, **db_args): - ret["comment"] = "User {} has been removed".format(name) + ret["comment"] = f"User {name} has been removed" ret["changes"][name] = "Absent" return ret else: ret["result"] = False - ret["comment"] = "User {} failed to be removed".format(name) + ret["comment"] = f"User {name} failed to be removed" return ret else: - ret["comment"] = "User {} is not present, so it cannot be removed".format(name) + ret["comment"] = f"User {name} is not present, so it cannot be removed" return ret diff --git a/salt/states/powerpath.py b/salt/states/powerpath.py index 829a6359e5c..0ee13997d0a 100644 --- a/salt/states/powerpath.py +++ b/salt/states/powerpath.py @@ -31,12 +31,12 @@ def license_present(name): if name in licenses: ret["result"] = True - ret["comment"] = "License key {} already present".format(name) + ret["comment"] = f"License key {name} already present" return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "License key {} is set to be added".format(name) + ret["comment"] = f"License key {name} is set to be added" return ret data = __salt__["powerpath.add_license"](name) @@ -70,12 +70,12 @@ def license_absent(name): if name not in licenses: ret["result"] = True - ret["comment"] = "License key {} not present".format(name) + ret["comment"] = f"License key {name} not present" return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "License key {} is set to be removed".format(name) + ret["comment"] = f"License key {name} is set to be removed" return ret data = __salt__["powerpath.remove_license"](name) diff --git a/salt/states/probes.py b/salt/states/probes.py index 2b5c566caf0..23f34e85328 100644 --- a/salt/states/probes.py +++ b/salt/states/probes.py @@ -54,7 +54,6 @@ def __virtual__(): def _default_ret(name): - """ Returns a default structure of the dictionary to be returned as output of the state functions. """ @@ -63,7 +62,6 @@ def _default_ret(name): def _retrieve_rpm_probes(): - """ Will retrieve the probes from the network device using salt module "probes" throught NAPALM proxy. """ @@ -72,7 +70,6 @@ def _retrieve_rpm_probes(): def _expand_probes(probes, defaults): - """ Updates the probes dictionary with different levels of default values. """ @@ -104,7 +101,6 @@ def _expand_probes(probes, defaults): def _clean_probes(probes): - """ Will remove empty and useless values from the probes dictionary. """ @@ -127,7 +123,6 @@ def _clean_probes(probes): def _compare_probes(configured_probes, expected_probes): - """ Compares configured probes on the device with the expected configuration and returns the differences. """ @@ -190,14 +185,12 @@ def _compare_probes(configured_probes, expected_probes): def _ordered_dict_to_dict(probes): - """Mandatory to be dict type in order to be used in the NAPALM Jinja template.""" return salt.utils.json.loads(salt.utils.json.dumps(probes)) def _set_rpm_probes(probes): - """ Calls the Salt module "probes" to configure the probes on the device. """ @@ -209,7 +202,6 @@ def _set_rpm_probes(probes): def _schedule_probes(probes): - """ Calls the Salt module "probes" to schedule the configured probes on the device. """ @@ -221,7 +213,6 @@ def _schedule_probes(probes): def _delete_rpm_probes(probes): - """ Calls the Salt module "probes" to delete probes from the device. """ @@ -240,7 +231,6 @@ def _delete_rpm_probes(probes): def managed(name, probes, defaults=None): - """ Ensure the networks device is configured as specified in the state SLS file. Probes not specified will be removed, while probes not confiured as expected will trigger config updates. diff --git a/salt/states/process.py b/salt/states/process.py index d4b40f81f01..b75a7f7cd7f 100644 --- a/salt/states/process.py +++ b/salt/states/process.py @@ -37,7 +37,7 @@ def absent(name, user=None, signal=None): running = __salt__["ps.pgrep"](name, user=user) ret["result"] = None if running: - ret["comment"] = "{} processes will be killed".format(len(running)) + ret["comment"] = f"{len(running)} processes will be killed" else: ret["comment"] = "No matching processes running" return ret diff --git a/salt/states/proxy.py b/salt/states/proxy.py index e951e97e133..231cba04195 100644 --- a/salt/states/proxy.py +++ b/salt/states/proxy.py @@ -78,13 +78,13 @@ def managed( ret["changes"] = {"new": []} for service in services: - current_settings = __salt__["proxy.get_{}_proxy".format(service)]() + current_settings = __salt__[f"proxy.get_{service}_proxy"]() if current_settings.get("server") == name and current_settings.get( "port" ) == str(port): - ret["comment"] += "{} proxy settings already set.\n".format(service) - elif __salt__["proxy.set_{}_proxy".format(service)]( + ret["comment"] += f"{service} proxy settings already set.\n" + elif __salt__[f"proxy.set_{service}_proxy"]( name, port, user, password, network_service ): ret["comment"] += "{} proxy settings updated correctly\n".format( diff --git a/salt/states/pyenv.py b/salt/states/pyenv.py index f68dd947970..0d2a30020ab 100644 --- a/salt/states/pyenv.py +++ b/salt/states/pyenv.py @@ -122,7 +122,7 @@ def installed(name, default=False, user=None): name = re.sub(r"^python-", "", name) if __opts__["test"]: - ret["comment"] = "python {} is set to be installed".format(name) + ret["comment"] = f"python {name} is set to be installed" return ret ret = _check_pyenv(ret, user) @@ -156,7 +156,7 @@ def _check_and_uninstall_python(ret, python, user=None): return ret else: ret["result"] = True - ret["comment"] = "python {} is already absent".format(python) + ret["comment"] = f"python {python} is already absent" return ret @@ -182,13 +182,13 @@ def absent(name, user=None): name = re.sub(r"^python-", "", name) if __opts__["test"]: - ret["comment"] = "python {} is set to be uninstalled".format(name) + ret["comment"] = f"python {name} is set to be uninstalled" return ret ret = _check_pyenv(ret, user) if ret["result"] is False: ret["result"] = True - ret["comment"] = "pyenv not installed, {} not either".format(name) + ret["comment"] = f"pyenv not installed, {name} not either" return ret else: return _check_and_uninstall_python(ret, name, user=user) diff --git a/salt/states/pyrax_queues.py b/salt/states/pyrax_queues.py index f1c951a510c..7aba6a2750b 100644 --- a/salt/states/pyrax_queues.py +++ b/salt/states/pyrax_queues.py @@ -53,7 +53,7 @@ def present(name, provider): if not is_present: if __opts__["test"]: - msg = "Rackspace queue {} is set to be created.".format(name) + msg = f"Rackspace queue {name} is set to be created." ret["comment"] = msg ret["result"] = None return ret @@ -68,10 +68,10 @@ def present(name, provider): ret["changes"]["new"] = {"queue": queue} else: ret["result"] = False - ret["comment"] = "Failed to create {} Rackspace queue.".format(name) + ret["comment"] = f"Failed to create {name} Rackspace queue." return ret else: - ret["comment"] = "{} present.".format(name) + ret["comment"] = f"{name} present." return ret @@ -98,7 +98,7 @@ def absent(name, provider): if is_present: if __opts__["test"]: - ret["comment"] = "Rackspace queue {} is set to be removed.".format(name) + ret["comment"] = f"Rackspace queue {name} is set to be removed." ret["result"] = None return ret queue = __salt__["cloud.action"]("queues_show", provider=provider, name=name) @@ -110,8 +110,8 @@ def absent(name, provider): ret["changes"]["new"] = {} else: ret["result"] = False - ret["comment"] = "Failed to delete {} Rackspace queue.".format(name) + ret["comment"] = f"Failed to delete {name} Rackspace queue." else: - ret["comment"] = "{} does not exist.".format(name) + ret["comment"] = f"{name} does not exist." return ret diff --git a/salt/states/quota.py b/salt/states/quota.py index 07fe25a87ee..6c032e42ddb 100644 --- a/salt/states/quota.py +++ b/salt/states/quota.py @@ -41,17 +41,17 @@ def mode(name, mode, quotatype): fun = "on" if __salt__["quota.get_mode"](name)[name][quotatype] == fun: ret["result"] = True - ret["comment"] = "Quota for {} already set to {}".format(name, fun) + ret["comment"] = f"Quota for {name} already set to {fun}" return ret if __opts__["test"]: - ret["comment"] = "Quota for {} needs to be set to {}".format(name, fun) + ret["comment"] = f"Quota for {name} needs to be set to {fun}" return ret - if __salt__["quota.{}".format(fun)](name): + if __salt__[f"quota.{fun}"](name): ret["changes"] = {"quota": name} ret["result"] = True - ret["comment"] = "Set quota for {} to {}".format(name, fun) + ret["comment"] = f"Set quota for {name} to {fun}" return ret else: ret["result"] = False - ret["comment"] = "Failed to set quota for {} to {}".format(name, fun) + ret["comment"] = f"Failed to set quota for {name} to {fun}" return ret diff --git a/salt/states/rabbitmq_cluster.py b/salt/states/rabbitmq_cluster.py index 8a845006dba..6af09e26099 100644 --- a/salt/states/rabbitmq_cluster.py +++ b/salt/states/rabbitmq_cluster.py @@ -48,7 +48,7 @@ def joined(name, host, user="rabbit", ram_node=None, runas="root"): ret = {"name": name, "result": True, "comment": "", "changes": {}} status = __salt__["rabbitmq.cluster_status"]() - if "{}@{}".format(user, host) in status: + if f"{user}@{host}" in status: ret["comment"] = "Already in cluster" return ret @@ -62,11 +62,11 @@ def joined(name, host, user="rabbit", ram_node=None, runas="root"): ret["comment"] = result["Join"] # If we've reached this far before returning, we have changes. - ret["changes"] = {"old": "", "new": "{}@{}".format(user, host)} + ret["changes"] = {"old": "", "new": f"{user}@{host}"} if __opts__["test"]: ret["result"] = None - ret["comment"] = "Node is set to join cluster {}@{}".format(user, host) + ret["comment"] = f"Node is set to join cluster {user}@{host}" return ret diff --git a/salt/states/rabbitmq_plugin.py b/salt/states/rabbitmq_plugin.py index d59e74fa035..76342b87b54 100644 --- a/salt/states/rabbitmq_plugin.py +++ b/salt/states/rabbitmq_plugin.py @@ -12,7 +12,6 @@ Example: rabbitmq_plugin.enabled: [] """ - import logging from salt.exceptions import CommandExecutionError @@ -45,11 +44,11 @@ def enabled(name, runas=None): plugin_enabled = __salt__["rabbitmq.plugin_is_enabled"](name, runas=runas) except CommandExecutionError as err: ret["result"] = False - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" return ret if plugin_enabled: - ret["comment"] = "Plugin '{}' is already enabled.".format(name) + ret["comment"] = f"Plugin '{name}' is already enabled." return ret if not __opts__["test"]: @@ -57,16 +56,16 @@ def enabled(name, runas=None): __salt__["rabbitmq.enable_plugin"](name, runas=runas) except CommandExecutionError as err: ret["result"] = False - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" return ret ret["changes"].update({"old": "", "new": name}) if __opts__["test"] and ret["changes"]: ret["result"] = None - ret["comment"] = "Plugin '{}' is set to be enabled.".format(name) + ret["comment"] = f"Plugin '{name}' is set to be enabled." return ret - ret["comment"] = "Plugin '{}' was enabled.".format(name) + ret["comment"] = f"Plugin '{name}' was enabled." return ret @@ -86,11 +85,11 @@ def disabled(name, runas=None): plugin_enabled = __salt__["rabbitmq.plugin_is_enabled"](name, runas=runas) except CommandExecutionError as err: ret["result"] = False - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" return ret if not plugin_enabled: - ret["comment"] = "Plugin '{}' is already disabled.".format(name) + ret["comment"] = f"Plugin '{name}' is already disabled." return ret if not __opts__["test"]: @@ -98,14 +97,14 @@ def disabled(name, runas=None): __salt__["rabbitmq.disable_plugin"](name, runas=runas) except CommandExecutionError as err: ret["result"] = False - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" return ret ret["changes"].update({"old": name, "new": ""}) if __opts__["test"] and ret["changes"]: ret["result"] = None - ret["comment"] = "Plugin '{}' is set to be disabled.".format(name) + ret["comment"] = f"Plugin '{name}' is set to be disabled." return ret - ret["comment"] = "Plugin '{}' was disabled.".format(name) + ret["comment"] = f"Plugin '{name}' was disabled." return ret diff --git a/salt/states/rabbitmq_policy.py b/salt/states/rabbitmq_policy.py index 120b6ec6f57..2e17f2fbc8e 100644 --- a/salt/states/rabbitmq_policy.py +++ b/salt/states/rabbitmq_policy.py @@ -79,13 +79,13 @@ def present( updates.append("Priority") if policy and not updates: - ret["comment"] = "Policy {} {} is already present".format(vhost, name) + ret["comment"] = f"Policy {vhost} {name} is already present" return ret if not policy: ret["changes"].update({"old": {}, "new": name}) if __opts__["test"]: - ret["comment"] = "Policy {} {} is set to be created".format(vhost, name) + ret["comment"] = f"Policy {vhost} {name} is set to be created" else: log.debug("Policy doesn't exist - Creating") result = __salt__["rabbitmq.set_policy"]( @@ -100,7 +100,7 @@ def present( elif updates: ret["changes"].update({"old": policy, "new": updates}) if __opts__["test"]: - ret["comment"] = "Policy {} {} is set to be updated".format(vhost, name) + ret["comment"] = f"Policy {vhost} {name} is set to be updated" else: log.debug("Policy exists but needs updating") result = __salt__["rabbitmq.set_policy"]( @@ -117,7 +117,7 @@ def present( ret["result"] = False ret["comment"] = result["Error"] elif ret["changes"] == {}: - ret["comment"] = "'{}' is already in the desired state.".format(name) + ret["comment"] = f"'{name}' is already in the desired state." elif __opts__["test"]: ret["result"] = None elif "Set" in result: @@ -142,7 +142,7 @@ def absent(name, vhost="/", runas=None): policy_exists = __salt__["rabbitmq.policy_exists"](vhost, name, runas=runas) if not policy_exists: - ret["comment"] = "Policy '{} {}' is not present.".format(vhost, name) + ret["comment"] = f"Policy '{vhost} {name}' is not present." return ret if not __opts__["test"]: @@ -159,6 +159,6 @@ def absent(name, vhost="/", runas=None): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Policy '{} {}' will be removed.".format(vhost, name) + ret["comment"] = f"Policy '{vhost} {name}' will be removed." return ret diff --git a/salt/states/rabbitmq_upstream.py b/salt/states/rabbitmq_upstream.py index da0e74ee746..21f39cc6ac2 100644 --- a/salt/states/rabbitmq_upstream.py +++ b/salt/states/rabbitmq_upstream.py @@ -17,7 +17,6 @@ Example: .. versionadded:: 3000 """ - import json import logging @@ -122,7 +121,7 @@ def present( try: current_upstreams = __salt__["rabbitmq.list_upstreams"](runas=runas) except CommandExecutionError as err: - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" return ret new_config = salt.utils.data.filter_falsey( { @@ -147,7 +146,7 @@ def present( action = "update" else: ret["result"] = True - ret["comment"] = 'Upstream "{}" already present as specified.'.format(name) + ret["comment"] = f'Upstream "{name}" already present as specified.' else: action = "create" diff_config = {"old": None, "new": new_config} @@ -155,7 +154,7 @@ def present( if action: if __opts__["test"]: ret["result"] = None - ret["comment"] = 'Upstream "{}" would have been {}d.'.format(name, action) + ret["comment"] = f'Upstream "{name}" would have been {action}d.' else: try: res = __salt__["rabbitmq.set_upstream"]( @@ -174,10 +173,10 @@ def present( runas=runas, ) ret["result"] = res - ret["comment"] = 'Upstream "{}" {}d.'.format(name, action) + ret["comment"] = f'Upstream "{name}" {action}d.' ret["changes"] = diff_config except CommandExecutionError as exp: - ret["comment"] = "Error trying to {} upstream: {}".format(action, exp) + ret["comment"] = f"Error trying to {action} upstream: {exp}" return ret @@ -195,23 +194,23 @@ def absent(name, runas=None): try: upstream_exists = __salt__["rabbitmq.upstream_exists"](name, runas=runas) except CommandExecutionError as err: - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" return ret if upstream_exists: if __opts__["test"]: ret["result"] = None - ret["comment"] = 'Upstream "{}" would have been deleted.'.format(name) + ret["comment"] = f'Upstream "{name}" would have been deleted.' else: try: res = __salt__["rabbitmq.delete_upstream"](name, runas=runas) if res: ret["result"] = True - ret["comment"] = 'Upstream "{}" has been deleted.'.format(name) + ret["comment"] = f'Upstream "{name}" has been deleted.' ret["changes"] = {"old": name, "new": None} except CommandExecutionError as err: - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" else: ret["result"] = True - ret["comment"] = 'The upstream "{}" is already absent.'.format(name) + ret["comment"] = f'The upstream "{name}" is already absent.' return ret diff --git a/salt/states/rabbitmq_user.py b/salt/states/rabbitmq_user.py index 8cf9d5f7e75..ce29c5da1c9 100644 --- a/salt/states/rabbitmq_user.py +++ b/salt/states/rabbitmq_user.py @@ -21,7 +21,6 @@ Example: - runas: rabbitmq """ - import logging import salt.utils.path @@ -106,7 +105,7 @@ def present(name, password=None, force=False, tags=None, perms=(), runas=None): try: user = __salt__["rabbitmq.user_exists"](name, runas=runas) except CommandExecutionError as err: - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" return ret passwd_reqs_update = False @@ -116,7 +115,7 @@ def present(name, password=None, force=False, tags=None, perms=(), runas=None): passwd_reqs_update = True log.debug("RabbitMQ user %s password update required", name) except CommandExecutionError as err: - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" return ret if user and not any((force, perms, tags, passwd_reqs_update)): @@ -124,7 +123,7 @@ def present(name, password=None, force=False, tags=None, perms=(), runas=None): "RabbitMQ user '%s' exists, password is up to date and force is not set.", name, ) - ret["comment"] = "User '{}' is already present.".format(name) + ret["comment"] = f"User '{name}' is already present." ret["result"] = True return ret @@ -132,14 +131,14 @@ def present(name, password=None, force=False, tags=None, perms=(), runas=None): ret["changes"].update({"user": {"old": "", "new": name}}) if __opts__["test"]: ret["result"] = None - ret["comment"] = "User '{}' is set to be created.".format(name) + ret["comment"] = f"User '{name}' is set to be created." return ret log.debug("RabbitMQ user '%s' doesn't exist - Creating.", name) try: __salt__["rabbitmq.add_user"](name, password, runas=runas) except CommandExecutionError as err: - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" return ret else: log.debug("RabbitMQ user '%s' exists", name) @@ -151,7 +150,7 @@ def present(name, password=None, force=False, tags=None, perms=(), runas=None): name, password, runas=runas ) except CommandExecutionError as err: - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" return ret ret["changes"].update({"password": {"old": "", "new": "Set password."}}) else: @@ -160,7 +159,7 @@ def present(name, password=None, force=False, tags=None, perms=(), runas=None): try: __salt__["rabbitmq.clear_password"](name, runas=runas) except CommandExecutionError as err: - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" return ret ret["changes"].update( {"password": {"old": "Removed password.", "new": ""}} @@ -177,13 +176,13 @@ def present(name, password=None, force=False, tags=None, perms=(), runas=None): try: __salt__["rabbitmq.set_user_tags"](name, tags, runas=runas) except CommandExecutionError as err: - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" return ret ret["changes"].update({"tags": {"old": current_tags, "new": tags}}) try: existing_perms = __salt__["rabbitmq.list_user_permissions"](name, runas=runas) except CommandExecutionError as err: - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" return ret if _check_perms_changes(name, perms, runas=runas, existing=existing_perms): @@ -195,7 +194,7 @@ def present(name, password=None, force=False, tags=None, perms=(), runas=None): vhost, name, perm[0], perm[1], perm[2], runas=runas ) except CommandExecutionError as err: - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" return ret new_perms = { vhost: {"configure": perm[0], "write": perm[1], "read": perm[2]} @@ -212,15 +211,15 @@ def present(name, password=None, force=False, tags=None, perms=(), runas=None): ret["result"] = True if ret["changes"] == {}: - ret["comment"] = "'{}' is already in the desired state.".format(name) + ret["comment"] = f"'{name}' is already in the desired state." return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Configuration for '{}' will change.".format(name) + ret["comment"] = f"Configuration for '{name}' will change." return ret - ret["comment"] = "'{}' was configured.".format(name) + ret["comment"] = f"'{name}' was configured." return ret @@ -238,7 +237,7 @@ def absent(name, runas=None): try: user_exists = __salt__["rabbitmq.user_exists"](name, runas=runas) except CommandExecutionError as err: - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" return ret if user_exists: @@ -246,19 +245,19 @@ def absent(name, runas=None): try: __salt__["rabbitmq.delete_user"](name, runas=runas) except CommandExecutionError as err: - ret["comment"] = "Error: {}".format(err) + ret["comment"] = f"Error: {err}" return ret ret["changes"].update({"name": {"old": name, "new": ""}}) else: ret["result"] = True - ret["comment"] = "The user '{}' is not present.".format(name) + ret["comment"] = f"The user '{name}' is not present." return ret if __opts__["test"] and ret["changes"]: ret["result"] = None - ret["comment"] = "The user '{}' will be removed.".format(name) + ret["comment"] = f"The user '{name}' will be removed." return ret ret["result"] = True - ret["comment"] = "The user '{}' was removed.".format(name) + ret["comment"] = f"The user '{name}' was removed." return ret diff --git a/salt/states/rabbitmq_vhost.py b/salt/states/rabbitmq_vhost.py index 4231e9519f4..5fb68e6d764 100644 --- a/salt/states/rabbitmq_vhost.py +++ b/salt/states/rabbitmq_vhost.py @@ -14,7 +14,6 @@ Example: - read: .* """ - import logging import salt.utils.path @@ -70,7 +69,7 @@ def present(name): vhost_exists = __salt__["rabbitmq.vhost_exists"](name) if vhost_exists: - ret["comment"] = "Virtual Host '{}' already exists.".format(name) + ret["comment"] = f"Virtual Host '{name}' already exists." return ret if not __opts__["test"]: @@ -87,7 +86,7 @@ def present(name): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Virtual Host '{}' will be created.".format(name) + ret["comment"] = f"Virtual Host '{name}' will be created." return ret @@ -108,7 +107,7 @@ def absent(name): vhost_exists = __salt__["rabbitmq.vhost_exists"](name) if not vhost_exists: - ret["comment"] = "Virtual Host '{}' is not present.".format(name) + ret["comment"] = f"Virtual Host '{name}' is not present." return ret if not __opts__["test"]: @@ -125,6 +124,6 @@ def absent(name): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Virtual Host '{}' will be removed.".format(name) + ret["comment"] = f"Virtual Host '{name}' will be removed." return ret diff --git a/salt/states/rbac_solaris.py b/salt/states/rbac_solaris.py index 551e5b9df83..74476640b33 100644 --- a/salt/states/rbac_solaris.py +++ b/salt/states/rbac_solaris.py @@ -41,7 +41,7 @@ def __virtual__(): else: return ( False, - "{} state module can only be loaded on Solaris".format(__virtualname__), + f"{__virtualname__} state module can only be loaded on Solaris", ) @@ -70,7 +70,7 @@ def managed(name, roles=None, profiles=None, authorizations=None): ## check properties if name not in __salt__["user.list_users"](): ret["result"] = False - ret["comment"] = "User {} does not exist!".format(name) + ret["comment"] = f"User {name} does not exist!" return ret if roles and not isinstance(roles, (list)): ret["result"] = False diff --git a/salt/states/rbenv.py b/salt/states/rbenv.py index c9c721f7104..34bce97ca80 100644 --- a/salt/states/rbenv.py +++ b/salt/states/rbenv.py @@ -130,9 +130,9 @@ def installed(name, default=False, user=None): if __opts__["test"]: ret = _ruby_installed(ret, name, user=user) if not ret["result"]: - ret["comment"] = "Ruby {} is set to be installed".format(name) + ret["comment"] = f"Ruby {name} is set to be installed" else: - ret["comment"] = "Ruby {} is already installed".format(name) + ret["comment"] = f"Ruby {name} is already installed" return ret rbenv_installed_ret = _check_and_install_rbenv(rbenv_installed_ret, user) @@ -164,7 +164,7 @@ def _check_and_uninstall_ruby(ret, ruby, user=None): return ret else: ret["result"] = True - ret["comment"] = "Ruby {} is already absent".format(ruby) + ret["comment"] = f"Ruby {ruby} is already absent" return ret @@ -192,17 +192,17 @@ def absent(name, user=None): ret = _check_rbenv(ret, user) if ret["result"] is False: ret["result"] = True - ret["comment"] = "Rbenv not installed, {} not either".format(name) + ret["comment"] = f"Rbenv not installed, {name} not either" return ret else: if __opts__["test"]: ret = _ruby_installed(ret, name, user=user) if ret["result"]: ret["result"] = None - ret["comment"] = "Ruby {} is set to be uninstalled".format(name) + ret["comment"] = f"Ruby {name} is set to be uninstalled" else: ret["result"] = True - ret["comment"] = "Ruby {} is already uninstalled".format(name) + ret["comment"] = f"Ruby {name} is already uninstalled" return ret return _check_and_uninstall_ruby(ret, name, user=user) diff --git a/salt/states/redismod.py b/salt/states/redismod.py index 4ff14c61881..47a4ac776c1 100644 --- a/salt/states/redismod.py +++ b/salt/states/redismod.py @@ -74,10 +74,10 @@ def string(name, value, expire=None, expireat=None, **connection_args): if expireat: __salt__["redis.expireat"](name, expireat, **connection_args) - ret["changes"]["expireat"] = "Key expires at {}".format(expireat) + ret["changes"]["expireat"] = f"Key expires at {expireat}" elif expire: __salt__["redis.expire"](name, expire, **connection_args) - ret["changes"]["expire"] = "TTL set to {} seconds".format(expire) + ret["changes"]["expire"] = f"TTL set to {expire} seconds" return ret @@ -126,7 +126,7 @@ def slaveof( sentinel_host=None, sentinel_port=None, sentinel_password=None, - **connection_args + **connection_args, ): """ Set this redis instance as a slave. @@ -156,13 +156,13 @@ def slaveof( ) if sentinel_master["master_host"] in __salt__["network.ip_addrs"](): ret["result"] = True - ret["comment"] = "Minion is the master: {}".format(name) + ret["comment"] = f"Minion is the master: {name}" return ret first_master = __salt__["redis.get_master_ip"](**connection_args) if first_master == sentinel_master: ret["result"] = True - ret["comment"] = "Minion already slave of master: {}".format(name) + ret["comment"] = f"Minion already slave of master: {name}" return ret if __opts__["test"] is True: @@ -184,6 +184,6 @@ def slaveof( "old": first_master, "new": current_master, } - ret["comment"] = "Minion successfully connected to master: {}".format(name) + ret["comment"] = f"Minion successfully connected to master: {name}" return ret diff --git a/salt/states/restconf.py b/salt/states/restconf.py index 4ac74e27bd4..44fcbc5896c 100644 --- a/salt/states/restconf.py +++ b/salt/states/restconf.py @@ -11,7 +11,6 @@ This state module was designed to manage RESTCONF states. This module relies on the RESTCONF proxy module to interface with the devices. """ - import difflib import json import logging diff --git a/salt/states/rsync.py b/salt/states/rsync.py index 79be3def583..4e01eb2e8dd 100644 --- a/salt/states/rsync.py +++ b/salt/states/rsync.py @@ -143,7 +143,7 @@ def synchronized( if not os.path.exists(name) and not force and not prepare: ret["result"] = False - ret["comment"] = "Destination directory {dest} was not found.".format(dest=name) + ret["comment"] = f"Destination directory {name} was not found." else: if not os.path.exists(name) and prepare: os.makedirs(name) diff --git a/salt/states/rvm.py b/salt/states/rvm.py index 5b7c4fa8e22..f593447093b 100644 --- a/salt/states/rvm.py +++ b/salt/states/rvm.py @@ -150,7 +150,7 @@ def _check_ruby(ret, ruby, user=None): for impl, version, default in __salt__["rvm.list"](runas=user): if impl != "ruby": - version = "{impl}-{version}".format(impl=impl, version=version) + version = f"{impl}-{version}" if not match_micro_version: version = micro_version_regex.sub("", version) if not match_version: @@ -188,7 +188,7 @@ def installed(name, default=False, user=None, opts=None, env=None): ret = {"name": name, "result": None, "comment": "", "changes": {}} if __opts__["test"]: - ret["comment"] = "Ruby {} is set to be installed".format(name) + ret["comment"] = f"Ruby {name} is set to be installed" return ret ret = _check_rvm(ret, user) @@ -241,7 +241,7 @@ def gemset_present(name, ruby="default", user=None): else: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Set to install gemset {}".format(name) + ret["comment"] = f"Set to install gemset {name}" return ret if __salt__["rvm.gemset_create"](ruby, name, runas=user): ret["result"] = True diff --git a/salt/states/salt_proxy.py b/salt/states/salt_proxy.py index 8a6ef6e2675..005ae65d24d 100644 --- a/salt/states/salt_proxy.py +++ b/salt/states/salt_proxy.py @@ -52,5 +52,5 @@ def configure_proxy(name, proxyname="p8000", start=True): """ ret = __salt__["salt_proxy.configure_proxy"](proxyname, start=start) - ret.update({"name": name, "comment": "{} config messages".format(name)}) + ret.update({"name": name, "comment": f"{name} config messages"}) return ret diff --git a/salt/states/saltmod.py b/salt/states/saltmod.py index f788c70a1e6..c6a194ef1db 100644 --- a/salt/states/saltmod.py +++ b/salt/states/saltmod.py @@ -349,9 +349,11 @@ def state( cmd_ret = { __opts__["id"]: { "ret": tmp_ret, - "out": tmp_ret.get("out", "highstate") - if isinstance(tmp_ret, dict) - else "highstate", + "out": ( + tmp_ret.get("out", "highstate") + if isinstance(tmp_ret, dict) + else "highstate" + ), } } diff --git a/salt/states/serverdensity_device.py b/salt/states/serverdensity_device.py index bce8db5bc92..02eced4b42f 100644 --- a/salt/states/serverdensity_device.py +++ b/salt/states/serverdensity_device.py @@ -46,7 +46,6 @@ Example: serverdensity_device.monitored """ - import logging import salt.utils.json @@ -206,9 +205,9 @@ def monitored( ret["changes"] = {} if __opts__["test"]: ret["result"] = None - ret[ - "comment" - ] = "Agent is not installed and device is not in the Server Density DB" + ret["comment"] = ( + "Agent is not installed and device is not in the Server Density DB" + ) return ret if __opts__["test"]: @@ -224,8 +223,8 @@ def monitored( ) ret["result"] = True - ret[ - "comment" - ] = "Successfully installed agent and created device in Server Density db." + ret["comment"] = ( + "Successfully installed agent and created device in Server Density db." + ) ret["changes"] = {"created_device": device, "installed_agent": installed_agent} return ret diff --git a/salt/states/service.py b/salt/states/service.py index 0bb04c34cc1..ab14ed0abf1 100644 --- a/salt/states/service.py +++ b/salt/states/service.py @@ -155,10 +155,10 @@ def _enable(name, started, result=True, **kwargs): # Check to see if this minion supports enable if "service.enable" not in __salt__ or "service.enabled" not in __salt__: if started is True: - ret[ - "comment" - ] = "Enable is not available on this minion, service {} started".format( - name + ret["comment"] = ( + "Enable is not available on this minion, service {} started".format( + name + ) ) elif started is None: ret["comment"] = ( @@ -166,10 +166,10 @@ def _enable(name, started, result=True, **kwargs): " service {} is in the desired state".format(name) ) else: - ret[ - "comment" - ] = "Enable is not available on this minion, service {} is dead".format( - name + ret["comment"] = ( + "Enable is not available on this minion, service {} is dead".format( + name + ) ) return ret @@ -184,19 +184,19 @@ def _enable(name, started, result=True, **kwargs): elif started is None: # always be sure in this case to reset the changes dict ret["changes"] = {} - ret[ - "comment" - ] = "Service {} is already enabled, and is in the desired state".format( - name + ret["comment"] = ( + "Service {} is already enabled, and is in the desired state".format( + name + ) ) else: - ret["comment"] = "Service {} is already enabled, and is dead".format(name) + ret["comment"] = f"Service {name} is already enabled, and is dead" return ret # Service needs to be enabled if __opts__["test"]: ret["result"] = None - ret["comment"] = "Service {} set to be enabled".format(name) + ret["comment"] = f"Service {name} set to be enabled" return ret try: @@ -214,13 +214,13 @@ def _enable(name, started, result=True, **kwargs): name ) elif started is None: - ret[ - "comment" - ] = "Service {} has been enabled, and is in the desired state".format( - name + ret["comment"] = ( + "Service {} has been enabled, and is in the desired state".format( + name + ) ) else: - ret["comment"] = "Service {} has been enabled, and is dead".format(name) + ret["comment"] = f"Service {name} has been enabled, and is dead" return ret except CommandExecutionError as exc: enable_error = exc.strerror @@ -240,14 +240,14 @@ def _enable(name, started, result=True, **kwargs): " but the service was already running".format(name) ) else: - ret[ - "comment" - ] = "Failed when setting service {} to start at boot, and the service is dead".format( - name + ret["comment"] = ( + "Failed when setting service {} to start at boot, and the service is dead".format( + name + ) ) if enable_error: - ret["comment"] += ". Additional information follows:\n\n{}".format(enable_error) + ret["comment"] += f". Additional information follows:\n\n{enable_error}" return ret @@ -274,10 +274,10 @@ def _disable(name, started, result=True, **kwargs): # is enable/disable available? if "service.disable" not in __salt__ or "service.disabled" not in __salt__: if started is True: - ret[ - "comment" - ] = "Disable is not available on this minion, service {} started".format( - name + ret["comment"] = ( + "Disable is not available on this minion, service {} started".format( + name + ) ) elif started is None: ret["comment"] = ( @@ -285,10 +285,10 @@ def _disable(name, started, result=True, **kwargs): " service {} is in the desired state".format(name) ) else: - ret[ - "comment" - ] = "Disable is not available on this minion, service {} is dead".format( - name + ret["comment"] = ( + "Disable is not available on this minion, service {} is dead".format( + name + ) ) return ret @@ -310,19 +310,19 @@ def _disable(name, started, result=True, **kwargs): elif started is None: # always be sure in this case to reset the changes dict ret["changes"] = {} - ret[ - "comment" - ] = "Service {} is already disabled, and is in the desired state".format( - name + ret["comment"] = ( + "Service {} is already disabled, and is in the desired state".format( + name + ) ) else: - ret["comment"] = "Service {} is already disabled, and is dead".format(name) + ret["comment"] = f"Service {name} is already disabled, and is dead" return ret # Service needs to be disabled if __opts__["test"]: ret["result"] = None - ret["comment"] = "Service {} set to be disabled".format(name) + ret["comment"] = f"Service {name} set to be disabled" return ret if __salt__["service.disable"](name, **kwargs): @@ -335,22 +335,22 @@ def _disable(name, started, result=True, **kwargs): if before_toggle_disable_status != after_toggle_disable_status: ret["changes"][name] = True if started is True: - ret["comment"] = "Service {} has been disabled, and is running".format(name) + ret["comment"] = f"Service {name} has been disabled, and is running" elif started is None: - ret[ - "comment" - ] = "Service {} has been disabled, and is in the desired state".format(name) + ret["comment"] = ( + f"Service {name} has been disabled, and is in the desired state" + ) else: - ret["comment"] = "Service {} has been disabled, and is dead".format(name) + ret["comment"] = f"Service {name} has been disabled, and is dead" return ret # Service failed to be disabled ret["result"] = False if started is True: - ret[ - "comment" - ] = "Failed when setting service {} to not start at boot, and is running".format( - name + ret["comment"] = ( + "Failed when setting service {} to not start at boot, and is running".format( + name + ) ) elif started is None: ret["comment"] = ( @@ -380,7 +380,7 @@ def _available(name, ret): avail = name in __salt__["service.get_all"]() if not avail: ret["result"] = False - ret["comment"] = "The named service {} is not available".format(name) + ret["comment"] = f"The named service {name} is not available" return avail @@ -505,7 +505,7 @@ def running(name, enable=None, sig=None, init_delay=None, **kwargs): [ _f for _f in [ - "The service {} is already running".format(name), + f"The service {name} is already running", unmask_ret["comment"], ] if _f @@ -524,7 +524,7 @@ def running(name, enable=None, sig=None, init_delay=None, **kwargs): [ _f for _f in [ - "Service {} is set to start".format(name), + f"Service {name} is set to start", unmask_ret["comment"], ] if _f @@ -566,7 +566,7 @@ def running(name, enable=None, sig=None, init_delay=None, **kwargs): if not func_ret: ret["result"] = False - ret["comment"] = "Service {} failed to start".format(name) + ret["comment"] = f"Service {name} failed to start" if enable is True: ret.update(_enable(name, False, result=False, **kwargs)) elif enable is False: @@ -589,9 +589,9 @@ def running(name, enable=None, sig=None, init_delay=None, **kwargs): ret["changes"][name] = after_toggle_status if after_toggle_status: - ret["comment"] = "Started service {}".format(name) + ret["comment"] = f"Started service {name}" else: - ret["comment"] = "Service {} failed to start".format(name) + ret["comment"] = f"Service {name} failed to start" ret["result"] = False if enable is True: @@ -708,7 +708,7 @@ def dead(name, enable=None, sig=None, init_delay=None, **kwargs): # See if the service is already dead if not before_toggle_status: - ret["comment"] = "The service {} is already dead".format(name) + ret["comment"] = f"The service {name} is already dead" if enable is True and not before_toggle_enable_status: ret.update(_enable(name, None, **kwargs)) elif enable is False and before_toggle_enable_status: @@ -718,7 +718,7 @@ def dead(name, enable=None, sig=None, init_delay=None, **kwargs): # Run the tests if __opts__["test"]: ret["result"] = None - ret["comment"] = "Service {} is set to be killed".format(name) + ret["comment"] = f"Service {name} is set to be killed" return ret # Conditionally add systemd-specific args to call to service.start @@ -732,7 +732,7 @@ def dead(name, enable=None, sig=None, init_delay=None, **kwargs): func_ret = __salt__["service.stop"](name, **stop_kwargs) if not func_ret: ret["result"] = False - ret["comment"] = "Service {} failed to die".format(name) + ret["comment"] = f"Service {name} failed to die" if enable is True: ret.update(_enable(name, True, result=False, **kwargs)) elif enable is False: @@ -757,9 +757,9 @@ def dead(name, enable=None, sig=None, init_delay=None, **kwargs): # be sure to stop, in case we mis detected in the check if after_toggle_status: ret["result"] = False - ret["comment"] = "Service {} failed to die".format(name) + ret["comment"] = f"Service {name} failed to die" else: - ret["comment"] = "Service {} was killed".format(name) + ret["comment"] = f"Service {name} was killed" if enable is True: ret.update( @@ -791,9 +791,10 @@ def enabled(name, **kwargs): __context__["service.state"] = "enabled" ret.update(_enable(name, None, **kwargs)) - if __opts__.get("test") and ret.get( - "comment" - ) == "The named service {} is not available".format(name): + if ( + __opts__.get("test") + and ret.get("comment") == f"The named service {name} is not available" + ): ret["result"] = None ret["comment"] = ( "Service {} not present; if created in this state run, " @@ -885,16 +886,16 @@ def masked(name, runtime=False): if __opts__["test"]: ret["result"] = None ret["changes"] = expected_changes - ret["comment"] = "Service {} would be {}".format(name, mask_type) + ret["comment"] = f"Service {name} would be {mask_type}" return ret __salt__["service.mask"](name, runtime) if __salt__["service.masked"](name, runtime): ret["changes"] = expected_changes - ret["comment"] = "Service {} was {}".format(name, mask_type) + ret["comment"] = f"Service {name} was {mask_type}" else: - ret["comment"] = "Failed to mask service {}".format(name) + ret["comment"] = f"Failed to mask service {name}" return ret except CommandExecutionError as exc: @@ -943,22 +944,22 @@ def unmasked(name, runtime=False): try: if not __salt__["service.masked"](name, runtime): - ret["comment"] = "Service {} was already {}".format(name, action) + ret["comment"] = f"Service {name} was already {action}" return ret if __opts__["test"]: ret["result"] = None ret["changes"] = expected_changes - ret["comment"] = "Service {} would be {}".format(name, action) + ret["comment"] = f"Service {name} would be {action}" return ret __salt__["service.unmask"](name, runtime) if not __salt__["service.masked"](name, runtime): ret["changes"] = expected_changes - ret["comment"] = "Service {} was {}".format(name, action) + ret["comment"] = f"Service {name} was {action}" else: - ret["comment"] = "Failed to unmask service {}".format(name) + ret["comment"] = f"Failed to unmask service {name}" return ret except CommandExecutionError as exc: @@ -975,7 +976,7 @@ def mod_watch( full_restart=False, init_delay=None, force=False, - **kwargs + **kwargs, ): """ The service watcher, called to invoke the watch command. @@ -1027,7 +1028,7 @@ def mod_watch( func = __salt__["service.stop"] else: ret["result"] = True - ret["comment"] = "Service is already {}".format(past_participle) + ret["comment"] = f"Service is already {past_participle}" return ret elif sfun == "running": if __salt__["service.status"](name, sig, **status_kwargs): @@ -1050,13 +1051,13 @@ def mod_watch( if not past_participle: past_participle = verb + "ed" else: - ret["comment"] = "Unable to trigger watch for service.{}".format(sfun) + ret["comment"] = f"Unable to trigger watch for service.{sfun}" ret["result"] = False return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Service is set to be {}".format(past_participle) + ret["comment"] = f"Service is set to be {past_participle}" return ret if verb == "start" and "service.stop" in __salt__: @@ -1080,9 +1081,7 @@ def mod_watch( ret["changes"] = {name: result} ret["result"] = result ret["comment"] = ( - "Service {}".format(past_participle) - if result - else "Failed to {} the service".format(verb) + f"Service {past_participle}" if result else f"Failed to {verb} the service" ) return ret @@ -1112,7 +1111,7 @@ def mod_beacon(name, **kwargs): data["emitatstartup"] = _beacon_data.get("emitatstartup", False) data["uncleanshutdown"] = _beacon_data.get("emitatstartup", None) - beacon_name = "beacon_{}_{}".format(beacon_module, name) + beacon_name = f"beacon_{beacon_module}_{name}" beacon_kwargs = { "name": beacon_name, diff --git a/salt/states/slack.py b/salt/states/slack.py index a0c1b3a2dfc..df271f2be1c 100644 --- a/salt/states/slack.py +++ b/salt/states/slack.py @@ -24,7 +24,6 @@ The api key can be specified in the master or minion configuration like below: """ - from salt.exceptions import SaltInvocationError @@ -162,11 +161,11 @@ def post_message(name, **kwargs): ) except SaltInvocationError as sie: - ret["comment"] = "Failed to send message ({}): {}".format(sie, name) + ret["comment"] = f"Failed to send message ({sie}): {name}" else: if isinstance(result, bool) and result: ret["result"] = True - ret["comment"] = "Sent message: {}".format(name) + ret["comment"] = f"Sent message: {name}" else: ret["comment"] = "Failed to send message ({}): {}".format( result["message"], name diff --git a/salt/states/smartos.py b/salt/states/smartos.py index afc536c2235..1309ad00c72 100644 --- a/salt/states/smartos.py +++ b/salt/states/smartos.py @@ -381,10 +381,10 @@ def config_present(name, value): ret["result"] = _write_config(config) if not ret["result"]: - ret[ - "comment" - ] = 'Could not add property {} with value "{}" to config'.format( - name, value + ret["comment"] = ( + 'Could not add property {} with value "{}" to config'.format( + name, value + ) ) return ret @@ -1021,9 +1021,9 @@ def vm_present(name, vmconfig, config=None): if f"update_{instance}" not in vmconfig["changed"]: vmconfig["changed"][f"update_{instance}"] = [] - update_cfg[ - vmconfig_type["instance"][instance] - ] = state_cfg[vmconfig_type["instance"][instance]] + update_cfg[vmconfig_type["instance"][instance]] = ( + state_cfg[vmconfig_type["instance"][instance]] + ) vmconfig["changed"][f"update_{instance}"].append( update_cfg ) @@ -1151,9 +1151,9 @@ def vm_present(name, vmconfig, config=None): ) if vmconfig["state"]["hostname"] not in ret["changes"]: ret["changes"][vmconfig["state"]["hostname"]] = {} - ret["changes"][vmconfig["state"]["hostname"]][ - "image_uuid" - ] = vmconfig["reprovision_uuid"] + ret["changes"][vmconfig["state"]["hostname"]]["image_uuid"] = ( + vmconfig["reprovision_uuid"] + ) else: log.warning( "smartos.vm_present::%s::reprovision - " diff --git a/salt/states/smtp.py b/salt/states/smtp.py index 2c8068363e7..1dd9fd9c799 100644 --- a/salt/states/smtp.py +++ b/salt/states/smtp.py @@ -86,8 +86,8 @@ def send_msg( recipient, name, atts ) else: - ret["comment"] = "Sent message to {}: {}".format(recipient, name) + ret["comment"] = f"Sent message to {recipient}: {name}" else: ret["result"] = False - ret["comment"] = "Unable to send message to {}: {}".format(recipient, name) + ret["comment"] = f"Unable to send message to {recipient}: {name}" return ret diff --git a/salt/states/snapper.py b/salt/states/snapper.py index 964c88c5001..2c61ab9722c 100644 --- a/salt/states/snapper.py +++ b/salt/states/snapper.py @@ -106,7 +106,6 @@ and include this change. :platform: Linux """ - import os @@ -178,9 +177,7 @@ def baseline_snapshot( if tag: snapshot = _get_baseline_from_tag(config, tag) if not snapshot: - ret.update( - {"result": False, "comment": 'Baseline tag "{}" not found'.format(tag)} - ) + ret.update({"result": False, "comment": f'Baseline tag "{tag}" not found'}) return ret number = snapshot["id"] diff --git a/salt/states/solrcloud.py b/salt/states/solrcloud.py index 6e9aaab545e..4858ecf84f5 100644 --- a/salt/states/solrcloud.py +++ b/salt/states/solrcloud.py @@ -5,7 +5,6 @@ States for solrcloud alias and collection configuration """ - import salt.utils.json @@ -39,11 +38,11 @@ def alias(name, collections, **kwargs): return ret if __opts__["test"]: - ret["comment"] = 'The alias "{}" will be updated.'.format(name) + ret["comment"] = f'The alias "{name}" will be updated.' ret["result"] = None else: __salt__["solrcloud.alias_set_collections"](name, collections, **kwargs) - ret["comment"] = 'The alias "{}" has been updated.'.format(name) + ret["comment"] = f'The alias "{name}" has been updated.' ret["result"] = True ret["changes"] = { @@ -53,11 +52,11 @@ def alias(name, collections, **kwargs): else: if __opts__["test"]: - ret["comment"] = 'The alias "{}" will be created.'.format(name) + ret["comment"] = f'The alias "{name}" will be created.' ret["result"] = None else: __salt__["solrcloud.alias_set_collections"](name, collections, **kwargs) - ret["comment"] = 'The alias "{}" has been created.'.format(name) + ret["comment"] = f'The alias "{name}" has been created.' ret["result"] = True ret["changes"] = { @@ -121,7 +120,7 @@ def collection(name, options=None, **kwargs): else: if __opts__["test"]: - ret["comment"] = 'Collection options "{}" will be changed.'.format(name) + ret["comment"] = f'Collection options "{name}" will be changed.' ret["result"] = None else: __salt__["solrcloud.collection_set_options"](name, diff, **kwargs) @@ -146,11 +145,11 @@ def collection(name, options=None, **kwargs): options, sort_keys=True, indent=4, separators=(",", ": ") ) if __opts__["test"]: - ret["comment"] = 'The collection "{}" will be created.'.format(name) + ret["comment"] = f'The collection "{name}" will be created.' ret["result"] = None else: __salt__["solrcloud.collection_create"](name, options, **kwargs) - ret["comment"] = 'The collection "{}" has been created.'.format(name) + ret["comment"] = f'The collection "{name}" has been created.' ret["result"] = True ret["changes"] = { diff --git a/salt/states/splunk.py b/salt/states/splunk.py index 272a516ff4a..54c175f5490 100644 --- a/salt/states/splunk.py +++ b/salt/states/splunk.py @@ -50,22 +50,22 @@ def present(email, profile="splunk", **kwargs): if not target: if __opts__["test"]: - ret["comment"] = "User {} will be created".format(name) + ret["comment"] = f"User {name} will be created" return ret # create the user result = __salt__["splunk.create_user"](email, profile=profile, **kwargs) if result: ret["changes"].setdefault("old", None) - ret["changes"].setdefault("new", "User {} exists".format(name)) + ret["changes"].setdefault("new", f"User {name} exists") ret["result"] = True else: ret["result"] = False - ret["comment"] = "Failed to create {}".format(name) + ret["comment"] = f"Failed to create {name}" return ret else: - ret["comment"] = "User {} set to be updated.".format(name) + ret["comment"] = f"User {name} set to be updated." if __opts__["test"]: ret["result"] = None return ret @@ -130,31 +130,31 @@ def absent(email, profile="splunk", **kwargs): "name": user_identity, "changes": {}, "result": None, - "comment": "User {} is absent.".format(user_identity), + "comment": f"User {user_identity} is absent.", } target = __salt__["splunk.get_user"](email, profile=profile) if not target: - ret["comment"] = "User {} does not exist".format(user_identity) + ret["comment"] = f"User {user_identity} does not exist" ret["result"] = True return ret if __opts__["test"]: - ret["comment"] = "User {} is all set to be deleted".format(user_identity) + ret["comment"] = f"User {user_identity} is all set to be deleted" ret["result"] = None return ret result = __salt__["splunk.delete_user"](email, profile=profile) if result: - ret["comment"] = "Deleted user {}".format(user_identity) - ret["changes"].setdefault("old", "User {} exists".format(user_identity)) - ret["changes"].setdefault("new", "User {} deleted".format(user_identity)) + ret["comment"] = f"Deleted user {user_identity}" + ret["changes"].setdefault("old", f"User {user_identity} exists") + ret["changes"].setdefault("new", f"User {user_identity} deleted") ret["result"] = True else: - ret["comment"] = "Failed to delete {}".format(user_identity) + ret["comment"] = f"Failed to delete {user_identity}" ret["result"] = False return ret diff --git a/salt/states/splunk_search.py b/salt/states/splunk_search.py index a12ca481e29..8c00b217e45 100644 --- a/salt/states/splunk_search.py +++ b/salt/states/splunk_search.py @@ -44,7 +44,7 @@ def present(name, profile="splunk", **kwargs): target = __salt__["splunk_search.get"](name, profile=profile) if target: if __opts__["test"]: - ret["comment"] = "Would update {}".format(name) + ret["comment"] = f"Would update {name}" return ret # found a search... updating result = __salt__["splunk_search.update"](name, profile=profile, **kwargs) @@ -64,7 +64,7 @@ def present(name, profile="splunk", **kwargs): ret["changes"]["new"] = newvalues else: if __opts__["test"]: - ret["comment"] = "Would create {}".format(name) + ret["comment"] = f"Would create {name}" return ret # creating a new search result = __salt__["splunk_search.create"](name, profile=profile, **kwargs) @@ -74,7 +74,7 @@ def present(name, profile="splunk", **kwargs): ret["changes"]["new"] = kwargs else: ret["result"] = False - ret["comment"] = "Failed to create {}".format(name) + ret["comment"] = f"Failed to create {name}" return ret @@ -96,7 +96,7 @@ def absent(name, profile="splunk"): "name": name, "changes": {}, "result": True, - "comment": "{} is absent.".format(name), + "comment": f"{name} is absent.", } target = __salt__["splunk_search.get"](name, profile=profile) @@ -104,14 +104,14 @@ def absent(name, profile="splunk"): if __opts__["test"]: ret = {} ret["name"] = name - ret["comment"] = "Would delete {}".format(name) + ret["comment"] = f"Would delete {name}" ret["result"] = None return ret result = __salt__["splunk_search.delete"](name, profile=profile) if result: - ret["comment"] = "{} was deleted".format(name) + ret["comment"] = f"{name} was deleted" else: - ret["comment"] = "Failed to delete {}".format(name) + ret["comment"] = f"Failed to delete {name}" ret["result"] = False return ret diff --git a/salt/states/sqlite3.py b/salt/states/sqlite3.py index d0eb0615dd2..3cddab97d97 100644 --- a/salt/states/sqlite3.py +++ b/salt/states/sqlite3.py @@ -92,7 +92,6 @@ can be approximated with sqlite3's module functions and module.run: - sqlite3: zone-insert-12 """ - try: import sqlite3 diff --git a/salt/states/ssh_auth.py b/salt/states/ssh_auth.py index 1806a34709a..19bc0ae2934 100644 --- a/salt/states/ssh_auth.py +++ b/salt/states/ssh_auth.py @@ -59,7 +59,6 @@ to use a YAML 'explicit key', as demonstrated in the second example below. - AAAAB3NzaC1kcQ9fJFF435bYTEyY== newcomment """ - import re import sys @@ -356,10 +355,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" @@ -386,9 +385,9 @@ def present( ) elif data == "invalid" or data == "Invalid public key": ret["result"] = False - ret[ - "comment" - ] = "Invalid public ssh key, most likely has spaces or invalid syntax" + ret["comment"] = ( + "Invalid public ssh key, most likely has spaces or invalid syntax" + ) return ret diff --git a/salt/states/ssh_known_hosts.py b/salt/states/ssh_known_hosts.py index 262c9cadb32..9502e827bff 100644 --- a/salt/states/ssh_known_hosts.py +++ b/salt/states/ssh_known_hosts.py @@ -148,18 +148,18 @@ def present( ) except CommandNotFoundError as err: ret["result"] = False - ret["comment"] = "ssh.check_known_host error: {}".format(err) + ret["comment"] = f"ssh.check_known_host error: {err}" return ret if result == "exists": - comment = "Host {} is already in {}".format(name, config) + comment = f"Host {name} is already in {config}" ret["result"] = True return dict(ret, comment=comment) elif result == "add": - comment = "Key for {} is set to be added to {}".format(name, config) + comment = f"Key for {name} is set to be added to {config}" return dict(ret, comment=comment) else: # 'update' - comment = "Key for {} is set to be updated in {}".format(name, config) + comment = f"Key for {name} is set to be updated in {config}" return dict(ret, comment=comment) result = __salt__["ssh.set_known_host"]( @@ -175,7 +175,7 @@ def present( fingerprint_hash_type=fingerprint_hash_type, ) if result["status"] == "exists": - return dict(ret, comment="{} already exists in {}".format(name, config)) + return dict(ret, comment=f"{name} already exists in {config}") elif result["status"] == "error": return dict(ret, result=False, comment=result["error"]) else: # 'updated' @@ -184,7 +184,7 @@ def present( return dict( ret, changes={"old": result["old"], "new": result["new"]}, - comment="{}'s key saved to {} (key: {})".format(name, config, new_key), + comment=f"{name}'s key saved to {config} (key: {new_key})", ) else: fingerprint = result["new"][0]["fingerprint"] @@ -235,7 +235,7 @@ def absent(name, user=None, config=None): return dict(ret, comment="Host is already absent") if __opts__["test"]: - comment = "Key for {} is set to be removed from {}".format(name, config) + comment = f"Key for {name} is set to be removed from {config}" ret["result"] = None return dict(ret, comment=comment) diff --git a/salt/states/status.py b/salt/states/status.py index 98cdffb3f08..5f84d07e16b 100644 --- a/salt/states/status.py +++ b/salt/states/status.py @@ -28,7 +28,7 @@ def loadavg(name, maximum=None, minimum=None): data = __salt__["status.loadavg"]() if name not in data: ret["result"] = False - ret["comment"] += "Requested load average {} not available ".format(name) + ret["comment"] += f"Requested load average {name} not available " return ret if minimum and maximum and minimum >= maximum: ret["comment"] += "Min must be less than max" @@ -44,7 +44,7 @@ def loadavg(name, maximum=None, minimum=None): return ret if maximum: if cap > float(maximum): - ret["comment"] = "Load avg above maximum of {} at {}".format(maximum, cap) + ret["comment"] = f"Load avg above maximum of {maximum} at {cap}" return ret ret["comment"] = "Load avg in acceptable range" ret["result"] = True @@ -69,9 +69,9 @@ def process(name): data = __salt__["status.pid"](name) if not data: ret["result"] = False - ret["comment"] += 'Process signature "{}" not found '.format(name) + ret["comment"] += f'Process signature "{name}" not found ' return ret ret["data"] = data - ret["comment"] += 'Process signature "{}" was found '.format(name) + ret["comment"] += f'Process signature "{name}" was found ' ret["result"] = True return ret diff --git a/salt/states/statuspage.py b/salt/states/statuspage.py index e8961aceca8..7d478ae82c9 100644 --- a/salt/states/statuspage.py +++ b/salt/states/statuspage.py @@ -207,7 +207,7 @@ def create( page_id=None, api_key=None, api_version=None, - **kwargs + **kwargs, ): """ Insert a new entry under a specific endpoint. @@ -259,14 +259,14 @@ def create( page_id=page_id, api_key=api_key, api_version=api_version, - **kwargs + **kwargs, ) if not sp_create.get("result"): ret["comment"] = "Unable to create {endpoint}: {msg}".format( endpoint=endpoint_sg, msg=sp_create.get("comment") ) else: - ret["comment"] = "{endpoint} created!".format(endpoint=endpoint_sg) + ret["comment"] = f"{endpoint_sg} created!" ret["result"] = True ret["changes"] = sp_create.get("out") @@ -279,7 +279,7 @@ def update( page_id=None, api_key=None, api_version=None, - **kwargs + **kwargs, ): """ Update attribute(s) of a specific endpoint. @@ -337,14 +337,14 @@ def update( page_id=page_id, api_key=api_key, api_version=api_version, - **kwargs + **kwargs, ) if not sp_update.get("result"): ret["comment"] = "Unable to update {endpoint} #{id}: {msg}".format( endpoint=endpoint_sg, id=id, msg=sp_update.get("comment") ) else: - ret["comment"] = "{endpoint} #{id} updated!".format(endpoint=endpoint_sg, id=id) + ret["comment"] = f"{endpoint_sg} #{id} updated!" ret["result"] = True ret["changes"] = sp_update.get("out") @@ -411,7 +411,7 @@ def delete( endpoint=endpoint_sg, id=id, msg=sp_delete.get("comment") ) else: - ret["comment"] = "{endpoint} #{id} deleted!".format(endpoint=endpoint_sg, id=id) + ret["comment"] = f"{endpoint_sg} #{id} deleted!" ret["result"] = True @@ -544,7 +544,7 @@ def managed( page_id=page_id, api_key=api_key, api_version=api_version, - **new_endpoint + **new_endpoint, ) if not adding.get("result"): ret.update({"comment": adding.get("comment")}) @@ -563,7 +563,7 @@ def managed( page_id=page_id, api_key=api_key, api_version=api_version, - **update_endpoint + **update_endpoint, ) if not updating.get("result"): ret.update({"comment": updating.get("comment")}) diff --git a/salt/states/supervisord.py b/salt/states/supervisord.py index d0a5614c939..4b0c7bbf23c 100644 --- a/salt/states/supervisord.py +++ b/salt/states/supervisord.py @@ -82,9 +82,9 @@ def running( if "supervisord.status" not in __salt__: ret["result"] = False - ret[ - "comment" - ] = "Supervisord module not activated. Do you need to install supervisord?" + ret["comment"] = ( + "Supervisord module not activated. Do you need to install supervisord?" + ) return ret all_processes = __salt__["supervisord.status"]( @@ -115,34 +115,34 @@ def running( if name.endswith(":"): # Process group if len(to_start) == len(matches): - ret[ - "comment" - ] = "All services in group '{}' will be started".format(name) + ret["comment"] = ( + f"All services in group '{name}' will be started" + ) else: - ret[ - "comment" - ] = "The following services will be started: {}".format( - " ".join(to_start) + ret["comment"] = ( + "The following services will be started: {}".format( + " ".join(to_start) + ) ) else: # Single program - ret["comment"] = "Service {} will be started".format(name) + ret["comment"] = f"Service {name} will be started" else: if name.endswith(":"): # Process group - ret[ - "comment" - ] = "All services in group '{}' are already running".format(name) + ret["comment"] = ( + f"All services in group '{name}' are already running" + ) else: - ret["comment"] = "Service {} is already running".format(name) + ret["comment"] = f"Service {name} is already running" else: ret["result"] = None # Process/group needs to be added if name.endswith(":"): - _type = "Group '{}'".format(name) + _type = f"Group '{name}'" else: - _type = "Service {}".format(name) - ret["comment"] = "{} will be added and started".format(_type) + _type = f"Service {name}" + ret["comment"] = f"{_type} will be added and started" return ret changes = [] @@ -162,11 +162,11 @@ def running( ret.update(_check_error(result, comment)) log.debug(comment) - if "{}: updated".format(name) in result: + if f"{name}: updated" in result: just_updated = True elif to_add: # Not sure if this condition is precise enough. - comment = "Adding service: {}".format(name) + comment = f"Adding service: {name}" __salt__["supervisord.reread"](user=user, conf_file=conf_file, bin_env=bin_env) # Causes supervisorctl to throw `ERROR: process group already active` # if process group exists. At this moment, I'm not sure how to handle @@ -205,7 +205,7 @@ def running( if is_stopped is False: if restart and not just_updated: comment = "Restarting{}: {}".format( - process_type is not None and " {}".format(process_type) or "", name + process_type is not None and f" {process_type}" or "", name ) log.debug(comment) result = __salt__["supervisord.restart"]( @@ -215,20 +215,20 @@ def running( changes.append(comment) elif just_updated: comment = "Not starting updated{}: {}".format( - process_type is not None and " {}".format(process_type) or "", name + process_type is not None and f" {process_type}" or "", name ) result = comment ret.update({"comment": comment}) else: comment = "Not starting already running{}: {}".format( - process_type is not None and " {}".format(process_type) or "", name + process_type is not None and f" {process_type}" or "", name ) result = comment ret.update({"comment": comment}) elif not just_updated: comment = "Starting{}: {}".format( - process_type is not None and " {}".format(process_type) or "", name + process_type is not None and f" {process_type}" or "", name ) changes.append(comment) log.debug(comment) @@ -268,9 +268,9 @@ def dead(name, user=None, conf_file=None, bin_env=None, **kwargs): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Service {} is set to be stopped".format(name) + ret["comment"] = f"Service {name} is set to be stopped" else: - comment = "Stopping service: {}".format(name) + comment = f"Stopping service: {name}" log.debug(comment) all_processes = __salt__["supervisord.status"]( @@ -303,11 +303,11 @@ def dead(name, user=None, conf_file=None, bin_env=None, **kwargs): is_stopped = False else: # process name doesn't exist - ret["comment"] = "Service {} doesn't exist".format(name) + ret["comment"] = f"Service {name} doesn't exist" return ret if is_stopped is True: - ret["comment"] = "Service {} is not running".format(name) + ret["comment"] = f"Service {name} is not running" else: result = { name: __salt__["supervisord.stop"]( diff --git a/salt/states/svn.py b/salt/states/svn.py index c041d4f27a6..aac0dca9fa9 100644 --- a/salt/states/svn.py +++ b/salt/states/svn.py @@ -101,7 +101,7 @@ def latest( opts = tuple() if os.path.exists(target) and not os.path.isdir(target): - return _fail(ret, 'The path "{}" exists and is not a directory.'.format(target)) + return _fail(ret, f'The path "{target}" exists and is not a directory.') if __opts__["test"]: if rev: @@ -123,11 +123,11 @@ def latest( ) svn_cmd = "svn.diff" except exceptions.CommandExecutionError: - return _fail(ret, "{} exists but is not a svn working copy.".format(target)) + return _fail(ret, f"{target} exists but is not a svn working copy.") current_rev = current_info[0]["Revision"] - opts += ("-r", "{}:{}".format(current_rev, new_rev)) + opts += ("-r", f"{current_rev}:{new_rev}") if trust: opts += ("--trust-server-cert",) @@ -173,7 +173,7 @@ def latest( fmt="dict", )[0]["Revision"] if current_rev != new_rev: - ret["changes"]["revision"] = "{} => {}".format(current_rev, new_rev) + ret["changes"]["revision"] = f"{current_rev} => {new_rev}" else: out = __salt__[svn_cmd](cwd, name, basename, user, username, password, *opts) @@ -260,11 +260,11 @@ def export( opts = () if not overwrite and os.path.exists(target) and not os.path.isdir(target): - return _fail(ret, 'The path "{}" exists and is not a directory.'.format(target)) + return _fail(ret, f'The path "{target}" exists and is not a directory.') if __opts__["test"]: if not os.path.exists(target): return _neutral_test( - ret, "{} doesn't exist and is set to be checked out.".format(target) + ret, f"{target} doesn't exist and is set to be checked out." ) svn_cmd = "svn.list" rev = "HEAD" @@ -288,7 +288,7 @@ def export( out = __salt__[svn_cmd](cwd, name, basename, user, username, password, rev, *opts) ret["changes"]["new"] = name - ret["changes"]["comment"] = "{} was Exported to {}".format(name, target) + ret["changes"]["comment"] = f"{name} was Exported to {target}" ret["comment"] = out return ret diff --git a/salt/states/sysctl.py b/salt/states/sysctl.py index 4498e672758..a417512bd1f 100644 --- a/salt/states/sysctl.py +++ b/salt/states/sysctl.py @@ -98,20 +98,20 @@ def present(name, value, config=None): return ret # otherwise, we don't have it set anywhere and need to set it ret["result"] = None - ret["comment"] = "Sysctl option {} would be changed to {}".format(name, value) + ret["comment"] = f"Sysctl option {name} would be changed to {value}" return ret try: update = __salt__["sysctl.persist"](name, value, config) except CommandExecutionError as exc: ret["result"] = False - ret["comment"] = "Failed to set {} to {}: {}".format(name, value, exc) + ret["comment"] = f"Failed to set {name} to {value}: {exc}" return ret if update == "Updated": ret["changes"] = {name: value} - ret["comment"] = "Updated sysctl value {} = {}".format(name, value) + ret["comment"] = f"Updated sysctl value {name} = {value}" elif update == "Already set": - ret["comment"] = "Sysctl value {} = {} is already set".format(name, value) + ret["comment"] = f"Sysctl value {name} = {value} is already set" return ret diff --git a/salt/states/sysfs.py b/salt/states/sysfs.py index afcaf609fbe..e63c6499bc9 100644 --- a/salt/states/sysfs.py +++ b/salt/states/sysfs.py @@ -41,33 +41,33 @@ def present(name, value, config=None): current = __salt__["sysfs.read"](name) if current is False: ret["result"] = False - ret["comment"] = "SysFS attribute {} doesn't exist.".format(name) + ret["comment"] = f"SysFS attribute {name} doesn't exist." else: # if the return is a dict, the "name" is an object not an attribute if isinstance(current, dict): ret["result"] = False - ret["comment"] = "{} is not a SysFS attribute.".format(name) + ret["comment"] = f"{name} is not a SysFS attribute." else: # some attribute files lists all available options and the selected one between [] if isinstance(current, str): current = re.sub(r"(.*\[|\].*)", "", current) if value == current: ret["result"] = True - ret["comment"] = "SysFS attribute {} is already set.".format(name) + ret["comment"] = f"SysFS attribute {name} is already set." else: ret["result"] = None if ret["result"] is None: if __opts__["test"]: - ret["comment"] = "SysFS attribute {} set to be changed.".format(name) + ret["comment"] = f"SysFS attribute {name} set to be changed." else: update = __salt__["sysfs.write"](name, value) if not update: ret["result"] = False - ret["comment"] = "Failed to set {} to {}".format(name, value) + ret["comment"] = f"Failed to set {name} to {value}" else: ret["result"] = True ret["changes"] = {name: value} - ret["comment"] = "Updated SysFS attribute {} to {}".format(name, value) + ret["comment"] = f"Updated SysFS attribute {name} to {value}" return ret diff --git a/salt/states/sysrc.py b/salt/states/sysrc.py index 991e33bbff9..4c7b0d2a57f 100644 --- a/salt/states/sysrc.py +++ b/salt/states/sysrc.py @@ -3,7 +3,6 @@ State to work with sysrc """ - # define the module's virtual name __virtualname__ = "sysrc" @@ -48,11 +47,11 @@ def managed(name, value, **kwargs): for rcname, rcdict in current_state.items(): if rcdict[name] == value: ret["result"] = True - ret["comment"] = "{} is already set to the desired value.".format(name) + ret["comment"] = f"{name} is already set to the desired value." return ret if __opts__["test"] is True: - ret["comment"] = 'The value of "{}" will be changed!'.format(name) + ret["comment"] = f'The value of "{name}" will be changed!' ret["changes"] = { "old": current_state, "new": name + " = " + value + " will be set.", @@ -65,7 +64,7 @@ def managed(name, value, **kwargs): new_state = __salt__["sysrc.set"](name=name, value=value, **kwargs) - ret["comment"] = 'The value of "{}" was changed!'.format(name) + ret["comment"] = f'The value of "{name}" was changed!' ret["changes"] = {"old": current_state, "new": new_state} @@ -92,14 +91,14 @@ def absent(name, **kwargs): current_state = __salt__["sysrc.get"](name=name, **kwargs) if current_state is None: ret["result"] = True - ret["comment"] = '"{}" is already absent.'.format(name) + ret["comment"] = f'"{name}" is already absent.' return ret if __opts__["test"] is True: - ret["comment"] = '"{}" will be removed!'.format(name) + ret["comment"] = f'"{name}" will be removed!' ret["changes"] = { "old": current_state, - "new": '"{}" will be removed.'.format(name), + "new": f'"{name}" will be removed.', } # When test=true return none @@ -109,7 +108,7 @@ def absent(name, **kwargs): new_state = __salt__["sysrc.remove"](name=name, **kwargs) - ret["comment"] = '"{}" was removed!'.format(name) + ret["comment"] = f'"{name}" was removed!' ret["changes"] = {"old": current_state, "new": new_state} diff --git a/salt/states/telemetry_alert.py b/salt/states/telemetry_alert.py index ccbe8fb9791..18ec2bc40ed 100644 --- a/salt/states/telemetry_alert.py +++ b/salt/states/telemetry_alert.py @@ -96,7 +96,7 @@ def present( # del saved_alert_config["_id"] for k, v in post_body.items(): if k not in saved_alert_config: - difference.append("{}={} (new)".format(k, v)) + difference.append(f"{k}={v} (new)") continue v2 = saved_alert_config[k] @@ -108,7 +108,7 @@ def present( continue if isinstance(v, int) and v == int(v2): continue - difference.append("{}='{}' was: '{}'".format(k, v, v2)) + difference.append(f"{k}='{v}' was: '{v2}'") else: difference.append("new alert config") @@ -122,10 +122,10 @@ def present( if saved_alert_config: # alert config is present. update, or do nothing # check to see if attributes matches is_present. If so, do nothing. if len(difference) == 0: - ret["comment"] = "alert config {} present and matching".format(metric_name) + ret["comment"] = f"alert config {metric_name} present and matching" return ret if __opts__["test"]: - msg = "alert config {} is to be updated.".format(metric_name) + msg = f"alert config {metric_name} is to be updated." ret["comment"] = msg ret["result"] = "\n".join(difference) return ret @@ -142,7 +142,7 @@ def present( ) else: # alert config is absent. create it. if __opts__["test"]: - msg = "alert config {} is to be created.".format(metric_name) + msg = f"alert config {metric_name} is to be created." ret["comment"] = msg ret["result"] = None return ret @@ -190,10 +190,10 @@ def absent(name, deployment_id, metric_name, api_key=None, profile="telemetry"): if is_present: alert_id = is_present.get("_id") if __opts__["test"]: - ret[ - "comment" - ] = "alert {} is set to be removed from deployment: {}.".format( - metric_name, deployment_id + ret["comment"] = ( + "alert {} is set to be removed from deployment: {}.".format( + metric_name, deployment_id + ) ) ret["result"] = None return ret diff --git a/salt/states/test.py b/salt/states/test.py index 464f3ee33aa..bdded67a16e 100644 --- a/salt/states/test.py +++ b/salt/states/test.py @@ -478,17 +478,17 @@ def check_pillar( fine[key] = key_type for key, key_type in failed.items(): - comment = 'Pillar key "{}" '.format(key) + comment = f'Pillar key "{key}" ' if key_type is None: comment += "is missing.\n" else: - comment += "is not {}.\n".format(key_type) + comment += f"is not {key_type}.\n" ret["comment"] += comment if verbose and fine: comment = "Those keys passed the check:\n" for key, key_type in fine.items(): - comment += "- {} ({})\n".format(key, key_type) + comment += f"- {key} ({key_type})\n" ret["comment"] += comment return ret diff --git a/salt/states/testinframod.py b/salt/states/testinframod.py index 493fc8ef2eb..d0107ae79d9 100644 --- a/salt/states/testinframod.py +++ b/salt/states/testinframod.py @@ -40,7 +40,7 @@ def _generate_functions(): modules_ = [module_ for module_ in modules.modules] for module_name in modules_: - func_name = "testinfra.{}".format(module_name) + func_name = f"testinfra.{module_name}" __all__.append(module_name) log.debug( "Generating state for module %s as function %s", module_name, func_name diff --git a/salt/states/timezone.py b/salt/states/timezone.py index 514e4c0dda6..208d18e5f0b 100644 --- a/salt/states/timezone.py +++ b/salt/states/timezone.py @@ -58,10 +58,10 @@ def system(name, utc=True): compzone = __salt__["timezone.zone_compare"](name) except (SaltInvocationError, CommandExecutionError) as exc: ret["result"] = False - ret[ - "comment" - ] = "Unable to compare desired timezone '{}' to system timezone: {}".format( - name, exc + ret["comment"] = ( + "Unable to compare desired timezone '{}' to system timezone: {}".format( + name, exc + ) ) return ret @@ -73,7 +73,7 @@ def system(name, utc=True): # Check the time zone if compzone is True: ret["result"] = True - messages.append("Timezone {} already set".format(name)) + messages.append(f"Timezone {name} already set") else: do_zone = True @@ -82,7 +82,7 @@ def system(name, utc=True): ret["result"] = None do_utc = True elif utc and utc == myutc: - messages.append("UTC already set to {}".format(name)) + messages.append(f"UTC already set to {name}") if ret["result"] is True: ret["comment"] = ", ".join(messages) @@ -91,9 +91,9 @@ def system(name, utc=True): if __opts__["test"]: messages = [] if compzone is False: - messages.append("Timezone {} needs to be set".format(name)) + messages.append(f"Timezone {name} needs to be set") if utc and myutc != utc: - messages.append("UTC needs to be set to {}".format(utc)) + messages.append(f"UTC needs to be set to {utc}") ret["comment"] = ", ".join(messages) return ret @@ -102,7 +102,7 @@ def system(name, utc=True): if do_zone: if __salt__["timezone.set_zone"](name): ret["changes"]["timezone"] = name - messages.append("Set timezone {}".format(name)) + messages.append(f"Set timezone {name}") ret["result"] = True else: messages.append("Failed to set timezone") @@ -114,10 +114,10 @@ def system(name, utc=True): clock = "UTC" if __salt__["timezone.set_hwclock"](clock): ret["changes"]["utc"] = utc - messages.append("Set UTC to {}".format(utc)) + messages.append(f"Set UTC to {utc}") ret["result"] = True else: - messages.append("Failed to set UTC to {}".format(utc)) + messages.append(f"Failed to set UTC to {utc}") ret["result"] = False ret["comment"] = ", ".join(messages) diff --git a/salt/states/tls.py b/salt/states/tls.py index 8e0f1249424..9c0fc451711 100644 --- a/salt/states/tls.py +++ b/salt/states/tls.py @@ -4,7 +4,6 @@ Enforce state for SSL/TLS """ - import datetime import logging import time @@ -31,7 +30,7 @@ def valid_certificate(name, weeks=0, days=0, hours=0, minutes=0, seconds=0): try: cert_info = __salt__["tls.cert_info"](name) except OSError as exc: - ret["comment"] = "{}".format(exc) + ret["comment"] = f"{exc}" ret["result"] = False log.error(ret["comment"]) return ret @@ -63,5 +62,5 @@ def valid_certificate(name, weeks=0, days=0, hours=0, minutes=0, seconds=0): return ret ret["result"] = True - ret["comment"] = "Certificate is valid for {}".format(delta_remaining) + ret["comment"] = f"Certificate is valid for {delta_remaining}" return ret diff --git a/salt/states/tomcat.py b/salt/states/tomcat.py index d4511911fd4..5b74573c143 100644 --- a/salt/states/tomcat.py +++ b/salt/states/tomcat.py @@ -142,7 +142,7 @@ def war_deployed( status = True # Gathered/specified new WAR version string - specified_ver = "version {}".format(version) if version else "no version" + specified_ver = f"version {version}" if version else "no version" # Determine what to do try: @@ -172,13 +172,13 @@ def war_deployed( name, specified_ver ) if webapps[name]["mode"] != "running": - ret["changes"]["start"] = "starting {}".format(name) + ret["changes"]["start"] = f"starting {name}" status = False else: return ret except Exception: # pylint: disable=broad-except deploy = True - ret["changes"]["deploy"] = "deployed {} with {}".format(name, specified_ver) + ret["changes"]["deploy"] = f"deployed {name} with {specified_ver}" # Test if __opts__["test"]: @@ -216,7 +216,7 @@ def war_deployed( if deploy_res.startswith("OK"): ret["result"] = True ret["comment"] = str(__salt__["tomcat.ls"](url, timeout)[name]) - ret["changes"]["deploy"] = "deployed {} with {}".format(name, specified_ver) + ret["changes"]["deploy"] = f"deployed {name} with {specified_ver}" else: ret["result"] = False ret["comment"] = deploy_res diff --git a/salt/states/trafficserver.py b/salt/states/trafficserver.py index c491f176bac..55edcd35836 100644 --- a/salt/states/trafficserver.py +++ b/salt/states/trafficserver.py @@ -209,7 +209,7 @@ def config(name, value): __salt__["trafficserver.set_config"](name, value) ret["result"] = True - ret["comment"] = "Configured {} to {}".format(name, value) + ret["comment"] = f"Configured {name} to {value}" return ret @@ -345,11 +345,11 @@ def offline(name, path): ret = {"name": name, "changes": {}, "result": None, "comment": ""} if __opts__["test"]: - ret["comment"] = "Setting {} to offline".format(path) + ret["comment"] = f"Setting {path} to offline" return ret __salt__["trafficserver.offline"](path) ret["result"] = True - ret["comment"] = "Set {} as offline".format(path) + ret["comment"] = f"Set {path} as offline" return ret diff --git a/salt/states/uptime.py b/salt/states/uptime.py index 590d1017066..5c284eeb2f1 100644 --- a/salt/states/uptime.py +++ b/salt/states/uptime.py @@ -53,7 +53,7 @@ def monitored(name, **params): ret = {"name": name, "changes": {}, "result": None, "comment": ""} if __salt__["uptime.check_exists"](name=name): ret["result"] = True - ret["comment"] = "URL {} is already monitored".format(name) + ret["comment"] = f"URL {name} is already monitored" ret["changes"] = {} return ret if not __opts__["test"]: @@ -65,7 +65,7 @@ def monitored(name, **params): ret["changes"] = {"url_monitored": url_monitored} else: ret["result"] = False - ret["comment"] = "Failed to add {} to uptime".format(name) + ret["comment"] = f"Failed to add {name} to uptime" ret["changes"] = {} else: msg = "URL {0} is going to be added to uptime" diff --git a/salt/states/user.py b/salt/states/user.py index 756ec17d19a..f0452fa2f60 100644 --- a/salt/states/user.py +++ b/salt/states/user.py @@ -932,10 +932,10 @@ def present( __salt__["shadow.set_password"](name, password) spost = __salt__["shadow.info"](name) if spost["passwd"] != password: - ret[ - "comment" - ] = "User {} created but failed to set password to {}".format( - name, "XXX-REDACTED-XXX" + ret["comment"] = ( + "User {} created but failed to set password to {}".format( + name, "XXX-REDACTED-XXX" + ) ) ret["result"] = False ret["changes"]["password"] = "XXX-REDACTED-XXX" @@ -943,9 +943,9 @@ def present( __salt__["shadow.del_password"](name) spost = __salt__["shadow.info"](name) if spost["passwd"] != "": - ret[ - "comment" - ] = f"User {name} created but failed to empty password" + ret["comment"] = ( + f"User {name} created but failed to empty password" + ) ret["result"] = False ret["changes"]["password"] = "" if date is not None: @@ -996,10 +996,10 @@ def present( __salt__["shadow.set_warndays"](name, warndays) spost = __salt__["shadow.info"](name) if spost["warn"] != warndays: - ret[ - "comment" - ] = "User {} created but failed to set warn days to {}".format( - name, warndays + ret["comment"] = ( + "User {} created but failed to set warn days to {}".format( + name, warndays + ) ) ret["result"] = False ret["changes"]["warndays"] = warndays @@ -1017,10 +1017,10 @@ def present( elif salt.utils.platform.is_windows(): if password and not empty_password: if not __salt__["user.setpassword"](name, password): - ret[ - "comment" - ] = "User {} created but failed to set password to {}".format( - name, "XXX-REDACTED-XXX" + ret["comment"] = ( + "User {} created but failed to set password to {}".format( + name, "XXX-REDACTED-XXX" + ) ) ret["result"] = False ret["changes"]["passwd"] = "XXX-REDACTED-XXX" @@ -1039,10 +1039,10 @@ def present( ret["changes"]["expiration_date"] = spost["expire"] elif salt.utils.platform.is_darwin() and password and not empty_password: if not __salt__["shadow.set_password"](name, password): - ret[ - "comment" - ] = "User {} created but failed to set password to {}".format( - name, "XXX-REDACTED-XXX" + ret["comment"] = ( + "User {} created but failed to set password to {}".format( + name, "XXX-REDACTED-XXX" + ) ) ret["result"] = False ret["changes"]["passwd"] = "XXX-REDACTED-XXX" diff --git a/salt/states/vagrant.py b/salt/states/vagrant.py index 4210715f92e..93650d54de0 100644 --- a/salt/states/vagrant.py +++ b/salt/states/vagrant.py @@ -103,7 +103,7 @@ def _vagrant_call(node, function, section, comment, status_when_done=None, **kwa except (IndexError, SaltInvocationError, CommandExecutionError): pass try: - response = __salt__["vagrant.{}".format(function)](node, **kwargs) + response = __salt__[f"vagrant.{function}"](node, **kwargs) if isinstance(response, dict): response = response["name"] changed_nodes.append({"node": node, function: response}) @@ -170,7 +170,7 @@ def running(name, **kwargs): "name": name, "changes": {}, "result": True, - "comment": "{} is already running".format(name), + "comment": f"{name} is already running", } try: @@ -178,14 +178,14 @@ def running(name, **kwargs): if info[0]["state"] != "running": __salt__["vagrant.start"](name) ret["changes"][name] = "Machine started" - ret["comment"] = "Node {} started".format(name) + ret["comment"] = f"Node {name} started" except (SaltInvocationError, CommandExecutionError): # there was no viable existing machine to start ret, kwargs = _find_init_change(name, ret, **kwargs) kwargs["start"] = True __salt__["vagrant.init"](name, **kwargs) ret["changes"][name] = "Node defined and started" - ret["comment"] = "Node {} defined and started".format(name) + ret["comment"] = f"Node {name} defined and started" return ret @@ -272,7 +272,7 @@ def initialized(name, **kwargs): kwargs["start"] = False __salt__["vagrant.init"](name, **kwargs) ret["changes"][name] = "Node initialized" - ret["comment"] = "Node {} defined but not started.".format(name) + ret["comment"] = f"Node {name} defined but not started." return ret diff --git a/salt/states/vbox_guest.py b/salt/states/vbox_guest.py index 45a78381d59..78907dd14f7 100644 --- a/salt/states/vbox_guest.py +++ b/salt/states/vbox_guest.py @@ -126,9 +126,9 @@ def grant_access_to_shared_folders_to(name, users=None): name=name, users=users ) - ret[ - "comment" - ] = "List of users who have access to auto-mounted shared folders was changed" + ret["comment"] = ( + "List of users who have access to auto-mounted shared folders was changed" + ) ret["changes"] = { "old": current_state, "new": new_state, diff --git a/salt/states/victorops.py b/salt/states/victorops.py index 54cf5353a2c..f89265fe2cb 100644 --- a/salt/states/victorops.py +++ b/salt/states/victorops.py @@ -93,7 +93,7 @@ def create_event(name, message_type, routing_key="everyone", **kwargs): ret = {"name": name, "changes": {}, "result": None, "comment": ""} if __opts__["test"]: - ret["comment"] = "Need to create event: {}".format(name) + ret["comment"] = f"Need to create event: {name}" return ret res = __salt__["victorops.create_event"]( diff --git a/salt/states/virt.py b/salt/states/virt.py index 3b958e32d60..33f35b0d8c8 100644 --- a/salt/states/virt.py +++ b/salt/states/virt.py @@ -11,7 +11,6 @@ for the generation and signing of certificates for systems running libvirt: virt.keys """ - import fnmatch import logging import os @@ -95,7 +94,7 @@ def keys(name, basepath="/etc/pki", **kwargs): # overriding anything existing pillar_kwargs = {} for key, value in kwargs.items(): - pillar_kwargs["ext_pillar_virt.{}".format(key)] = value + pillar_kwargs[f"ext_pillar_virt.{key}"] = value pillar = __salt__["pillar.ext"]({"libvirt": "_"}, pillar_kwargs) paths = { @@ -107,7 +106,7 @@ def keys(name, basepath="/etc/pki", **kwargs): } for key in paths: - p_key = "libvirt.{}.pem".format(key) + p_key = f"libvirt.{key}.pem" if p_key not in pillar: continue if not os.path.exists(os.path.dirname(paths[key])): @@ -128,9 +127,7 @@ def keys(name, basepath="/etc/pki", **kwargs): else: for key in ret["changes"]: with salt.utils.files.fopen(paths[key], "w+") as fp_: - fp_.write( - salt.utils.stringutils.to_str(pillar["libvirt.{}.pem".format(key)]) - ) + fp_.write(salt.utils.stringutils.to_str(pillar[f"libvirt.{key}.pem"])) ret["comment"] = "Updated libvirt certs and keys" @@ -146,7 +143,7 @@ def _virt_call( connection=None, username=None, password=None, - **kwargs + **kwargs, ): """ Helper to call the virt functions. Wildcards supported. @@ -174,12 +171,12 @@ def _virt_call( if action_needed: response = True if not __opts__["test"]: - response = __salt__["virt.{}".format(function)]( + response = __salt__[f"virt.{function}"]( targeted_domain, connection=connection, username=username, password=password, - **kwargs + **kwargs, ) if isinstance(response, dict): response = response["name"] @@ -677,14 +674,12 @@ def defined( ret["changes"][name] = status if not status.get("definition"): ret["changes"] = {} - ret["comment"] = "Domain {} unchanged".format(name) + ret["comment"] = f"Domain {name} unchanged" ret["result"] = True elif status.get("errors"): - ret[ - "comment" - ] = "Domain {} updated with live update(s) failures".format(name) + ret["comment"] = f"Domain {name} updated with live update(s) failures" else: - ret["comment"] = "Domain {} updated".format(name) + ret["comment"] = f"Domain {name} updated" else: if not __opts__["test"]: __salt__["virt.init"]( @@ -718,7 +713,7 @@ def defined( host_devices=host_devices, ) ret["changes"][name] = {"definition": True} - ret["comment"] = "Domain {} defined".format(name) + ret["comment"] = f"Domain {name} defined" except libvirt.libvirtError as err: # Something bad happened when defining / updating the VM, report it ret["comment"] = str(err) @@ -1050,7 +1045,7 @@ def running( username=username, password=password, ) - comment = "Domain {} started".format(name) + comment = f"Domain {name} started" if not ret["comment"].endswith("unchanged"): comment = "{} and started".format(ret["comment"]) ret["comment"] = comment @@ -1058,7 +1053,7 @@ def running( ret["changes"][name] = {} ret["changes"][name]["started"] = True elif not changed: - ret["comment"] = "Domain {} exists and is running".format(name) + ret["comment"] = f"Domain {name} exists and is running" except libvirt.libvirtError as err: # Something bad happened when starting / updating the VM, report it @@ -1207,7 +1202,7 @@ def reverted( try: domains = fnmatch.filter(__salt__["virt.list_domains"](), name) if not domains: - ret["comment"] = 'No domains found for criteria "{}"'.format(name) + ret["comment"] = f'No domains found for criteria "{name}"' else: ignored_domains = list() if len(domains) > 1: @@ -1516,10 +1511,10 @@ def network_defined( password=password, ) action = ", autostart flag changed" if needs_autostart else "" - ret["changes"][name] = "Network updated{}".format(action) - ret["comment"] = "Network {} updated{}".format(name, action) + ret["changes"][name] = f"Network updated{action}" + ret["comment"] = f"Network {name} updated{action}" else: - ret["comment"] = "Network {} unchanged".format(name) + ret["comment"] = f"Network {name} unchanged" ret["result"] = True else: needs_autostart = autostart @@ -1547,10 +1542,10 @@ def network_defined( ) if needs_autostart: ret["changes"][name] = "Network defined, marked for autostart" - ret["comment"] = "Network {} defined, marked for autostart".format(name) + ret["comment"] = f"Network {name} defined, marked for autostart" else: ret["changes"][name] = "Network defined" - ret["comment"] = "Network {} defined".format(name) + ret["comment"] = f"Network {name} defined" if needs_autostart: if not __opts__["test"]: @@ -1975,15 +1970,13 @@ def pool_defined( action = ", built" action = ( - "{}, autostart flag changed".format(action) - if needs_autostart - else action + f"{action}, autostart flag changed" if needs_autostart else action ) - ret["changes"][name] = "Pool updated{}".format(action) - ret["comment"] = "Pool {} updated{}".format(name, action) + ret["changes"][name] = f"Pool updated{action}" + ret["comment"] = f"Pool {name} updated{action}" else: - ret["comment"] = "Pool {} unchanged".format(name) + ret["comment"] = f"Pool {name} unchanged" ret["result"] = True else: needs_autostart = autostart @@ -2026,10 +2019,10 @@ def pool_defined( ) if needs_autostart: ret["changes"][name] = "Pool defined, marked for autostart" - ret["comment"] = "Pool {} defined, marked for autostart".format(name) + ret["comment"] = f"Pool {name} defined, marked for autostart" else: ret["changes"][name] = "Pool defined" - ret["comment"] = "Pool {} defined".format(name) + ret["comment"] = f"Pool {name} defined" if needs_autostart: if not __opts__["test"]: @@ -2147,7 +2140,7 @@ def pool_running( username=username, password=password, ) - action = "built, {}".format(action) + action = f"built, {action}" else: action = "already running" result = True @@ -2161,16 +2154,16 @@ def pool_running( password=password, ) - comment = "Pool {}".format(name) + comment = f"Pool {name}" change = "Pool" if name in ret["changes"]: comment = "{},".format(ret["comment"]) change = "{},".format(ret["changes"][name]) if action != "already running": - ret["changes"][name] = "{} {}".format(change, action) + ret["changes"][name] = f"{change} {action}" - ret["comment"] = "{} {}".format(comment, action) + ret["comment"] = f"{comment} {action}" ret["result"] = result except libvirt.libvirtError as err: @@ -2302,9 +2295,9 @@ def pool_deleted(name, purge=False, connection=None, username=None, password=Non info[name]["type"], ", ".join(unsupported) ) else: - ret["comment"] = "Storage pool could not be found: {}".format(name) + ret["comment"] = f"Storage pool could not be found: {name}" except libvirt.libvirtError as err: - ret["comment"] = "Failed deleting pool: {}".format(err.get_error_message()) + ret["comment"] = f"Failed deleting pool: {err.get_error_message()}" ret["result"] = False return ret @@ -2390,7 +2383,7 @@ def volume_defined( connection=connection, username=username, password=password ) if pool not in pools: - raise SaltInvocationError("Storage pool {} not existing".format(pool)) + raise SaltInvocationError(f"Storage pool {pool} not existing") vol_infos = ( __salt__["virt.volume_infos"]( @@ -2422,9 +2415,9 @@ def volume_defined( # otherwise assume the volume has already been defined # if the sizes don't match, issue a warning comment: too dangerous to do this for now if int(vol_infos.get("capacity")) != int(size) * 1024 * 1024: - ret[ - "comment" - ] = "The capacity of the volume is different, but no resize performed" + ret["comment"] = ( + "The capacity of the volume is different, but no resize performed" + ) return ret ret["result"] = None if __opts__["test"] else True @@ -2450,7 +2443,7 @@ def volume_defined( ret["comment"] = "Volume {} {}defined in pool {}".format( name, test_comment, pool ) - ret["changes"] = {"{}/{}".format(pool, name): {"old": "", "new": "defined"}} + ret["changes"] = {f"{pool}/{name}": {"old": "", "new": "defined"}} except libvirt.libvirtError as err: ret["comment"] = err.get_error_message() ret["result"] = False diff --git a/salt/states/virtualenv_mod.py b/salt/states/virtualenv_mod.py index d395dd2cc1a..957f44265bc 100644 --- a/salt/states/virtualenv_mod.py +++ b/salt/states/virtualenv_mod.py @@ -4,7 +4,6 @@ Setup of Python virtualenv sandboxes. .. versionadded:: 0.17.0 """ - import logging import os @@ -58,7 +57,7 @@ def managed( pip_cache_dir=None, process_dependency_links=False, no_binary=None, - **kwargs + **kwargs, ): """ Create a virtualenv and optionally manage it with pip @@ -172,21 +171,19 @@ def managed( # If it already exists, grab the version for posterity if venv_exists and clear: ret["changes"]["cleared_packages"] = __salt__["pip.freeze"](bin_env=name) - ret["changes"]["old"] = __salt__["cmd.run_stderr"]( - "{} -V".format(venv_py) - ).strip("\n") + ret["changes"]["old"] = __salt__["cmd.run_stderr"](f"{venv_py} -V").strip("\n") # Create (or clear) the virtualenv if __opts__["test"]: if venv_exists and clear: ret["result"] = None - ret["comment"] = "Virtualenv {} is set to be cleared".format(name) + ret["comment"] = f"Virtualenv {name} is set to be cleared" return ret if venv_exists and not clear: - ret["comment"] = "Virtualenv {} is already created".format(name) + ret["comment"] = f"Virtualenv {name} is already created" return ret ret["result"] = None - ret["comment"] = "Virtualenv {} is set to be created".format(name) + ret["comment"] = f"Virtualenv {name} is set to be created" return ret if not venv_exists or (venv_exists and clear): @@ -203,11 +200,11 @@ def managed( prompt=prompt, user=user, use_vt=use_vt, - **kwargs + **kwargs, ) except CommandNotFoundError as err: ret["result"] = False - ret["comment"] = "Failed to create virtualenv: {}".format(err) + ret["comment"] = f"Failed to create virtualenv: {err}" return ret if venv_ret["retcode"] != 0: @@ -216,9 +213,7 @@ def managed( return ret ret["result"] = True - ret["changes"]["new"] = __salt__["cmd.run_stderr"]( - "{} -V".format(venv_py) - ).strip("\n") + ret["changes"]["new"] = __salt__["cmd.run_stderr"](f"{venv_py} -V").strip("\n") if clear: ret["comment"] = "Cleared existing virtualenv" @@ -329,7 +324,7 @@ def managed( env_vars=env_vars, no_cache_dir=pip_no_cache_dir, cache_dir=pip_cache_dir, - **kwargs + **kwargs, ) ret["result"] &= pip_ret["retcode"] == 0 if pip_ret["retcode"] > 0: diff --git a/salt/states/webutil.py b/salt/states/webutil.py index 573e494cef6..d83190f8ac9 100644 --- a/salt/states/webutil.py +++ b/salt/states/webutil.py @@ -14,7 +14,6 @@ Support for htpasswd module. Requires the apache2-utils package for Debian-based """ - import salt.utils.path __virtualname__ = "webutil" @@ -67,9 +66,7 @@ def user_exists( ret = {"name": name, "changes": {}, "comment": "", "result": None} if __salt__["file.file_exists"](htpasswd_file): - exists = ( - __salt__["file.grep"](htpasswd_file, "^{}:".format(name))["retcode"] == 0 - ) + exists = __salt__["file.grep"](htpasswd_file, f"^{name}:")["retcode"] == 0 else: exists = False @@ -127,7 +124,7 @@ def user_absent(name, htpasswd_file=None, runas=None): """ ret = {"name": name, "changes": {}, "comment": "", "result": None} - exists = __salt__["file.grep"](htpasswd_file, "^{}:".format(name))["retcode"] == 0 + exists = __salt__["file.grep"](htpasswd_file, f"^{name}:")["retcode"] == 0 if not exists: if __opts__["test"]: diff --git a/salt/states/win_appx.py b/salt/states/win_appx.py index e3e1e9a3fb6..432c1556d75 100644 --- a/salt/states/win_appx.py +++ b/salt/states/win_appx.py @@ -4,6 +4,7 @@ deprovision the app from the online Windows image. .. versionadded:: 3007.0 """ + import fnmatch import logging diff --git a/salt/states/win_certutil.py b/salt/states/win_certutil.py index 392139d8a49..fa3c78e4af3 100644 --- a/salt/states/win_certutil.py +++ b/salt/states/win_certutil.py @@ -61,38 +61,38 @@ def add_store(name, store, saltenv="base"): cert_file = __salt__["cp.cache_file"](name, saltenv) if cert_file is False: - ret["comment"] = "Certificate file not found: {}".format(name) + ret["comment"] = f"Certificate file not found: {name}" ret["result"] = False return ret cert_serial = __salt__["certutil.get_cert_serial"](name) if cert_serial is None: - ret["comment"] = "Invalid certificate file: {}".format(name) + ret["comment"] = f"Invalid certificate file: {name}" ret["result"] = False return ret old_serials = __salt__["certutil.get_stored_cert_serials"](store=store) if cert_serial in old_serials: - ret["comment"] = "Certificate already present: {}".format(name) + ret["comment"] = f"Certificate already present: {name}" return ret if __opts__["test"]: - ret["comment"] = "Certificate will be added: {}".format(name) + ret["comment"] = f"Certificate will be added: {name}" ret["result"] = None return ret retcode = __salt__["certutil.add_store"](name, store, retcode=True) if retcode != 0: - ret["comment"] = "Error adding certificate: {}".format(name) + ret["comment"] = f"Error adding certificate: {name}" ret["result"] = False return ret new_serials = __salt__["certutil.get_stored_cert_serials"](store=store) if cert_serial in new_serials: ret["changes"]["added"] = name - ret["comment"] = "Added certificate: {}".format(name) + ret["comment"] = f"Added certificate: {name}" else: - ret["comment"] = "Failed to add certificate: {}".format(name) + ret["comment"] = f"Failed to add certificate: {name}" ret["result"] = False return ret @@ -131,38 +131,38 @@ def del_store(name, store, saltenv="base"): cert_file = __salt__["cp.cache_file"](name, saltenv) if cert_file is False: - ret["comment"] = "Certificate file not found: {}".format(name) + ret["comment"] = f"Certificate file not found: {name}" ret["result"] = False return ret cert_serial = __salt__["certutil.get_cert_serial"](name) if cert_serial is None: - ret["comment"] = "Invalid certificate file: {}".format(name) + ret["comment"] = f"Invalid certificate file: {name}" ret["result"] = False return ret old_serials = __salt__["certutil.get_stored_cert_serials"](store=store) if cert_serial not in old_serials: - ret["comment"] = "Certificate already absent: {}".format(name) + ret["comment"] = f"Certificate already absent: {name}" return ret if __opts__["test"]: - ret["comment"] = "Certificate will be removed: {}".format(name) + ret["comment"] = f"Certificate will be removed: {name}" ret["result"] = None return ret retcode = __salt__["certutil.del_store"](name, store, retcode=True) if retcode != 0: - ret["comment"] = "Error removing certificate: {}".format(name) + ret["comment"] = f"Error removing certificate: {name}" ret["result"] = False return ret new_serials = __salt__["certutil.get_stored_cert_serials"](store=store) if cert_serial not in new_serials: ret["changes"]["removed"] = name - ret["comment"] = "Removed certificate: {}".format(name) + ret["comment"] = f"Removed certificate: {name}" else: - ret["comment"] = "Failed to remove certificate: {}".format(name) + ret["comment"] = f"Failed to remove certificate: {name}" ret["result"] = False return ret diff --git a/salt/states/win_dns_client.py b/salt/states/win_dns_client.py index 9afa0faf368..dcd56a4eada 100644 --- a/salt/states/win_dns_client.py +++ b/salt/states/win_dns_client.py @@ -53,7 +53,7 @@ def dns_exists(name, servers=None, interface="Local Area Connection", replace=Fa # Do nothing is already configured configured_list = __salt__["win_dns_client.get_dns_servers"](interface) if configured_list == servers: - ret["comment"] = "{} are already configured".format(servers) + ret["comment"] = f"{servers} are already configured" ret["changes"] = {} ret["result"] = True return ret @@ -89,9 +89,9 @@ def dns_exists(name, servers=None, interface="Local Area Connection", replace=Fa ret["changes"]["Servers Removed"].append(server) else: if not __salt__["win_dns_client.rm_dns"](server, interface): - ret[ - "comment" - ] = "Failed to remove {} from DNS server list".format(server) + ret["comment"] = ( + f"Failed to remove {server} from DNS server list" + ) ret["result"] = False return ret else: @@ -109,7 +109,7 @@ def dns_dhcp(name, interface="Local Area Connection"): # Check the config config = __salt__["win_dns_client.get_dns_config"](interface) if config == "dhcp": - ret["comment"] = "{} already configured with DNS from DHCP".format(interface) + ret["comment"] = f"{interface} already configured with DNS from DHCP" return ret else: ret["changes"] = {"dns": "configured from DHCP"} @@ -208,7 +208,7 @@ def primary_suffix(name, suffix=None, updates=False): return ret # Changes to update policy needed else: - ret["comment"] = "{} suffix updates".format(updates_operation) + ret["comment"] = f"{updates_operation} suffix updates" ret["changes"] = { "old": {"updates": reg_data["updates"]["old"]}, "new": {"updates": reg_data["updates"]["new"]}, @@ -217,10 +217,10 @@ def primary_suffix(name, suffix=None, updates=False): else: # Changes to updates policy needed if reg_data["updates"]["new"] != reg_data["updates"]["old"]: - ret[ - "comment" - ] = "Updated primary DNS suffix ({}) and {} suffix updates".format( - suffix, updates_operation + ret["comment"] = ( + "Updated primary DNS suffix ({}) and {} suffix updates".format( + suffix, updates_operation + ) ) ret["changes"] = { "old": { @@ -234,7 +234,7 @@ def primary_suffix(name, suffix=None, updates=False): } # No changes to updates policy needed else: - ret["comment"] = "Updated primary DNS suffix ({})".format(suffix) + ret["comment"] = f"Updated primary DNS suffix ({suffix})" ret["changes"] = { "old": {"suffix": reg_data["suffix"]["old"]}, "new": {"suffix": reg_data["suffix"]["new"]}, diff --git a/salt/states/win_firewall.py b/salt/states/win_firewall.py index 959021ede74..151519f8ee0 100644 --- a/salt/states/win_firewall.py +++ b/salt/states/win_firewall.py @@ -52,12 +52,12 @@ def disabled(name="allprofiles"): # Make sure the profile name is valid if name not in profile_map: - raise SaltInvocationError("Invalid profile name: {}".format(name)) + raise SaltInvocationError(f"Invalid profile name: {name}") current_config = __salt__["firewall.get_config"]() if name != "allprofiles" and profile_map[name] not in current_config: ret["result"] = False - ret["comment"] = "Profile {} does not exist in firewall.get_config".format(name) + ret["comment"] = f"Profile {name} does not exist in firewall.get_config" return ret for key in current_config: @@ -83,7 +83,7 @@ def disabled(name="allprofiles"): if name == "allprofiles": msg = "All the firewall profiles are disabled" else: - msg = "Firewall profile {} is disabled".format(name) + msg = f"Firewall profile {name} is disabled" ret["comment"] = msg return ret @@ -211,12 +211,12 @@ def enabled(name="allprofiles"): # Make sure the profile name is valid if name not in profile_map: - raise SaltInvocationError("Invalid profile name: {}".format(name)) + raise SaltInvocationError(f"Invalid profile name: {name}") current_config = __salt__["firewall.get_config"]() if name != "allprofiles" and profile_map[name] not in current_config: ret["result"] = False - ret["comment"] = "Profile {} does not exist in firewall.get_config".format(name) + ret["comment"] = f"Profile {name} does not exist in firewall.get_config" return ret for key in current_config: @@ -242,7 +242,7 @@ def enabled(name="allprofiles"): if name == "allprofiles": msg = "All the firewall profiles are enabled" else: - msg = "Firewall profile {} is enabled".format(name) + msg = f"Firewall profile {name} is enabled" ret["comment"] = msg return ret diff --git a/salt/states/win_iis.py b/salt/states/win_iis.py index 773f7e7b3ad..da9a01a2b35 100644 --- a/salt/states/win_iis.py +++ b/salt/states/win_iis.py @@ -8,7 +8,6 @@ from Microsoft IIS. """ - # Define the module's virtual name __virtualname__ = "win_iis" @@ -85,13 +84,13 @@ def deployed( current_sites = __salt__["win_iis.list_sites"]() if name in current_sites: - ret["comment"] = "Site already present: {}".format(name) + ret["comment"] = f"Site already present: {name}" ret["result"] = True elif __opts__["test"]: - ret["comment"] = "Site will be created: {}".format(name) + ret["comment"] = f"Site will be created: {name}" ret["changes"] = {"old": None, "new": name} else: - ret["comment"] = "Created site: {}".format(name) + ret["comment"] = f"Created site: {name}" ret["changes"] = {"old": None, "new": name} ret["result"] = __salt__["win_iis.create_site"]( name, sourcepath, apppool, hostheader, ipaddress, port, protocol @@ -119,13 +118,13 @@ def remove_site(name): current_sites = __salt__["win_iis.list_sites"]() if name not in current_sites: - ret["comment"] = "Site has already been removed: {}".format(name) + ret["comment"] = f"Site has already been removed: {name}" ret["result"] = True elif __opts__["test"]: - ret["comment"] = "Site will be removed: {}".format(name) + ret["comment"] = f"Site will be removed: {name}" ret["changes"] = {"old": name, "new": None} else: - ret["comment"] = "Removed site: {}".format(name) + ret["comment"] = f"Removed site: {name}" ret["changes"] = {"old": name, "new": None} ret["result"] = __salt__["win_iis.remove_site"](name) return ret @@ -177,13 +176,13 @@ def create_binding( current_bindings = __salt__["win_iis.list_bindings"](site) if binding_info in current_bindings: - ret["comment"] = "Binding already present: {}".format(binding_info) + ret["comment"] = f"Binding already present: {binding_info}" ret["result"] = True elif __opts__["test"]: - ret["comment"] = "Binding will be created: {}".format(binding_info) + ret["comment"] = f"Binding will be created: {binding_info}" ret["changes"] = {"old": None, "new": binding_info} else: - ret["comment"] = "Created binding: {}".format(binding_info) + ret["comment"] = f"Created binding: {binding_info}" ret["changes"] = {"old": None, "new": binding_info} ret["result"] = __salt__["win_iis.create_binding"]( site, hostheader, ipaddress, port, protocol, sslflags @@ -225,13 +224,13 @@ def remove_binding(name, site, hostheader="", ipaddress="*", port=80): current_bindings = __salt__["win_iis.list_bindings"](site) if binding_info not in current_bindings: - ret["comment"] = "Binding has already been removed: {}".format(binding_info) + ret["comment"] = f"Binding has already been removed: {binding_info}" ret["result"] = True elif __opts__["test"]: - ret["comment"] = "Binding will be removed: {}".format(binding_info) + ret["comment"] = f"Binding will be removed: {binding_info}" ret["changes"] = {"old": binding_info, "new": None} else: - ret["comment"] = "Removed binding: {}".format(binding_info) + ret["comment"] = f"Removed binding: {binding_info}" ret["changes"] = {"old": binding_info, "new": None} ret["result"] = __salt__["win_iis.remove_binding"]( site, hostheader, ipaddress, port @@ -287,7 +286,7 @@ def create_cert_binding(name, site, hostheader="", ipaddress="*", port=443, sslf current_name = current_cert_bindings[binding_info]["certificatehash"] if name == current_name: - ret["comment"] = "Certificate binding already present: {}".format(name) + ret["comment"] = f"Certificate binding already present: {name}" ret["result"] = True return ret ret["comment"] = ( @@ -296,10 +295,10 @@ def create_cert_binding(name, site, hostheader="", ipaddress="*", port=443, sslf ) ret["result"] = False elif __opts__["test"]: - ret["comment"] = "Certificate binding will be created: {}".format(name) + ret["comment"] = f"Certificate binding will be created: {name}" ret["changes"] = {"old": None, "new": name} else: - ret["comment"] = "Created certificate binding: {}".format(name) + ret["comment"] = f"Created certificate binding: {name}" ret["changes"] = {"old": None, "new": name} ret["result"] = __salt__["win_iis.create_cert_binding"]( name, site, hostheader, ipaddress, port, sslflags @@ -351,16 +350,16 @@ def remove_cert_binding(name, site, hostheader="", ipaddress="*", port=443): current_cert_bindings = __salt__["win_iis.list_cert_bindings"](site) if binding_info not in current_cert_bindings: - ret["comment"] = "Certificate binding has already been removed: {}".format(name) + ret["comment"] = f"Certificate binding has already been removed: {name}" ret["result"] = True elif __opts__["test"]: - ret["comment"] = "Certificate binding will be removed: {}".format(name) + ret["comment"] = f"Certificate binding will be removed: {name}" ret["changes"] = {"old": name, "new": None} else: current_name = current_cert_bindings[binding_info]["certificatehash"] if name == current_name: - ret["comment"] = "Removed certificate binding: {}".format(name) + ret["comment"] = f"Removed certificate binding: {name}" ret["changes"] = {"old": name, "new": None} ret["result"] = __salt__["win_iis.remove_cert_binding"]( name, site, hostheader, ipaddress, port @@ -394,13 +393,13 @@ def create_apppool(name): current_apppools = __salt__["win_iis.list_apppools"]() if name in current_apppools: - ret["comment"] = "Application pool already present: {}".format(name) + ret["comment"] = f"Application pool already present: {name}" ret["result"] = True elif __opts__["test"]: - ret["comment"] = "Application pool will be created: {}".format(name) + ret["comment"] = f"Application pool will be created: {name}" ret["changes"] = {"old": None, "new": name} else: - ret["comment"] = "Created application pool: {}".format(name) + ret["comment"] = f"Created application pool: {name}" ret["changes"] = {"old": None, "new": name} ret["result"] = __salt__["win_iis.create_apppool"](name) return ret @@ -427,13 +426,13 @@ def remove_apppool(name): current_apppools = __salt__["win_iis.list_apppools"]() if name not in current_apppools: - ret["comment"] = "Application pool has already been removed: {}".format(name) + ret["comment"] = f"Application pool has already been removed: {name}" ret["result"] = True elif __opts__["test"]: - ret["comment"] = "Application pool will be removed: {}".format(name) + ret["comment"] = f"Application pool will be removed: {name}" ret["changes"] = {"old": name, "new": None} else: - ret["comment"] = "Removed application pool: {}".format(name) + ret["comment"] = f"Removed application pool: {name}" ret["changes"] = {"old": name, "new": None} ret["result"] = __salt__["win_iis.remove_apppool"](name) return ret @@ -606,13 +605,13 @@ def create_app(name, site, sourcepath, apppool=None): current_apps = __salt__["win_iis.list_apps"](site) if name in current_apps: - ret["comment"] = "Application already present: {}".format(name) + ret["comment"] = f"Application already present: {name}" ret["result"] = True elif __opts__["test"]: - ret["comment"] = "Application will be created: {}".format(name) + ret["comment"] = f"Application will be created: {name}" ret["changes"] = {"old": None, "new": name} else: - ret["comment"] = "Created application: {}".format(name) + ret["comment"] = f"Created application: {name}" ret["changes"] = {"old": None, "new": name} ret["result"] = __salt__["win_iis.create_app"](name, site, sourcepath, apppool) return ret @@ -639,13 +638,13 @@ def remove_app(name, site): current_apps = __salt__["win_iis.list_apps"](site) if name not in current_apps: - ret["comment"] = "Application has already been removed: {}".format(name) + ret["comment"] = f"Application has already been removed: {name}" ret["result"] = True elif __opts__["test"]: - ret["comment"] = "Application will be removed: {}".format(name) + ret["comment"] = f"Application will be removed: {name}" ret["changes"] = {"old": name, "new": None} else: - ret["comment"] = "Removed application: {}".format(name) + ret["comment"] = f"Removed application: {name}" ret["changes"] = {"old": name, "new": None} ret["result"] = __salt__["win_iis.remove_app"](name, site) return ret @@ -692,13 +691,13 @@ def create_vdir(name, site, sourcepath, app="/"): current_vdirs = __salt__["win_iis.list_vdirs"](site, app) if name in current_vdirs: - ret["comment"] = "Virtual directory already present: {}".format(name) + ret["comment"] = f"Virtual directory already present: {name}" ret["result"] = True elif __opts__["test"]: - ret["comment"] = "Virtual directory will be created: {}".format(name) + ret["comment"] = f"Virtual directory will be created: {name}" ret["changes"] = {"old": None, "new": name} else: - ret["comment"] = "Created virtual directory: {}".format(name) + ret["comment"] = f"Created virtual directory: {name}" ret["changes"] = {"old": None, "new": name} ret["result"] = __salt__["win_iis.create_vdir"](name, site, sourcepath, app) @@ -737,13 +736,13 @@ def remove_vdir(name, site, app="/"): current_vdirs = __salt__["win_iis.list_vdirs"](site, app) if name not in current_vdirs: - ret["comment"] = "Virtual directory has already been removed: {}".format(name) + ret["comment"] = f"Virtual directory has already been removed: {name}" ret["result"] = True elif __opts__["test"]: - ret["comment"] = "Virtual directory will be removed: {}".format(name) + ret["comment"] = f"Virtual directory will be removed: {name}" ret["changes"] = {"old": name, "new": None} else: - ret["comment"] = "Removed virtual directory: {}".format(name) + ret["comment"] = f"Removed virtual directory: {name}" ret["changes"] = {"old": name, "new": None} ret["result"] = __salt__["win_iis.remove_vdir"](name, site, app) diff --git a/salt/states/win_lgpo.py b/salt/states/win_lgpo.py index 07b5d98cb08..669a3d44dae 100644 --- a/salt/states/win_lgpo.py +++ b/salt/states/win_lgpo.py @@ -206,6 +206,7 @@ Multiple policy configuration Windows Components\\Windows Update\\Configure Automatic Updates: """ + import logging import salt.utils.data @@ -428,7 +429,7 @@ def set_( ) deprecation_comments.append(msg) else: - msg = "Invalid element name: {}".format(e_name) + msg = f"Invalid element name: {e_name}" ret["comment"] = "\n".join( [ret["comment"], msg] ).strip() @@ -525,7 +526,7 @@ def set_( ) policy_changes.append(p_name) else: - msg = '"{}" is already set'.format(p_name) + msg = f'"{p_name}" is already set' log.debug(msg) else: policy_changes.append(p_name) diff --git a/salt/states/win_lgpo_reg.py b/salt/states/win_lgpo_reg.py index 8377817a198..1a01ea17c0f 100644 --- a/salt/states/win_lgpo_reg.py +++ b/salt/states/win_lgpo_reg.py @@ -53,6 +53,7 @@ configure that policy. you will have to find the values needed to set them with this module using a different method. """ + import salt.utils.data import salt.utils.platform @@ -251,7 +252,7 @@ def value_disabled(name, key, policy_class="Machine"): old = _get_current(key=key, name=name, policy_class=policy_class) - pol_correct = old["pol"].get("data", "") == "**del.{}".format(name) + pol_correct = old["pol"].get("data", "") == f"**del.{name}" reg_correct = old["reg"] == {} if pol_correct and reg_correct: @@ -273,7 +274,7 @@ def value_disabled(name, key, policy_class="Machine"): new = _get_current(key=key, name=name, policy_class=policy_class) - pol_correct = new["pol"].get("data", "") == "**del.{}".format(name) + pol_correct = new["pol"].get("data", "") == f"**del.{name}" reg_correct = new["reg"] == {} if pol_correct and reg_correct: diff --git a/salt/states/win_network.py b/salt/states/win_network.py index 72bf74fca13..c35ee8ed6ad 100644 --- a/salt/states/win_network.py +++ b/salt/states/win_network.py @@ -137,7 +137,7 @@ def _validate(dns_proto, dns_servers, ip_proto, ip_addrs, gateway): # Validate default gateway if gateway is not None: if not salt.utils.validate.net.ipv4_addr(gateway): - errors.append("Gateway IP {} is invalid".format(gateway)) + errors.append(f"Gateway IP {gateway} is invalid") return errors @@ -198,7 +198,7 @@ def managed( ip_addrs=None, gateway=None, enabled=True, - **kwargs + **kwargs, ): """ Ensure that the named interface is configured properly. @@ -262,7 +262,7 @@ def managed( "name": name, "changes": {}, "result": True, - "comment": "Interface '{}' is up to date".format(name), + "comment": f"Interface '{name}' is up to date", } dns_proto = str(dns_proto).lower() @@ -296,11 +296,11 @@ def managed( if currently_enabled: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Interface '{}' will be disabled".format(name) + ret["comment"] = f"Interface '{name}' will be disabled" else: ret["result"] = __salt__["ip.disable"](name) if not ret["result"]: - ret["comment"] = "Failed to disable interface '{}'".format(name) + ret["comment"] = f"Failed to disable interface '{name}'" else: ret["comment"] += " (already disabled)" return ret @@ -308,31 +308,31 @@ def managed( if not currently_enabled: if __opts__["test"]: ret["result"] = None - ret["comment"] = "Interface '{}' will be enabled".format(name) + ret["comment"] = f"Interface '{name}' will be enabled" else: if not __salt__["ip.enable"](name): ret["result"] = False - ret[ - "comment" - ] = "Failed to enable interface '{}' to make changes".format(name) + ret["comment"] = ( + f"Failed to enable interface '{name}' to make changes" + ) 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 old = __salt__["ip.get_interface"](name) if not old: ret["result"] = False - ret[ - "comment" - ] = "Unable to get current configuration for interface '{}'".format(name) + ret["comment"] = ( + f"Unable to get current configuration for interface '{name}'" + ) return ret changes = _changes(old, dns_proto, dns_servers, ip_proto, ip_addrs, gateway) @@ -382,10 +382,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 @@ -431,7 +431,7 @@ def managed( "for interface '{}'".format(name) ) else: - ret[ - "comment" - ] = "Successfully updated configuration for interface '{}'".format(name) + ret["comment"] = ( + f"Successfully updated configuration for interface '{name}'" + ) return ret diff --git a/salt/states/win_path.py b/salt/states/win_path.py index 5463cacfdcd..8b3d76ff391 100644 --- a/salt/states/win_path.py +++ b/salt/states/win_path.py @@ -35,21 +35,21 @@ def absent(name): ret = {"name": name, "result": True, "changes": {}, "comment": ""} if not __salt__["win_path.exists"](name): - ret["comment"] = "{} is not in the PATH".format(name) + ret["comment"] = f"{name} is not in the PATH" return ret if __opts__["test"]: - ret["comment"] = "{} would be removed from the PATH".format(name) + ret["comment"] = f"{name} would be removed from the PATH" ret["result"] = None return ret __salt__["win_path.remove"](name) if __salt__["win_path.exists"](name): - ret["comment"] = "Failed to remove {} from the PATH".format(name) + ret["comment"] = f"Failed to remove {name} from the PATH" ret["result"] = False else: - ret["comment"] = "Removed {} from the PATH".format(name) + ret["comment"] = f"Removed {name} from the PATH" ret["changes"]["removed"] = name return ret @@ -143,13 +143,11 @@ def exists(name, index=None): if index is None: # We're not enforcing the index, and the directory is in the PATH. # There's nothing to do here. - comments.append("{} already exists in the PATH.".format(name)) + comments.append(f"{name} already exists in the PATH.") return _format_comments(ret, comments) else: if index == old_index: - comments.append( - "{} already exists in the PATH at index {}.".format(name, index) - ) + comments.append(f"{name} already exists in the PATH at index {index}.") return _format_comments(ret, comments) else: if __opts__["test"]: @@ -168,7 +166,7 @@ def exists(name, index=None): ret["result"] = None comments.append( "{} would be added to the PATH{}.".format( - name, " at index {}".format(index) if index is not None else "" + name, f" at index {index}" if index is not None else "" ) ) ret["changes"] = _changes(old_index, index) @@ -177,7 +175,7 @@ def exists(name, index=None): try: ret["result"] = __salt__["win_path.add"](name, index=index, rehash=False) except Exception as exc: # pylint: disable=broad-except - comments.append("Encountered error: {}.".format(exc)) + comments.append(f"Encountered error: {exc}.") ret["result"] = False if ret["result"]: @@ -203,7 +201,7 @@ def exists(name, index=None): "{} {} to the PATH{}.".format( "Added" if ret["result"] else "Failed to add", name, - " at index {}".format(index) if index is not None else "", + f" at index {index}" if index is not None else "", ) ) diff --git a/salt/states/win_pki.py b/salt/states/win_pki.py index 168939374e1..0e0724209f1 100644 --- a/salt/states/win_pki.py +++ b/salt/states/win_pki.py @@ -6,7 +6,6 @@ Microsoft certificate management via the Pki PowerShell module. .. versionadded:: 2016.11.0 """ - _DEFAULT_CONTEXT = "LocalMachine" _DEFAULT_FORMAT = "cer" _DEFAULT_STORE = "My" @@ -65,7 +64,7 @@ def import_cert( """ ret = {"name": name, "changes": dict(), "comment": "", "result": None} - store_path = r"Cert:\{}\{}".format(context, store) + store_path = rf"Cert:\{context}\{store}" cached_source_path = __salt__["cp.cache_file"](name, saltenv) current_certs = __salt__["win_pki.get_certs"](context=context, store=store) @@ -104,10 +103,10 @@ def import_cert( cert_props["thumbprint"], store_path ) else: - ret[ - "comment" - ] = "Certificate '{}' unable to be imported into store: {}".format( - cert_props["thumbprint"], store_path + ret["comment"] = ( + "Certificate '{}' unable to be imported into store: {}".format( + cert_props["thumbprint"], store_path + ) ) return ret @@ -140,7 +139,7 @@ def remove_cert(name, thumbprint, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE """ ret = {"name": name, "changes": dict(), "comment": "", "result": None} - store_path = r"Cert:\{}\{}".format(context, store) + store_path = rf"Cert:\{context}\{store}" current_certs = __salt__["win_pki.get_certs"](context=context, store=store) if thumbprint not in current_certs: @@ -163,9 +162,9 @@ def remove_cert(name, thumbprint, context=_DEFAULT_CONTEXT, store=_DEFAULT_STORE thumbprint, store_path ) else: - ret[ - "comment" - ] = "Certificate '{}' unable to be removed from store: {}".format( - thumbprint, store_path + ret["comment"] = ( + "Certificate '{}' unable to be removed from store: {}".format( + thumbprint, store_path + ) ) return ret diff --git a/salt/states/win_powercfg.py b/salt/states/win_powercfg.py index b7f4e82a139..46aba50985f 100644 --- a/salt/states/win_powercfg.py +++ b/salt/states/win_powercfg.py @@ -14,7 +14,6 @@ powercfg. - power: dc """ - import logging import salt.utils.data @@ -89,7 +88,7 @@ def set_timeout(name, value, power="ac", scheme=None): name = name.lower() if name not in ["monitor", "disk", "standby", "hibernate"]: ret["result"] = False - ret["comment"] = '"{}" is not a valid setting'.format(name) + ret["comment"] = f'"{name}" is not a valid setting' log.debug(ret["comment"]) return ret @@ -97,12 +96,12 @@ def set_timeout(name, value, power="ac", scheme=None): power = power.lower() if power not in ["ac", "dc"]: ret["result"] = False - ret["comment"] = '"{}" is not a power type'.format(power) + ret["comment"] = f'"{power}" is not a power type' log.debug(ret["comment"]) return ret # Get current settings - old = __salt__["powercfg.get_{}_timeout".format(name)](scheme=scheme) + old = __salt__[f"powercfg.get_{name}_timeout"](scheme=scheme) # Check current settings if old[power] == value: @@ -121,12 +120,10 @@ def set_timeout(name, value, power="ac", scheme=None): return ret # Set the timeout value - __salt__["powercfg.set_{}_timeout".format(name)]( - timeout=value, power=power, scheme=scheme - ) + __salt__[f"powercfg.set_{name}_timeout"](timeout=value, power=power, scheme=scheme) # Get the setting after the change - new = __salt__["powercfg.get_{}_timeout".format(name)](scheme=scheme) + new = __salt__[f"powercfg.get_{name}_timeout"](scheme=scheme) changes = salt.utils.data.compare_dicts(old, new) diff --git a/salt/states/win_shortcut.py b/salt/states/win_shortcut.py index 8443a187a3c..a1fa46a2f9e 100644 --- a/salt/states/win_shortcut.py +++ b/salt/states/win_shortcut.py @@ -6,6 +6,7 @@ shortcuts. .. versionadded:: 3005 """ + import salt.utils.data import salt.utils.path import salt.utils.platform @@ -187,10 +188,10 @@ def present( if __opts__["test"]: if changes: - ret["comment"] = "Shortcut will be modified: {}".format(name) + ret["comment"] = f"Shortcut will be modified: {name}" ret["changes"] = changes else: - ret["comment"] = "Shortcut will be created: {}".format(name) + ret["comment"] = f"Shortcut will be created: {name}" ret["result"] = None return ret @@ -212,7 +213,7 @@ def present( user=user, ) except CommandExecutionError as exc: - ret["comment"] = ["Failed to create the shortcut: {}".format(name)] + ret["comment"] = [f"Failed to create the shortcut: {name}"] ret["comment"].append(exc.message) ret["result"] = False return ret @@ -220,7 +221,7 @@ def present( try: new = __salt__["shortcut.get"](name) except CommandExecutionError as exc: - ret["comment"] = ["Failed to create the shortcut: {}".format(name)] + ret["comment"] = [f"Failed to create the shortcut: {name}"] ret["comment"].append(exc.message) ret["result"] = False return ret @@ -233,9 +234,9 @@ def present( return ret if changes: - ret["comment"] = "Shortcut modified: {}".format(name) + ret["comment"] = f"Shortcut modified: {name}" ret["changes"] = changes else: - ret["comment"] = "Shortcut created: {}".format(name) + ret["comment"] = f"Shortcut created: {name}" return ret diff --git a/salt/states/win_smtp_server.py b/salt/states/win_smtp_server.py index e3eadc82745..91df2a6586a 100644 --- a/salt/states/win_smtp_server.py +++ b/salt/states/win_smtp_server.py @@ -3,7 +3,6 @@ Module for managing IIS SMTP server configuration on Windows servers. """ - import salt.utils.args _DEFAULT_SERVER = "SmtpSvc/1" @@ -39,7 +38,7 @@ def _normalize_server_settings(**settings): if isinstance(settings[setting], dict): value_from_key = next(iter(settings[setting].keys())) - ret[setting] = "{{{0}}}".format(value_from_key) + ret[setting] = f"{{{value_from_key}}}" else: ret[setting] = settings[setting] return ret @@ -144,17 +143,17 @@ def active_log_format(name, log_format, server=_DEFAULT_SERVER): current_log_format = __salt__["win_smtp_server.get_log_format"](server) if log_format == current_log_format: - ret[ - "comment" - ] = "LogPluginClsid already contains the id of the provided log format." + ret["comment"] = ( + "LogPluginClsid already contains the id of the provided log format." + ) ret["result"] = True elif __opts__["test"]: ret["comment"] = "LogPluginClsid will be changed." ret["changes"] = {"old": current_log_format, "new": log_format} else: - ret[ - "comment" - ] = "Set LogPluginClsid to contain the id of the provided log format." + ret["comment"] = ( + "Set LogPluginClsid to contain the id of the provided log format." + ) ret["changes"] = {"old": current_log_format, "new": log_format} ret["result"] = __salt__["win_smtp_server.set_log_format"](log_format, server) return ret diff --git a/salt/states/win_snmp.py b/salt/states/win_snmp.py index 0b5dfac12d8..9d70ebc1b8e 100644 --- a/salt/states/win_snmp.py +++ b/salt/states/win_snmp.py @@ -104,13 +104,13 @@ def auth_traps_enabled(name, status=True): current_status = __salt__["win_snmp.get_auth_traps_enabled"]() if status == current_status: - ret["comment"] = "{} already contains the provided value.".format(vname) + ret["comment"] = f"{vname} already contains the provided value." ret["result"] = True elif __opts__["test"]: - ret["comment"] = "{} will be changed.".format(vname) + ret["comment"] = f"{vname} will be changed." ret["changes"] = {"old": current_status, "new": status} else: - ret["comment"] = "Set {} to contain the provided value.".format(vname) + ret["comment"] = f"Set {vname} to contain the provided value." ret["changes"] = {"old": current_status, "new": status} ret["result"] = __salt__["win_snmp.set_auth_traps_enabled"](status=status) diff --git a/salt/states/win_system.py b/salt/states/win_system.py index 34f47f15e0d..0aa5438b0ec 100644 --- a/salt/states/win_system.py +++ b/salt/states/win_system.py @@ -52,7 +52,7 @@ def computer_desc(name): "name": name, "changes": {}, "result": True, - "comment": "Computer description already set to '{}'".format(name), + "comment": f"Computer description already set to '{name}'", } before_desc = __salt__["system.get_computer_desc"]() @@ -62,7 +62,7 @@ def computer_desc(name): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Computer description will be changed to '{}'".format(name) + ret["comment"] = f"Computer description will be changed to '{name}'" return ret result = __salt__["system.set_computer_desc"](name) @@ -73,7 +73,7 @@ def computer_desc(name): ret["changes"] = {"old": before_desc, "new": name} else: ret["result"] = False - ret["comment"] = "Unable to set computer description to '{}'".format(name) + ret["comment"] = f"Unable to set computer description to '{name}'" return ret @@ -96,7 +96,7 @@ def computer_name(name): "name": name, "changes": {}, "result": True, - "comment": "Computer name already set to '{}'".format(name), + "comment": f"Computer name already set to '{name}'", } before_name = __salt__["system.get_computer_name"]() @@ -113,7 +113,7 @@ def computer_name(name): if __opts__["test"]: ret["result"] = None - ret["comment"] = "Computer name will be changed to '{}'".format(name) + ret["comment"] = f"Computer name will be changed to '{name}'" return ret result = __salt__["system.set_computer_name"](name) @@ -123,13 +123,13 @@ def computer_name(name): if (after_pending is not None and after_pending == name) or ( after_pending is None and after_name == name ): - ret["comment"] = "Computer name successfully set to '{}'".format(name) + ret["comment"] = f"Computer name successfully set to '{name}'" if after_pending is not None: ret["comment"] += " (reboot required for change to take effect)" ret["changes"] = {"old": before_name, "new": name} else: ret["result"] = False - ret["comment"] = "Unable to set computer name to '{}'".format(name) + ret["comment"] = f"Unable to set computer name to '{name}'" return ret @@ -147,7 +147,7 @@ def hostname(name): current_hostname = __salt__["system.get_hostname"]() if current_hostname.upper() == name.upper(): - ret["comment"] = "Hostname is already set to '{}'".format(name) + ret["comment"] = f"Hostname is already set to '{name}'" return ret out = __salt__["system.set_hostname"](name) @@ -191,22 +191,20 @@ def workgroup(name): current_workgroup = ( out["Domain"] if "Domain" in out - else out["Workgroup"] - if "Workgroup" in out - else "" + else out["Workgroup"] if "Workgroup" in out else "" ) # Notify the user if the requested workgroup is the same if current_workgroup.upper() == name.upper(): ret["result"] = True - ret["comment"] = "Workgroup is already set to '{}'".format(name.upper()) + ret["comment"] = f"Workgroup is already set to '{name.upper()}'" return ret # If being run in test-mode, inform the user what is supposed to happen if __opts__["test"]: ret["result"] = None ret["changes"] = {} - ret["comment"] = "Computer will be joined to workgroup '{}'".format(name) + ret["comment"] = f"Computer will be joined to workgroup '{name}'" return ret # Set our new workgroup, and then immediately ask the machine what it @@ -216,9 +214,7 @@ def workgroup(name): new_workgroup = ( out["Domain"] if "Domain" in out - else out["Workgroup"] - if "Workgroup" in out - else "" + else out["Workgroup"] if "Workgroup" in out else "" ) # Return our results based on the changes @@ -299,7 +295,7 @@ def join_domain( "name": name, "changes": {}, "result": True, - "comment": "Computer already added to '{}'".format(name), + "comment": f"Computer already added to '{name}'", } current_domain_dic = __salt__["system.get_domain_workgroup"]() @@ -311,12 +307,12 @@ def join_domain( current_domain = None if name.lower() == current_domain.lower(): - ret["comment"] = "Computer already added to '{}'".format(name) + ret["comment"] = f"Computer already added to '{name}'" return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Computer will be added to '{}'".format(name) + ret["comment"] = f"Computer will be added to '{name}'" return ret result = __salt__["system.join_domain"]( @@ -328,14 +324,14 @@ def join_domain( restart=restart, ) if result is not False: - ret["comment"] = "Computer added to '{}'".format(name) + ret["comment"] = f"Computer added to '{name}'" if restart: ret["comment"] += "\nSystem will restart" else: ret["comment"] += "\nSystem needs to be restarted" ret["changes"] = {"old": current_domain, "new": name} else: - ret["comment"] = "Computer failed to join '{}'".format(name) + ret["comment"] = f"Computer failed to join '{name}'" ret["result"] = False return ret @@ -461,20 +457,20 @@ def shutdown( if only_on_pending_reboot and not __salt__["system.get_pending_reboot"](): if __opts__["test"]: - ret[ - "comment" - ] = "System {} will be skipped because no reboot is pending".format(action) + ret["comment"] = ( + f"System {action} will be skipped because no reboot is pending" + ) else: - ret[ - "comment" - ] = "System {} has been skipped because no reboot was pending".format( - action + ret["comment"] = ( + "System {} has been skipped because no reboot was pending".format( + action + ) ) return ret if __opts__["test"]: ret["result"] = None - ret["comment"] = "Will attempt to schedule a {}".format(action) + ret["comment"] = f"Will attempt to schedule a {action}" return ret ret["result"] = __salt__["system.shutdown"]( @@ -489,9 +485,9 @@ def shutdown( if ret["result"]: ret["changes"] = { "old": "No reboot or shutdown was scheduled", - "new": "A {} has been scheduled".format(action), + "new": f"A {action} has been scheduled", } - ret["comment"] = "Request to {} was successful".format(action) + ret["comment"] = f"Request to {action} was successful" else: - ret["comment"] = "Request to {} failed".format(action) + ret["comment"] = f"Request to {action} failed" return ret diff --git a/salt/states/win_task.py b/salt/states/win_task.py index 6a83392ebee..990724c5da6 100644 --- a/salt/states/win_task.py +++ b/salt/states/win_task.py @@ -406,9 +406,9 @@ def present( if __opts__["test"]: # if force is False and task is found then no changes will take place if not force and before["task_found"]: - ret[ - "comment" - ] = '"force=True" will allow the new task to replace the old one' + ret["comment"] = ( + '"force=True" will allow the new task to replace the old one' + ) ret["result"] = None log.warning("force=False") return ret diff --git a/salt/states/win_wusa.py b/salt/states/win_wusa.py index 4371bfc1341..70cf1f00436 100644 --- a/salt/states/win_wusa.py +++ b/salt/states/win_wusa.py @@ -7,7 +7,6 @@ without WSUS or Windows Update .. versionadded:: 2018.3.4 """ - import logging import salt.utils.platform @@ -62,13 +61,13 @@ def installed(name, source): # Is the KB already installed if __salt__["wusa.is_installed"](name): ret["result"] = True - ret["comment"] = "{} already installed".format(name) + ret["comment"] = f"{name} already installed" return ret # Check for test=True if __opts__["test"] is True: ret["result"] = None - ret["comment"] = "{} would be installed".format(name) + ret["comment"] = f"{name} would be installed" ret["result"] = None return ret @@ -92,11 +91,11 @@ def installed(name, source): # Verify successful install if __salt__["wusa.is_installed"](name): - ret["comment"] = "{} was installed. {}".format(name, additional_comment) + ret["comment"] = f"{name} was installed. {additional_comment}" ret["changes"] = {"old": False, "new": True} ret["result"] = True else: - ret["comment"] = "{} failed to install. {}".format(name, additional_comment) + ret["comment"] = f"{name} failed to install. {additional_comment}" return ret @@ -122,13 +121,13 @@ def uninstalled(name): # Is the KB already uninstalled if not __salt__["wusa.is_installed"](name): ret["result"] = True - ret["comment"] = "{} already uninstalled".format(name) + ret["comment"] = f"{name} already uninstalled" return ret # Check for test=True if __opts__["test"] is True: ret["result"] = None - ret["comment"] = "{} would be uninstalled".format(name) + ret["comment"] = f"{name} would be uninstalled" ret["result"] = None return ret @@ -137,10 +136,10 @@ def uninstalled(name): # Verify successful uninstall if not __salt__["wusa.is_installed"](name): - ret["comment"] = "{} was uninstalled".format(name) + ret["comment"] = f"{name} was uninstalled" ret["changes"] = {"old": True, "new": False} ret["result"] = True else: - ret["comment"] = "{} failed to uninstall".format(name) + ret["comment"] = f"{name} failed to uninstall" return ret diff --git a/salt/states/winrepo.py b/salt/states/winrepo.py index 23858551592..241c66c1ca6 100644 --- a/salt/states/winrepo.py +++ b/salt/states/winrepo.py @@ -60,11 +60,11 @@ def genrepo(name, force=False, allow_empty=False): if not force: if not os.path.exists(winrepo_dir): ret["result"] = False - ret["comment"] = "{} is missing".format(winrepo_dir) + ret["comment"] = f"{winrepo_dir} is missing" return ret elif not os.path.exists(winrepo_cachefile): execute = True - ret["comment"] = "{} is missing".format(winrepo_cachefile) + ret["comment"] = f"{winrepo_cachefile} is missing" else: winrepo_cachefile_mtime = os.stat(winrepo_cachefile)[stat.ST_MTIME] for root, dirs, files in salt.utils.path.os_walk(winrepo_dir): diff --git a/salt/states/wordpress.py b/salt/states/wordpress.py index e672e30be4a..5e208458ef7 100644 --- a/salt/states/wordpress.py +++ b/salt/states/wordpress.py @@ -53,11 +53,11 @@ def installed(name, user, admin_user, admin_password, admin_email, title, url): if check: ret["result"] = True - ret["comment"] = "Wordpress is already installed: {}".format(name) + ret["comment"] = f"Wordpress is already installed: {name}" return ret elif __opts__["test"]: ret["result"] = None - ret["comment"] = "Wordpress will be installed: {}".format(name) + ret["comment"] = f"Wordpress will be installed: {name}" return ret resp = __salt__["wordpress.install"]( @@ -65,10 +65,10 @@ def installed(name, user, admin_user, admin_password, admin_email, title, url): ) if resp: ret["result"] = True - ret["comment"] = "Wordpress Installed: {}".format(name) + ret["comment"] = f"Wordpress Installed: {name}" ret["changes"] = {"new": resp} else: - ret["comment"] = "Failed to install wordpress: {}".format(name) + ret["comment"] = f"Failed to install wordpress: {name}" return ret @@ -99,30 +99,30 @@ def activated(name, path, user): if check["status"] == "active": ret["result"] = True - ret["comment"] = "Plugin already activated: {}".format(name) + ret["comment"] = f"Plugin already activated: {name}" return ret elif __opts__["test"]: ret["result"] = None - ret["comment"] = "Plugin will be activated: {}".format(name) + ret["comment"] = f"Plugin will be activated: {name}" return ret resp = __salt__["wordpress.activate"](name, path, user) if resp is True: ret["result"] = True - ret["comment"] = "Plugin activated: {}".format(name) + ret["comment"] = f"Plugin activated: {name}" ret["changes"] = { "old": check, "new": __salt__["wordpress.show_plugin"](name, path, user), } elif resp is None: ret["result"] = True - ret["comment"] = "Plugin already activated: {}".format(name) + ret["comment"] = f"Plugin already activated: {name}" ret["changes"] = { "old": check, "new": __salt__["wordpress.show_plugin"](name, path, user), } else: - ret["comment"] = "Plugin failed to activate: {}".format(name) + ret["comment"] = f"Plugin failed to activate: {name}" return ret @@ -153,29 +153,29 @@ def deactivated(name, path, user): if check["status"] == "inactive": ret["result"] = True - ret["comment"] = "Plugin already deactivated: {}".format(name) + ret["comment"] = f"Plugin already deactivated: {name}" return ret elif __opts__["test"]: ret["result"] = None - ret["comment"] = "Plugin will be deactivated: {}".format(name) + ret["comment"] = f"Plugin will be deactivated: {name}" return ret resp = __salt__["wordpress.deactivate"](name, path, user) if resp is True: ret["result"] = True - ret["comment"] = "Plugin deactivated: {}".format(name) + ret["comment"] = f"Plugin deactivated: {name}" ret["changes"] = { "old": check, "new": __salt__["wordpress.show_plugin"](name, path, user), } elif resp is None: ret["result"] = True - ret["comment"] = "Plugin already deactivated: {}".format(name) + ret["comment"] = f"Plugin already deactivated: {name}" ret["changes"] = { "old": check, "new": __salt__["wordpress.show_plugin"](name, path, user), } else: - ret["comment"] = "Plugin failed to deactivate: {}".format(name) + ret["comment"] = f"Plugin failed to deactivate: {name}" return ret diff --git a/salt/states/x509_v2.py b/salt/states/x509_v2.py index 4987d272922..773006b6694 100644 --- a/salt/states/x509_v2.py +++ b/salt/states/x509_v2.py @@ -180,6 +180,7 @@ according to the www policy. - require: - x509: /etc/pki/www.key """ + import base64 import copy import datetime @@ -433,9 +434,9 @@ def certificate_managed( file_managed_test = _file_managed(name, test=True, replace=False, **file_args) if file_managed_test["result"] is False: ret["result"] = False - ret[ - "comment" - ] = "Problem while testing file.managed changes, see its output" + ret["comment"] = ( + "Problem while testing file.managed changes, see its output" + ) _add_sub_state_run(ret, file_managed_test) return ret @@ -839,9 +840,9 @@ def crl_managed( if file_managed_test["result"] is False: ret["result"] = False - ret[ - "comment" - ] = "Problem while testing file.managed changes, see its output" + ret["comment"] = ( + "Problem while testing file.managed changes, see its output" + ) _add_sub_state_run(ret, file_managed_test) return ret @@ -1078,9 +1079,9 @@ def csr_managed( if file_managed_test["result"] is False: ret["result"] = False - ret[ - "comment" - ] = "Problem while testing file.managed changes, see its output" + ret["comment"] = ( + "Problem while testing file.managed changes, see its output" + ) _add_sub_state_run(ret, file_managed_test) return ret @@ -1362,9 +1363,9 @@ def private_key_managed( if file_managed_test["result"] is False: ret["result"] = False - ret[ - "comment" - ] = "Problem while testing file.managed changes, see its output" + ret["comment"] = ( + "Problem while testing file.managed changes, see its output" + ) _add_sub_state_run(ret, file_managed_test) return ret @@ -1584,9 +1585,9 @@ def _file_managed(name, test=None, **kwargs): def _check_file_ret(fret, ret, current): if fret["result"] is False: ret["result"] = False - ret[ - "comment" - ] = f"Could not {'create' if not current else 'update'} file, see file.managed output" + ret["comment"] = ( + f"Could not {'create' if not current else 'update'} file, see file.managed output" + ) ret["changes"] = {} return False return True diff --git a/salt/states/xml.py b/salt/states/xml.py index 67cf30a825b..48bcb4eb5db 100644 --- a/salt/states/xml.py +++ b/salt/states/xml.py @@ -51,20 +51,20 @@ def value_present(name, xpath, value, **kwargs): current_value = __salt__["xml.get_value"](name, xpath) if not current_value: ret["result"] = False - ret["comment"] = "xpath query {} not found in {}".format(xpath, name) + ret["comment"] = f"xpath query {xpath} not found in {name}" return ret if current_value != value: if kwargs["test"]: ret["result"] = None - ret["comment"] = "{} will be updated".format(name) + ret["comment"] = f"{name} will be updated" ret["changes"] = {name: {"old": current_value, "new": value}} else: results = __salt__["xml.set_value"](name, xpath, value) ret["result"] = results - ret["comment"] = "{} updated".format(name) + ret["comment"] = f"{name} updated" ret["changes"] = {name: {"old": current_value, "new": value}} else: - ret["comment"] = "{} is already present".format(value) + ret["comment"] = f"{value} is already present" return ret diff --git a/salt/states/xmpp.py b/salt/states/xmpp.py index 2186c37bbca..84b4a6a3017 100644 --- a/salt/states/xmpp.py +++ b/salt/states/xmpp.py @@ -54,7 +54,7 @@ def send_msg(name, recipient, profile): profile=profile, ) ret["result"] = True - ret["comment"] = "Sent message to {}: {}".format(recipient, name) + ret["comment"] = f"Sent message to {recipient}: {name}" return ret @@ -84,10 +84,10 @@ def send_msg_multi(name, profile, recipients=None, rooms=None): comment = "" if recipients: - comment += " users {}".format(recipients) + comment += f" users {recipients}" if rooms: - comment += " rooms {}".format(rooms) - comment += ", message: {}".format(name) + comment += f" rooms {rooms}" + comment += f", message: {name}" if __opts__["test"]: ret["comment"] = "Need to send" + comment diff --git a/salt/states/zabbix_action.py b/salt/states/zabbix_action.py index 9b92aa528e0..33215891904 100644 --- a/salt/states/zabbix_action.py +++ b/salt/states/zabbix_action.py @@ -170,10 +170,10 @@ def present(name, params, **kwargs): else: ret["result"] = True - ret[ - "comment" - ] = 'Zabbix Action "{}" already exists and corresponds to a definition.'.format( - name + ret["comment"] = ( + 'Zabbix Action "{}" already exists and corresponds to a definition.'.format( + name + ) ) else: diff --git a/salt/states/zabbix_hostgroup.py b/salt/states/zabbix_hostgroup.py index 772a32e9528..3b573abac55 100644 --- a/salt/states/zabbix_hostgroup.py +++ b/salt/states/zabbix_hostgroup.py @@ -5,6 +5,7 @@ Management of Zabbix host groups. """ + __deprecated__ = ( 3009, "zabbix", diff --git a/salt/states/zabbix_template.py b/salt/states/zabbix_template.py index e489c185301..cefd692fa77 100644 --- a/salt/states/zabbix_template.py +++ b/salt/states/zabbix_template.py @@ -873,10 +873,10 @@ def present(name, params, static_host_list=True, **kwargs): if not CHANGE_STACK: ret["result"] = True - ret[ - "comment" - ] = 'Zabbix Template "{}" already exists and corresponds to a definition.'.format( - name + ret["comment"] = ( + 'Zabbix Template "{}" already exists and corresponds to a definition.'.format( + name + ) ) else: tmpl_action = next( diff --git a/salt/states/zabbix_user.py b/salt/states/zabbix_user.py index 1c43e0f8f06..fa8ba6c4b3f 100644 --- a/salt/states/zabbix_user.py +++ b/salt/states/zabbix_user.py @@ -90,9 +90,9 @@ def admin_password_present(name, password=None, **kwargs): unique_passwords.reverse() if not unique_passwords: - ret[ - "comment" - ] = "Could not find any Zabbix Admin password setting! See documentation." + ret["comment"] = ( + "Could not find any Zabbix Admin password setting! See documentation." + ) return ret else: desired_password = unique_passwords[0] diff --git a/salt/states/zabbix_valuemap.py b/salt/states/zabbix_valuemap.py index 7bf57263c14..641f929fa17 100644 --- a/salt/states/zabbix_valuemap.py +++ b/salt/states/zabbix_valuemap.py @@ -138,10 +138,10 @@ def present(name, params, **kwargs): else: ret["result"] = True - ret[ - "comment" - ] = 'Zabbix Value map "{}" already exists and corresponds to a definition.'.format( - name + ret["comment"] = ( + 'Zabbix Value map "{}" already exists and corresponds to a definition.'.format( + name + ) ) else: diff --git a/salt/states/zenoss.py b/salt/states/zenoss.py index 0a05c67af23..ed06e9a249d 100644 --- a/salt/states/zenoss.py +++ b/salt/states/zenoss.py @@ -17,7 +17,6 @@ Allows for setting a state of minions in Zenoss using the Zenoss API. Currently - prod_state: 1000 """ - import logging log = logging.getLogger(__name__) @@ -55,30 +54,30 @@ def monitored(name, device_class=None, collector="localhost", prod_state=None): if device: ret["result"] = True ret["changes"] = None - ret["comment"] = "{} is already monitored".format(name) + ret["comment"] = f"{name} is already monitored" # if prod_state is set, ensure it matches with the current state if prod_state is not None and device["productionState"] != prod_state: if __opts__["test"]: - ret[ - "comment" - ] = "{} is already monitored but prodState will be updated".format(name) + ret["comment"] = ( + f"{name} is already monitored but prodState will be updated" + ) ret["result"] = None else: __salt__["zenoss.set_prod_state"](prod_state, name) - ret[ - "comment" - ] = "{} is already monitored but prodState was updated".format(name) + ret["comment"] = ( + f"{name} is already monitored but prodState was updated" + ) ret["changes"] = { "old": "prodState == {}".format(device["productionState"]), - "new": "prodState == {}".format(prod_state), + "new": f"prodState == {prod_state}", } return ret # Device not yet in Zenoss if __opts__["test"]: - ret["comment"] = 'The state of "{}" will be changed.'.format(name) + ret["comment"] = f'The state of "{name}" will be changed.' ret["changes"] = {"old": "monitored == False", "new": "monitored == True"} ret["result"] = None return ret @@ -87,9 +86,9 @@ def monitored(name, device_class=None, collector="localhost", prod_state=None): if __salt__["zenoss.add_device"](name, device_class, collector, prod_state): ret["result"] = True ret["changes"] = {"old": "monitored == False", "new": "monitored == True"} - ret["comment"] = "{} has been added to Zenoss".format(name) + ret["comment"] = f"{name} has been added to Zenoss" else: ret["result"] = False ret["changes"] = None - ret["comment"] = "Unable to add {} to Zenoss".format(name) + ret["comment"] = f"Unable to add {name} to Zenoss" return ret diff --git a/salt/states/zk_concurrency.py b/salt/states/zk_concurrency.py index f76ffdd64d4..d376e51c955 100644 --- a/salt/states/zk_concurrency.py +++ b/salt/states/zk_concurrency.py @@ -45,7 +45,6 @@ This example would allow the file state to change, but would limit the concurrency of the trafficserver service restart to 4. """ - # TODO: use depends decorator to make these per function deps, instead of all or nothing REQUIRED_FUNCS = ( "zk_concurrency.lock", @@ -103,7 +102,7 @@ def lock( max_concurrency=max_concurrency, timeout=timeout, ephemeral_lease=ephemeral_lease, - **conn_kwargs + **conn_kwargs, ) if locked: ret["result"] = True @@ -152,13 +151,13 @@ def unlock( identifier=identifier, max_concurrency=max_concurrency, ephemeral_lease=ephemeral_lease, - **conn_kwargs + **conn_kwargs, ) if unlocked: ret["result"] = True else: - ret["comment"] = "Unable to find lease for path {}".format(name) + ret["comment"] = f"Unable to find lease for path {name}" return ret diff --git a/salt/states/zone.py b/salt/states/zone.py index bb6de7dfc13..0c908ed34c4 100644 --- a/salt/states/zone.py +++ b/salt/states/zone.py @@ -193,10 +193,10 @@ def property_present(name, property, value): else: ## zone does not exist ret["result"] = False - ret[ - "comment" - ] = "The zone {} is not in the configured, installed, or booted state.".format( - name + ret["comment"] = ( + "The zone {} is not in the configured, installed, or booted state.".format( + name + ) ) return ret @@ -250,10 +250,10 @@ def property_absent(name, property): else: ## zone does not exist ret["result"] = False - ret[ - "comment" - ] = "The zone {} is not in the configured, installed, or booted state.".format( - name + ret["comment"] = ( + "The zone {} is not in the configured, installed, or booted state.".format( + name + ) ) return ret @@ -373,31 +373,31 @@ def resource_present( ) if ret["comment"] == "": if resource_selector_property: - ret[ - "comment" - ] = "The {} resource {} was updated.".format( - resource_type, - resource_selector_value, + ret["comment"] = ( + "The {} resource {} was updated.".format( + resource_type, + resource_selector_value, + ) ) else: - ret[ - "comment" - ] = "The {} resource was updated.".format( - resource_type, + ret["comment"] = ( + "The {} resource was updated.".format( + resource_type, + ) ) elif ret["comment"] == "": if resource_selector_property: - ret[ - "comment" - ] = "The {} resource {} was not updated.".format( - resource_type, - resource_selector_value, + ret["comment"] = ( + "The {} resource {} was not updated.".format( + resource_type, + resource_selector_value, + ) ) else: - ret[ - "comment" - ] = "The {} resource was not updated.".format( - resource_type, + ret["comment"] = ( + "The {} resource was not updated.".format( + resource_type, + ) ) if ret["result"] is None: ## add @@ -418,9 +418,9 @@ def resource_present( ret["changes"][resource_type][resource_selector_value] = {} for key in kwargs if ret["result"] else []: if resource_selector_property: - ret["changes"][resource_type][resource_selector_value][ - key - ] = _parse_value(kwargs[key]) + ret["changes"][resource_type][resource_selector_value][key] = ( + _parse_value(kwargs[key]) + ) else: ret["changes"][resource_type][key] = _parse_value(kwargs[key]) if ret["comment"] == "": @@ -436,10 +436,10 @@ def resource_present( else: ## zone does not exist ret["result"] = False - ret[ - "comment" - ] = "The zone {} is not in the configured, installed, or booted state.".format( - name + ret["comment"] = ( + "The zone {} is not in the configured, installed, or booted state.".format( + name + ) ) return ret @@ -541,10 +541,10 @@ def resource_absent( else: ## zone does not exist ret["result"] = False - ret[ - "comment" - ] = "The zone {} is not in the configured, installed, or booted state.".format( - name + ret["comment"] = ( + "The zone {} is not in the configured, installed, or booted state.".format( + name + ) ) return ret @@ -682,11 +682,11 @@ def export(name, path, replace=False): if __salt__["file.file_exists"](path) and not replace: ret["result"] = False ret["changes"] = {} - ret[ - "comment" - ] = "File {} exists, zone configuration for {} not exported.".format( - path, - name, + ret["comment"] = ( + "File {} exists, zone configuration for {} not exported.".format( + path, + name, + ) ) else: ## export and update file @@ -700,29 +700,29 @@ def export(name, path, replace=False): if __salt__["file.file_exists"](cfg_tmp): __salt__["file.remove"](cfg_tmp) ret["result"] = False - ret[ - "comment" - ] = "Unable to export zone configuration for {} to {}!".format( - name, - path, + ret["comment"] = ( + "Unable to export zone configuration for {} to {}!".format( + name, + path, + ) ) else: ret["result"] = True - ret[ - "comment" - ] = "Zone configuration for {} was exported to {}.".format( - name, - path, + ret["comment"] = ( + "Zone configuration for {} was exported to {}.".format( + name, + path, + ) ) ret["changes"][name] = "exported" else: cfg_diff = __salt__["file.get_diff"](path, cfg_tmp) if not cfg_diff: ret["result"] = True - ret[ - "comment" - ] = "Zone configuration for {} was already exported to {}.".format( - name, path + ret["comment"] = ( + "Zone configuration for {} was already exported to {}.".format( + name, path + ) ) if __salt__["file.file_exists"](cfg_tmp): __salt__["file.remove"](cfg_tmp) @@ -743,11 +743,11 @@ def export(name, path, replace=False): ) else: ret["result"] = True - ret[ - "comment" - ] = "Zone configuration for {} was re-exported to {}.".format( - name, - path, + ret["comment"] = ( + "Zone configuration for {} was re-exported to {}.".format( + name, + path, + ) ) ret["changes"][name] = "exported" else: @@ -1016,25 +1016,25 @@ def present(name, brand, zonepath, properties=None, resources=None): name, resource_cfg["resource_type"], resource_selector_property=resource_selector_property, - resource_selector_value=resource_cfg[ - resource_selector_property - ] - if resource_selector_property - else None, + resource_selector_value=( + resource_cfg[resource_selector_property] + if resource_selector_property + else None + ), ) else: - resource_cfg[ - "resource_selector_property" - ] = resource_selector_property + resource_cfg["resource_selector_property"] = ( + resource_selector_property + ) if resource_selector_property in resource_cfg: resource_cfg["resource_selector_value"] = resource_cfg[ resource_selector_property ] else: resource_cfg["resource_selector_value"] = None - resource_cfg[ - "name" - ] = name # we do this last because name can also be a attrib value + resource_cfg["name"] = ( + name # we do this last because name can also be a attrib value + ) res = resource_present(**resource_cfg) if res: ret["result"] = ret["result"] if res["result"] else False diff --git a/salt/states/zookeeper.py b/salt/states/zookeeper.py index 5fb20f1d813..e6674e9911b 100644 --- a/salt/states/zookeeper.py +++ b/salt/states/zookeeper.py @@ -27,7 +27,6 @@ The following options can be included in the acl dictionary: :type all: bool """ - __virtualname__ = "zookeeper" @@ -134,7 +133,7 @@ def present( ret = { "name": name, "result": False, - "comment": "Failed to setup znode {}".format(name), + "comment": f"Failed to setup znode {name}", "changes": {}, } connkwargs = { @@ -154,15 +153,15 @@ def present( cur_acls = __salt__["zookeeper.get_acls"](name, **connkwargs) if cur_value == value and _check_acls(cur_acls, chk_acls): ret["result"] = True - ret[ - "comment" - ] = "Znode {} is already set to the correct value with the correct acls".format( - name + ret["comment"] = ( + "Znode {} is already set to the correct value with the correct acls".format( + name + ) ) return ret elif __opts__["test"] is True: ret["result"] = None - ret["comment"] = "Znode {} is will be updated".format(name) + ret["comment"] = f"Znode {name} is will be updated" ret["changes"]["old"] = {} ret["changes"]["new"] = {} if value != cur_value: @@ -190,12 +189,12 @@ def present( ret["changes"] = changes if value_result and acl_result: ret["result"] = True - ret["comment"] = "Znode {} successfully updated".format(name) + ret["comment"] = f"Znode {name} successfully updated" return ret if __opts__["test"] is True: ret["result"] = None - ret["comment"] = "{} is will be created".format(name) + ret["comment"] = f"{name} is will be created" ret["changes"]["old"] = {} ret["changes"]["new"] = {} ret["changes"]["new"]["acls"] = chk_acls @@ -220,7 +219,7 @@ def present( ret["changes"] = changes if value_result and acl_result: ret["result"] = True - ret["comment"] = "Znode {} successfully created".format(name) + ret["comment"] = f"Znode {name} successfully created" return ret @@ -278,7 +277,7 @@ def absent( ret = { "name": name, "result": False, - "comment": "Failed to delete znode {}".format(name), + "comment": f"Failed to delete znode {name}", "changes": {}, } connkwargs = { @@ -292,7 +291,7 @@ def absent( if __salt__["zookeeper.exists"](name, **connkwargs) is False: ret["result"] = True - ret["comment"] = "Znode {} does not exist".format(name) + ret["comment"] = f"Znode {name} does not exist" return ret changes = {} @@ -303,7 +302,7 @@ def absent( if __opts__["test"] is True: ret["result"] = None - ret["comment"] = "Znode {} will be removed".format(name) + ret["comment"] = f"Znode {name} will be removed" ret["changes"]["old"] = changes return ret @@ -311,7 +310,7 @@ def absent( if __salt__["zookeeper.exists"](name, **connkwargs) is False: ret["result"] = True - ret["comment"] = "Znode {} has been removed".format(name) + ret["comment"] = f"Znode {name} has been removed" ret["changes"]["old"] = changes return ret @@ -375,7 +374,7 @@ def acls( ret = { "name": name, "result": False, - "comment": "Failed to set acls on znode {}".format(name), + "comment": f"Failed to set acls on znode {name}", "changes": {}, } connkwargs = { @@ -397,12 +396,12 @@ def acls( cur_acls = __salt__["zookeeper.get_acls"](name, **connkwargs) if _check_acls(cur_acls, chk_acls): ret["result"] = True - ret["comment"] = "Znode {} acls already set".format(name) + ret["comment"] = f"Znode {name} acls already set" return ret if __opts__["test"] is True: ret["result"] = None - ret["comment"] = "Znode {} acls will be updated".format(name) + ret["comment"] = f"Znode {name} acls will be updated" ret["changes"]["old"] = cur_acls ret["changes"]["new"] = chk_acls return ret @@ -413,7 +412,7 @@ def acls( ret["changes"] = {"old": cur_acls, "new": new_acls} if _check_acls(new_acls, chk_acls): ret["result"] = True - ret["comment"] = "Znode {} acls updated".format(name) + ret["comment"] = f"Znode {name} acls updated" return ret - ret["comment"] = "Znode {} acls failed to update".format(name) + ret["comment"] = f"Znode {name} acls failed to update" return ret diff --git a/salt/syspaths.py b/salt/syspaths.py index ce9bbc44ef6..23445622614 100644 --- a/salt/syspaths.py +++ b/salt/syspaths.py @@ -13,7 +13,6 @@ paths that are set in the master/minion config files. """ - import logging import os import os.path diff --git a/salt/template.py b/salt/template.py index 7de759dc4fb..7cdd8ed2055 100644 --- a/salt/template.py +++ b/salt/template.py @@ -1,6 +1,7 @@ """ Manage basic template commands """ + import codecs import io import logging @@ -33,7 +34,7 @@ def compile_template( sls="", input_data="", context=None, - **kwargs + **kwargs, ): """ Take the path to a template and return the high data structure @@ -208,7 +209,7 @@ for comb in ( ): fmt, tmpl = comb.split("_") - OLD_STYLE_RENDERERS[comb] = "{}|{}".format(tmpl, fmt) + OLD_STYLE_RENDERERS[comb] = f"{tmpl}|{fmt}" def check_render_pipe_str(pipestr, renderers, blacklist, whitelist): diff --git a/salt/thorium/__init__.py b/salt/thorium/__init__.py index 0b2bfb37f0d..6dffc972a07 100644 --- a/salt/thorium/__init__.py +++ b/salt/thorium/__init__.py @@ -1,6 +1,7 @@ """ The thorium system allows for advanced event tracking and reactions """ + # Needed: # Use a top file to load sls files locally # use the existing state system to compile a low state @@ -49,7 +50,7 @@ class ThorState(salt.state.HighState): regdata = {} if self.reg_ret is not None: try: - regdata = self.returners["{}.load_reg".format(self.reg_ret)]() + regdata = self.returners[f"{self.reg_ret}.load_reg"]() except Exception as exc: # pylint: disable=broad-except log.error(exc) @@ -67,7 +68,7 @@ class ThorState(salt.state.HighState): if not minions: return cache for minion in minions: - total = self.cache.fetch("minions/{}".format(minion), "data") + total = self.cache.fetch(f"minions/{minion}", "data") if "pillar" in total: if self.pillar_keys: @@ -175,5 +176,5 @@ class ThorState(salt.state.HighState): cache = self.gather_cache() chunks = self.get_chunks() if self.reg_ret is not None: - self.returners["{}.save_reg".format(self.reg_ret)](chunks) + self.returners[f"{self.reg_ret}.save_reg"](chunks) r_start = time.time() diff --git a/salt/thorium/calc.py b/salt/thorium/calc.py index 9eba4317779..d5487966a54 100644 --- a/salt/thorium/calc.py +++ b/salt/thorium/calc.py @@ -7,7 +7,6 @@ values are stored and computed, such as averages etc. :depends: statistics PyPi module """ - try: import statistics @@ -49,7 +48,7 @@ def calc(name, num, oper, minimum=0, maximum=0, ref=None): """ ret = {"name": name, "changes": {}, "comment": "", "result": True} if name not in __reg__: - ret["comment"] = "{} not found in register".format(name) + ret["comment"] = f"{name} not found in register" ret["result"] = False def opadd(vals): diff --git a/salt/thorium/check.py b/salt/thorium/check.py index ee41cfb9034..48149f3c426 100644 --- a/salt/thorium/check.py +++ b/salt/thorium/check.py @@ -35,7 +35,7 @@ def gt(name, value): ret = {"name": name, "result": False, "comment": "", "changes": {}} if name not in __reg__: ret["result"] = False - ret["comment"] = "Value {} not in register".format(name) + ret["comment"] = f"Value {name} not in register" return ret if __reg__[name]["val"] > value: ret["result"] = True @@ -65,7 +65,7 @@ def gte(name, value): ret = {"name": name, "result": False, "comment": "", "changes": {}} if name not in __reg__: ret["result"] = False - ret["comment"] = "Value {} not in register".format(name) + ret["comment"] = f"Value {name} not in register" return ret if __reg__[name]["val"] >= value: ret["result"] = True @@ -95,7 +95,7 @@ def lt(name, value): ret = {"name": name, "result": False, "comment": "", "changes": {}} if name not in __reg__: ret["result"] = False - ret["comment"] = "Value {} not in register".format(name) + ret["comment"] = f"Value {name} not in register" return ret if __reg__[name]["val"] < value: ret["result"] = True @@ -125,7 +125,7 @@ def lte(name, value): ret = {"name": name, "result": False, "comment": "", "changes": {}} if name not in __reg__: ret["result"] = False - ret["comment"] = "Value {} not in register".format(name) + ret["comment"] = f"Value {name} not in register" return ret if __reg__[name]["val"] <= value: ret["result"] = True @@ -155,7 +155,7 @@ def eq(name, value): ret = {"name": name, "result": False, "comment": "", "changes": {}} if name not in __reg__: ret["result"] = False - ret["comment"] = "Value {} not in register".format(name) + ret["comment"] = f"Value {name} not in register" return ret if __reg__[name]["val"] == value: ret["result"] = True @@ -185,7 +185,7 @@ def ne(name, value): ret = {"name": name, "result": False, "comment": "", "changes": {}} if name not in __reg__: ret["result"] = False - ret["comment"] = "Value {} not in register".format(name) + ret["comment"] = f"Value {name} not in register" return ret if __reg__[name]["val"] != value: ret["result"] = True @@ -224,7 +224,7 @@ def contains( ret = {"name": name, "result": False, "comment": "", "changes": {}} if name not in __reg__: ret["result"] = False - ret["comment"] = "Value {} not in register".format(name) + ret["comment"] = f"Value {name} not in register" return ret try: count_compare = ( @@ -305,7 +305,7 @@ def len_gt(name, value): ret = {"name": name, "result": False, "comment": "", "changes": {}} if name not in __reg__: ret["result"] = False - ret["comment"] = "Value {} not in register".format(name) + ret["comment"] = f"Value {name} not in register" return ret if len(__reg__[name]["val"]) > value: ret["result"] = True @@ -335,7 +335,7 @@ def len_gte(name, value): ret = {"name": name, "result": False, "comment": "", "changes": {}} if name not in __reg__: ret["result"] = False - ret["comment"] = "Value {} not in register".format(name) + ret["comment"] = f"Value {name} not in register" return ret if len(__reg__[name]["val"]) >= value: ret["result"] = True @@ -365,7 +365,7 @@ def len_lt(name, value): ret = {"name": name, "result": False, "comment": "", "changes": {}} if name not in __reg__: ret["result"] = False - ret["comment"] = "Value {} not in register".format(name) + ret["comment"] = f"Value {name} not in register" return ret if len(__reg__[name]["val"]) < value: ret["result"] = True @@ -395,7 +395,7 @@ def len_lte(name, value): ret = {"name": name, "result": False, "comment": "", "changes": {}} if name not in __reg__: ret["result"] = False - ret["comment"] = "Value {} not in register".format(name) + ret["comment"] = f"Value {name} not in register" return ret if len(__reg__[name]["val"]) <= value: ret["result"] = True @@ -425,7 +425,7 @@ def len_eq(name, value): ret = {"name": name, "result": False, "comment": "", "changes": {}} if name not in __reg__: ret["result"] = False - ret["comment"] = "Value {} not in register".format(name) + ret["comment"] = f"Value {name} not in register" return ret if __reg__[name]["val"] == value: ret["result"] = True @@ -455,7 +455,7 @@ def len_ne(name, value): ret = {"name": name, "result": False, "comment": "", "changes": {}} if name not in __reg__: ret["result"] = False - ret["comment"] = "Value {} not in register".format(name) + ret["comment"] = f"Value {name} not in register" return ret if len(__reg__[name]["val"]) != value: ret["result"] = True diff --git a/salt/thorium/file.py b/salt/thorium/file.py index 1e7dcc8f09e..ad6911e9003 100644 --- a/salt/thorium/file.py +++ b/salt/thorium/file.py @@ -37,7 +37,6 @@ Be warned that if you do this, then the file will be saved, but not in a format that can be re-imported into Python. """ - import os import salt.utils.data diff --git a/salt/thorium/reg.py b/salt/thorium/reg.py index 20cbebb253f..57842202cdf 100644 --- a/salt/thorium/reg.py +++ b/salt/thorium/reg.py @@ -3,7 +3,6 @@ Used to manage the thorium register. The thorium register is where compound values are stored and computed, such as averages etc. """ - import salt.utils.stringutils __func_alias__ = { diff --git a/salt/thorium/timer.py b/salt/thorium/timer.py index a1eefa3aa6f..bc67ec502a0 100644 --- a/salt/thorium/timer.py +++ b/salt/thorium/timer.py @@ -3,7 +3,6 @@ Allow for flow based timers. These timers allow for a sleep to exist across multiple runs of the flow """ - import time diff --git a/salt/tokens/localfs.py b/salt/tokens/localfs.py index afebb1a9ea7..93cfffa934f 100644 --- a/salt/tokens/localfs.py +++ b/salt/tokens/localfs.py @@ -2,7 +2,6 @@ Stores eauth tokens in the filesystem of the master. Location is configured by the master config option 'token_dir' """ - import hashlib import logging import os @@ -93,7 +92,7 @@ def list_tokens(opts): :returns: List of dicts (tokens) """ ret = [] - for (dirpath, dirnames, filenames) in salt.utils.path.os_walk(opts["token_dir"]): + for dirpath, dirnames, filenames in salt.utils.path.os_walk(opts["token_dir"]): for token in filenames: ret.append(token) return ret diff --git a/salt/tops/cobbler.py b/salt/tops/cobbler.py index 7a5d66662ab..5e5aed16a4b 100644 --- a/salt/tops/cobbler.py +++ b/salt/tops/cobbler.py @@ -20,9 +20,8 @@ Module Documentation """ import logging -import xmlrpc.client +import xmlrpc.client # nosec -# Set up logging log = logging.getLogger(__name__) diff --git a/salt/tops/ext_nodes.py b/salt/tops/ext_nodes.py index 4aa7ee1566c..a32c9f8eae8 100644 --- a/salt/tops/ext_nodes.py +++ b/salt/tops/ext_nodes.py @@ -44,6 +44,7 @@ The above essentially is the same as a top.sls containing the following: - basepackages - database """ + import logging import shlex import subprocess diff --git a/salt/tops/reclass_adapter.py b/salt/tops/reclass_adapter.py index 65fe33b0a5f..9b04bb55b58 100644 --- a/salt/tops/reclass_adapter.py +++ b/salt/tops/reclass_adapter.py @@ -120,7 +120,7 @@ def top(**kwargs): except ImportError as e: if "reclass" in str(e): raise SaltInvocationError( - "master_tops.reclass: cannot find reclass module in {}".format(sys.path) + f"master_tops.reclass: cannot find reclass module in {sys.path}" ) else: raise @@ -128,9 +128,7 @@ def top(**kwargs): except TypeError as e: if "unexpected keyword argument" in str(e): arg = str(e).split()[-1] - raise SaltInvocationError( - "master_tops.reclass: unexpected option: {}".format(arg) - ) + raise SaltInvocationError(f"master_tops.reclass: unexpected option: {arg}") else: raise @@ -143,4 +141,4 @@ def top(**kwargs): raise except ReclassException as e: - raise SaltInvocationError("master_tops.reclass: {}".format(str(e))) + raise SaltInvocationError(f"master_tops.reclass: {str(e)}") diff --git a/salt/tops/saltclass.py b/salt/tops/saltclass.py index 94dbae8b156..f9057842f47 100644 --- a/salt/tops/saltclass.py +++ b/salt/tops/saltclass.py @@ -207,7 +207,6 @@ Not using ``^`` as the first entry will simply merge the lists escaped one will not be correctly rendered - '\${xx}' will stay as is instead of being rendered as '${xx}' """ - import logging import salt.utils.saltclass as sc diff --git a/salt/tops/varstack_top.py b/salt/tops/varstack_top.py index 7f0f833cb65..479701d60ac 100644 --- a/salt/tops/varstack_top.py +++ b/salt/tops/varstack_top.py @@ -42,7 +42,6 @@ managed by salt as if given from a top.sls file. """ - try: import varstack except ImportError: diff --git a/salt/transport/__init__.py b/salt/transport/__init__.py index 83d327cdbc4..8795cb9d52a 100644 --- a/salt/transport/__init__.py +++ b/salt/transport/__init__.py @@ -1,6 +1,7 @@ """ Encapsulate the different transports available to Salt. """ + import logging import warnings diff --git a/salt/transport/client.py b/salt/transport/client.py index 6b079c9756b..899532380f6 100644 --- a/salt/transport/client.py +++ b/salt/transport/client.py @@ -7,6 +7,7 @@ This includes client side transport, for the ReqServer and the Publisher NOTE: This module has been deprecated and will be removed in Argon. Please use salt.channel.server instead. """ + import logging from salt.utils.versions import warn_until diff --git a/salt/transport/frame.py b/salt/transport/frame.py index c545a6ee7cf..aa6961f5ad9 100644 --- a/salt/transport/frame.py +++ b/salt/transport/frame.py @@ -2,7 +2,6 @@ Helper functions for transport components to handle message framing """ - import salt.utils.msgpack diff --git a/salt/transport/ipc.py b/salt/transport/ipc.py index 5265467112a..5421c60d1e5 100644 --- a/salt/transport/ipc.py +++ b/salt/transport/ipc.py @@ -2,7 +2,6 @@ IPC transport classes """ - import errno import logging import socket diff --git a/salt/transport/server.py b/salt/transport/server.py index 5b162b90e5b..1883ca1d1f6 100644 --- a/salt/transport/server.py +++ b/salt/transport/server.py @@ -7,6 +7,7 @@ This includes server side transport, for the ReqServer and the Publisher NOTE: This module has been deprecated and will be removed in Argon. Please use salt.channel.server instead. """ + import logging from salt.utils.versions import warn_until diff --git a/salt/transport/tcp.py b/salt/transport/tcp.py index 0dca8d6e4cf..42ab887aec9 100644 --- a/salt/transport/tcp.py +++ b/salt/transport/tcp.py @@ -4,6 +4,7 @@ TCP transport classes Wire protocol: "len(payload) msgpack({'head': SOMEHEADER, 'body': SOMEBODY})" """ + import asyncio import asyncio.exceptions import errno diff --git a/salt/transport/zeromq.py b/salt/transport/zeromq.py index c7e07408ae5..43f335a2338 100644 --- a/salt/transport/zeromq.py +++ b/salt/transport/zeromq.py @@ -1,6 +1,7 @@ """ Zeromq transport classes """ + import asyncio import asyncio.exceptions import errno @@ -365,7 +366,6 @@ class PublishClient(salt.transport.base.PublishClient): # self.on_recv_task = asyncio.create_task(self.on_recv_handler(callback)) def on_recv(self, callback): - """ Register a callback for received messages (that we didn't initiate) diff --git a/salt/utils/aggregation.py b/salt/utils/aggregation.py index e668f2c3782..eadbd2cfeb5 100644 --- a/salt/utils/aggregation.py +++ b/salt/utils/aggregation.py @@ -102,7 +102,6 @@ """ - import copy import logging @@ -132,7 +131,6 @@ class Sequence(list, Aggregate): def Scalar(obj): - """ Shortcut for Sequence creation diff --git a/salt/utils/ansible.py b/salt/utils/ansible.py index b91c931dff6..d75740e30f2 100644 --- a/salt/utils/ansible.py +++ b/salt/utils/ansible.py @@ -24,7 +24,7 @@ def targets(inventory="/etc/ansible/hosts", yaml=False, export=False): Default: /etc/salt/roster """ if not os.path.isfile(inventory): - raise CommandExecutionError("Inventory file not found: {}".format(inventory)) + raise CommandExecutionError(f"Inventory file not found: {inventory}") if not os.path.isabs(inventory): raise CommandExecutionError("Path to inventory file must be an absolute path") @@ -44,6 +44,4 @@ def targets(inventory="/etc/ansible/hosts", yaml=False, export=False): try: return salt.utils.json.loads(salt.utils.stringutils.to_str(inv)) except ValueError: - raise CommandExecutionError( - "Error processing the inventory: {}".format(inv) - ) + raise CommandExecutionError(f"Error processing the inventory: {inv}") diff --git a/salt/utils/args.py b/salt/utils/args.py index 536aea38166..e34c208d6dd 100644 --- a/salt/utils/args.py +++ b/salt/utils/args.py @@ -49,7 +49,7 @@ def invalid_kwargs(invalid_kwargs, raise_exc=True): """ if invalid_kwargs: if isinstance(invalid_kwargs, dict): - new_invalid = ["{}={}".format(x, y) for x, y in invalid_kwargs.items()] + new_invalid = [f"{x}={y}" for x, y in invalid_kwargs.items()] invalid_kwargs = new_invalid msg = "The following keyword arguments are not valid: {}".format( ", ".join(invalid_kwargs) @@ -236,7 +236,7 @@ def get_function_argspec(func, is_class_method=None): the argspec unless ``is_class_method`` is True. """ if not callable(func): - raise TypeError("{} is not a callable".format(func)) + raise TypeError(f"{func} is not a callable") while hasattr(func, "__wrapped__"): func = func.__wrapped__ @@ -244,7 +244,7 @@ def get_function_argspec(func, is_class_method=None): try: sig = inspect.signature(func) except TypeError: - raise TypeError("Cannot inspect argument list for '{}'".format(func)) + raise TypeError(f"Cannot inspect argument list for '{func}'") # Build a namedtuple which looks like the result of a Python 2 argspec _ArgSpec = namedtuple("ArgSpec", "args varargs keywords defaults") @@ -466,18 +466,18 @@ def format_call( # In case this is being called for a state module "full", # Not a state module, build the name - "{}.{}".format(fun.__module__, fun.__name__), + f"{fun.__module__}.{fun.__name__}", ), ) else: msg = "{} and '{}' are invalid keyword arguments for '{}'".format( - ", ".join(["'{}'".format(e) for e in extra][:-1]), + ", ".join([f"'{e}'" for e in extra][:-1]), list(extra.keys())[-1], ret.get( # In case this is being called for a state module "full", # Not a state module, build the name - "{}.{}".format(fun.__module__, fun.__name__), + f"{fun.__module__}.{fun.__name__}", ), ) @@ -529,7 +529,8 @@ def parse_function(s): key = None word = [] elif token in "]})": - if not brackets or token != {"[": "]", "{": "}", "(": ")"}[brackets.pop()]: + _tokens = {"[": "]", "{": "}", "(": ")"} + if not brackets or token != _tokens[brackets.pop()]: break word.append(token) elif token == "=" and not brackets: diff --git a/salt/utils/asynchronous.py b/salt/utils/asynchronous.py index f983a4ec64f..316fc5c478d 100644 --- a/salt/utils/asynchronous.py +++ b/salt/utils/asynchronous.py @@ -2,7 +2,6 @@ Helpers/utils for working with tornado asynchronous stuff """ - import asyncio import contextlib import logging diff --git a/salt/utils/atomicfile.py b/salt/utils/atomicfile.py index 574797b77e3..d36733c83fb 100644 --- a/salt/utils/atomicfile.py +++ b/salt/utils/atomicfile.py @@ -2,6 +2,7 @@ A module written originally by Armin Ronacher to manage file transfers in an atomic way """ + import errno import os import random @@ -90,7 +91,7 @@ if os.name == "nt": # pragma: no cover except OSError as err: if err.errno != errno.EEXIST: raise - old = "{}-{:08x}".format(dst, random.randint(0, sys.maxint)) + old = f"{dst}-{random.randint(0, sys.maxint):08x}" os.rename(dst, old) os.rename(src, dst) try: diff --git a/salt/utils/aws.py b/salt/utils/aws.py index 36a99d92bcf..4c581a06c92 100644 --- a/salt/utils/aws.py +++ b/salt/utils/aws.py @@ -7,6 +7,7 @@ This is a base library used by a number of AWS services. :depends: requests """ + import binascii import copy import hashlib diff --git a/salt/utils/boto3mod.py b/salt/utils/boto3mod.py index 3692ae5549e..4e84c2ee70c 100644 --- a/salt/utils/boto3mod.py +++ b/salt/utils/boto3mod.py @@ -24,7 +24,6 @@ Example Usage: .. versionadded:: 2015.8.0 """ - import hashlib import logging import sys @@ -104,7 +103,7 @@ def _get_profile(service, region, key, keyid, profile): if not keyid and _option(service + ".keyid"): keyid = _option(service + ".keyid") - label = "boto_{}:".format(service) + label = f"boto_{service}:" if keyid: hash_string = region + keyid + key hash_string = salt.utils.stringutils.to_bytes(hash_string) @@ -138,9 +137,9 @@ def cache_id( cxkey, _, _, _ = _get_profile(service, region, key, keyid, profile) if sub_resource: - cxkey = "{}:{}:{}:id".format(cxkey, sub_resource, name) + cxkey = f"{cxkey}:{sub_resource}:{name}:id" else: - cxkey = "{}:{}:id".format(cxkey, name) + cxkey = f"{cxkey}:{name}:id" if invalidate: if cxkey in __context__: @@ -197,10 +196,10 @@ def get_connection( aws_access_key_id=keyid, aws_secret_access_key=key, region_name=region ) if session is None: - raise SaltInvocationError('Region "{}" is not valid.'.format(region)) + raise SaltInvocationError(f'Region "{region}" is not valid.') conn = session.client(module) if conn is None: - raise SaltInvocationError('Region "{}" is not valid.'.format(region)) + raise SaltInvocationError(f'Region "{region}" is not valid.') except botocore.exceptions.NoCredentialsError: raise SaltInvocationError( "No authentication credentials found when " diff --git a/salt/utils/botomod.py b/salt/utils/botomod.py index 8d9d5cad535..ac9b510d689 100644 --- a/salt/utils/botomod.py +++ b/salt/utils/botomod.py @@ -24,7 +24,6 @@ Example Usage: .. versionadded:: 2015.8.0 """ - import hashlib import logging import sys @@ -91,7 +90,7 @@ def _get_profile(service, region, key, keyid, profile): if not keyid and __salt__["config.option"](service + ".keyid"): keyid = __salt__["config.option"](service + ".keyid") - label = "boto_{}:".format(service) + label = f"boto_{service}:" if keyid: hash_string = region + keyid + key hash_string = salt.utils.stringutils.to_bytes(hash_string) @@ -125,9 +124,9 @@ def cache_id( cxkey, _, _, _ = _get_profile(service, region, key, keyid, profile) if sub_resource: - cxkey = "{}:{}:{}:id".format(cxkey, sub_resource, name) + cxkey = f"{cxkey}:{sub_resource}:{name}:id" else: - cxkey = "{}:{}:id".format(cxkey, name) + cxkey = f"{cxkey}:{name}:id" if invalidate: if cxkey in __context__: @@ -187,7 +186,7 @@ def get_connection( region, aws_access_key_id=keyid, aws_secret_access_key=key ) if conn is None: - raise SaltInvocationError('Region "{}" is not valid.'.format(region)) + raise SaltInvocationError(f'Region "{region}" is not valid.') except boto.exception.NoAuthHandlerFound: raise SaltInvocationError( "No authentication credentials found when " diff --git a/salt/utils/cloud.py b/salt/utils/cloud.py index 3e026a0bb57..0f3e27c2a24 100644 --- a/salt/utils/cloud.py +++ b/salt/utils/cloud.py @@ -2,7 +2,6 @@ Utility functions for salt.cloud """ - import codecs import copy import errno @@ -565,9 +564,9 @@ def bootstrap(vm_, opts=None): ) if saltify_driver: - deploy_kwargs[ - "wait_for_passwd_maxtries" - ] = 0 # No need to wait/retry with Saltify + deploy_kwargs["wait_for_passwd_maxtries"] = ( + 0 # No need to wait/retry with Saltify + ) win_installer = salt.config.get_cloud_config_value("win_installer", vm_, opts) if win_installer: diff --git a/salt/utils/color.py b/salt/utils/color.py index d765288f496..8ef55ccad20 100644 --- a/salt/utils/color.py +++ b/salt/utils/color.py @@ -2,7 +2,6 @@ Functions used for CLI color themes. """ - import logging import os @@ -28,7 +27,7 @@ def get_color_theme(theme): colors = salt.utils.data.decode(salt.utils.yaml.safe_load(fp_)) ret = {} for color in colors: - ret[color] = "\033[{}m".format(colors[color]) + ret[color] = f"\033[{colors[color]}m" if not isinstance(colors, dict): log.warning("The theme file %s is not a dict", theme) return {} diff --git a/salt/utils/configcomparer.py b/salt/utils/configcomparer.py index ef67e65e5f1..1ab770a5a96 100644 --- a/salt/utils/configcomparer.py +++ b/salt/utils/configcomparer.py @@ -32,7 +32,7 @@ def compare_and_update_config(config, update_config, changes, namespace=""): for key, value in config.items(): _namespace = key if namespace: - _namespace = "{}.{}".format(namespace, _namespace) + _namespace = f"{namespace}.{_namespace}" update_config[key] = compare_and_update_config( value, update_config.get(key, None), @@ -61,9 +61,9 @@ def compare_and_update_config(config, update_config, changes, namespace=""): # iterate through config list, ensuring that each index in the # update_config list is the same for idx, item in enumerate(config): - _namespace = "[{}]".format(idx) + _namespace = f"[{idx}]" if namespace: - _namespace = "{}{}".format(namespace, _namespace) + _namespace = f"{namespace}{_namespace}" _update = None if len(update_config) > idx: _update = update_config[idx] @@ -86,9 +86,9 @@ def compare_and_update_config(config, update_config, changes, namespace=""): for idx, old_item in enumerate(update_config): if idx < len(config): continue - _namespace = "[{}]".format(idx) + _namespace = f"[{idx}]" if namespace: - _namespace = "{}{}".format(namespace, _namespace) + _namespace = f"{namespace}{_namespace}" changes[_namespace] = { "new": None, "old": old_item, diff --git a/salt/utils/configparser.py b/salt/utils/configparser.py index 6a3b1e689ea..f4d72c68343 100644 --- a/salt/utils/configparser.py +++ b/salt/utils/configparser.py @@ -267,12 +267,12 @@ class GitConfigParser(RawConfigParser): ) if self._defaults: fp_.write(convert("[%s]\n" % self.DEFAULTSECT)) - for (key, value) in self._defaults.items(): + for key, value in self._defaults.items(): value = salt.utils.stringutils.to_unicode(value).replace("\n", "\n\t") - fp_.write(convert("{} = {}\n".format(key, value))) + fp_.write(convert(f"{key} = {value}\n")) for section in self._sections: fp_.write(convert("[%s]\n" % section)) - for (key, value) in self._sections[section].items(): + for key, value in self._sections[section].items(): if (value is not None) or (self._optcre == self.OPTCRE): if not isinstance(value, list): value = [value] diff --git a/salt/utils/crypt.py b/salt/utils/crypt.py index e34576c175a..044eebe7a77 100644 --- a/salt/utils/crypt.py +++ b/salt/utils/crypt.py @@ -1,6 +1,7 @@ """ Functions dealing with encryption """ + import hashlib import logging import os diff --git a/salt/utils/data.py b/salt/utils/data.py index 5f9d7484868..5b7cc8fbea6 100644 --- a/salt/utils/data.py +++ b/salt/utils/data.py @@ -3,7 +3,6 @@ Functions for manipulating, inspecting, or otherwise working with data types and data structures. """ - import copy import datetime import fnmatch @@ -1380,7 +1379,7 @@ def recursive_diff( append_old = list(old.keys())[min_length:] append_new = list(new.keys())[min_length:] # Compare ordered - for (key_old, key_new) in zip(old, new): + for key_old, key_new in zip(old, new): if key_old == key_new: if key_old in ignore_keys: del ret_old[key_old] diff --git a/salt/utils/dateutils.py b/salt/utils/dateutils.py index b55d9a40027..2b680672eb6 100644 --- a/salt/utils/dateutils.py +++ b/salt/utils/dateutils.py @@ -2,7 +2,6 @@ Convenience functions for dealing with datetime classes """ - import datetime import salt.utils.stringutils @@ -47,11 +46,9 @@ def date_cast(date): return datetime.datetime.fromtimestamp(date) except Exception: # pylint: disable=broad-except if HAS_TIMELIB: - raise ValueError("Unable to parse {}".format(date)) + raise ValueError(f"Unable to parse {date}") - raise RuntimeError( - "Unable to parse {}. Consider installing timelib".format(date) - ) + raise RuntimeError(f"Unable to parse {date}. Consider installing timelib") @jinja_filter("date_format") diff --git a/salt/utils/debug.py b/salt/utils/debug.py index e1fda0a8aec..e74bad3dda2 100644 --- a/salt/utils/debug.py +++ b/salt/utils/debug.py @@ -34,7 +34,7 @@ def _handle_sigusr1(sig, stack): output = sys.stderr _makepretty(output, stack) else: - filename = "salt-debug-{}.log".format(int(time.time())) + filename = f"salt-debug-{int(time.time())}.log" destfile = os.path.join(tempfile.gettempdir(), filename) with salt.utils.files.fopen(destfile, "w") as output: _makepretty(output, stack) @@ -50,11 +50,11 @@ def _handle_sigusr2(sig, stack): return if yappi.is_running(): yappi.stop() - filename = "callgrind.salt-{}-{}".format(int(time.time()), os.getpid()) + filename = f"callgrind.salt-{int(time.time())}-{os.getpid()}" destfile = os.path.join(tempfile.gettempdir(), filename) yappi.get_func_stats().save(destfile, type="CALLGRIND") if sys.stderr.isatty(): - sys.stderr.write("Saved profiling data to: {}\n".format(destfile)) + sys.stderr.write(f"Saved profiling data to: {destfile}\n") yappi.clear_stats() else: if sys.stderr.isatty(): @@ -135,5 +135,5 @@ def caller_name(skip=2, include_lineno=False): del parentframe fullname = ".".join(name) if include_lineno and lineno: - fullname += ":{}".format(lineno) + fullname += f":{lineno}" return fullname diff --git a/salt/utils/decorators/__init__.py b/salt/utils/decorators/__init__.py index 1f62d5f3d65..4ddf359d23c 100644 --- a/salt/utils/decorators/__init__.py +++ b/salt/utils/decorators/__init__.py @@ -2,7 +2,6 @@ Helpful decorators for module writing """ - import errno import inspect import logging @@ -117,7 +116,7 @@ class Depends: @staticmethod def run_command(dependency, mod_name, func_name): - full_name = "{}.{}".format(mod_name, func_name) + full_name = f"{mod_name}.{func_name}" log.trace("Running '%s' for '%s'", dependency, full_name) if IS_WINDOWS: args = salt.utils.args.shlex_split(dependency, posix=False) @@ -217,9 +216,11 @@ class Depends: mod_name, func_name, dependency, - " version {}".format(params["version"]) - if "version" in params - else "", + ( + " version {}".format(params["version"]) + if "version" in params + else "" + ), ) # if not, unload the function if frame: @@ -228,7 +229,7 @@ class Depends: except (AttributeError, KeyError): pass - mod_key = "{}.{}".format(mod_name, func_name) + mod_key = f"{mod_name}.{func_name}" # if we don't have this module loaded, skip it! if mod_key not in functions: @@ -263,7 +264,7 @@ def timing(function): mod_name = function.__module__[16:] else: mod_name = function.__module__ - fstr = "Function %s.%s took %.{}f seconds to execute".format(sys.float_info.dig) + fstr = f"Function %s.%s took %.{sys.float_info.dig}f seconds to execute" log.profile(fstr, mod_name, function.__name__, end_time - start_time) return ret @@ -290,9 +291,7 @@ def memoize(func): else: str_args.append(arg) - args_ = ",".join( - list(str_args) + ["{}={}".format(k, kwargs[k]) for k in sorted(kwargs)] - ) + args_ = ",".join(list(str_args) + [f"{k}={kwargs[k]}" for k in sorted(kwargs)]) if args_ not in cache: cache[args_] = func(*args, **kwargs) return cache[args_] @@ -623,9 +622,7 @@ class _WithDeprecated(_DeprecationDecorator): "Function '{}' is mentioned both in deprecated " "and superseded sections. Please remove any of that.".format(full_name) ) - old_function = self._globals.get( - self._with_name or "_{}".format(function.__name__) - ) + old_function = self._globals.get(self._with_name or f"_{function.__name__}") if self._policy == self.OPT_IN: self._function = function if use_superseded else old_function else: diff --git a/salt/utils/decorators/extension_deprecation.py b/salt/utils/decorators/extension_deprecation.py index a540eb0825f..bced8ea180e 100644 --- a/salt/utils/decorators/extension_deprecation.py +++ b/salt/utils/decorators/extension_deprecation.py @@ -1,6 +1,7 @@ """ Decorators for deprecation of modules to Salt extensions """ + import logging from functools import wraps diff --git a/salt/utils/decorators/path.py b/salt/utils/decorators/path.py index 254593553a3..af08960b3e5 100644 --- a/salt/utils/decorators/path.py +++ b/salt/utils/decorators/path.py @@ -18,7 +18,7 @@ def which(exe): def wrapped(*args, **kwargs): if salt.utils.path.which(exe) is None: raise CommandNotFoundError( - "The '{}' binary was not found in $PATH.".format(exe) + f"The '{exe}' binary was not found in $PATH." ) return function(*args, **kwargs) @@ -38,7 +38,7 @@ def which_bin(exes): if salt.utils.path.which_bin(exes) is None: raise CommandNotFoundError( "None of provided binaries({}) were found in $PATH.".format( - ["'{}'".format(exe) for exe in exes] + [f"'{exe}'" for exe in exes] ) ) return function(*args, **kwargs) diff --git a/salt/utils/decorators/state.py b/salt/utils/decorators/state.py index bcca040b996..0d0fbf4254f 100644 --- a/salt/utils/decorators/state.py +++ b/salt/utils/decorators/state.py @@ -4,7 +4,6 @@ Decorators for salt.state :codeauthor: :email:`Bo Maryniuk (bo@suse.de)` """ - import logging import salt.utils.stringutils @@ -18,7 +17,7 @@ class OutputUnifier: self.policies = [] for pls in policies: if not hasattr(self, pls): - raise SaltException("Unknown policy: {}".format(pls)) + raise SaltException(f"Unknown policy: {pls}") else: self.policies.append(getattr(self, pls)) @@ -36,7 +35,7 @@ class OutputUnifier: "result": False, "name": "later", "changes": {}, - "comment": "An exception occurred in this state: {}".format(exc), + "comment": f"An exception occurred in this state: {exc}", } return data diff --git a/salt/utils/dns.py b/salt/utils/dns.py index dc0d680c773..2a7cd420cf7 100644 --- a/salt/utils/dns.py +++ b/salt/utils/dns.py @@ -123,7 +123,7 @@ def _to_port(port): assert 1 <= port <= 65535 return port except (ValueError, AssertionError): - raise ValueError("Invalid port {}".format(port)) + raise ValueError(f"Invalid port {port}") def _tree(domain, tld=False): @@ -276,24 +276,24 @@ def _lookup_dig(name, rdtype, timeout=None, servers=None, secure=None): :param servers: [] of servers to use :return: [] of records or False if error """ - cmd = "dig {} -t {} ".format(DIG_OPTIONS, rdtype) + cmd = f"dig {DIG_OPTIONS} -t {rdtype} " if servers: - cmd += "".join(["@{} ".format(srv) for srv in servers]) + cmd += "".join([f"@{srv} " for srv in servers]) if timeout is not None: if servers: timeout = int(float(timeout) / len(servers)) else: timeout = int(timeout) - cmd += "+time={} ".format(timeout) + cmd += f"+time={timeout} " if secure: cmd += "+dnssec +adflag " cmd = __salt__["cmd.run_all"]( - "{} {}".format(cmd, name), python_shell=False, output_loglevel="quiet" + f"{cmd} {name}", python_shell=False, output_loglevel="quiet" ) if "ignoring invalid type" in cmd["stderr"]: - raise ValueError("Invalid DNS type {}".format(rdtype)) + raise ValueError(f"Invalid DNS type {rdtype}") elif cmd["retcode"] != 0: log.warning( "dig returned (%s): %s", @@ -333,9 +333,9 @@ def _lookup_drill(name, rdtype, timeout=None, servers=None, secure=None): cmd = "drill " if secure: cmd += "-D -o ad " - cmd += "{} {} ".format(rdtype, name) + cmd += f"{rdtype} {name} " if servers: - cmd += "".join(["@{} ".format(srv) for srv in servers]) + cmd += "".join([f"@{srv} " for srv in servers]) cmd = __salt__["cmd.run_all"]( cmd, timeout=timeout, python_shell=False, output_loglevel="quiet" ) @@ -364,7 +364,7 @@ def _lookup_drill(name, rdtype, timeout=None, servers=None, secure=None): validated = True continue elif l_type != rdtype: - raise ValueError("Invalid DNS type {}".format(rdtype)) + raise ValueError(f"Invalid DNS type {rdtype}") res.append(_data_clean(l_rec)) @@ -385,10 +385,12 @@ def _lookup_gai(name, rdtype, timeout=None): :param timeout: ignored :return: [] of addresses or False if error """ - try: - sock_t = {"A": socket.AF_INET, "AAAA": socket.AF_INET6}[rdtype] - except KeyError: - raise ValueError("Invalid DNS type {} for gai lookup".format(rdtype)) + if rdtype == "A": + sock_t = socket.AF_INET + elif rdtype == "AAAA": + sock_t = socket.AF_INET6 + else: + raise ValueError(f"Invalid DNS type {rdtype} for gai lookup") if timeout: log.info("Ignoring timeout on gai resolver; fix resolv.conf to do that") @@ -412,18 +414,18 @@ def _lookup_host(name, rdtype, timeout=None, server=None): :param timeout: server response wait :return: [] of records or False if error """ - cmd = "host -t {} ".format(rdtype) + cmd = f"host -t {rdtype} " if timeout: - cmd += "-W {} ".format(int(timeout)) + cmd += f"-W {int(timeout)} " cmd += name if server is not None: - cmd += " {}".format(server) + cmd += f" {server}" cmd = __salt__["cmd.run_all"](cmd, python_shell=False, output_loglevel="quiet") if "invalid type" in cmd["stderr"]: - raise ValueError("Invalid DNS type {}".format(rdtype)) + raise ValueError(f"Invalid DNS type {rdtype}") elif cmd["retcode"] != 0: log.warning("host returned (%s): %s", cmd["retcode"], cmd["stderr"]) return False @@ -470,7 +472,7 @@ def _lookup_dnspython(name, rdtype, timeout=None, servers=None, secure=None): ] return res except dns.rdatatype.UnknownRdatatype: - raise ValueError("Invalid DNS type {}".format(rdtype)) + raise ValueError(f"Invalid DNS type {rdtype}") except ( dns.resolver.NXDOMAIN, dns.resolver.YXDOMAIN, @@ -489,12 +491,12 @@ def _lookup_nslookup(name, rdtype, timeout=None, server=None): :param server: server to query :return: [] of records or False if error """ - cmd = "nslookup -query={} {}".format(rdtype, name) + cmd = f"nslookup -query={rdtype} {name}" if timeout is not None: - cmd += " -timeout={}".format(int(timeout)) + cmd += f" -timeout={int(timeout)}" if server is not None: - cmd += " {}".format(server) + cmd += f" {server}" cmd = __salt__["cmd.run_all"](cmd, python_shell=False, output_loglevel="quiet") @@ -511,7 +513,7 @@ def _lookup_nslookup(name, rdtype, timeout=None, server=None): try: line = next(lookup_res) if "unknown query type" in line: - raise ValueError("Invalid DNS type {}".format(rdtype)) + raise ValueError(f"Invalid DNS type {rdtype}") while True: if name in line: @@ -895,7 +897,7 @@ def spf_rec(rdata): # It's a modifier mod, val = mech_spec.split("=", 1) if mod in mods: - raise KeyError("Modifier {} can only appear once".format(mod)) + raise KeyError(f"Modifier {mod} can only appear once") mods.add(mod) continue @@ -959,7 +961,7 @@ def srv_name(svc, proto="tcp", domain=None): if domain: domain = "." + domain - return "_{}._{}{}".format(svc, proto, domain) + return f"_{svc}._{proto}{domain}" def srv_rec(rdatas): @@ -1133,7 +1135,7 @@ def services(services_file="/etc/services"): if not curr_desc: pp_res["desc"] = comment elif comment != curr_desc: - pp_res["desc"] = "{}, {}".format(curr_desc, comment) + pp_res["desc"] = f"{curr_desc}, {comment}" res[name] = svc_res for svc, data in res.items(): @@ -1210,7 +1212,7 @@ def parse_resolv(src="/etc/resolv.conf"): ip_addr ) ip_net = ipaddress.ip_network( - "{}{}".format(ip_addr, mask), strict=False + f"{ip_addr}{mask}", strict=False ) if ip_net.version == 6: # TODO diff --git a/salt/utils/doc.py b/salt/utils/doc.py index 9f80bc3337b..4fcbe1549d6 100644 --- a/salt/utils/doc.py +++ b/salt/utils/doc.py @@ -1,6 +1,7 @@ """ Functions for analyzing/parsing docstrings """ + import logging import re diff --git a/salt/utils/dockermod/__init__.py b/salt/utils/dockermod/__init__.py index f703ee7b1e6..73f1be23a15 100644 --- a/salt/utils/dockermod/__init__.py +++ b/salt/utils/dockermod/__init__.py @@ -5,7 +5,6 @@ This module contains logic to accommodate docker/salt CLI usage, as well as input as formatted by states. """ - import copy import logging diff --git a/salt/utils/dockermod/translate/container.py b/salt/utils/dockermod/translate/container.py index b155308bf74..a59fd9c7e82 100644 --- a/salt/utils/dockermod/translate/container.py +++ b/salt/utils/dockermod/translate/container.py @@ -137,7 +137,7 @@ def binds(val, **kwargs): # pylint: disable=unused-argument val = helpers.split(val) except AttributeError: raise SaltInvocationError( - "'{}' is not a dictionary or list of bind definitions".format(val) + f"'{val}' is not a dictionary or list of bind definitions" ) return val @@ -453,9 +453,11 @@ def port_bindings(val, **kwargs): bind_vals = [ ( _format_port(val, proto), - (host_ip,) - if hport_list[idx] is None - else (host_ip, hport_list[idx]), + ( + (host_ip,) + if hport_list[idx] is None + else (host_ip, hport_list[idx]) + ), ) for idx, val in enumerate(cport_list) ] @@ -509,9 +511,7 @@ def ports(val, **kwargs): # pylint: disable=unused-argument if isinstance(val, int): val = [val] else: - raise SaltInvocationError( - "'{}' is not a valid port definition".format(val) - ) + raise SaltInvocationError(f"'{val}' is not a valid port definition") new_ports = set() for item in val: if isinstance(item, int): @@ -520,9 +520,7 @@ def ports(val, **kwargs): # pylint: disable=unused-argument try: item, _, proto = item.partition("/") except AttributeError: - raise SaltInvocationError( - "'{}' is not a valid port definition".format(item) - ) + raise SaltInvocationError(f"'{item}' is not a valid port definition") try: range_start, range_end = helpers.get_port_range(item) except ValueError as exc: @@ -633,7 +631,7 @@ def ulimits(val, **kwargs): # pylint: disable=unused-argument } except (TypeError, ValueError): raise SaltInvocationError( - "Limit '{}' contains non-numeric value(s)".format(item) + f"Limit '{item}' contains non-numeric value(s)" ) return val @@ -655,7 +653,7 @@ def user(val, **kwargs): # pylint: disable=unused-argument if not isinstance(val, (int, str)): raise SaltInvocationError("Value must be a username or uid") elif isinstance(val, int) and val < 0: - raise SaltInvocationError("'{}' is an invalid uid".format(val)) + raise SaltInvocationError(f"'{val}' is an invalid uid") return val @@ -674,7 +672,7 @@ def volumes(val, **kwargs): # pylint: disable=unused-argument val = helpers.translate_stringlist(val) for item in val: if not os.path.isabs(item): - raise SaltInvocationError("'{}' is not an absolute path".format(item)) + raise SaltInvocationError(f"'{item}' is not an absolute path") return val @@ -691,5 +689,5 @@ def working_dir(val, **kwargs): # pylint: disable=unused-argument except AttributeError: is_abs = False if not is_abs: - raise SaltInvocationError("'{}' is not an absolute path".format(val)) + raise SaltInvocationError(f"'{val}' is not an absolute path") return val diff --git a/salt/utils/dockermod/translate/helpers.py b/salt/utils/dockermod/translate/helpers.py index f172d080cdc..deb0e50ec5f 100644 --- a/salt/utils/dockermod/translate/helpers.py +++ b/salt/utils/dockermod/translate/helpers.py @@ -78,7 +78,7 @@ def get_port_range(port_def): "port range ({})".format(range_start, range_end) ) else: - msg = "'{}' is non-numeric or an invalid port range".format(port_def) + msg = f"'{port_def}' is non-numeric or an invalid port range" raise ValueError(msg) else: return range_start, range_end @@ -110,9 +110,11 @@ def map_vals(val, *names, **extra_opts): "'{}' contains {} value(s) (expected {})".format( item, num_elements, - expected_num_elements - if fill is NOTSET - else "up to {}".format(expected_num_elements), + ( + expected_num_elements + if fill is NOTSET + else f"up to {expected_num_elements}" + ), ) ) val[idx] = dict(zip(names, elements)) @@ -122,7 +124,7 @@ def map_vals(val, *names, **extra_opts): def validate_ip(val): try: if not salt.utils.network.is_ip(val): - raise SaltInvocationError("'{}' is not a valid IP address".format(val)) + raise SaltInvocationError(f"'{val}' is not a valid IP address") except RuntimeError: pass @@ -130,7 +132,7 @@ def validate_ip(val): def validate_subnet(val): try: if not salt.utils.network.is_subnet(val): - raise SaltInvocationError("'{}' is not a valid subnet".format(val)) + raise SaltInvocationError(f"'{val}' is not a valid subnet") except RuntimeError: pass @@ -144,7 +146,7 @@ def translate_int(val): try: val = int(val) except (TypeError, ValueError): - raise SaltInvocationError("'{}' is not an integer".format(val)) + raise SaltInvocationError(f"'{val}' is not an integer") return val @@ -157,7 +159,7 @@ def translate_dict(val): Not really translating, just raising an exception if it's not a dict """ if not isinstance(val, dict): - raise SaltInvocationError("'{}' is not a dictionary".format(val)) + raise SaltInvocationError(f"'{val}' is not a dictionary") return val @@ -255,9 +257,7 @@ def translate_key_val(val, delimiter="="): try: lvalue, rvalue = split(item, delimiter, 1) except (AttributeError, TypeError, ValueError): - raise SaltInvocationError( - "'{}' is not a key{}value pair".format(item, delimiter) - ) + raise SaltInvocationError(f"'{item}' is not a key{delimiter}value pair") new_val[lvalue] = rvalue return new_val diff --git a/salt/utils/extend.py b/salt/utils/extend.py index 72903af23fc..2317feb2bf8 100644 --- a/salt/utils/extend.py +++ b/salt/utils/extend.py @@ -12,7 +12,6 @@ This tool is accessed using `salt-extend` :codeauthor: Anthony Shaw """ - import logging import os import shutil @@ -175,19 +174,15 @@ def _prompt_choice(var_name, options): :returns: The selected user """ choice_map = OrderedDict( - ("{}".format(i), value) - for i, value in enumerate(options, 1) - if value[0] != "test" + (f"{i}", value) for i, value in enumerate(options, 1) if value[0] != "test" ) choices = choice_map.keys() default = "1" - choice_lines = [ - "{} - {} - {}".format(c[0], c[1][0], c[1][1]) for c in choice_map.items() - ] + choice_lines = [f"{c[0]} - {c[1][0]} - {c[1][1]}" for c in choice_map.items()] prompt = "\n".join( ( - "Select {}:".format(var_name), + f"Select {var_name}:", "\n".join(choice_lines), "Choose from {}".format(", ".join(choices)), ) @@ -273,7 +268,7 @@ def run( if description is None: description = _prompt_user_variable("Short description of the module", "") - template_dir = "templates/{}".format(extension_type) + template_dir = f"templates/{extension_type}" module_name = name param_dict = { diff --git a/salt/utils/files.py b/salt/utils/files.py index 3c57cce7132..8f6cf980d66 100644 --- a/salt/utils/files.py +++ b/salt/utils/files.py @@ -2,7 +2,6 @@ Functions for working with files """ - import codecs import contextlib import errno @@ -131,9 +130,9 @@ def copyfile(source, dest, backup_mode="", cachedir=""): specified cache the file. """ if not os.path.isfile(source): - raise OSError("[Errno 2] No such file or directory: {}".format(source)) + raise OSError(f"[Errno 2] No such file or directory: {source}") if not os.path.isdir(os.path.dirname(dest)): - raise OSError("[Errno 2] No such file or directory: {}".format(dest)) + raise OSError(f"[Errno 2] No such file or directory: {dest}") bname = os.path.basename(dest) dname = os.path.dirname(os.path.abspath(dest)) tgt = mkstemp(prefix=bname, dir=dname) @@ -199,9 +198,7 @@ def rename(src, dst): os.remove(dst) except OSError as exc: if exc.errno != errno.ENOENT: - raise MinionError( - "Error: Unable to remove {}: {}".format(dst, exc.strerror) - ) + raise MinionError(f"Error: Unable to remove {dst}: {exc.strerror}") os.rename(src, dst) @@ -222,9 +219,9 @@ def process_read_exception(exc, path, ignore=None): return if exc.errno == errno.ENOENT: - raise CommandExecutionError("{} does not exist".format(path)) + raise CommandExecutionError(f"{path} does not exist") elif exc.errno == errno.EACCES: - raise CommandExecutionError("Permission denied reading from {}".format(path)) + raise CommandExecutionError(f"Permission denied reading from {path}") else: raise CommandExecutionError( "Error {} encountered reading from {}: {}".format( @@ -254,7 +251,7 @@ def wait_lock(path, lock_fn=None, timeout=5, sleep=0.1, time_start=None): try: if os.path.exists(lock_fn) and not os.path.isfile(lock_fn): - _raise_error("lock_fn {} exists and is not a file".format(lock_fn)) + _raise_error(f"lock_fn {lock_fn} exists and is not a file") open_flags = os.O_CREAT | os.O_EXCL | os.O_WRONLY while time.time() - time_start < timeout: @@ -294,9 +291,7 @@ def wait_lock(path, lock_fn=None, timeout=5, sleep=0.1, time_start=None): raise except Exception as exc: # pylint: disable=broad-except - _raise_error( - "Error encountered obtaining file lock {}: {}".format(lock_fn, exc) - ) + _raise_error(f"Error encountered obtaining file lock {lock_fn}: {exc}") finally: if obtained_lock: @@ -347,7 +342,7 @@ def fopen(*args, **kwargs): # and True are treated by Python 3's open() as file descriptors 0 # and 1, respectively. if args[0] in (0, 1, 2): - raise TypeError("{} is not a permitted file descriptor".format(args[0])) + raise TypeError(f"{args[0]} is not a permitted file descriptor") except IndexError: pass binary = None @@ -488,7 +483,7 @@ def safe_walk(top, topdown=True, onerror=None, followlinks=True, _seen=None): # Note that listdir and error are globals in this module due # to earlier import-*. names = os.listdir(top) - except os.error as err: + except OSError as err: if onerror is not None: onerror(err) return @@ -694,7 +689,7 @@ def is_binary(path): return salt.utils.stringutils.is_binary(data) except UnicodeDecodeError: return True - except os.error: + except OSError: return False @@ -787,8 +782,8 @@ def backup_minion(path, bkroot): stamp = time.strftime("%a_%b_%d_%H-%M-%S_%Y") else: stamp = time.strftime("%a_%b_%d_%H:%M:%S_%Y") - stamp = "{}{}_{}".format(stamp[:-4], msecs, stamp[-4:]) - bkpath = os.path.join(bkroot, src_dir, "{}_{}".format(bname, stamp)) + stamp = f"{stamp[:-4]}{msecs}_{stamp[-4:]}" + bkpath = os.path.join(bkroot, src_dir, f"{bname}_{stamp}") if not os.path.isdir(os.path.dirname(bkpath)): os.makedirs(os.path.dirname(bkpath)) shutil.copyfile(path, bkpath) @@ -883,7 +878,7 @@ def get_encoding(path): try: with fopen(path, "rb") as fp_: data = fp_.read(2048) - except os.error: + except OSError: raise CommandExecutionError("Failed to open file") # Check for Unicode BOM diff --git a/salt/utils/find.py b/salt/utils/find.py index d722066caa2..b8ae01b1e4a 100644 --- a/salt/utils/find.py +++ b/salt/utils/find.py @@ -82,7 +82,6 @@ the following: user: user name """ - import logging import os import re @@ -163,7 +162,7 @@ def _parse_interval(value): """ match = _INTERVAL_REGEX.match(str(value)) if match is None: - raise ValueError("invalid time interval: '{}'".format(value)) + raise ValueError(f"invalid time interval: '{value}'") result = 0 resolution = None @@ -212,7 +211,7 @@ def _parse_size(value): try: num = int(float(scalar) * multiplier) except ValueError: - raise ValueError('invalid size: "{}"'.format(value)) + raise ValueError(f'invalid size: "{value}"') if style == "-": min_size = 0 @@ -280,7 +279,7 @@ class RegexOption(Option): try: self.regex = re.compile(value) except re.error: - raise ValueError('invalid regular expression: "{}"'.format(value)) + raise ValueError(f'invalid regular expression: "{value}"') def match(self, dirname, filename, fstat): return self.regex.match(filename) @@ -297,7 +296,7 @@ class IregexOption(Option): try: self.regex = re.compile(value, re.IGNORECASE) except re.error: - raise ValueError('invalid regular expression: "{}"'.format(value)) + raise ValueError(f'invalid regular expression: "{value}"') def match(self, dirname, filename, fstat): return self.regex.match(filename) @@ -326,7 +325,7 @@ class TypeOption(Option): try: self.ftypes.add(_FILE_TYPES[ftype]) except KeyError: - raise ValueError('invalid file type "{}"'.format(ftype)) + raise ValueError(f'invalid file type "{ftype}"') def requires(self): return _REQUIRES_STAT @@ -352,7 +351,7 @@ class OwnerOption(Option): try: self.uids.add(pwd.getpwnam(value).pw_uid) except KeyError: - raise ValueError('no such user "{}"'.format(name)) + raise ValueError(f'no such user "{name}"') def requires(self): return _REQUIRES_STAT @@ -378,7 +377,7 @@ class GroupOption(Option): try: self.gids.add(grp.getgrnam(name).gr_gid) except KeyError: - raise ValueError('no such group "{}"'.format(name)) + raise ValueError(f'no such group "{name}"') def requires(self): return _REQUIRES_STAT @@ -450,7 +449,7 @@ class GrepOption(Option): try: self.regex = re.compile(value) except re.error: - raise ValueError('invalid regular expression: "{}"'.format(value)) + raise ValueError(f'invalid regular expression: "{value}"') def requires(self): return _REQUIRES_CONTENTS | _REQUIRES_STAT @@ -590,11 +589,11 @@ class ExecOption(Option): command, salt.utils.stringutils.to_str(err), ) - return "{}:\n{}\n".format(command, salt.utils.stringutils.to_str(out)) + return f"{command}:\n{salt.utils.stringutils.to_str(out)}\n" except Exception as e: # pylint: disable=broad-except log.error('Exception while executing command "%s":\n\n%s', command, e) - return "{}: Failed".format(fullpath) + return f"{fullpath}: Failed" class Finder: @@ -622,11 +621,11 @@ class Finder: # this is a passthrough object, continue continue if not value: - raise ValueError('missing value for "{}" option'.format(key)) + raise ValueError(f'missing value for "{key}" option') try: obj = globals()[key.title() + "Option"](key, value) except KeyError: - raise ValueError('invalid option "{}"'.format(key)) + raise ValueError(f'invalid option "{key}"') if hasattr(obj, "match"): requires = obj.requires() if requires & _REQUIRES_CONTENTS: @@ -722,7 +721,7 @@ def find(path, options): def _main(): if len(sys.argv) < 2: - sys.stderr.write("usage: {} path [options]\n".format(sys.argv[0])) + sys.stderr.write(f"usage: {sys.argv[0]} path [options]\n") sys.exit(salt.defaults.exitcodes.EX_USAGE) path = sys.argv[1] @@ -734,7 +733,7 @@ def _main(): try: finder = Finder(criteria) except ValueError as ex: - sys.stderr.write("error: {}\n".format(ex)) + sys.stderr.write(f"error: {ex}\n") sys.exit(salt.defaults.exitcodes.EX_GENERIC) for result in finder.find(path): diff --git a/salt/utils/fsutils.py b/salt/utils/fsutils.py index 7b0eb084f64..6c93534085c 100644 --- a/salt/utils/fsutils.py +++ b/salt/utils/fsutils.py @@ -1,6 +1,7 @@ """ Run-time utilities """ + # # Copyright (C) 2014 SUSE LLC @@ -112,7 +113,7 @@ def _is_device(path): """ Return True if path is a physical device. """ - out = __salt__["cmd.run_all"]("file -i {}".format(path)) + out = __salt__["cmd.run_all"](f"file -i {path}") _verify_run(out) # Always [device, mime, charset]. See (file --help) diff --git a/salt/utils/functools.py b/salt/utils/functools.py index 5398434adf8..74e9012124c 100644 --- a/salt/utils/functools.py +++ b/salt/utils/functools.py @@ -1,6 +1,7 @@ """ Utility functions to modify other functions """ + import logging import types diff --git a/salt/utils/gitfs.py b/salt/utils/gitfs.py index a7ab90d62ab..056e4782636 100644 --- a/salt/utils/gitfs.py +++ b/salt/utils/gitfs.py @@ -575,8 +575,8 @@ class GitProvider: """ def _getconf(self, tgt_env="base"): - strip_sep = ( - lambda x: x.rstrip(os.sep) if name in ("root", "mountpoint") else x + strip_sep = lambda x: ( + x.rstrip(os.sep) if name in ("root", "mountpoint") else x ) if self.role != "gitfs": return strip_sep(getattr(self, "_" + name)) @@ -3004,9 +3004,9 @@ class GitFS(GitBase): remotes if remotes is not None else [], per_remote_overrides=per_remote_overrides, per_remote_only=per_remote_only, - git_providers=git_providers - if git_providers is not None - else GIT_PROVIDERS, + git_providers=( + git_providers if git_providers is not None else GIT_PROVIDERS + ), cache_root=cache_root, init_remotes=init_remotes, ) @@ -3241,7 +3241,7 @@ class GitFS(GitBase): if not os.path.isdir(self.file_list_cachedir): try: os.makedirs(self.file_list_cachedir) - except os.error: + except OSError: log.error("Unable to make cachedir %s", self.file_list_cachedir) return [] list_cache = salt.utils.path.join( diff --git a/salt/utils/github.py b/salt/utils/github.py index 1d6824f2ae9..4ee55c39a73 100644 --- a/salt/utils/github.py +++ b/salt/utils/github.py @@ -2,7 +2,6 @@ Connection library for GitHub """ - import logging import salt.utils.http @@ -44,7 +43,7 @@ def get_user_pubkeys(users): key_ids = user[tmp_user] user = tmp_user - url = "https://api.github.com/users/{}/keys".format(user) + url = f"https://api.github.com/users/{user}/keys" result = salt.utils.http.query( url, "GET", diff --git a/salt/utils/gzip_util.py b/salt/utils/gzip_util.py index 5946d2269ab..49592e7280e 100644 --- a/salt/utils/gzip_util.py +++ b/salt/utils/gzip_util.py @@ -4,7 +4,6 @@ Helper module for handling gzip consistently between 2.7+ and 2.6- """ - import gzip import io diff --git a/salt/utils/hashutils.py b/salt/utils/hashutils.py index 02d234af068..4969465acbe 100644 --- a/salt/utils/hashutils.py +++ b/salt/utils/hashutils.py @@ -160,7 +160,7 @@ def get_hash(path, form="sha256", chunk_size=65536): """ hash_type = hasattr(hashlib, form) and getattr(hashlib, form) or None if hash_type is None: - raise ValueError("Invalid hash type: {}".format(form)) + raise ValueError(f"Invalid hash type: {form}") with salt.utils.files.fopen(path, "rb") as ifile: hash_obj = hash_type() @@ -182,7 +182,7 @@ class DigestCollector: """ self.__digest = hasattr(hashlib, form) and getattr(hashlib, form)() or None if self.__digest is None: - raise ValueError("Invalid hash type: {}".format(form)) + raise ValueError(f"Invalid hash type: {form}") self.__buff = buff def add(self, path): diff --git a/salt/utils/http.py b/salt/utils/http.py index 9f31082fffb..7405566b12b 100644 --- a/salt/utils/http.py +++ b/salt/utils/http.py @@ -487,10 +487,10 @@ def query( try: match_hostname(sockwrap.getpeercert(), hostname) except CertificateError as exc: - ret[ - "error" - ] = "The certificate was invalid. Error returned was: {}".format( - pprint.pformat(exc) + ret["error"] = ( + "The certificate was invalid. Error returned was: {}".format( + pprint.pformat(exc) + ) ) return ret @@ -727,10 +727,10 @@ def query( valid_decodes = ("json", "xml", "yaml", "plain") if decode_type not in valid_decodes: - ret[ - "error" - ] = "Invalid decode_type specified. Valid decode types are: {}".format( - pprint.pformat(valid_decodes) + ret["error"] = ( + "Invalid decode_type specified. Valid decode types are: {}".format( + pprint.pformat(valid_decodes) + ) ) log.error(ret["error"]) return ret diff --git a/salt/utils/idem.py b/salt/utils/idem.py index 5c14cf7c47a..d488ed22f7e 100644 --- a/salt/utils/idem.py +++ b/salt/utils/idem.py @@ -6,6 +6,7 @@ This util provides access to an idem-ready hub .. versionadded:: 3002 """ + import logging try: diff --git a/salt/utils/immutabletypes.py b/salt/utils/immutabletypes.py index 183dc3606ef..fde42753801 100644 --- a/salt/utils/immutabletypes.py +++ b/salt/utils/immutabletypes.py @@ -30,7 +30,7 @@ class ImmutableDict(Mapping): return freeze(self.__obj[key]) def __repr__(self): - return "<{} {}>".format(self.__class__.__name__, repr(self.__obj)) + return f"<{self.__class__.__name__} {repr(self.__obj)}>" def __deepcopy__(self, memo): return copy.deepcopy(self.__obj) @@ -66,7 +66,7 @@ class ImmutableList(Sequence): return freeze(self.__obj[key]) def __repr__(self): - return "<{} {}>".format(self.__class__.__name__, repr(self.__obj)) + return f"<{self.__class__.__name__} {repr(self.__obj)}>" def __deepcopy__(self, memo): return copy.deepcopy(self.__obj) @@ -96,7 +96,7 @@ class ImmutableSet(Set): return key in self.__obj def __repr__(self): - return "<{} {}>".format(self.__class__.__name__, repr(self.__obj)) + return f"<{self.__class__.__name__} {repr(self.__obj)}>" def __deepcopy__(self, memo): return copy.deepcopy(self.__obj) diff --git a/salt/utils/itertools.py b/salt/utils/itertools.py index a1f55cb026a..3e0635e15c7 100644 --- a/salt/utils/itertools.py +++ b/salt/utils/itertools.py @@ -2,7 +2,6 @@ Helpful generators and other tools """ - import fnmatch import re diff --git a/salt/utils/jid.py b/salt/utils/jid.py index c3dbf8a078a..69d926469b9 100644 --- a/salt/utils/jid.py +++ b/salt/utils/jid.py @@ -27,11 +27,11 @@ def gen_jid(opts): jid_dt = _utc_now() if not opts.get("unique_jid", False): - return "{:%Y%m%d%H%M%S%f}".format(jid_dt) + return f"{jid_dt:%Y%m%d%H%M%S%f}" if LAST_JID_DATETIME and LAST_JID_DATETIME >= jid_dt: jid_dt = LAST_JID_DATETIME + datetime.timedelta(microseconds=1) LAST_JID_DATETIME = jid_dt - return "{:%Y%m%d%H%M%S%f}_{}".format(jid_dt, os.getpid()) + return f"{jid_dt:%Y%m%d%H%M%S%f}_{os.getpid()}" def is_jid(jid): diff --git a/salt/utils/job.py b/salt/utils/job.py index 1172fa7c32d..5b52449666f 100644 --- a/salt/utils/job.py +++ b/salt/utils/job.py @@ -2,7 +2,6 @@ Functions for interacting with the job cache """ - import logging import salt.minion diff --git a/salt/utils/json.py b/salt/utils/json.py index 33cdbf401df..5e14872309f 100644 --- a/salt/utils/json.py +++ b/salt/utils/json.py @@ -2,7 +2,6 @@ Functions to work with JSON """ - import json import logging diff --git a/salt/utils/kickstart.py b/salt/utils/kickstart.py index 6674999a4e9..6869d2b5ba9 100644 --- a/salt/utils/kickstart.py +++ b/salt/utils/kickstart.py @@ -64,7 +64,7 @@ def parse_auth(rule): "disablewins", ) for arg in noargs: - parser.add_argument("--{}".format(arg), dest=arg, action="store_true") + parser.add_argument(f"--{arg}", dest=arg, action="store_true") parser.add_argument("--enablenis", dest="enablenis", action="store") parser.add_argument("--hesiodrhs", dest="hesiodrhs", action="store") diff --git a/salt/utils/lazy.py b/salt/utils/lazy.py index cdc963aa801..87b356eac9a 100644 --- a/salt/utils/lazy.py +++ b/salt/utils/lazy.py @@ -2,7 +2,6 @@ Lazily-evaluated data structures, primarily used by Salt's loader """ - import logging from collections.abc import MutableMapping @@ -78,7 +77,7 @@ class LazyDict(MutableMapping): Override this to return a more meaningfull error message if possible """ - return "'{}' is not available.".format(function_name) + return f"'{function_name}' is not available." def __setitem__(self, key, val): self._dict[key] = val diff --git a/salt/utils/locales.py b/salt/utils/locales.py index 43c0f1c68d7..cd42a8c9e8a 100644 --- a/salt/utils/locales.py +++ b/salt/utils/locales.py @@ -1,6 +1,7 @@ """ the locale utils used by salt """ + import sys from salt.utils.decorators import memoize as real_memoize diff --git a/salt/utils/mac_utils.py b/salt/utils/mac_utils.py index dbfc9f05f82..1614d2189b3 100644 --- a/salt/utils/mac_utils.py +++ b/salt/utils/mac_utils.py @@ -154,7 +154,7 @@ def execute_return_success(cmd): log.debug("Execute return success %s: %r", cmd, ret) if ret["retcode"] != 0 or "not supported" in ret["stdout"].lower(): - msg = "Command Failed: {}\n".format(cmd) + msg = f"Command Failed: {cmd}\n" msg += "Return Code: {}\n".format(ret["retcode"]) msg += "Output: {}\n".format(ret["stdout"]) msg += "Error: {}\n".format(ret["stderr"]) @@ -178,7 +178,7 @@ def execute_return_result(cmd): ret = _run_all(cmd) if ret["retcode"] != 0 or "not supported" in ret["stdout"].lower(): - msg = "Command Failed: {}\n".format(cmd) + msg = f"Command Failed: {cmd}\n" msg += "Return Code: {}\n".format(ret["retcode"]) msg += "Output: {}\n".format(ret["stdout"]) msg += "Error: {}\n".format(ret["stderr"]) @@ -313,7 +313,7 @@ def launchctl(sub_cmd, *args, **kwargs): # Raise an error or return successful result if ret["retcode"] or error: - out = "Failed to {} service:\n".format(sub_cmd) + out = f"Failed to {sub_cmd} service:\n" out += "stdout: {}\n".format(ret["stdout"]) out += "stderr: {}\n".format(ret["stderr"]) out += "retcode: {}".format(ret["retcode"]) diff --git a/salt/utils/master.py b/salt/utils/master.py index 031b151caef..6aa661c0607 100644 --- a/salt/utils/master.py +++ b/salt/utils/master.py @@ -5,6 +5,7 @@ Utilities that can only be used on a salt master. """ + import logging import os import signal @@ -108,7 +109,7 @@ def _check_cmdline(data): return False if not os.path.isdir("/proc"): return True - path = os.path.join("/proc/{}/cmdline".format(pid)) + path = os.path.join(f"/proc/{pid}/cmdline") if not os.path.isfile(path): return False try: @@ -160,7 +161,7 @@ class MasterPillarUtil: if opts is None: log.error("%s: Missing master opts init arg.", self.__class__.__name__) raise SaltException( - "{}: Missing master opts init arg.".format(self.__class__.__name__) + f"{self.__class__.__name__}: Missing master opts init arg." ) else: self.opts = opts @@ -201,7 +202,7 @@ class MasterPillarUtil: for minion_id in minion_ids: if not salt.utils.verify.valid_id(self.opts, minion_id): continue - mdata = self.cache.fetch("minions/{}".format(minion_id), "mine") + mdata = self.cache.fetch(f"minions/{minion_id}", "mine") if isinstance(mdata, dict): mine_data[minion_id] = mdata return mine_data @@ -219,7 +220,7 @@ class MasterPillarUtil: for minion_id in minion_ids: if not salt.utils.verify.valid_id(self.opts, minion_id): continue - mdata = self.cache.fetch("minions/{}".format(minion_id), "data") + mdata = self.cache.fetch(f"minions/{minion_id}", "data") if not isinstance(mdata, dict): log.warning( "cache.fetch should always return a dict. ReturnedType: %s," @@ -488,7 +489,7 @@ class MasterPillarUtil: if clear_mine: clear_what.append("mine") if clear_mine_func is not None: - clear_what.append("mine_func: '{}'".format(clear_mine_func)) + clear_what.append(f"mine_func: '{clear_mine_func}'") if not clear_what: log.debug("No cached data types specified for clearing.") return False @@ -514,7 +515,7 @@ class MasterPillarUtil: if minion_id not in c_minions: # Cache bank for this minion does not exist. Nothing to do. continue - bank = "minions/{}".format(minion_id) + bank = f"minions/{minion_id}" minion_pillar = pillars.pop(minion_id, False) minion_grains = grains.pop(minion_id, False) if ( @@ -822,7 +823,7 @@ def get_master_key(key_user, opts, skip_perm_errors=False): # The username may contain '\' if it is in Windows # 'DOMAIN\username' format. Fix this for the keyfile path. key_user = key_user.replace("\\", "_") - keyfile = os.path.join(opts["cachedir"], ".{}_key".format(key_user)) + keyfile = os.path.join(opts["cachedir"], f".{key_user}_key") # Make sure all key parent directories are accessible salt.utils.verify.check_path_traversal(opts["cachedir"], key_user, skip_perm_errors) diff --git a/salt/utils/mattermost.py b/salt/utils/mattermost.py index b8b49c32e75..17c2d6b8ffe 100644 --- a/salt/utils/mattermost.py +++ b/salt/utils/mattermost.py @@ -39,7 +39,7 @@ def query(hook=None, api_url=None, data=None): result = salt.utils.http.query(url, method, data=data, decode=True, status=True) if result.get("status", None) == http.client.OK: - ret["message"] = "Message posted {} correctly".format(data) + ret["message"] = f"Message posted {data} correctly" return ret elif result.get("status", None) == http.client.NO_CONTENT: return True diff --git a/salt/utils/memcached.py b/salt/utils/memcached.py index 3bb1fa94000..881f923979a 100644 --- a/salt/utils/memcached.py +++ b/salt/utils/memcached.py @@ -34,7 +34,6 @@ specified, rather than top-level configurations. This being the case, it is better to always use a named configuration profile, as shown above. """ - import logging from salt.exceptions import CommandExecutionError, SaltInvocationError @@ -92,7 +91,7 @@ def get_conn(opts, profile=None, host=None, port=None): raise SaltInvocationError("port must be an integer") if HAS_LIBS: - return memcache.Client(["{}:{}".format(host, port)]) + return memcache.Client([f"{host}:{port}"]) else: raise CommandExecutionError( "(unable to import memcache, module most likely not installed)" diff --git a/salt/utils/mine.py b/salt/utils/mine.py index 4f6416e554f..04795b0f8a3 100644 --- a/salt/utils/mine.py +++ b/salt/utils/mine.py @@ -2,7 +2,6 @@ This module contains routines used for the salt mine """ - import logging import salt.utils.data diff --git a/salt/utils/minion.py b/salt/utils/minion.py index 28e63af1df3..39bae1a2302 100644 --- a/salt/utils/minion.py +++ b/salt/utils/minion.py @@ -2,7 +2,6 @@ Utility functions for minions """ - import logging import os import threading @@ -132,7 +131,7 @@ def _check_cmdline(data): return False if not os.path.isdir("/proc"): return True - path = os.path.join("/proc/{}/cmdline".format(pid)) + path = os.path.join(f"/proc/{pid}/cmdline") if not os.path.isfile(path): return False try: diff --git a/salt/utils/minions.py b/salt/utils/minions.py index f3d791f4d31..65d6fd5b8d9 100644 --- a/salt/utils/minions.py +++ b/salt/utils/minions.py @@ -3,7 +3,6 @@ This module contains routines used to verify the matcher against the minions expected to return """ - import fnmatch import logging import os diff --git a/salt/utils/mount.py b/salt/utils/mount.py index 019cac5562b..c09791e668e 100644 --- a/salt/utils/mount.py +++ b/salt/utils/mount.py @@ -2,7 +2,6 @@ Common functions for managing mounts """ - import logging import os diff --git a/salt/utils/msgpack.py b/salt/utils/msgpack.py index 9c1baedbf12..034ce5dd366 100644 --- a/salt/utils/msgpack.py +++ b/salt/utils/msgpack.py @@ -1,6 +1,7 @@ """ Functions to work with MessagePack """ + import logging log = logging.getLogger(__name__) diff --git a/salt/utils/namecheap.py b/salt/utils/namecheap.py index 343ecfb62b6..c09a04b6ac6 100644 --- a/salt/utils/namecheap.py +++ b/salt/utils/namecheap.py @@ -15,7 +15,6 @@ """ - import logging import xml.dom.minidom diff --git a/salt/utils/napalm.py b/salt/utils/napalm.py index 082be2167c9..6d3ef580eed 100644 --- a/salt/utils/napalm.py +++ b/salt/utils/napalm.py @@ -14,7 +14,6 @@ Utils for the NAPALM modules and proxy. .. versionadded:: 2017.7.0 """ - import copy import importlib import logging @@ -95,7 +94,7 @@ def virtual(opts, virtualname, filename): False, '"{vname}"" {filename} cannot be loaded: ' "NAPALM is not installed: ``pip install napalm``".format( - vname=virtualname, filename="({filename})".format(filename=filename) + vname=virtualname, filename=f"({filename})" ), ) diff --git a/salt/utils/nb_popen.py b/salt/utils/nb_popen.py index 12cdc39e1b0..e878c730396 100644 --- a/salt/utils/nb_popen.py +++ b/salt/utils/nb_popen.py @@ -147,8 +147,8 @@ class NonBlockingPopen(subprocess.Popen): return self._close(which) raise - getattr(self, "{}_buff".format(which)).write(read) - getattr(self, "_{}_logger".format(which)).debug(read.rstrip()) + getattr(self, f"{which}_buff").write(read) + getattr(self, f"_{which}_logger").debug(read.rstrip()) if self.stream_stds: getattr(sys, which).write(read) @@ -195,8 +195,8 @@ class NonBlockingPopen(subprocess.Popen): if self.universal_newlines: buff = self._translate_newlines(buff) - getattr(self, "{}_buff".format(which)).write(buff) - getattr(self, "_{}_logger".format(which)).debug(buff.rstrip()) + getattr(self, f"{which}_buff").write(buff) + getattr(self, f"_{which}_logger").debug(buff.rstrip()) if self.stream_stds: getattr(sys, which).write(buff) diff --git a/salt/utils/network.py b/salt/utils/network.py index fae91e01ecb..ed274a34eea 100644 --- a/salt/utils/network.py +++ b/salt/utils/network.py @@ -2180,9 +2180,7 @@ def dns_check(addr, port, safe=False, ipv6=None): family = ( socket.AF_INET6 if ipv6 - else socket.AF_INET - if ipv6 is False - else socket.AF_UNSPEC + else socket.AF_INET if ipv6 is False else socket.AF_UNSPEC ) socket_error = False try: diff --git a/salt/utils/nxos.py b/salt/utils/nxos.py index 2572a762670..5615e9216b6 100644 --- a/salt/utils/nxos.py +++ b/salt/utils/nxos.py @@ -83,7 +83,7 @@ class NxapiClient: if self.nxargs["connect_over_uds"]: if not os.path.exists(self.NXAPI_UDS): raise NxosClientError( - "No host specified and no UDS found at {}\n".format(self.NXAPI_UDS) + f"No host specified and no UDS found at {self.NXAPI_UDS}\n" ) # Create UHTTPConnection object for NX-API communication over UDS. @@ -190,7 +190,7 @@ class NxapiClient: header_dict=req["headers"], decode=True, decode_type="json", - **self.nxargs + **self.nxargs, ) return self.parse_response(response, command_list) @@ -202,9 +202,9 @@ class NxapiClient: # Check for 500 level NX-API Server Errors if isinstance(response, Iterable) and "status" in response: if int(response["status"]) >= 500: - raise NxosError("{}".format(response)) + raise NxosError(f"{response}") else: - raise NxosError("NX-API Request Not Supported: {}".format(response)) + raise NxosError(f"NX-API Request Not Supported: {response}") if isinstance(response, Iterable): body = response["dict"] @@ -218,7 +218,7 @@ class NxapiClient: # Don't just return body['ins_api']['outputs']['output'] directly. output = body.get("ins_api") if output is None: - raise NxosClientError("Unexpected JSON output\n{}".format(body)) + raise NxosClientError(f"Unexpected JSON output\n{body}") if output.get("outputs"): output = output["outputs"] if output.get("output"): @@ -257,9 +257,9 @@ class NxapiClient: } ) elif code == "413": - raise NxosRequestNotSupported("Error 413: {}".format(msg)) + raise NxosRequestNotSupported(f"Error 413: {msg}") elif code != "200": - raise NxosError("Unknown Error: {}, Code: {}".format(msg, code)) + raise NxosError(f"Unknown Error: {msg}, Code: {code}") else: previous_commands.append(cmd) result.append(cmd_result["body"]) @@ -321,7 +321,7 @@ def ping(**kwargs): def _parser(block): - return re.compile("^{block}\n(?:^[ \n].*$\n?)+".format(block=block), re.MULTILINE) + return re.compile(f"^{block}\n(?:^[ \n].*$\n?)+", re.MULTILINE) def _parse_software(data): diff --git a/salt/utils/openstack/neutron.py b/salt/utils/openstack/neutron.py index 8cf675e453c..c6707b18bfe 100644 --- a/salt/utils/openstack/neutron.py +++ b/salt/utils/openstack/neutron.py @@ -2,7 +2,6 @@ Neutron class """ - import logging import salt.utils.versions @@ -89,7 +88,6 @@ class SaltNeutron(NeutronShell): use_keystoneauth=False, **kwargs ): - """ Set up neutron credentials """ diff --git a/salt/utils/openstack/nova.py b/salt/utils/openstack/nova.py index 4c3855edb31..9b8a15264b8 100644 --- a/salt/utils/openstack/nova.py +++ b/salt/utils/openstack/nova.py @@ -2,7 +2,6 @@ Nova class """ - import inspect import logging import time @@ -205,7 +204,7 @@ def get_entry(dict_, key, value, raise_error=True): if entry[key] == value: return entry if raise_error is True: - raise SaltCloudSystemExit("Unable to find {} in {}.".format(key, dict_)) + raise SaltCloudSystemExit(f"Unable to find {key} in {dict_}.") return {} @@ -214,7 +213,7 @@ def get_entry_multi(dict_, pairs, raise_error=True): if all([entry[key] == value for key, value in pairs]): return entry if raise_error is True: - raise SaltCloudSystemExit("Unable to find {} in {}.".format(pairs, dict_)) + raise SaltCloudSystemExit(f"Unable to find {pairs} in {dict_}.") return {} @@ -282,7 +281,7 @@ class SaltNova: password=None, os_auth_plugin=None, use_keystoneauth=False, - **kwargs + **kwargs, ): """ Set up nova credentials @@ -295,7 +294,7 @@ class SaltNova: region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, - **kwargs + **kwargs, ) else: self._old_init( @@ -305,7 +304,7 @@ class SaltNova: region_name=region_name, password=password, os_auth_plugin=os_auth_plugin, - **kwargs + **kwargs, ) def _new_init( @@ -318,7 +317,7 @@ class SaltNova: os_auth_plugin, auth=None, verify=True, - **kwargs + **kwargs, ): if auth is None: auth = {} @@ -387,7 +386,7 @@ class SaltNova: region_name, password, os_auth_plugin, - **kwargs + **kwargs, ): self.kwargs = kwargs.copy() if not self.extensions: @@ -675,7 +674,7 @@ class SaltNova: try: volume = self.volume_show(name) except KeyError as exc: - raise SaltCloudSystemExit("Unable to find {} volume: {}".format(name, exc)) + raise SaltCloudSystemExit(f"Unable to find {name} volume: {exc}") if volume["status"] == "deleted": return volume response = nt_ks.volumes.delete(volume["id"]) @@ -688,7 +687,7 @@ class SaltNova: try: volume = self.volume_show(name) except KeyError as exc: - raise SaltCloudSystemExit("Unable to find {} volume: {}".format(name, exc)) + raise SaltCloudSystemExit(f"Unable to find {name} volume: {exc}") if not volume["attachments"]: return True response = self.compute_conn.volumes.delete_server_volume( @@ -720,7 +719,7 @@ class SaltNova: try: volume = self.volume_show(name) except KeyError as exc: - raise SaltCloudSystemExit("Unable to find {} volume: {}".format(name, exc)) + raise SaltCloudSystemExit(f"Unable to find {name} volume: {exc}") server = self.server_by_name(server_name) response = self.compute_conn.volumes.create_server_volume( server.id, volume["id"], device=device @@ -824,7 +823,7 @@ class SaltNova: """ nt_ks = self.compute_conn nt_ks.flavors.delete(flavor_id) - return "Flavor deleted: {}".format(flavor_id) + return f"Flavor deleted: {flavor_id}" def keypair_list(self): """ @@ -860,7 +859,7 @@ class SaltNova: """ nt_ks = self.compute_conn nt_ks.keypairs.delete(name) - return "Keypair deleted: {}".format(name) + return f"Keypair deleted: {name}" def image_show(self, image_id): """ @@ -949,7 +948,7 @@ class SaltNova: if not image_id: return {"Error": "A valid image name or id was not specified"} nt_ks.images.delete_meta(image_id, pairs) - return {image_id: "Deleted: {}".format(pairs)} + return {image_id: f"Deleted: {pairs}"} def server_list(self): """ @@ -1033,9 +1032,9 @@ class SaltNova: "OS-EXT-SRV-ATTR:host" ] if hasattr(item.__dict__, "OS-EXT-SRV-ATTR:hypervisor_hostname"): - ret[item.name]["OS-EXT-SRV-ATTR"][ - "hypervisor_hostname" - ] = item.__dict__["OS-EXT-SRV-ATTR:hypervisor_hostname"] + ret[item.name]["OS-EXT-SRV-ATTR"]["hypervisor_hostname"] = ( + item.__dict__["OS-EXT-SRV-ATTR:hypervisor_hostname"] + ) if hasattr(item.__dict__, "OS-EXT-SRV-ATTR:instance_name"): ret[item.name]["OS-EXT-SRV-ATTR"]["instance_name"] = item.__dict__[ "OS-EXT-SRV-ATTR:instance_name" @@ -1089,8 +1088,8 @@ class SaltNova: for item in nt_ks.security_groups.list(): if item.name == name: nt_ks.security_groups.delete(item.id) - return {name: "Deleted security group: {}".format(name)} - return "Security group not found: {}".format(name) + return {name: f"Deleted security group: {name}"} + return f"Security group not found: {name}" def secgroup_list(self): """ diff --git a/salt/utils/oset.py b/salt/utils/oset.py index d0bd6536e82..fb1db32b4e9 100644 --- a/salt/utils/oset.py +++ b/salt/utils/oset.py @@ -85,9 +85,7 @@ class OrderedSet(MutableSet): elif is_iterable(index): return OrderedSet([self.items[i] for i in index]) else: - raise TypeError( - "Don't know how to index an OrderedSet by {}".format(repr(index)) - ) + raise TypeError(f"Don't know how to index an OrderedSet by {repr(index)}") def copy(self): return OrderedSet(self) @@ -137,9 +135,7 @@ class OrderedSet(MutableSet): for item in sequence: item_index = self.add(item) except TypeError: - raise ValueError( - "Argument needs to be an iterable, got {}".format(type(sequence)) - ) + raise ValueError(f"Argument needs to be an iterable, got {type(sequence)}") return item_index def index(self, key): @@ -198,8 +194,8 @@ class OrderedSet(MutableSet): def __repr__(self): if not self: - return "{}()".format(self.__class__.__name__) - return "{}({})".format(self.__class__.__name__, repr(list(self))) + return f"{self.__class__.__name__}()" + return f"{self.__class__.__name__}({repr(list(self))})" def __eq__(self, other): if isinstance(other, OrderedSet): diff --git a/salt/utils/pagerduty.py b/salt/utils/pagerduty.py index 44c039a9f6b..62c663196e5 100644 --- a/salt/utils/pagerduty.py +++ b/salt/utils/pagerduty.py @@ -44,7 +44,7 @@ def query( """ Query the PagerDuty API """ - user_agent = "SaltStack {}".format(__version__) + user_agent = f"SaltStack {__version__}" if opts is None: opts = {} diff --git a/salt/utils/parsers.py b/salt/utils/parsers.py index 013c5e8ff74..df044de4241 100644 --- a/salt/utils/parsers.py +++ b/salt/utils/parsers.py @@ -7,6 +7,7 @@ This is where all the black magic happens on all of salt's CLI tools. """ + # pylint: disable=missing-docstring,protected-access,too-many-ancestors,too-few-public-methods # pylint: disable=attribute-defined-outside-init,no-self-use diff --git a/salt/utils/path.py b/salt/utils/path.py index cf3e4cf50bf..e940321446a 100644 --- a/salt/utils/path.py +++ b/salt/utils/path.py @@ -3,7 +3,6 @@ Platform independent versions of some os/os.path functions. Gets around PY2's lack of support for reading NTFS links. """ - import logging import os import posixpath diff --git a/salt/utils/pbm.py b/salt/utils/pbm.py index c8eceaeedb3..420d69912ab 100644 --- a/salt/utils/pbm.py +++ b/salt/utils/pbm.py @@ -37,7 +37,6 @@ version currently listed in PyPi, run the following: pip install pyVmomi==5.5.0.2014.1.1 """ - import logging import salt.utils.vmware @@ -89,7 +88,7 @@ def get_profile_manager(service_instance): except vim.fault.NoPermission as exc: log.exception(exc) raise VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -116,7 +115,7 @@ def get_placement_solver(service_instance): except vim.fault.NoPermission as exc: log.exception(exc) raise VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -142,7 +141,7 @@ def get_capability_definitions(profile_manager): except vim.fault.NoPermission as exc: log.exception(exc) raise VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -171,7 +170,7 @@ def get_policies_by_id(profile_manager, policy_ids): except vim.fault.NoPermission as exc: log.exception(exc) raise VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -204,7 +203,7 @@ def get_storage_policies(profile_manager, policy_names=None, get_all_policies=Fa except vim.fault.NoPermission as exc: log.exception(exc) raise VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -241,7 +240,7 @@ def create_storage_policy(profile_manager, policy_spec): except vim.fault.NoPermission as exc: log.exception(exc) raise VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -269,7 +268,7 @@ def update_storage_policy(profile_manager, policy, policy_spec): except vim.fault.NoPermission as exc: log.exception(exc) raise VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -297,7 +296,7 @@ def get_default_storage_policy_of_datastore(profile_manager, datastore): except vim.fault.NoPermission as exc: log.exception(exc) raise VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -308,7 +307,7 @@ def get_default_storage_policy_of_datastore(profile_manager, datastore): policy_refs = get_policies_by_id(profile_manager, [policy_id]) if not policy_refs: raise VMwareObjectRetrievalError( - "Storage policy with id '{}' was not found".format(policy_id) + f"Storage policy with id '{policy_id}' was not found" ) return policy_refs[0] @@ -337,7 +336,7 @@ def assign_default_storage_policy_to_datastore(profile_manager, policy, datastor except vim.fault.NoPermission as exc: log.exception(exc) raise VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) diff --git a/salt/utils/pkg/rpm.py b/salt/utils/pkg/rpm.py index f9975f8dff1..7574a068e83 100644 --- a/salt/utils/pkg/rpm.py +++ b/salt/utils/pkg/rpm.py @@ -1,6 +1,7 @@ """ Common functions for working with RPM packages """ + import collections import datetime import logging @@ -105,7 +106,7 @@ def resolve_name(name, arch, osarch=None): osarch = get_osarch() if not check_32(arch, osarch) and arch not in (osarch, "noarch"): - name += ".{}".format(arch) + name += f".{arch}" return name @@ -123,7 +124,7 @@ def parse_pkginfo(line, osarch=None): name = resolve_name(name, arch, osarch) if release: - version += "-{}".format(release) + version += f"-{release}" if epoch not in ("(none)", "0"): version = ":".join((epoch, version)) diff --git a/salt/utils/pkg/win.py b/salt/utils/pkg/win.py index c34fa2c26b3..fa013196420 100644 --- a/salt/utils/pkg/win.py +++ b/salt/utils/pkg/win.py @@ -10,6 +10,7 @@ Collect information about software installed on Windows OS Known Issue: install_date may not match Control Panel\Programs\Programs and Features """ + import collections import datetime import locale @@ -143,7 +144,7 @@ class RegSoftwareInfo: ) ) self.__reg_upgradecode_path = ( - "{}\\Software\\Microsoft\\Installer\\UpgradeCodes".format(sid) + f"{sid}\\Software\\Microsoft\\Installer\\UpgradeCodes" ) self.__reg_patches_path = ( "Software\\Microsoft\\Windows\\CurrentVersion\\Installer\\UserData\\" @@ -160,7 +161,7 @@ class RegSoftwareInfo: ) if self.__squid: self.__reg_products_path = ( - "Software\\Classes\\Installer\\Products\\{}".format(self.__squid) + f"Software\\Classes\\Installer\\Products\\{self.__squid}" ) self.__reg_upgradecode_path = ( "Software\\Classes\\Installer\\UpgradeCodes" @@ -603,7 +604,7 @@ class RegSoftwareInfo: Returns: str: \\ """ - return "{}\\{}".format(self.__reg_hive, self.__reg_uninstall_path) + return f"{self.__reg_hive}\\{self.__reg_uninstall_path}" @property def registry_path(self): @@ -929,7 +930,7 @@ class WinSoftware: name, domain, _account_type = win32security.LookupAccountSid( None, sid_bin ) # pylint: disable=no-member - user_name = "{}\\{}".format(domain, name) + user_name = f"{domain}\\{name}" except pywintypes.error as exc: # pylint: disable=no-member # if user does not exist... # winerror.ERROR_NONE_MAPPED = No mapping between account names and @@ -961,7 +962,7 @@ class WinSoftware: winerror.ERROR_INVALID_DOMAINNAME, winerror.ERROR_NONE_MAPPED, ): - return "{}@{}".format(name.lower(), domain.lower()) + return f"{name.lower()}@{domain.lower()}" else: raise return user_principal @@ -1441,9 +1442,7 @@ def __main(): system|system+user: System installed and System and User installs. """ if len(sys.argv) < 3: - sys.stderr.write( - "usage: {} \n".format(sys.argv[0]) - ) + sys.stderr.write(f"usage: {sys.argv[0]} \n") sys.exit(64) user_pkgs = False version_only = False @@ -1463,10 +1462,10 @@ def __main(): print( salt.utils.json.dumps(pkg_list.data, sort_keys=True, indent=4) ) # pylint: disable=superfluous-parens - print("Total: {}".format(len(pkg_list))) # pylint: disable=superfluous-parens + print(f"Total: {len(pkg_list)}") # pylint: disable=superfluous-parens print( - "Time Taken: {}".format(timeit.timeit(run, number=1)) + f"Time Taken: {timeit.timeit(run, number=1)}" ) # pylint: disable=superfluous-parens diff --git a/salt/utils/platform.py b/salt/utils/platform.py index 35bb7ff3f81..c6ca7fe8cae 100644 --- a/salt/utils/platform.py +++ b/salt/utils/platform.py @@ -1,6 +1,7 @@ """ Functions for identifying which platform a machine is """ + import contextlib import multiprocessing import os diff --git a/salt/utils/powershell.py b/salt/utils/powershell.py index bcca243239a..2ac67bfa665 100644 --- a/salt/utils/powershell.py +++ b/salt/utils/powershell.py @@ -73,13 +73,13 @@ def get_modules(): system_dir = "{}\\System32".format(os.environ.get("WINDIR", "C:\\Windows")) program_files = os.environ.get("ProgramFiles", "C:\\Program Files") default_paths = [ - "{}/.local/share/powershell/Modules".format(home_dir), + f"{home_dir}/.local/share/powershell/Modules", # Once version is available, these can be enabled # '/opt/microsoft/powershell/{0}/Modules'.format(ps_version), # '/usr/local/microsoft/powershell/{0}/Modules'.format(ps_version), "/usr/local/share/powershell/Modules", - "{}\\WindowsPowerShell\\v1.0\\Modules\\".format(system_dir), - "{}\\WindowsPowerShell\\Modules".format(program_files), + f"{system_dir}\\WindowsPowerShell\\v1.0\\Modules\\", + f"{program_files}\\WindowsPowerShell\\Modules", ] default_paths = ";".join(default_paths) diff --git a/salt/utils/process.py b/salt/utils/process.py index e1ee5ff83df..52dd19f8479 100644 --- a/salt/utils/process.py +++ b/salt/utils/process.py @@ -1,6 +1,7 @@ """ Functions for daemonizing and otherwise modifying running processes """ + import contextlib import copy import errno @@ -55,7 +56,7 @@ def appendproctitle(name): current = setproctitle.getproctitle() if current.strip().endswith("MainProcess"): current, _ = current.rsplit("MainProcess", 1) - setproctitle.setproctitle("{} {}".format(current.rstrip(), name)) + setproctitle.setproctitle(f"{current.rstrip()} {name}") def daemonize(redirect_out=True): @@ -173,7 +174,7 @@ def notify_systemd(): if notify_socket: # Handle abstract namespace socket if notify_socket.startswith("@"): - notify_socket = "\0{}".format(notify_socket[1:]) + notify_socket = f"\0{notify_socket[1:]}" try: sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) sock.connect(notify_socket) @@ -351,7 +352,7 @@ def set_pidfile(pidfile, user): pidfile, user ) log.debug("%s Traceback follows:", msg, exc_info=True) - sys.stderr.write("{}\n".format(msg)) + sys.stderr.write(f"{msg}\n") sys.exit(err.errno) log.debug("Chowned pidfile: %s to user: %s", pidfile, user) @@ -921,9 +922,9 @@ class Process(multiprocessing.Process): self.__init__(*args, **kwargs) # Override self.__logging_config__ with what's in state self.__logging_config__ = logging_config - for (function, args, kwargs) in state["after_fork_methods"]: + for function, args, kwargs in state["after_fork_methods"]: self.register_after_fork_method(function, *args, **kwargs) - for (function, args, kwargs) in state["finalize_methods"]: + for function, args, kwargs in state["finalize_methods"]: self.register_finalize_method(function, *args, **kwargs) def __getstate__(self): @@ -1062,7 +1063,7 @@ class SignalHandlingProcess(Process): def _handle_signals(self, signum, sigframe): signal.signal(signal.SIGTERM, signal.SIG_IGN) signal.signal(signal.SIGINT, signal.SIG_IGN) - msg = "{} received a ".format(self.__class__.__name__) + msg = f"{self.__class__.__name__} received a " if signum == signal.SIGINT: msg += "SIGINT" elif signum == signal.SIGTERM: diff --git a/salt/utils/profile.py b/salt/utils/profile.py index 30f4276ef0c..e301cd196ef 100644 --- a/salt/utils/profile.py +++ b/salt/utils/profile.py @@ -2,7 +2,6 @@ Decorator and functions to profile Salt using cProfile """ - import datetime import logging import os @@ -35,7 +34,7 @@ def profile_func(filename=None): try: profiler = cProfile.Profile() retval = profiler.runcall(fun, *args, **kwargs) - profiler.dump_stats(filename or "{}_func.profile".format(fun.__name__)) + profiler.dump_stats(filename or f"{fun.__name__}_func.profile") except OSError: logging.exception("Could not open profile file %s", filename) @@ -66,9 +65,9 @@ def output_profile(pr, stats_path="/tmp/stats", stop=False, id_=None): date = datetime.datetime.now().isoformat() if id_ is None: id_ = salt.utils.hashutils.random_hash(size=32) - ficp = os.path.join(stats_path, "{}.{}.pstats".format(id_, date)) - fico = os.path.join(stats_path, "{}.{}.dot".format(id_, date)) - ficn = os.path.join(stats_path, "{}.{}.stats".format(id_, date)) + ficp = os.path.join(stats_path, f"{id_}.{date}.pstats") + fico = os.path.join(stats_path, f"{id_}.{date}.dot") + ficn = os.path.join(stats_path, f"{id_}.{date}.stats") if not os.path.exists(ficp): pr.dump_stats(ficp) with salt.utils.files.fopen(ficn, "w") as fic: diff --git a/salt/utils/proxy.py b/salt/utils/proxy.py index 6677134f478..b9db9251582 100644 --- a/salt/utils/proxy.py +++ b/salt/utils/proxy.py @@ -2,7 +2,6 @@ Utils for proxy. """ - import logging import salt.utils.platform diff --git a/salt/utils/psutil_compat.py b/salt/utils/psutil_compat.py index e6684e5ca46..bd6656945cd 100644 --- a/salt/utils/psutil_compat.py +++ b/salt/utils/psutil_compat.py @@ -9,7 +9,6 @@ Should be removed once support for psutil <2.0 is dropped. (eg RHEL 6) Built off of http://grodola.blogspot.com/2014/01/psutil-20-porting.html """ - # No exception handling, as we want ImportError if psutil doesn't exist import psutil # pylint: disable=3rd-party-module-not-gated diff --git a/salt/utils/pushover.py b/salt/utils/pushover.py index bf733a9d064..2917ef4fc28 100644 --- a/salt/utils/pushover.py +++ b/salt/utils/pushover.py @@ -106,10 +106,10 @@ def validate_sound(sound, token): if _message.get("dict", {}).get("status", "") == 1: sounds = _message.get("dict", {}).get("sounds", "") if sound in sounds: - ret["message"] = "Valid sound {}.".format(sound) + ret["message"] = f"Valid sound {sound}." ret["res"] = True else: - ret["message"] = "Warning: {} not a valid sound.".format(sound) + ret["message"] = f"Warning: {sound} not a valid sound." ret["res"] = False else: ret["message"] = "".join(_message.get("dict", {}).get("errors")) diff --git a/salt/utils/pycrypto.py b/salt/utils/pycrypto.py index a0f3874035e..e50ac323eb7 100644 --- a/salt/utils/pycrypto.py +++ b/salt/utils/pycrypto.py @@ -1,6 +1,7 @@ """ Use pycrypto to generate random passwords on the fly. """ + import logging import random import re @@ -87,7 +88,7 @@ def secure_password( continue pw += re.sub( salt.utils.stringutils.to_str( - r"[^{}]".format(re.escape(chars)), encoding=encoding + rf"[^{re.escape(chars)}]", encoding=encoding ), "", char, @@ -140,7 +141,7 @@ def _gen_hash_crypt(crypt_salt=None, password=None, algorithm=None): else: if algorithm != "crypt": # all non-crypt algorithms are specified as part of the salt - crypt_salt = "${}${}".format(methods[algorithm].ident, crypt_salt) + crypt_salt = f"${methods[algorithm].ident}${crypt_salt}" try: ret = crypt.crypt(password, crypt_salt) diff --git a/salt/utils/pydsl.py b/salt/utils/pydsl.py index 385a24d6a05..4a6f71a4fdb 100644 --- a/salt/utils/pydsl.py +++ b/salt/utils/pydsl.py @@ -153,7 +153,7 @@ class Sls: highstate = self.included_highstate slsmods = [] # a list of pydsl sls modules rendered. for sls in sls_names: - r_env = "{}:{}".format(saltenv, sls) + r_env = f"{saltenv}:{sls}" if r_env not in self.rendered_sls: self.rendered_sls.add( sls @@ -166,7 +166,7 @@ class Sls: raise PyDslError("\n".join(errors)) HIGHSTATE.clean_duplicate_extends(highstate) - state_id = "_slsmod_{}".format(sls) + state_id = f"_slsmod_{sls}" if state_id not in highstate: slsmods.append(None) else: @@ -194,7 +194,7 @@ class Sls: def state(self, id=None): if not id: - id = ".{}".format(_uuid()) + id = f".{_uuid()}" # adds a leading dot to make use of stateconf's namespace feature. try: return self.get_all_decls()[id] @@ -408,7 +408,7 @@ class StateFunction: def _repr(self, context=None): if not self.name and context != "extend": raise PyDslError( - "No state function specified for module: {}".format(self.mod._name) + f"No state function specified for module: {self.mod._name}" ) if not self.name and context == "extend": return self.args @@ -440,9 +440,7 @@ class StateFunction: if isinstance(mod, StateModule): ref = mod._state_id elif not (mod and ref): - raise PyDslError( - "Invalid a requisite reference declaration! {}: {}".format(mod, ref) - ) + raise PyDslError(f"Invalid a requisite reference declaration! {mod}: {ref}") self.args.append({req_type: [{str(mod): str(ref)}]}) ns = locals() diff --git a/salt/utils/pyobjects.py b/salt/utils/pyobjects.py index eec61b79148..54bbc4ac6e4 100644 --- a/salt/utils/pyobjects.py +++ b/salt/utils/pyobjects.py @@ -250,10 +250,10 @@ class State: @property def full_func(self): - return "{!s}.{!s}".format(self.module, self.func) + return f"{self.module!s}.{self.func!s}" def __str__(self): - return "{!s} = {!s}:{!s}".format(self.id_, self.full_func, self.attrs) + return f"{self.id_!s} = {self.full_func!s}:{self.attrs!s}" def __call__(self): return {self.full_func: self.attrs} @@ -283,7 +283,7 @@ class SaltObject: class __wrapper__: def __getattr__(wself, func): # pylint: disable=E0213 try: - return self._salt["{}.{}".format(mod, func)] + return self._salt[f"{mod}.{func}"] except KeyError: raise AttributeError diff --git a/salt/utils/reactor.py b/salt/utils/reactor.py index 19420a51cf0..2cbcd3a1ab5 100644 --- a/salt/utils/reactor.py +++ b/salt/utils/reactor.py @@ -1,6 +1,7 @@ """ Functions which implement running reactor jobs """ + import fnmatch import glob import logging diff --git a/salt/utils/roster_matcher.py b/salt/utils/roster_matcher.py index db5dfda3e03..c424c63bb0e 100644 --- a/salt/utils/roster_matcher.py +++ b/salt/utils/roster_matcher.py @@ -55,7 +55,7 @@ class RosterMatcher: Execute the correct tgt_type routine and return """ try: - return getattr(self, "ret_{}_minions".format(self.tgt_type))() + return getattr(self, f"ret_{self.tgt_type}_minions")() except AttributeError: return {} diff --git a/salt/utils/s3.py b/salt/utils/s3.py index ba46c5ee7cc..51586cb18e3 100644 --- a/salt/utils/s3.py +++ b/salt/utils/s3.py @@ -111,10 +111,10 @@ def query( if not bucket or path_style: endpoint = service_url else: - endpoint = "{}.{}".format(bucket, service_url) + endpoint = f"{bucket}.{service_url}" if path_style and bucket: - path = "{}/{}".format(bucket, path) + path = f"{bucket}/{path}" # Try grabbing the credentials from the EC2 instance IAM metadata if available if not key: @@ -150,7 +150,7 @@ def query( endpoint, params, data=data, - uri="/{}".format(path), + uri=f"/{path}", prov_dict={"id": keyid, "key": key}, role_arn=role_arn, location=location, @@ -222,7 +222,7 @@ def query( log.debug( "Failed to parse s3 err response. %s: %s", type(err).__name__, err ) - err_code = "http-{}".format(result.status_code) + err_code = f"http-{result.status_code}" err_msg = err_text log.debug("S3 Response Status Code: %s", result.status_code) @@ -236,7 +236,7 @@ def query( ) ) raise CommandExecutionError( - "Failed to create bucket {}. {}: {}".format(bucket, err_code, err_msg) + f"Failed to create bucket {bucket}. {err_code}: {err_msg}" ) if local_file: @@ -254,7 +254,7 @@ def query( ) ) raise CommandExecutionError( - "Failed to delete bucket {}. {}: {}".format(bucket, err_code, err_msg) + f"Failed to delete bucket {bucket}. {err_code}: {err_msg}" ) if path: @@ -266,20 +266,16 @@ def query( # This can be used to save a binary object to disk if local_file and method == "GET": if result.status_code < 200 or result.status_code >= 300: - raise CommandExecutionError( - "Failed to get file. {}: {}".format(err_code, err_msg) - ) + raise CommandExecutionError(f"Failed to get file. {err_code}: {err_msg}") log.debug("Saving to local file: %s", local_file) with salt.utils.files.fopen(local_file, "wb") as out: for chunk in result.iter_content(chunk_size=chunk_size): out.write(chunk) - return "Saved to local file: {}".format(local_file) + return f"Saved to local file: {local_file}" if result.status_code < 200 or result.status_code >= 300: - raise CommandExecutionError( - "Failed s3 operation. {}: {}".format(err_code, err_msg) - ) + raise CommandExecutionError(f"Failed s3 operation. {err_code}: {err_msg}") # This can be used to return a binary object wholesale if return_bin: diff --git a/salt/utils/saltclass.py b/salt/utils/saltclass.py index bbd33068b06..7d6fec7c578 100644 --- a/salt/utils/saltclass.py +++ b/salt/utils/saltclass.py @@ -67,7 +67,7 @@ def get_class_paths(_class, saltclass_path): :return: 3-tuple of possible file counterparts :rtype: tuple(str) """ - straight = os.path.join(saltclass_path, "classes", "{}.yml".format(_class)) + straight = os.path.join(saltclass_path, "classes", f"{_class}.yml") sub_straight = os.path.join( saltclass_path, "classes", "{}.yml".format(_class.replace(".", os.sep)) ) @@ -138,7 +138,7 @@ def dict_merge(a, b, path=None): # Recursive search and replace in a dict def dict_search_and_replace(d, old, new, expanded): - for (k, v) in d.items(): + for k, v in d.items(): if isinstance(v, dict): dict_search_and_replace(d[k], old, new, expanded) @@ -206,7 +206,7 @@ def expand_variables(a, b, expanded, path=None): b = a.copy() path = [] - for (k, v) in a.items(): + for k, v in a.items(): if isinstance(v, dict): expand_variables(v, b, expanded, path + [str(k)]) else: @@ -365,7 +365,7 @@ def expanded_dict_from_minion(minion_id, salt_data): os.path.join(saltclass_path, "nodes"), followlinks=True ): for minion_file in files: - if minion_file == "{}.yml".format(minion_id): + if minion_file == f"{minion_id}.yml": _file = os.path.join(root, minion_file) # Load the minion_id definition if existing, else an empty dict diff --git a/salt/utils/schedule.py b/salt/utils/schedule.py index 6565dda59e6..5eca89fb6ee 100644 --- a/salt/utils/schedule.py +++ b/salt/utils/schedule.py @@ -834,7 +834,7 @@ class Schedule: # this function accepts **kwargs, pack in the publish data for key, val in ret.items(): if key != "kwargs": - kwargs["__pub_{}".format(key)] = copy.deepcopy(val) + kwargs[f"__pub_{key}"] = copy.deepcopy(val) # Only include these when running runner modules if self.opts["__role"] == "master": @@ -899,7 +899,7 @@ class Schedule: rets.extend(returner) # simple de-duplication with order retained for returner in OrderedDict.fromkeys(rets): - ret_str = "{}.returner".format(returner) + ret_str = f"{returner}.returner" if ret_str in self.returners: self.returners[ret_str](ret) else: @@ -1108,10 +1108,10 @@ class Schedule: 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 @@ -1123,10 +1123,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 @@ -1382,10 +1382,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 @@ -1394,10 +1394,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 @@ -1753,7 +1753,7 @@ class Schedule: miss_msg = "" if seconds < 0: - miss_msg = " (runtime missed by {} seconds)".format(abs(seconds)) + miss_msg = f" (runtime missed by {abs(seconds)} seconds)" try: if run: @@ -1883,7 +1883,6 @@ class Schedule: def clean_proc_dir(opts): - """ Loop through jid files in the minion proc directory (default /var/cache/salt/minion/proc) and remove any that refer to processes that no longer exist diff --git a/salt/utils/schema.py b/salt/utils/schema.py index 8bc73c9d068..2ac9a45f266 100644 --- a/salt/utils/schema.py +++ b/salt/utils/schema.py @@ -512,7 +512,7 @@ class Schema(metaclass=SchemaMeta): serialized = OrderedDict() if id_ is not None: # This is meant as a configuration section, sub json schema - serialized["id"] = "{}/{}.json#".format(BASE_SCHEMA_URL, id_) + serialized["id"] = f"{BASE_SCHEMA_URL}/{id_}.json#" else: # Main configuration block, json schema serialized["$schema"] = "http://json-schema.org/draft-04/schema#" @@ -687,7 +687,7 @@ class SchemaItem(metaclass=BaseSchemaItemMeta): Return the argname value looking up on all possible attributes """ # Let's see if there's a private function to get the value - argvalue = getattr(self, "__get_{}__".format(argname), None) + argvalue = getattr(self, f"__get_{argname}__", None) if argvalue is not None and callable(argvalue): argvalue = argvalue() # pylint: disable=not-callable if argvalue is None: @@ -695,7 +695,7 @@ class SchemaItem(metaclass=BaseSchemaItemMeta): argvalue = getattr(self, argname, None) if argvalue is None: # Let's see if it's defined as a private class variable - argvalue = getattr(self, "__{}__".format(argname), None) + argvalue = getattr(self, f"__{argname}__", None) if argvalue is None: # Let's look for it in the extra dictionary argvalue = self.extra.get(argname, None) @@ -737,7 +737,7 @@ class BaseSchemaItem(SchemaItem): default=None, enum=None, enumNames=None, - **kwargs + **kwargs, ): """ :param required: @@ -876,7 +876,7 @@ class StringItem(BaseSchemaItem): pattern=None, min_length=None, max_length=None, - **kwargs + **kwargs, ): """ :param required: @@ -1006,7 +1006,7 @@ class NumberItem(BaseSchemaItem): exclusive_minimum=None, maximum=None, exclusive_maximum=None, - **kwargs + **kwargs, ): """ :param required: @@ -1071,7 +1071,7 @@ class ArrayItem(BaseSchemaItem): max_items=None, unique_items=None, additional_items=None, - **kwargs + **kwargs, ): """ :param required: @@ -1169,7 +1169,7 @@ class DictItem(BaseSchemaItem): additional_properties=None, min_properties=None, max_properties=None, - **kwargs + **kwargs, ): """ :param required: @@ -1481,7 +1481,7 @@ class ComplexSchemaItem(BaseSchemaItem): The serialization of the complex item is a pointer to the item definition """ - return {"$ref": "#/definitions/{}".format(self.definition_name)} + return {"$ref": f"#/definitions/{self.definition_name}"} def get_definition(self): """Returns the definition of the complex item""" diff --git a/salt/utils/slack.py b/salt/utils/slack.py index 74b98af46d3..b4f1b5e3b7c 100644 --- a/salt/utils/slack.py +++ b/salt/utils/slack.py @@ -85,7 +85,7 @@ def query( # send the token in an HTTP POST body. # Apps created before February 24, 2021 will continue functioning no # matter which way you pass your token. - header_dict["Authorization"] = "Bearer {}".format(api_key) + header_dict["Authorization"] = f"Bearer {api_key}" result = salt.utils.http.query( url, method, diff --git a/salt/utils/smb.py b/salt/utils/smb.py index d3468078a48..de32b52b2fa 100644 --- a/salt/utils/smb.py +++ b/salt/utils/smb.py @@ -4,7 +4,6 @@ Utility functions for SMB connections :depends: impacket """ - import logging import socket import uuid @@ -73,7 +72,7 @@ class SMBProto: def tree_connect(self, share): if share.endswith("$"): - share = r"\\{}\{}".format(self.server, share) + share = rf"\\{self.server}\{share}" tree = TreeConnect(self.session, share) tree.connect() return tree @@ -87,9 +86,9 @@ class SMBProto: file = cls.normalize_filename(file) # ensure file is created, get maximal access, and set everybody read access max_req = SMB2CreateContextRequest() - max_req[ - "buffer_name" - ] = CreateContextName.SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST + max_req["buffer_name"] = ( + CreateContextName.SMB2_CREATE_QUERY_MAXIMAL_ACCESS_REQUEST + ) max_req["buffer_data"] = SMB2CreateQueryMaximalAccessRequest() # create security buffer that sets the ACL for everyone to have read access diff --git a/salt/utils/smtp.py b/salt/utils/smtp.py index bab7a3aa4eb..a138a03110b 100644 --- a/salt/utils/smtp.py +++ b/salt/utils/smtp.py @@ -83,10 +83,10 @@ def send(kwargs, opts): config["smtp.content"] = str(encrypted_data) else: log.error("SMTP: Encryption failed, only an error message will be sent") - config[ - "smtp.content" - ] = "Encryption failed, the return data was not sent.\r\n\r\n{}\r\n{}".format( - encrypted_data.status, encrypted_data.stderr + config["smtp.content"] = ( + "Encryption failed, the return data was not sent.\r\n\r\n{}\r\n{}".format( + encrypted_data.status, encrypted_data.stderr + ) ) message = "From: {}\r\nTo: {}\r\nDate: {}\r\nSubject: {}\r\n\r\n{}".format( diff --git a/salt/utils/ssdp.py b/salt/utils/ssdp.py index 497accb522e..40a0d82d067 100644 --- a/salt/utils/ssdp.py +++ b/salt/utils/ssdp.py @@ -282,7 +282,7 @@ class SSDPDiscoveryServer(SSDPBase): family=family, type=socket.SOCK_DGRAM, proto=proto, - flags=flags + flags=flags, ) ) if not infos: @@ -303,7 +303,7 @@ class SSDPDiscoveryServer(SSDPBase): if not addr_pairs_info: raise ValueError("can not get address information") exceptions = [] - for ((family, proto), (local_address, remote_address)) in addr_pairs_info: + for (family, proto), (local_address, remote_address) in addr_pairs_info: sock = r_addr = None try: sock = socket.socket(family=family, type=socket.SOCK_DGRAM, proto=proto) @@ -404,9 +404,7 @@ class SSDPDiscoveryClient(SSDPBase): Query the broadcast for defined services. :return: """ - query = salt.utils.stringutils.to_bytes( - "{}{}".format(self.signature, time.time()) - ) + query = salt.utils.stringutils.to_bytes(f"{self.signature}{time.time()}") self._socket.sendto(query, ("", self.port)) return query diff --git a/salt/utils/ssh.py b/salt/utils/ssh.py index 6c59a5cab02..8e436904434 100644 --- a/salt/utils/ssh.py +++ b/salt/utils/ssh.py @@ -20,6 +20,6 @@ def key_is_encrypted(key): del key_data if not is_private_key: - raise CommandExecutionError("{} is not a private key".format(key)) + raise CommandExecutionError(f"{key} is not a private key") return is_encrypted diff --git a/salt/utils/state.py b/salt/utils/state.py index de3913e0286..41c2e191cc9 100644 --- a/salt/utils/state.py +++ b/salt/utils/state.py @@ -4,7 +4,6 @@ Utility functions for state functions .. versionadded:: 2018.3.0 """ - import copy import salt.state diff --git a/salt/utils/stringio.py b/salt/utils/stringio.py index 1dae9346484..0d3cadf2936 100644 --- a/salt/utils/stringio.py +++ b/salt/utils/stringio.py @@ -2,7 +2,6 @@ Functions for StringIO objects """ - import io readable_types = (io.StringIO,) diff --git a/salt/utils/stringutils.py b/salt/utils/stringutils.py index 30ca46fee5c..d43798df3df 100644 --- a/salt/utils/stringutils.py +++ b/salt/utils/stringutils.py @@ -2,7 +2,6 @@ Functions for manipulating or otherwise processing strings """ - import base64 import difflib import errno @@ -50,7 +49,7 @@ def to_bytes(s, encoding=None, errors="strict"): # raised, otherwise we would have already returned (or raised some # other exception). raise exc # pylint: disable=raising-bad-type - raise TypeError("expected str, bytes, or bytearray not {}".format(type(s))) + raise TypeError(f"expected str, bytes, or bytearray not {type(s)}") def to_str(s, encoding=None, errors="strict", normalize=False): @@ -88,7 +87,7 @@ def to_str(s, encoding=None, errors="strict", normalize=False): # raised, otherwise we would have already returned (or raised some # other exception). raise exc # pylint: disable=raising-bad-type - raise TypeError("expected str, bytes, or bytearray not {}".format(type(s))) + raise TypeError(f"expected str, bytes, or bytearray not {type(s)}") def to_unicode(s, encoding=None, errors="strict", normalize=False): @@ -112,7 +111,7 @@ def to_unicode(s, encoding=None, errors="strict", normalize=False): return _normalize(s) elif isinstance(s, (bytes, bytearray)): return _normalize(to_str(s, encoding, errors)) - raise TypeError("expected str, bytes, or bytearray not {}".format(type(s))) + raise TypeError(f"expected str, bytes, or bytearray not {type(s)}") @jinja_filter("str_to_num") @@ -301,7 +300,7 @@ def build_whitespace_split_regex(text): for line in text.splitlines(): parts = [re.escape(s) for s in __build_parts(line)] regex += r"(?:[\s]+)?{}(?:[\s]+)?".format(r"(?:[\s]+)?".join(parts)) - return r"(?m)^{}$".format(regex) + return rf"(?m)^{regex}$" def expr_match(line, expr): @@ -323,7 +322,7 @@ def expr_match(line, expr): if fnmatch.fnmatch(line, expr): return True try: - if re.match(r"\A{}\Z".format(expr), line): + if re.match(rf"\A{expr}\Z", line): return True except re.error: pass @@ -460,7 +459,7 @@ def print_cli(msg, retries=10, step=0.01): except UnicodeEncodeError: print(msg.encode("utf-8")) except OSError as exc: - err = "{}".format(exc) + err = f"{exc}" if exc.errno != errno.EPIPE: if ( "temporarily unavailable" in err or exc.errno in (errno.EAGAIN,) @@ -523,7 +522,7 @@ def get_diff(a, b, *args, **kwargs): salt.utils.data.decode_list(a, encoding=encoding), salt.utils.data.decode_list(b, encoding=encoding), *args, - **kwargs + **kwargs, ) ) diff --git a/salt/utils/templates.py b/salt/utils/templates.py index 317ccb43460..7623d49577b 100644 --- a/salt/utils/templates.py +++ b/salt/utils/templates.py @@ -1,6 +1,7 @@ """ Template render systems """ + import codecs import importlib.machinery import importlib.util diff --git a/salt/utils/textformat.py b/salt/utils/textformat.py index 304456a0e50..c02c1f175a4 100644 --- a/salt/utils/textformat.py +++ b/salt/utils/textformat.py @@ -3,7 +3,6 @@ ANSI escape code utilities, see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-048.pdf """ - graph_prefix = "\x1b[" graph_suffix = "m" codes = { @@ -170,7 +169,7 @@ class TextFormat: 'The answer is: {0}'.format(green_blink_text(42)) """ end = TextFormat("reset") if reset else "" - return "{}{}{}".format(self.sequence, text, end) + return f"{self.sequence}{text}{end}" def __str__(self): return self.sequence diff --git a/salt/utils/thin.py b/salt/utils/thin.py index e6f75041db5..a760fcc02f5 100644 --- a/salt/utils/thin.py +++ b/salt/utils/thin.py @@ -148,7 +148,7 @@ def find_site_modules(name): except RuntimeError: log.debug("No site package directories found") for site_path in site_paths: - path = os.path.join(site_path, "{}.py".format(name)) + path = os.path.join(site_path, f"{name}.py") lib = import_module(name, path) if lib: libs.append(lib) @@ -549,9 +549,7 @@ def _pack_alternative(extended_cfg, digest_collector, tfp): top = os.path.normpath(top) base, top_dirname = os.path.basename(top), os.path.dirname(top) os.chdir(top_dirname) - site_pkg_dir = ( - _is_shareable(base) and "pyall" or "py{}".format(py_ver_major) - ) + site_pkg_dir = _is_shareable(base) and "pyall" or f"py{py_ver_major}" log.debug( 'Packing alternative "%s" to "%s/%s" destination', base, @@ -701,11 +699,11 @@ def gen_thin( # This is likely a compressed python .egg tempdir = tempfile.mkdtemp() egg = zipfile.ZipFile(top_dirname) - egg.extractall(tempdir) + egg.extractall(tempdir) # nosec top = os.path.join(tempdir, base) os.chdir(tempdir) - site_pkg_dir = _is_shareable(base) and "pyall" or "py{}".format(py_ver) + site_pkg_dir = _is_shareable(base) and "pyall" or f"py{py_ver}" log.debug('Packing "%s" to "%s" destination', base, site_pkg_dir) if not os.path.isdir(top): @@ -773,7 +771,7 @@ def thin_sum(cachedir, form="sha1"): code_checksum_path = os.path.join(cachedir, "thin", "code-checksum") if os.path.isfile(code_checksum_path): with salt.utils.files.fopen(code_checksum_path, "r") as fh: - code_checksum = "'{}'".format(fh.read().strip()) + code_checksum = f"'{fh.read().strip()}'" else: code_checksum = "'0'" @@ -973,12 +971,12 @@ def gen_min( # This is likely a compressed python .egg tempdir = tempfile.mkdtemp() egg = zipfile.ZipFile(top_dirname) - egg.extractall(tempdir) + egg.extractall(tempdir) # nosec top = os.path.join(tempdir, base) os.chdir(tempdir) if not os.path.isdir(top): # top is a single file module - tfp.add(base, arcname=os.path.join("py{}".format(py_ver), base)) + tfp.add(base, arcname=os.path.join(f"py{py_ver}", base)) continue for root, dirs, files in salt.utils.path.os_walk(base, followlinks=True): for name in files: @@ -991,7 +989,7 @@ def gen_min( continue tfp.add( os.path.join(root, name), - arcname=os.path.join("py{}".format(py_ver), root, name), + arcname=os.path.join(f"py{py_ver}", root, name), ) if tempdir is not None: shutil.rmtree(tempdir) diff --git a/salt/utils/timed_subprocess.py b/salt/utils/timed_subprocess.py index a3ffe3d38e4..627d3f712ed 100644 --- a/salt/utils/timed_subprocess.py +++ b/salt/utils/timed_subprocess.py @@ -44,7 +44,7 @@ class TimedProc: if self.timeout and not isinstance(self.timeout, (int, float)): raise salt.exceptions.TimedProcTimeoutError( - "Error: timeout {} must be a number".format(self.timeout) + f"Error: timeout {self.timeout} must be a number" ) if kwargs.get("shell", False): args = salt.utils.data.decode(args, to_str=True) diff --git a/salt/utils/url.py b/salt/utils/url.py index a30610394c1..478d8e911c2 100644 --- a/salt/utils/url.py +++ b/salt/utils/url.py @@ -2,7 +2,6 @@ URL utils """ - import re import sys from urllib.parse import urlparse, urlunparse @@ -46,7 +45,7 @@ def create(path, saltenv=None): path = salt.utils.path.sanitize_win_path(path) path = salt.utils.data.decode(path) - query = "saltenv={}".format(saltenv) if saltenv else "" + query = f"saltenv={saltenv}" if saltenv else "" url = salt.utils.data.decode(urlunparse(("file", "", path, "", query, ""))) return "salt://{}".format(url[len("file:///") :]) @@ -80,13 +79,13 @@ def escape(url): if url.startswith("|"): return url else: - return "|{}".format(url) + return f"|{url}" elif scheme == "salt": path, saltenv = parse(url) if path.startswith("|"): return create(path, saltenv) else: - return create("|{}".format(path), saltenv) + return create(f"|{path}", saltenv) else: return url @@ -158,11 +157,11 @@ def add_http_basic_auth(url, user=None, password=None, https_only=False): if https_only and urltuple.scheme != "https": raise ValueError("Basic Auth only supported for HTTPS") if password is None: - netloc = "{}@{}".format(user, urltuple.netloc) + netloc = f"{user}@{urltuple.netloc}" urltuple = urltuple._replace(netloc=netloc) return urlunparse(urltuple) else: - netloc = "{}:{}@{}".format(user, password, urltuple.netloc) + netloc = f"{user}:{password}@{urltuple.netloc}" urltuple = urltuple._replace(netloc=netloc) return urlunparse(urltuple) diff --git a/salt/utils/user.py b/salt/utils/user.py index be2abdced2b..d48d2641c0f 100644 --- a/salt/utils/user.py +++ b/salt/utils/user.py @@ -3,7 +3,6 @@ Functions for querying and modifying a user account and the groups to which it belongs. """ - import ctypes import getpass import logging diff --git a/salt/utils/validate/net.py b/salt/utils/validate/net.py index a58fb2b2d70..c098281b654 100644 --- a/salt/utils/validate/net.py +++ b/salt/utils/validate/net.py @@ -37,7 +37,7 @@ def __ip_addr(addr, address_family=socket.AF_INET): try: if "/" not in addr: - addr = "{addr}/{mask_max}".format(addr=addr, mask_max=mask_max) + addr = f"{addr}/{mask_max}" except TypeError: return False diff --git a/salt/utils/vault/cache.py b/salt/utils/vault/cache.py index 3c93a0dda28..7e14681699e 100644 --- a/salt/utils/vault/cache.py +++ b/salt/utils/vault/cache.py @@ -317,9 +317,11 @@ class VaultLeaseCache(LeaseCacheMixin, CommonCache): self.expire_events( tag=f"vault/lease/{ckey}/expire", data={ - "valid_for_less": valid_for - if valid_for is not None - else data.get("min_ttl") or 0, + "valid_for_less": ( + valid_for + if valid_for is not None + else data.get("min_ttl") or 0 + ), }, ) ret = None diff --git a/salt/utils/vault/helpers.py b/salt/utils/vault/helpers.py index 6798a892f3b..7fb4ef1c2b8 100644 --- a/salt/utils/vault/helpers.py +++ b/salt/utils/vault/helpers.py @@ -111,7 +111,7 @@ def expand_pattern_lists(pattern, **mappings): # very expensive, since patterns will typically involve a handful of lists at # most. - for (_, field_name, _, _) in f.parse(pattern): + for _, field_name, _, _ in f.parse(pattern): if field_name is None: continue (value, _) = f.get_field(field_name, None, mappings) diff --git a/salt/utils/versions.py b/salt/utils/versions.py index 7c65e74deab..04dac7d4280 100644 --- a/salt/utils/versions.py +++ b/salt/utils/versions.py @@ -6,6 +6,7 @@ which works under python 3 because on python 3 you can no longer compare strings against integers. """ + import datetime import inspect import logging diff --git a/salt/utils/virt.py b/salt/utils/virt.py index fcd3d4fd4ea..42fe6a8cde1 100644 --- a/salt/utils/virt.py +++ b/salt/utils/virt.py @@ -28,7 +28,7 @@ def download_remote(url, dir): try: rand = hashlib.md5(os.urandom(32)).hexdigest() remote_filename = urllib.parse.urlparse(url).path.split("/")[-1] - full_directory = os.path.join(dir, "{}-{}".format(rand, remote_filename)) + full_directory = os.path.join(dir, f"{rand}-{remote_filename}") with salt.utils.files.fopen( full_directory, "wb" ) as file, urllib.request.urlopen(url) as response: diff --git a/salt/utils/virtualbox.py b/salt/utils/virtualbox.py index d551cc1d386..e8a89dd5dd9 100644 --- a/salt/utils/virtualbox.py +++ b/salt/utils/virtualbox.py @@ -382,7 +382,7 @@ def vb_get_network_addresses(machine_name=None, machine=None, wait_for_pattern=N for i in range(total_slots): try: address = machine.getGuestPropertyValue( - "/VirtualBox/GuestInfo/Net/{}/V4/IP".format(i) + f"/VirtualBox/GuestInfo/Net/{i}/V4/IP" ) if address: ip_addresses.append(address) @@ -607,7 +607,7 @@ def vb_xpcom_to_attribute_dict( """ # Check the interface if interface_name: - m = re.search(r"XPCOM.+implementing {}".format(interface_name), str(xpcom)) + m = re.search(rf"XPCOM.+implementing {interface_name}", str(xpcom)) if not m: # TODO maybe raise error here? log.warning( diff --git a/salt/utils/vmware.py b/salt/utils/vmware.py index 92a3be8e3cf..f6c230c398f 100644 --- a/salt/utils/vmware.py +++ b/salt/utils/vmware.py @@ -159,7 +159,7 @@ def esxcli( protocol = "https" if credstore: - esx_cmd += " --credstore '{}'".format(credstore) + esx_cmd += f" --credstore '{credstore}'" if not esxi_host: # Then we are connecting directly to an ESXi server, @@ -259,7 +259,7 @@ def _get_service_instance( raise salt.exceptions.CommandExecutionError(err_msg) else: raise salt.exceptions.CommandExecutionError( - "Unsupported mechanism: '{}'".format(mechanism) + f"Unsupported mechanism: '{mechanism}'" ) log.trace( @@ -343,7 +343,7 @@ def _get_service_instance( log.exception(exc) err_msg = exc.msg if hasattr(exc, "msg") else str(exc) raise salt.exceptions.VMwareConnectionError( - "Could not connect to host '{}': {}".format(host, err_msg) + f"Could not connect to host '{host}': {err_msg}" ) else: err_msg = exc.msg if hasattr(exc, "msg") else default_msg @@ -494,7 +494,7 @@ def get_service_instance( except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -574,7 +574,7 @@ def disconnect(service_instance): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -597,7 +597,7 @@ def is_connection_to_a_vcenter(service_instance): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -629,7 +629,7 @@ def get_service_info(service_instance): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -727,7 +727,7 @@ def get_gssapi_token(principal, host, domain): if not HAS_GSSAPI: raise ImportError("The gssapi library is not imported.") - service = "{}/{}@{}".format(principal, host, domain) + service = f"{principal}/{host}@{domain}" log.debug("Retrieving gsspi token for service %s", service) service_name = gssapi.Name(service, gssapi.C_NT_USER_NAME) ctx = gssapi.InitContext(service_name) @@ -858,7 +858,7 @@ def get_root_folder(service_instance): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -923,7 +923,7 @@ def get_content( except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -968,7 +968,7 @@ def get_content( except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -984,7 +984,7 @@ def get_content( except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -1139,7 +1139,7 @@ def get_properties_of_managed_object(mo_ref, properties): ) if not items: raise salt.exceptions.VMwareApiError( - "Properties of managed object '{}' weren't retrieved".format(mo_name) + f"Properties of managed object '{mo_name}' weren't retrieved" ) return items[0] @@ -1263,7 +1263,7 @@ def get_network_folder(dc_ref): ) if not entries: raise salt.exceptions.VMwareObjectRetrievalError( - "Network folder in datacenter '{}' wasn't retrieved".format(dc_name) + f"Network folder in datacenter '{dc_name}' wasn't retrieved" ) return entries[0]["object"] @@ -1296,7 +1296,7 @@ def create_dvs(dc_ref, dvs_name, dvs_create_spec=None): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -1325,7 +1325,7 @@ def update_dvs(dvs_ref, dvs_config_spec): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -1357,7 +1357,7 @@ def set_dvs_network_resource_management_enabled(dvs_ref, enabled): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -1452,7 +1452,7 @@ def get_uplink_dvportgroup(dvs_ref): ] if not items: raise salt.exceptions.VMwareObjectRetrievalError( - "Uplink portgroup of DVS '{}' wasn't found".format(dvs_name) + f"Uplink portgroup of DVS '{dvs_name}' wasn't found" ) return items[0] @@ -1476,7 +1476,7 @@ def create_dvportgroup(dvs_ref, spec): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -1504,7 +1504,7 @@ def update_dvportgroup(portgroup_ref, spec): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -1529,7 +1529,7 @@ def remove_dvportgroup(portgroup_ref): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -1630,7 +1630,7 @@ def get_license_manager(service_instance): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -1657,7 +1657,7 @@ def get_license_assignment_manager(service_instance): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -1692,7 +1692,7 @@ def get_licenses(service_instance, license_manager=None): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -1730,7 +1730,7 @@ def add_license(service_instance, key, description, license_manager=None): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -1783,7 +1783,7 @@ def get_assigned_licenses( except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -1800,7 +1800,7 @@ def get_assigned_licenses( except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -1874,7 +1874,7 @@ def assign_license( except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: raise salt.exceptions.VMwareApiError(exc.msg) @@ -1894,7 +1894,7 @@ def assign_license( except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -1952,7 +1952,7 @@ def get_datacenter(service_instance, datacenter_name): items = get_datacenters(service_instance, datacenter_names=[datacenter_name]) if not items: raise salt.exceptions.VMwareObjectRetrievalError( - "Datacenter '{}' was not found".format(datacenter_name) + f"Datacenter '{datacenter_name}' was not found" ) return items[0] @@ -1976,7 +1976,7 @@ def create_datacenter(service_instance, datacenter_name): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -2023,7 +2023,7 @@ def get_cluster(dc_ref, cluster): ] if not items: raise salt.exceptions.VMwareObjectRetrievalError( - "Cluster '{}' was not found in datacenter '{}'".format(cluster, dc_name) + f"Cluster '{cluster}' was not found in datacenter '{dc_name}'" ) return items[0] @@ -2049,7 +2049,7 @@ def create_cluster(dc_ref, cluster_name, cluster_spec): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -2077,7 +2077,7 @@ def update_cluster(cluster_ref, cluster_spec): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -2150,13 +2150,13 @@ def get_datastore_files( for datobj in datastore_objects: try: task = datobj.browser.SearchDatastore_Task( - datastorePath="[{}] {}".format(datobj.name, directory), + datastorePath=f"[{datobj.name}] {directory}", searchSpec=browser_spec, ) except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -2313,7 +2313,7 @@ def get_datastores( ) else: raise salt.exceptions.ArgumentValueError( - "Unsupported reference type '{}'".format(reference.__class__.__name__) + f"Unsupported reference type '{reference.__class__.__name__}'" ) items = get_mors_with_properties( @@ -2346,7 +2346,7 @@ def rename_datastore(datastore_ref, new_datastore_name): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -2376,7 +2376,7 @@ def get_storage_system(service_instance, host_ref, hostname=None): ) if not objs: raise salt.exceptions.VMwareObjectRetrievalError( - "Host's '{}' storage system was not retrieved".format(hostname) + f"Host's '{hostname}' storage system was not retrieved" ) log.trace("[%s] Retrieved storage system", hostname) return objs[0]["object"] @@ -2394,7 +2394,7 @@ def _get_partition_info(storage_system, device_path): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -2443,7 +2443,7 @@ def _get_new_computed_partition_spec(storage_system, device_path, partition_info except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -2531,7 +2531,7 @@ def create_vmfs_datastore( except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -2569,7 +2569,7 @@ def get_host_datastore_system(host_ref, hostname=None): ) if not objs: raise salt.exceptions.VMwareObjectRetrievalError( - "Host's '{}' datastore system was not retrieved".format(hostname) + f"Host's '{hostname}' datastore system was not retrieved" ) log.trace("[%s] Retrieved datastore system", hostname) return objs[0]["object"] @@ -2591,7 +2591,7 @@ def remove_datastore(service_instance, datastore_ref): ds_hosts = ds_props.get("host") if not ds_hosts: raise salt.exceptions.VMwareApiError( - "Datastore '{}' can't be removed. No attached hosts found".format(ds_name) + f"Datastore '{ds_name}' can't be removed. No attached hosts found" ) hostname = get_managed_object_name(ds_hosts[0].key) host_ds_system = get_host_datastore_system(ds_hosts[0].key, hostname=hostname) @@ -2600,7 +2600,7 @@ def remove_datastore(service_instance, datastore_ref): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -2715,7 +2715,7 @@ def _get_scsi_address_to_lun_key_map( except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -2725,16 +2725,16 @@ def _get_scsi_address_to_lun_key_map( raise salt.exceptions.VMwareRuntimeError(exc.msg) if not device_info: raise salt.exceptions.VMwareObjectRetrievalError( - "Host's '{}' storage device info was not retrieved".format(hostname) + f"Host's '{hostname}' storage device info was not retrieved" ) multipath_info = device_info.multipathInfo if not multipath_info: raise salt.exceptions.VMwareObjectRetrievalError( - "Host's '{}' multipath info was not retrieved".format(hostname) + f"Host's '{hostname}' multipath info was not retrieved" ) if multipath_info.lun is None: raise salt.exceptions.VMwareObjectRetrievalError( - "No luns were retrieved from host '{}'".format(hostname) + f"No luns were retrieved from host '{hostname}'" ) lun_key_by_scsi_addr = {} for l in multipath_info.lun: @@ -2768,14 +2768,14 @@ def get_all_luns(host_ref, storage_system=None, hostname=None): storage_system = get_storage_system(si, host_ref, hostname) if not storage_system: raise salt.exceptions.VMwareObjectRetrievalError( - "Host's '{}' storage system was not retrieved".format(hostname) + f"Host's '{hostname}' storage system was not retrieved" ) try: device_info = storage_system.storageDeviceInfo except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -2785,7 +2785,7 @@ def get_all_luns(host_ref, storage_system=None, hostname=None): raise salt.exceptions.VMwareRuntimeError(exc.msg) if not device_info: raise salt.exceptions.VMwareObjectRetrievalError( - "Host's '{}' storage device info was not retrieved".format(hostname) + f"Host's '{hostname}' storage device info was not retrieved" ) scsi_luns = device_info.scsiLun @@ -2926,7 +2926,7 @@ def get_disk_partition_info(host_ref, disk_id, storage_system=None): ) if not props.get("storageDeviceInfo.scsiLun"): raise salt.exceptions.VMwareObjectRetrievalError( - "No devices were retrieved in host '{}'".format(hostname) + f"No devices were retrieved in host '{hostname}'" ) log.trace( "[%s] Retrieved %s devices: %s", @@ -2941,7 +2941,7 @@ def get_disk_partition_info(host_ref, disk_id, storage_system=None): ] if not disks: raise salt.exceptions.VMwareObjectRetrievalError( - "Disk '{}' was not found in host '{}'".format(disk_id, hostname) + f"Disk '{disk_id}' was not found in host '{hostname}'" ) log.trace("[%s] device_path = %s", hostname, disks[0].devicePath) partition_info = _get_partition_info(storage_system, disks[0].devicePath) @@ -2995,7 +2995,7 @@ def erase_disk_partitions( ) if not results: raise salt.exceptions.VMwareObjectRetrievalError( - "Host's '{}' devices were not retrieved".format(hostname) + f"Host's '{hostname}' devices were not retrieved" ) log.trace( "[%s] Retrieved %s devices: %s", @@ -3012,7 +3012,7 @@ def erase_disk_partitions( ] if not disks: raise salt.exceptions.VMwareObjectRetrievalError( - "Disk '{}' was not found in host '{}'".format(disk_id, hostname) + f"Disk '{disk_id}' was not found in host '{hostname}'" ) log.trace("[%s] device_path = %s", hostname, disks[0].devicePath) # Erase the partitions by setting an empty partition spec @@ -3023,7 +3023,7 @@ def erase_disk_partitions( except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -3069,7 +3069,7 @@ def get_diskgroups(host_ref, cache_disk_ids=None, get_all_disk_groups=False): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -3079,12 +3079,12 @@ def get_diskgroups(host_ref, cache_disk_ids=None, get_all_disk_groups=False): raise salt.exceptions.VMwareRuntimeError(exc.msg) if not vsan_host_config: raise salt.exceptions.VMwareObjectRetrievalError( - "No host config found on host '{}'".format(hostname) + f"No host config found on host '{hostname}'" ) vsan_storage_info = vsan_host_config.storageInfo if not vsan_storage_info: raise salt.exceptions.VMwareObjectRetrievalError( - "No vsan storage info found on host '{}'".format(hostname) + f"No vsan storage info found on host '{hostname}'" ) vsan_disk_mappings = vsan_storage_info.diskMapping if not vsan_disk_mappings: @@ -3199,7 +3199,7 @@ def configure_host_cache( ) if not props.get("configManager.cacheConfigurationManager"): raise salt.exceptions.VMwareObjectRetrievalError( - "Host '{}' has no host cache".format(hostname) + f"Host '{hostname}' has no host cache" ) host_cache_manager = props["configManager.cacheConfigurationManager"] log.trace( @@ -3218,7 +3218,7 @@ def configure_host_cache( except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -3396,7 +3396,7 @@ def wait_for_task(task, instance_name, task_type, sleep_seconds=1, log_level="de except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.FileNotFound as exc: log.exception(exc) @@ -3423,7 +3423,7 @@ def wait_for_task(task, instance_name, task_type, sleep_seconds=1, log_level="de except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.FileNotFound as exc: log.exception(exc) @@ -3451,7 +3451,7 @@ def wait_for_task(task, instance_name, task_type, sleep_seconds=1, log_level="de except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.FileNotFound as exc: log.exception(exc) @@ -3466,7 +3466,7 @@ def wait_for_task(task, instance_name, task_type, sleep_seconds=1, log_level="de log.exception(exc) exc_message = exc.msg if exc.faultMessage: - exc_message = "{} ({})".format(exc_message, exc.faultMessage[0].message) + exc_message = f"{exc_message} ({exc.faultMessage[0].message})" raise salt.exceptions.VMwareApiError(exc_message) @@ -3745,7 +3745,7 @@ def power_cycle_vm(virtual_machine, action="on"): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -3760,7 +3760,7 @@ def power_cycle_vm(virtual_machine, action="on"): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -3777,7 +3777,7 @@ def power_cycle_vm(virtual_machine, action="on"): " ".join( [ "An error occurred during power", - "operation, a file was not found: {}".format(exc), + f"operation, a file was not found: {exc}", ] ) ) @@ -3818,7 +3818,7 @@ def create_vm( except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -3866,7 +3866,7 @@ def register_vm(datacenter, name, vmx_path, resourcepool_object, host_object=Non except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -3901,7 +3901,7 @@ def update_vm(vm_ref, vm_config_spec): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -3927,7 +3927,7 @@ def delete_vm(vm_ref): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -3952,7 +3952,7 @@ def unregister_vm(vm_ref): except vim.fault.NoPermission as exc: log.exception(exc) raise salt.exceptions.VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: raise salt.exceptions.VMwareApiError(exc.msg) diff --git a/salt/utils/vsan.py b/salt/utils/vsan.py index 7f893150fa6..a10c101d4d9 100644 --- a/salt/utils/vsan.py +++ b/salt/utils/vsan.py @@ -41,7 +41,6 @@ The 5.5.0.2014.1.1 is a known stable version that this original VMware utils fil was developed against. """ - import logging import ssl import sys @@ -99,7 +98,7 @@ def vsan_supported(service_instance): except vim.fault.NoPermission as exc: log.exception(exc) raise VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -187,7 +186,7 @@ def get_host_vsan_system(service_instance, host_ref, hostname=None): ) if not objs: raise VMwareObjectRetrievalError( - "Host's '{}' VSAN system was not retrieved".format(hostname) + f"Host's '{hostname}' VSAN system was not retrieved" ) log.trace("[%s] Retrieved VSAN system", hostname) return objs[0]["object"] @@ -238,14 +237,14 @@ def create_diskgroup( except vim.fault.NoPermission as exc: log.exception(exc) raise VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) raise VMwareApiError(exc.msg) except vmodl.fault.MethodNotFound as exc: log.exception(exc) - raise VMwareRuntimeError("Method '{}' not found".format(exc.method)) + raise VMwareRuntimeError(f"Method '{exc.method}' not found") except vmodl.RuntimeFault as exc: log.exception(exc) raise VMwareRuntimeError(exc.msg) @@ -305,14 +304,14 @@ def add_capacity_to_diskgroup( except vim.fault.NoPermission as exc: log.exception(exc) raise VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) raise VMwareApiError(exc.msg) except vmodl.fault.MethodNotFound as exc: log.exception(exc) - raise VMwareRuntimeError("Method '{}' not found".format(exc.method)) + raise VMwareRuntimeError(f"Method '{exc.method}' not found") except vmodl.RuntimeFault as exc: raise VMwareRuntimeError(exc.msg) _wait_for_tasks([task], service_instance) @@ -389,7 +388,7 @@ def remove_capacity_from_diskgroup( except vim.fault.NoPermission as exc: log.exception(exc) raise VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -457,7 +456,7 @@ def remove_diskgroup( except vim.fault.NoPermission as exc: log.exception(exc) raise VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -490,7 +489,7 @@ def get_cluster_vsan_info(cluster_ref): except vim.fault.NoPermission as exc: log.exception(exc) raise VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -519,7 +518,7 @@ def reconfigure_cluster_vsan(cluster_ref, cluster_vsan_spec): except vim.fault.NoPermission as exc: log.exception(exc) raise VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) @@ -540,7 +539,7 @@ def _wait_for_tasks(tasks, service_instance): except vim.fault.NoPermission as exc: log.exception(exc) raise VMwareApiError( - "Not enough permissions. Required privilege: {}".format(exc.privilegeId) + f"Not enough permissions. Required privilege: {exc.privilegeId}" ) except vim.fault.VimFault as exc: log.exception(exc) diff --git a/salt/utils/vt.py b/salt/utils/vt.py index 42635b3be29..4e81046820e 100644 --- a/salt/utils/vt.py +++ b/salt/utils/vt.py @@ -215,7 +215,7 @@ class Terminal: log.warning( "Failed to spawn the VT: %s", err, exc_info_on_loglevel=logging.DEBUG ) - raise TerminalException("Failed to spawn the VT. Error: {}".format(err)) + raise TerminalException(f"Failed to spawn the VT. Error: {err}") log.debug( "Child Forked! PID: %s STDOUT_FD: %s STDERR_FD: %s", @@ -246,7 +246,7 @@ class Terminal: self.stdin_logger_level = LOG_LEVELS.get(log_stdin_level, log_stdin_level) if log_stdin is True: self.stdin_logger = logging.getLogger( - "{}.{}.PID-{}.STDIN".format(__name__, self.__class__.__name__, self.pid) + f"{__name__}.{self.__class__.__name__}.PID-{self.pid}.STDIN" ) elif log_stdin is not None: if not isinstance(log_stdin, logging.Logger): @@ -294,7 +294,7 @@ class Terminal: """ Send the provided data to the terminal appending a line feed. """ - return self.send("{}{}".format(data, linesep)) + return self.send(f"{data}{linesep}") def recv(self, maxsize=None): """ @@ -373,7 +373,7 @@ class Terminal: elif sig == signal.CTRL_BREAK_EVENT: os.kill(self.pid, signal.CTRL_BREAK_EVENT) else: - raise ValueError("Unsupported signal: {}".format(sig)) + raise ValueError(f"Unsupported signal: {sig}") # pylint: enable=E1101 def terminate(self, force=False): @@ -442,9 +442,7 @@ class Terminal: tty_fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY) if tty_fd >= 0: os.close(tty_fd) - raise TerminalException( - "Could not open child pty, {}".format(child_name) - ) + raise TerminalException(f"Could not open child pty, {child_name}") # which exception, shouldn't we catch explicitly .. ? except Exception: # pylint: disable=broad-except # Good! We are disconnected from a controlling tty. @@ -452,9 +450,7 @@ class Terminal: tty_fd = os.open(child_name, os.O_RDWR) setwinsize(tty_fd, rows, cols) if tty_fd < 0: - raise TerminalException( - "Could not open child pty, {}".format(child_name) - ) + raise TerminalException(f"Could not open child pty, {child_name}") else: os.close(tty_fd) if os.name != "posix": diff --git a/salt/utils/vt_helper.py b/salt/utils/vt_helper.py index b18feba3793..aeafbd4f332 100644 --- a/salt/utils/vt_helper.py +++ b/salt/utils/vt_helper.py @@ -61,7 +61,7 @@ class SSHConnection: Example: '-o PubkeyAuthentication=no' """ self.conn = Terminal( - "ssh {} -l {} {}".format(ssh_args, username, host), + f"ssh {ssh_args} -l {username} {host}", shell=True, log_stdout=True, log_stdout_level="trace", diff --git a/salt/utils/win_chcp.py b/salt/utils/win_chcp.py index 2f4d2891267..62cfb1608af 100644 --- a/salt/utils/win_chcp.py +++ b/salt/utils/win_chcp.py @@ -53,7 +53,7 @@ def chcp(page_id, raise_error=False): try: page_id = int(page_id) except ValueError: - error = "The `page_id` needs to be an integer, not {}".format(type(page_id)) + error = f"The `page_id` needs to be an integer, not {type(page_id)}" if raise_error: raise CodePageError(error) log.error(error) @@ -98,7 +98,7 @@ def get_codepage_id(raise_error=False): return win32console.GetConsoleCP() except pywintypes.error as exc: _, _, msg = exc.args - error = "Failed to get the windows code page: {}".format(msg) + error = f"Failed to get the windows code page: {msg}" if raise_error: raise CodePageError(error) else: @@ -129,7 +129,7 @@ def set_codepage_id(page_id, raise_error=False): try: page_id = int(page_id) except ValueError: - error = "The `page_id` needs to be an integer, not {}".format(type(page_id)) + error = f"The `page_id` needs to be an integer, not {type(page_id)}" if raise_error: raise CodePageError(error) log.error(error) @@ -139,7 +139,7 @@ def set_codepage_id(page_id, raise_error=False): return get_codepage_id(raise_error=raise_error) except pywintypes.error as exc: _, _, msg = exc.args - error = "Failed to set the windows code page: {}".format(msg) + error = f"Failed to set the windows code page: {msg}" if raise_error: raise CodePageError(error) else: diff --git a/salt/utils/win_dotnet.py b/salt/utils/win_dotnet.py index 65325da75c3..c798a6329ad 100644 --- a/salt/utils/win_dotnet.py +++ b/salt/utils/win_dotnet.py @@ -98,12 +98,12 @@ def versions(): else: continue - service_pack = " SP{}".format(sp) if sp != "N/A" else "" + service_pack = f" SP{sp}" if sp != "N/A" else "" return_dict["versions"].append(version) return_dict["details"][ver_key] = { "version": version, "service_pack": sp, - "full": "{}{}".format(version, service_pack), + "full": f"{version}{service_pack}", } return return_dict diff --git a/salt/utils/win_functions.py b/salt/utils/win_functions.py index 97e3e0878a2..c3906b1e210 100644 --- a/salt/utils/win_functions.py +++ b/salt/utils/win_functions.py @@ -135,7 +135,7 @@ def get_sid_from_name(name): try: sid = win32security.LookupAccountName(None, name)[0] except pywintypes.error as exc: - raise CommandExecutionError("User {} not found: {}".format(name, exc)) + raise CommandExecutionError(f"User {name} not found: {exc}") return win32security.ConvertSidToStringSid(sid) @@ -166,7 +166,7 @@ def get_current_user(with_domain=True): elif not with_domain: user_name = win32api.GetUserName() except pywintypes.error as exc: - raise CommandExecutionError("Failed to get current user: {}".format(exc)) + raise CommandExecutionError(f"Failed to get current user: {exc}") if not user_name: return False @@ -253,7 +253,7 @@ def escape_for_cmd_exe(arg): meta_re = re.compile( "(" + "|".join(re.escape(char) for char in list(meta_chars)) + ")" ) - meta_map = {char: "^{}".format(char) for char in meta_chars} + meta_map = {char: f"^{char}" for char in meta_chars} def escape_meta_chars(m): char = m.group(1) diff --git a/salt/utils/win_lgpo_auditpol.py b/salt/utils/win_lgpo_auditpol.py index e155ce0000f..47f0d8e8912 100644 --- a/salt/utils/win_lgpo_auditpol.py +++ b/salt/utils/win_lgpo_auditpol.py @@ -116,11 +116,11 @@ def _auditpol_cmd(cmd): Raises: CommandExecutionError: If the command encounters an error """ - ret = salt.modules.cmdmod.run_all(cmd="auditpol {}".format(cmd), python_shell=True) + ret = salt.modules.cmdmod.run_all(cmd=f"auditpol {cmd}", python_shell=True) if ret["retcode"] == 0: return ret["stdout"].splitlines() - msg = "Error executing auditpol command: {}\n".format(cmd) + msg = f"Error executing auditpol command: {cmd}\n" msg += "\n".join(ret["stdout"]) raise CommandExecutionError(msg) @@ -173,9 +173,9 @@ def get_settings(category="All"): if category.lower() in ["all", "*"]: category = "*" elif category.lower() not in [x.lower() for x in categories]: - raise KeyError('Invalid category: "{}"'.format(category)) + raise KeyError(f'Invalid category: "{category}"') - cmd = '/get /category:"{}"'.format(category) + cmd = f'/get /category:"{category}"' results = _auditpol_cmd(cmd) ret = {} @@ -213,7 +213,7 @@ def get_setting(name): for setting in current_settings: if name.lower() == setting.lower(): return current_settings[setting] - raise KeyError("Invalid name: {}".format(name)) + raise KeyError(f"Invalid name: {name}") def _get_valid_names(): @@ -264,13 +264,13 @@ def set_setting(name, value): """ # Input validation if name.lower() not in _get_valid_names(): - raise KeyError("Invalid name: {}".format(name)) + raise KeyError(f"Invalid name: {name}") for setting in settings: if value.lower() == setting.lower(): - cmd = '/set /subcategory:"{}" {}'.format(name, settings[setting]) + cmd = f'/set /subcategory:"{name}" {settings[setting]}' break else: - raise KeyError("Invalid setting value: {}".format(value)) + raise KeyError(f"Invalid setting value: {value}") _auditpol_cmd(cmd) @@ -298,7 +298,7 @@ def get_auditpol_dump(): with tempfile.NamedTemporaryFile(suffix=".csv") as tmp_file: csv_file = tmp_file.name - cmd = "/backup /file:{}".format(csv_file) + cmd = f"/backup /file:{csv_file}" _auditpol_cmd(cmd) with salt.utils.files.fopen(csv_file) as fp: diff --git a/salt/utils/win_lgpo_netsh.py b/salt/utils/win_lgpo_netsh.py index 7037b9f75dc..30ea51fc10d 100644 --- a/salt/utils/win_lgpo_netsh.py +++ b/salt/utils/win_lgpo_netsh.py @@ -117,14 +117,14 @@ def _netsh_file(content): fp.write(content) try: log.debug("%s:\n%s", fp.name, content) - return salt.modules.cmdmod.run("netsh -f {}".format(fp.name), python_shell=True) + return salt.modules.cmdmod.run(f"netsh -f {fp.name}", python_shell=True) finally: os.remove(fp.name) def _netsh_command(command, store): if store.lower() not in ("local", "lgpo"): - raise ValueError("Incorrect store: {}".format(store)) + raise ValueError(f"Incorrect store: {store}") # set the store for local or lgpo if store.lower() == "local": netsh_script = dedent( @@ -190,12 +190,12 @@ def get_settings(profile, section, store="local"): """ # validate input if profile.lower() not in ("domain", "public", "private"): - raise ValueError("Incorrect profile: {}".format(profile)) + raise ValueError(f"Incorrect profile: {profile}") if section.lower() not in ("state", "firewallpolicy", "settings", "logging"): - raise ValueError("Incorrect section: {}".format(section)) + raise ValueError(f"Incorrect section: {section}") if store.lower() not in ("local", "lgpo"): - raise ValueError("Incorrect store: {}".format(store)) - command = "show {}profile {}".format(profile, section) + raise ValueError(f"Incorrect store: {store}") + command = f"show {profile}profile {section}" # run it results = _netsh_command(command=command, store=store) # sample output: @@ -209,7 +209,7 @@ def get_settings(profile, section, store="local"): # if it's less than 3 lines it failed if len(results) < 3: - raise CommandExecutionError("Invalid results: {}".format(results)) + raise CommandExecutionError(f"Invalid results: {results}") ret = {} # Skip the first 2 lines. Add everything else to a dictionary for line in results[3:]: @@ -339,20 +339,20 @@ def set_firewall_settings(profile, inbound=None, outbound=None, store="local"): """ # Input validation if profile.lower() not in ("domain", "public", "private"): - raise ValueError("Incorrect profile: {}".format(profile)) + raise ValueError(f"Incorrect profile: {profile}") if inbound and inbound.lower() not in ( "blockinbound", "blockinboundalways", "allowinbound", "notconfigured", ): - raise ValueError("Incorrect inbound value: {}".format(inbound)) + raise ValueError(f"Incorrect inbound value: {inbound}") if outbound and outbound.lower() not in ( "allowoutbound", "blockoutbound", "notconfigured", ): - raise ValueError("Incorrect outbound value: {}".format(outbound)) + raise ValueError(f"Incorrect outbound value: {outbound}") if not inbound and not outbound: raise ValueError("Must set inbound or outbound") @@ -366,12 +366,12 @@ def set_firewall_settings(profile, inbound=None, outbound=None, store="local"): if not outbound: outbound = ret["Outbound"] - command = "set {}profile firewallpolicy {},{}".format(profile, inbound, outbound) + command = f"set {profile}profile firewallpolicy {inbound},{outbound}" results = _netsh_command(command=command, store=store) if results: - raise CommandExecutionError("An error occurred: {}".format(results)) + raise CommandExecutionError(f"An error occurred: {results}") return True @@ -441,17 +441,17 @@ def set_logging_settings(profile, setting, value, store="local"): """ # Input validation if profile.lower() not in ("domain", "public", "private"): - raise ValueError("Incorrect profile: {}".format(profile)) + raise ValueError(f"Incorrect profile: {profile}") if setting.lower() not in ( "allowedconnections", "droppedconnections", "filename", "maxfilesize", ): - raise ValueError("Incorrect setting: {}".format(setting)) + raise ValueError(f"Incorrect setting: {setting}") if setting.lower() in ("allowedconnections", "droppedconnections"): if value.lower() not in ("enable", "disable", "notconfigured"): - raise ValueError("Incorrect value: {}".format(value)) + raise ValueError(f"Incorrect value: {value}") # TODO: Consider adding something like the following to validate filename # https://stackoverflow.com/questions/9532499/check-whether-a-path-is-valid-in-python-without-creating-a-file-at-the-paths-ta if setting.lower() == "maxfilesize": @@ -460,16 +460,16 @@ def set_logging_settings(profile, setting, value, store="local"): try: int(value) except ValueError: - raise ValueError("Incorrect value: {}".format(value)) + raise ValueError(f"Incorrect value: {value}") if not 1 <= int(value) <= 32767: - raise ValueError("Incorrect value: {}".format(value)) + raise ValueError(f"Incorrect value: {value}") # Run the command - command = "set {}profile logging {} {}".format(profile, setting, value) + command = f"set {profile}profile logging {setting} {value}" results = _netsh_command(command=command, store=store) # A successful run should return an empty list if results: - raise CommandExecutionError("An error occurred: {}".format(results)) + raise CommandExecutionError(f"An error occurred: {results}") return True @@ -521,7 +521,7 @@ def set_settings(profile, setting, value, store="local"): """ # Input validation if profile.lower() not in ("domain", "public", "private"): - raise ValueError("Incorrect profile: {}".format(profile)) + raise ValueError(f"Incorrect profile: {profile}") if setting.lower() not in ( "localfirewallrules", "localconsecrules", @@ -529,17 +529,17 @@ def set_settings(profile, setting, value, store="local"): "remotemanagement", "unicastresponsetomulticast", ): - raise ValueError("Incorrect setting: {}".format(setting)) + raise ValueError(f"Incorrect setting: {setting}") if value.lower() not in ("enable", "disable", "notconfigured"): - raise ValueError("Incorrect value: {}".format(value)) + raise ValueError(f"Incorrect value: {value}") # Run the command - command = "set {}profile settings {} {}".format(profile, setting, value) + command = f"set {profile}profile settings {setting} {value}" results = _netsh_command(command=command, store=store) # A successful run should return an empty list if results: - raise CommandExecutionError("An error occurred: {}".format(results)) + raise CommandExecutionError(f"An error occurred: {results}") return True @@ -582,16 +582,16 @@ def set_state(profile, state, store="local"): """ # Input validation if profile.lower() not in ("domain", "public", "private"): - raise ValueError("Incorrect profile: {}".format(profile)) + raise ValueError(f"Incorrect profile: {profile}") if state.lower() not in ("on", "off", "notconfigured"): - raise ValueError("Incorrect state: {}".format(state)) + raise ValueError(f"Incorrect state: {state}") # Run the command - command = "set {}profile state {}".format(profile, state) + command = f"set {profile}profile state {state}" results = _netsh_command(command=command, store=store) # A successful run should return an empty list if results: - raise CommandExecutionError("An error occurred: {}".format(results)) + raise CommandExecutionError(f"An error occurred: {results}") return True diff --git a/salt/utils/win_lgpo_reg.py b/salt/utils/win_lgpo_reg.py index 8e3af61b858..4f2761d8a90 100644 --- a/salt/utils/win_lgpo_reg.py +++ b/salt/utils/win_lgpo_reg.py @@ -2,6 +2,7 @@ A Salt Util for working with the Registry.pol file. The Registry.pol file is the source of truth for registry settings that are configured via LGPO. """ + import logging import os import re diff --git a/salt/utils/win_network.py b/salt/utils/win_network.py index eeae8fc091b..1fae2ffe2f2 100644 --- a/salt/utils/win_network.py +++ b/salt/utils/win_network.py @@ -18,6 +18,7 @@ depending on the version of Windows this is run on. Once support for Windows :depends: - pythonnet - wmi """ + # https://docs.microsoft.com/en-us/dotnet/api/system.net.networkinformation.networkinterface.getallnetworkinterfaces?view=netframework-4.7.2 import logging diff --git a/salt/utils/win_osinfo.py b/salt/utils/win_osinfo.py index 56f1e12d50f..99a3b0ad9fd 100644 --- a/salt/utils/win_osinfo.py +++ b/salt/utils/win_osinfo.py @@ -1,6 +1,7 @@ """ Get Version information from Windows """ + # http://stackoverflow.com/questions/32300004/python-ctypes-getting-0-with-getversionex-function import ctypes diff --git a/salt/utils/win_pdh.py b/salt/utils/win_pdh.py index fcd395184a4..4d3dde820c2 100644 --- a/salt/utils/win_pdh.py +++ b/salt/utils/win_pdh.py @@ -167,7 +167,7 @@ class Counter: ) if win32pdh.ValidatePath(path) == 0: return Counter(path, obj, instance, instance_index, counter) - raise CommandExecutionError("Invalid counter specified: {}".format(path)) + raise CommandExecutionError(f"Invalid counter specified: {path}") build_counter = staticmethod(build_counter) diff --git a/salt/utils/win_service.py b/salt/utils/win_service.py index c05652c65c5..2713d40aeec 100644 --- a/salt/utils/win_service.py +++ b/salt/utils/win_service.py @@ -114,9 +114,7 @@ def info(name): None, None, win32service.SC_MANAGER_CONNECT ) except pywintypes.error as exc: - raise CommandExecutionError( - "Failed to connect to the SCM: {}".format(exc.strerror) - ) + raise CommandExecutionError(f"Failed to connect to the SCM: {exc.strerror}") try: handle_svc = win32service.OpenService( @@ -128,7 +126,7 @@ def info(name): | win32service.SERVICE_QUERY_STATUS, ) except pywintypes.error as exc: - raise CommandExecutionError("Failed To Open {}: {}".format(name, exc.strerror)) + raise CommandExecutionError(f"Failed To Open {name}: {exc.strerror}") try: config_info = win32service.QueryServiceConfig(handle_svc) @@ -150,7 +148,7 @@ def info(name): ret = dict() try: - sid = win32security.LookupAccountName("", "NT Service\\{}".format(name))[0] + sid = win32security.LookupAccountName("", f"NT Service\\{name}")[0] ret["sid"] = win32security.ConvertSidToStringSid(sid) except pywintypes.error: ret["sid"] = "Failed to get SID" diff --git a/salt/utils/win_system.py b/salt/utils/win_system.py index e9f38c9171e..125024674ce 100644 --- a/salt/utils/win_system.py +++ b/salt/utils/win_system.py @@ -5,6 +5,7 @@ Functions shared with salt.modules.win_system and salt.grains.pending_reboot .. versionadded:: 3001 """ + # NOTE: DO NOT USE RAW STRINGS IN THIS MODULE! UNICODE_LITERALS DOES NOT PLAY # NICELY WITH RAW STRINGS CONTAINING \u or \U. diff --git a/salt/utils/win_update.py b/salt/utils/win_update.py index 778acd141fa..dd54f213963 100644 --- a/salt/utils/win_update.py +++ b/salt/utils/win_update.py @@ -1,6 +1,7 @@ """ Classes for working with Windows Update Agent """ + import logging import subprocess @@ -398,14 +399,14 @@ class WindowsUpdateAgent: results = searcher.Search(search_string) if results.Updates.Count == 0: log.debug("No Updates found for:\n\t\t%s", search_string) - return "No Updates found: {}".format(search_string) + return f"No Updates found: {search_string}" except pywintypes.com_error as error: # Something happened, raise an error hr, msg, exc, arg = error.args # pylint: disable=W0633 try: failure_code = self.fail_codes[exc[5]] except KeyError: - failure_code = "Unknown Failure: {}".format(error) + failure_code = f"Unknown Failure: {error}" log.error("Search Failed: %s\n\t\t%s", failure_code, search_string) raise CommandExecutionError(failure_code) @@ -719,7 +720,7 @@ class WindowsUpdateAgent: try: failure_code = self.fail_codes[exc[5]] except KeyError: - failure_code = "Unknown Failure: {}".format(error) + failure_code = f"Unknown Failure: {error}" log.error("Download Failed: %s", failure_code) raise CommandExecutionError(failure_code) @@ -828,7 +829,7 @@ class WindowsUpdateAgent: try: failure_code = self.fail_codes[exc[5]] except KeyError: - failure_code = "Unknown Failure: {}".format(error) + failure_code = f"Unknown Failure: {error}" log.error("Install Failed: %s", failure_code) raise CommandExecutionError(failure_code) @@ -962,7 +963,7 @@ class WindowsUpdateAgent: try: failure_code = self.fail_codes[exc[5]] except KeyError: - failure_code = "Unknown Failure: {}".format(error) + failure_code = f"Unknown Failure: {error}" # If "Uninstall Not Allowed" error, try using DISM if exc[5] == -2145124312: @@ -992,7 +993,7 @@ class WindowsUpdateAgent: "dism", "/Online", "/Remove-Package", - "/PackageName:{}".format(pkg), + f"/PackageName:{pkg}", "/Quiet", "/NoRestart", ] @@ -1004,7 +1005,7 @@ class WindowsUpdateAgent: log.debug("Command: %s", " ".join(cmd)) log.debug("Error: %s", exc) raise CommandExecutionError( - "Uninstall using DISM failed: {}".format(exc) + f"Uninstall using DISM failed: {exc}" ) # DISM Uninstall Completed Successfully diff --git a/salt/utils/x509.py b/salt/utils/x509.py index c0b3fb47cc3..d09e8b9762a 100644 --- a/salt/utils/x509.py +++ b/salt/utils/x509.py @@ -1190,21 +1190,21 @@ def _create_authority_key_identifier(val, ca_crt, ca_pub, **kwargs): cx509.SubjectKeyIdentifier ).value.digest except cx509.ExtensionNotFound: - args[ - "key_identifier" - ] = cx509.AuthorityKeyIdentifier.from_issuer_public_key( - ca_crt.public_key() - ).key_identifier + args["key_identifier"] = ( + cx509.AuthorityKeyIdentifier.from_issuer_public_key( + ca_crt.public_key() + ).key_identifier + ) except Exception: # pylint: disable=broad-except pass if not args["key_identifier"] and ca_pub: # this should happen for self-signed certificates try: - args[ - "key_identifier" - ] = cx509.AuthorityKeyIdentifier.from_issuer_public_key( - ca_pub - ).key_identifier + args["key_identifier"] = ( + cx509.AuthorityKeyIdentifier.from_issuer_public_key( + ca_pub + ).key_identifier + ) except Exception: # pylint: disable=broad-except pass @@ -1484,12 +1484,14 @@ def _create_policy_constraints(val, **kwargs): if isinstance(val, str): val, critical = _deserialize_openssl_confstring(val) args = { - "require_explicit_policy": int(val["requireExplicitPolicy"]) - if "requireExplicitPolicy" in val - else None, - "inhibit_policy_mapping": int(val["inhibitPolicyMapping"]) - if "inhibitPolicyMapping" in val - else None, + "require_explicit_policy": ( + int(val["requireExplicitPolicy"]) + if "requireExplicitPolicy" in val + else None + ), + "inhibit_policy_mapping": ( + int(val["inhibitPolicyMapping"]) if "inhibitPolicyMapping" in val else None + ), } try: # not sure why pylint complains about this line having kwargs from keyUsage @@ -1544,12 +1546,12 @@ def _create_name_constraints(val, **kwargs): ], } args = { - "permitted_subtrees": _parse_general_names(val["permitted"]) - if "permitted" in val - else None, - "excluded_subtrees": _parse_general_names(val["excluded"]) - if "excluded" in val - else None, + "permitted_subtrees": ( + _parse_general_names(val["permitted"]) if "permitted" in val else None + ), + "excluded_subtrees": ( + _parse_general_names(val["excluded"]) if "excluded" in val else None + ), } if not any(args.values()): raise SaltInvocationError("nameConstraints needs at least one definition") @@ -1954,13 +1956,15 @@ def _render_subject_key_identifier(ext): def _render_authority_key_identifier(ext): return { - "keyid": pretty_hex(ext.value.key_identifier) - if ext.value.key_identifier - else None, + "keyid": ( + pretty_hex(ext.value.key_identifier) if ext.value.key_identifier else None + ), "issuer": [render_gn(x) for x in ext.value.authority_cert_issuer or []] or None, - "issuer_sn": dec2hex(ext.value.authority_cert_serial_number) - if ext.value.authority_cert_serial_number - else None, + "issuer_sn": ( + dec2hex(ext.value.authority_cert_serial_number) + if ext.value.authority_cert_serial_number + else None + ), } @@ -1994,11 +1998,11 @@ def _render_authority_info_access(ext): for description in ext.value._descriptions: rendered.append( { - description.access_method._name - if description.access_method._name != "Unknown OID" - else description.access_method.dotted_string: render_gn( - description.access_location.value - ) + ( + description.access_method._name + if description.access_method._name != "Unknown OID" + else description.access_method.dotted_string + ): render_gn(description.access_location.value) } ) except AttributeError: @@ -2015,9 +2019,11 @@ def _render_distribution_points(ext): "crlissuer": [render_gn(x) for x in dpoint.crl_issuer or []], "fullname": [render_gn(x) for x in dpoint.full_name or []], "reasons": list(sorted(x.value for x in dpoint.reasons or [])), - "relativename": dpoint.relative_name.rfc4514_string() - if dpoint.relative_name - else None, + "relativename": ( + dpoint.relative_name.rfc4514_string() + if dpoint.relative_name + else None + ), } ) except AttributeError: @@ -2031,9 +2037,11 @@ def _render_issuing_distribution_point(ext): "onysomereasons": list( sorted(x.value for x in ext.value.only_some_reasons or []) ), - "relativename": ext.value.relative_name.rfc4514_string() - if ext.value.relative_name - else None, + "relativename": ( + ext.value.relative_name.rfc4514_string() + if ext.value.relative_name + else None + ), "onlyuser": ext.value.only_contains_user_certs, "onlyCA": ext.value.only_contains_ca_certs, "onlyAA": ext.value.only_contains_attribute_certs, diff --git a/salt/utils/xmlutil.py b/salt/utils/xmlutil.py index 46e2946f914..2c68afd67a6 100644 --- a/salt/utils/xmlutil.py +++ b/salt/utils/xmlutil.py @@ -115,7 +115,7 @@ def get_xml_node(node, xpath): xpath: simple XPath to look for. """ if not xpath.startswith("./"): - xpath = "./{}".format(xpath) + xpath = f"./{xpath}" res = node.find(xpath) if res is None: parent_xpath = xpath[: xpath.rfind("/")] @@ -304,7 +304,7 @@ def change_xml(doc, data, mapping): xpath = param["xpath"] # Prepend the xpath with ./ to handle the root more easily if not xpath.startswith("./"): - xpath = "./{}".format(xpath) + xpath = f"./{xpath}" placeholders = [ s[1:-1] @@ -331,9 +331,7 @@ def change_xml(doc, data, mapping): if new_value is not None: # We need to increment ids from arrays since xpath starts at 1 converters = { - p: (lambda n: n + 1) - if "[${}]".format(p) in xpath - else (lambda n: n) + p: (lambda n: n + 1) if f"[${p}]" in xpath else (lambda n: n) for p in placeholders } ctx = { diff --git a/salt/utils/yaml.py b/salt/utils/yaml.py index f590d493261..8e9e202b15f 100644 --- a/salt/utils/yaml.py +++ b/salt/utils/yaml.py @@ -1,6 +1,7 @@ """ Convenience module that provides our custom loader and dumper in a single module """ + # pylint: disable=wildcard-import,unused-wildcard-import,unused-import from yaml import YAMLError, parser, scanner diff --git a/salt/utils/yamldumper.py b/salt/utils/yamldumper.py index e5e937cac7d..8c6e40394a3 100644 --- a/salt/utils/yamldumper.py +++ b/salt/utils/yamldumper.py @@ -3,6 +3,7 @@ ~~~~~~~~~~~~~~~~~~~~~ """ + # pylint: disable=W0232 # class has no __init__ method diff --git a/salt/utils/yamlencoding.py b/salt/utils/yamlencoding.py index 7e26b9afcb5..b9c2d20d6c8 100644 --- a/salt/utils/yamlencoding.py +++ b/salt/utils/yamlencoding.py @@ -2,7 +2,6 @@ Functions for adding yaml encoding to the jinja context """ - import io import sys diff --git a/salt/utils/yamlloader.py b/salt/utils/yamlloader.py index 25b4b3bb936..89ac51b8367 100644 --- a/salt/utils/yamlloader.py +++ b/salt/utils/yamlloader.py @@ -2,7 +2,6 @@ Custom YAML loading in Salt """ - import yaml # pylint: disable=blacklisted-import from yaml.constructor import ConstructorError from yaml.nodes import MappingNode, SequenceNode @@ -56,7 +55,7 @@ class SaltYamlSafeLoader(BaseLoader): raise ConstructorError( None, None, - "expected a mapping node, but found {}".format(node.id), + f"expected a mapping node, but found {node.id}", node.start_mark, ) @@ -72,7 +71,7 @@ class SaltYamlSafeLoader(BaseLoader): raise ConstructorError( context, node.start_mark, - "found unacceptable key {}".format(key_node.value), + f"found unacceptable key {key_node.value}", key_node.start_mark, ) value = self.construct_object(value_node, deep=deep) @@ -80,7 +79,7 @@ class SaltYamlSafeLoader(BaseLoader): raise ConstructorError( context, node.start_mark, - "found conflicting ID '{}'".format(key), + f"found conflicting ID '{key}'", key_node.start_mark, ) mapping[key] = value diff --git a/salt/utils/yamlloader_old.py b/salt/utils/yamlloader_old.py index d24717a79b2..ea483c197b2 100644 --- a/salt/utils/yamlloader_old.py +++ b/salt/utils/yamlloader_old.py @@ -2,7 +2,6 @@ Custom YAML loading in Salt """ - import re import yaml # pylint: disable=blacklisted-import @@ -61,7 +60,7 @@ class SaltYamlSafeLoader(yaml.SafeLoader): raise ConstructorError( None, None, - "expected a mapping node, but found {}".format(node.id), + f"expected a mapping node, but found {node.id}", node.start_mark, ) @@ -77,7 +76,7 @@ class SaltYamlSafeLoader(yaml.SafeLoader): raise ConstructorError( context, node.start_mark, - "found unacceptable key {}".format(key_node.value), + f"found unacceptable key {key_node.value}", key_node.start_mark, ) value = self.construct_object(value_node, deep=deep) @@ -85,7 +84,7 @@ class SaltYamlSafeLoader(yaml.SafeLoader): raise ConstructorError( context, node.start_mark, - "found conflicting ID '{}'".format(key), + f"found conflicting ID '{key}'", key_node.start_mark, ) mapping[key] = value diff --git a/salt/utils/zfs.py b/salt/utils/zfs.py index 6612302a072..52d5ede4ea0 100644 --- a/salt/utils/zfs.py +++ b/salt/utils/zfs.py @@ -12,7 +12,6 @@ These functions are for dealing with type conversion and basic execution """ - import logging import math import os diff --git a/salt/version.py b/salt/version.py index ee8a70e2bd3..82f1b6f3519 100644 --- a/salt/version.py +++ b/salt/version.py @@ -1,6 +1,7 @@ """ Set up the version of Salt """ + import argparse import operator import os @@ -686,7 +687,6 @@ def salt_information(): def package_information(): - """ Report package type """ diff --git a/salt/wheel/config.py b/salt/wheel/config.py index a5dfee0b602..10a62efda6e 100644 --- a/salt/wheel/config.py +++ b/salt/wheel/config.py @@ -86,6 +86,6 @@ def update_config(file_name, yaml_contents): with salt.utils.files.fopen(file_path, "w") as fp_: fp_.write(yaml_out) - return "Wrote {}".format(file_name) + return f"Wrote {file_name}" except (OSError, salt.utils.yaml.YAMLError, ValueError) as err: return str(err) diff --git a/salt/wheel/file_roots.py b/salt/wheel/file_roots.py index d29a82cbbba..bcc259eea0e 100644 --- a/salt/wheel/file_roots.py +++ b/salt/wheel/file_roots.py @@ -2,7 +2,6 @@ Read in files from the file_root and save files to the file root """ - import os import salt.utils.files diff --git a/salt/wheel/key.py b/salt/wheel/key.py index 66bee797220..76156b7e29e 100644 --- a/salt/wheel/key.py +++ b/salt/wheel/key.py @@ -26,7 +26,6 @@ The wheel key functions can also be called via a ``salt`` command at the CLI using the :mod:`saltutil execution module `. """ - import hashlib import logging import os diff --git a/salt/wheel/minions.py b/salt/wheel/minions.py index 75d06a94f02..65ac422f268 100644 --- a/salt/wheel/minions.py +++ b/salt/wheel/minions.py @@ -2,7 +2,6 @@ Wheel system wrapper for connected minions """ - import salt.config import salt.utils.minions from salt.utils.cache import CacheCli diff --git a/salt/wheel/pillar_roots.py b/salt/wheel/pillar_roots.py index 53078f9f9dd..fff560bf933 100644 --- a/salt/wheel/pillar_roots.py +++ b/salt/wheel/pillar_roots.py @@ -93,7 +93,7 @@ def write(data, path, saltenv="base", index=0): index of the file can be specified to write to a lower priority file root """ if saltenv not in __opts__["pillar_roots"]: - return "Named environment {} is not present".format(saltenv) + return f"Named environment {saltenv} is not present" if len(__opts__["pillar_roots"][saltenv]) <= index: return "Specified index {} in environment {} is not present".format( index, saltenv @@ -112,4 +112,4 @@ def write(data, path, saltenv="base", index=0): os.makedirs(dest_dir) with salt.utils.files.fopen(dest, "w+") as fp_: fp_.write(salt.utils.stringutils.to_str(data)) - return "Wrote data to file {}".format(dest) + return f"Wrote data to file {dest}" diff --git a/scripts/suse/yum/plugins/yumnotify.py b/scripts/suse/yum/plugins/yumnotify.py index 4e137191a00..18dfa5bb8ce 100644 --- a/scripts/suse/yum/plugins/yumnotify.py +++ b/scripts/suse/yum/plugins/yumnotify.py @@ -52,6 +52,4 @@ def posttrans_hook(conduit): # Integrate Yum with Salt if "SALT_RUNNING" not in os.environ: with open(CK_PATH, "w") as ck_fh: - ck_fh.write( - "{chksum} {mtime}\n".format(chksum=_get_checksum(), mtime=_get_mtime()) - ) + ck_fh.write(f"{_get_checksum()} {_get_mtime()}\n") diff --git a/tests/buildpackage.py b/tests/buildpackage.py index 108cd729a0b..fcd3c734752 100644 --- a/tests/buildpackage.py +++ b/tests/buildpackage.py @@ -133,7 +133,7 @@ def _init(): if not opts.platform: problems.append("Platform ('os' grain) required") if not os.path.isdir(opts.source_dir): - problems.append("Source directory {} not found".format(opts.source_dir)) + problems.append(f"Source directory {opts.source_dir} not found") try: shutil.rmtree(opts.build_dir) except OSError as exc: @@ -245,11 +245,11 @@ def build_centos(opts): "contents: '{}'".format(redhat_release) ) except OSError as exc: - _abort("{}".format(exc)) + _abort(f"{exc}") log.info("major_release: %s", major_release) - define_opts = ["--define", "_topdir {}".format(os.path.join(opts.build_dir))] + define_opts = ["--define", f"_topdir {os.path.join(opts.build_dir)}"] build_reqs = ["rpm-build"] if major_release == 5: python_bin = "python26" @@ -262,7 +262,7 @@ def build_centos(opts): elif major_release == 7: build_reqs.extend(["python-devel", "systemd-units"]) else: - _abort("Unsupported major release: {}".format(major_release)) + _abort(f"Unsupported major release: {major_release}") # Install build deps _run_command(["yum", "-y", "install"] + build_reqs) @@ -280,7 +280,7 @@ def build_centos(opts): try: base, offset, oid = tarball_re.match(os.path.basename(sdist)).groups() except AttributeError: - _abort("Unable to extract version info from sdist filename '{}'".format(sdist)) + _abort(f"Unable to extract version info from sdist filename '{sdist}'") if offset is None: salt_pkgver = salt_srcver = base @@ -299,7 +299,7 @@ def build_centos(opts): except OSError: pass if not os.path.isdir(path): - _abort("Unable to make directory: {}".format(path)) + _abort(f"Unable to make directory: {path}") # Get sources into place build_sources_path = os.path.join(opts.build_dir, "SOURCES") @@ -327,9 +327,9 @@ def build_centos(opts): with open(spec_path, "w") as fp_: for line in spec_lines: if line.startswith("%global srcver "): - line = "%global srcver {}".format(salt_srcver) + line = f"%global srcver {salt_srcver}" elif line.startswith("Version: "): - line = "Version: {}".format(salt_pkgver) + line = f"Version: {salt_pkgver}" fp_.write(line + "\n") # Do the thing @@ -346,15 +346,11 @@ def build_centos(opts): opts.build_dir, "RPMS", "noarch", - "salt-*{}*.noarch.rpm".format(salt_pkgver), + f"salt-*{salt_pkgver}*.noarch.rpm", ) ) packages.extend( - glob.glob( - os.path.join( - opts.build_dir, "SRPMS", "salt-{}*.src.rpm".format(salt_pkgver) - ) - ) + glob.glob(os.path.join(opts.build_dir, "SRPMS", f"salt-{salt_pkgver}*.src.rpm")) ) return packages @@ -393,9 +389,9 @@ if __name__ == "__main__": elif opts.platform.lower() == "centos": artifacts = build_centos(opts) else: - _abort("Unsupported platform '{}'".format(opts.platform)) + _abort(f"Unsupported platform '{opts.platform}'") - msg = "Build complete. Artifacts will be stored in {}".format(opts.artifact_dir) + msg = f"Build complete. Artifacts will be stored in {opts.artifact_dir}" log.info(msg) print(msg) # pylint: disable=C0325 for artifact in artifacts: diff --git a/tests/committer_parser.py b/tests/committer_parser.py index 8056b7fd406..914bc7c3dba 100644 --- a/tests/committer_parser.py +++ b/tests/committer_parser.py @@ -78,7 +78,7 @@ def parse_gitlog(filename=None): if len(line) < 2 and new_commit: new_commit = False - key = "{}-{}".format(d.year, str(d.month).zfill(2)) + key = f"{d.year}-{str(d.month).zfill(2)}" if key not in results: results[key] = [] @@ -108,15 +108,15 @@ def counts_by_contributor(commits_by_contributor, results): output = "" dates = sorted(results.keys()) for d in dates: - output += "\t{}".format(d) + output += f"\t{d}" output += "\n" for email in sorted(commits_by_contributor.keys()): - output += "'{}".format(email) + output += f"'{email}" for d in dates: if d in commits_by_contributor[email]: - output += "\t{}".format(commits_by_contributor[email][d]) + output += f"\t{commits_by_contributor[email][d]}" else: output += "\t" output += "\n" @@ -127,7 +127,7 @@ def count_results(results, commits): result_str = "" print("Date\tContributors\tCommits") for k in sorted(results.keys()): - result_str += "{}\t{}\t{}".format(k, len(results[k]), commits[k]) + result_str += f"{k}\t{len(results[k])}\t{commits[k]}" result_str += "\n" return result_str diff --git a/tests/conftest.py b/tests/conftest.py index b25db4172e8..fbcf2901e27 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -519,7 +519,9 @@ def pytest_collection_modifyitems(config, items): log.debug("Finish called on %s", self) try: return func(request) - except BaseException as exc: # pylint: disable=broad-except + except ( + BaseException # pylint: disable=broad-except + ) as exc: pytest.fail( "Failed to run finish() on {}: {}".format( fixturedef, exc diff --git a/tests/eventlisten.py b/tests/eventlisten.py index 8ff5ada8232..8016f93bb8b 100644 --- a/tests/eventlisten.py +++ b/tests/eventlisten.py @@ -5,7 +5,6 @@ what the sock_dir is. This script is a generic tool to test event output """ - import optparse import os import pprint @@ -135,7 +134,7 @@ def listen(opts): ) continue else: - print("Event fired at {}".format(time.asctime())) + print(f"Event fired at {time.asctime()}") print("*" * 25) print("Tag: {}".format(ret["tag"])) print("Data:") diff --git a/tests/integration/cloud/clouds/test_digitalocean.py b/tests/integration/cloud/clouds/test_digitalocean.py index c0f98e39233..8f10ad0c305 100644 --- a/tests/integration/cloud/clouds/test_digitalocean.py +++ b/tests/integration/cloud/clouds/test_digitalocean.py @@ -1,6 +1,7 @@ """ Integration tests for DigitalOcean APIv2 """ + import base64 import hashlib diff --git a/tests/integration/cloud/clouds/test_dimensiondata.py b/tests/integration/cloud/clouds/test_dimensiondata.py index 56ac83042c3..5aba20bed74 100644 --- a/tests/integration/cloud/clouds/test_dimensiondata.py +++ b/tests/integration/cloud/clouds/test_dimensiondata.py @@ -2,7 +2,6 @@ Integration tests for the Dimension Data cloud provider """ - from tests.integration.cloud.helpers.cloud_test_base import TIMEOUT, CloudTest @@ -18,14 +17,14 @@ class DimensionDataTest(CloudTest): """ Tests the return of running the --list-images command for the dimensiondata cloud provider """ - image_list = self.run_cloud("--list-images {}".format(self.PROVIDER)) + image_list = self.run_cloud(f"--list-images {self.PROVIDER}") self.assertIn("Ubuntu 14.04 2 CPU", [i.strip() for i in image_list]) def test_list_locations(self): """ Tests the return of running the --list-locations command for the dimensiondata cloud provider """ - _list_locations = self.run_cloud("--list-locations {}".format(self.PROVIDER)) + _list_locations = self.run_cloud(f"--list-locations {self.PROVIDER}") self.assertIn( "Australia - Melbourne MCP2", [i.strip() for i in _list_locations] ) @@ -34,7 +33,7 @@ class DimensionDataTest(CloudTest): """ Tests the return of running the --list-sizes command for the dimensiondata cloud provider """ - _list_sizes = self.run_cloud("--list-sizes {}".format(self.PROVIDER)) + _list_sizes = self.run_cloud(f"--list-sizes {self.PROVIDER}") self.assertIn("default", [i.strip() for i in _list_sizes]) def test_instance(self): @@ -43,7 +42,7 @@ class DimensionDataTest(CloudTest): """ # check if instance with salt installed returned ret_val = self.run_cloud( - "-p dimensiondata-test {}".format(self.instance_name), timeout=TIMEOUT + f"-p dimensiondata-test {self.instance_name}", timeout=TIMEOUT ) self.assertInstanceExists(ret_val) diff --git a/tests/integration/cloud/clouds/test_ec2.py b/tests/integration/cloud/clouds/test_ec2.py index c3c3da8484e..3713a365ab3 100644 --- a/tests/integration/cloud/clouds/test_ec2.py +++ b/tests/integration/cloud/clouds/test_ec2.py @@ -1,6 +1,7 @@ """ :codeauthor: Nicole Thomas """ + import os import pytest @@ -61,7 +62,7 @@ class EC2Test(CloudTest): if not group_or_subnet: self.skipTest( - "securitygroup or subnetid missing for {} config".format(self.PROVIDER) + f"securitygroup or subnetid missing for {self.PROVIDER} config" ) super().setUp() @@ -117,7 +118,7 @@ class EC2Test(CloudTest): """ # create the instance ret_val = self.run_cloud( - "-p ec2-test {} --no-deploy".format(self.instance_name), timeout=TIMEOUT + f"-p ec2-test {self.instance_name} --no-deploy", timeout=TIMEOUT ) # check if instance returned self.assertInstanceExists(ret_val) @@ -132,7 +133,7 @@ class EC2Test(CloudTest): ) self.assertFalse( self._instance_exists(), - "Instance wasn't renamed: |\n{}".format(rename_result), + f"Instance wasn't renamed: |\n{rename_result}", ) self.assertInstanceExists(instance_name=changed_name) diff --git a/tests/integration/cloud/clouds/test_gce.py b/tests/integration/cloud/clouds/test_gce.py index affa0134fc5..e8bd45d4efa 100644 --- a/tests/integration/cloud/clouds/test_gce.py +++ b/tests/integration/cloud/clouds/test_gce.py @@ -3,7 +3,6 @@ :codeauthor: Tomas Sirny """ - from tests.integration.cloud.helpers.cloud_test_base import TIMEOUT, CloudTest @@ -25,9 +24,7 @@ class GCETest(CloudTest): """ # create the instance - ret_str = self.run_cloud( - "-p gce-test {}".format(self.instance_name), timeout=TIMEOUT - ) + ret_str = self.run_cloud(f"-p gce-test {self.instance_name}", timeout=TIMEOUT) # check if instance returned with salt installed self.assertInstanceExists(ret_str) @@ -40,7 +37,7 @@ class GCETest(CloudTest): # create the instance ret_str = self.run_cloud( - "-p gce-test-extra {}".format(self.instance_name), timeout=TIMEOUT + f"-p gce-test-extra {self.instance_name}", timeout=TIMEOUT ) # check if instance returned with salt installed diff --git a/tests/integration/cloud/clouds/test_gogrid.py b/tests/integration/cloud/clouds/test_gogrid.py index 4943839f46b..f45d3891d90 100644 --- a/tests/integration/cloud/clouds/test_gogrid.py +++ b/tests/integration/cloud/clouds/test_gogrid.py @@ -22,7 +22,7 @@ class GoGridTest(CloudTest): """ # check if instance with salt installed returned ret_str = self.run_cloud( - "-p gogrid-test {}".format(self.instance_name), timeout=TIMEOUT + f"-p gogrid-test {self.instance_name}", timeout=TIMEOUT ) self.assertInstanceExists(ret_str) diff --git a/tests/integration/cloud/clouds/test_oneandone.py b/tests/integration/cloud/clouds/test_oneandone.py index 632f2b871d3..d0f5e30ee9f 100644 --- a/tests/integration/cloud/clouds/test_oneandone.py +++ b/tests/integration/cloud/clouds/test_oneandone.py @@ -1,6 +1,7 @@ """ :codeauthor: :email:`Amel Ajdinovic ` """ + import pytest from tests.integration.cloud.helpers.cloud_test_base import TIMEOUT, CloudTest @@ -26,7 +27,7 @@ class OneAndOneTest(CloudTest): """ Tests the return of running the --list-images command for 1and1 """ - image_list = self.run_cloud("--list-images {}".format(self.PROVIDER_NAME)) + image_list = self.run_cloud(f"--list-images {self.PROVIDER_NAME}") self.assertIn("coreOSimage", [i.strip() for i in image_list]) def test_instance(self): @@ -35,7 +36,7 @@ class OneAndOneTest(CloudTest): """ # check if instance with salt installed returned ret_str = self.run_cloud( - "-p oneandone-test {}".format(self.instance_name), timeout=TIMEOUT + f"-p oneandone-test {self.instance_name}", timeout=TIMEOUT ) self.assertInstanceExists(ret_str) diff --git a/tests/integration/cloud/clouds/test_openstack.py b/tests/integration/cloud/clouds/test_openstack.py index bc76184f16d..c0f7a4df720 100644 --- a/tests/integration/cloud/clouds/test_openstack.py +++ b/tests/integration/cloud/clouds/test_openstack.py @@ -219,7 +219,7 @@ class RackspaceTest(CloudTest): """ # check if instance with salt installed returned ret_val = self.run_cloud( - "-p rackspace-test {}".format(self.instance_name), timeout=TIMEOUT + f"-p rackspace-test {self.instance_name}", timeout=TIMEOUT ) self.assertInstanceExists(ret_val) diff --git a/tests/integration/cloud/clouds/test_profitbricks.py b/tests/integration/cloud/clouds/test_profitbricks.py index 0428b40c260..f8f4e1c744f 100644 --- a/tests/integration/cloud/clouds/test_profitbricks.py +++ b/tests/integration/cloud/clouds/test_profitbricks.py @@ -1,6 +1,7 @@ """ :codeauthor: Ethan Devenport """ + import pytest from tests.integration.cloud.helpers.cloud_test_base import TIMEOUT, CloudTest @@ -45,7 +46,7 @@ class ProfitBricksTest(CloudTest): """ Tests the return of running the --list-images command for ProfitBricks """ - list_images = self.run_cloud("--list-images {}".format(self.PROVIDER)) + list_images = self.run_cloud(f"--list-images {self.PROVIDER}") self.assertIn( "Ubuntu-16.04-LTS-server-2017-10-01", [i.strip() for i in list_images] ) @@ -55,7 +56,7 @@ class ProfitBricksTest(CloudTest): Tests the return of running the -f list_images command for ProfitBricks """ - cmd = "-f list_images {}".format(self.PROVIDER) + cmd = f"-f list_images {self.PROVIDER}" list_images = self.run_cloud(cmd) self.assertIn("- ubuntu:latest", [i.strip() for i in list_images]) @@ -63,7 +64,7 @@ class ProfitBricksTest(CloudTest): """ Tests the return of running the --list_sizes command for ProfitBricks """ - list_sizes = self.run_cloud("--list-sizes {}".format(self.PROVIDER)) + list_sizes = self.run_cloud(f"--list-sizes {self.PROVIDER}") self.assertIn("Micro Instance:", [i.strip() for i in list_sizes]) def test_list_datacenters(self): @@ -71,7 +72,7 @@ class ProfitBricksTest(CloudTest): Tests the return of running the -f list_datacenters command for ProfitBricks """ - cmd = "-f list_datacenters {}".format(self.PROVIDER) + cmd = f"-f list_datacenters {self.PROVIDER}" list_datacenters = self.run_cloud(cmd) self.assertIn( self.provider_config["datacenter_id"], [i.strip() for i in list_datacenters] @@ -81,7 +82,7 @@ class ProfitBricksTest(CloudTest): """ Tests the return of running the -f list_nodes command for ProfitBricks """ - list_nodes = self.run_cloud("-f list_nodes {}".format(self.PROVIDER)) + list_nodes = self.run_cloud(f"-f list_nodes {self.PROVIDER}") self.assertIn("state:", [i.strip() for i in list_nodes]) self.assertIn("name:", [i.strip() for i in list_nodes]) @@ -91,7 +92,7 @@ class ProfitBricksTest(CloudTest): Tests the return of running the -f list_nodes_full command for ProfitBricks """ - cmd = "-f list_nodes_full {}".format(self.PROVIDER) + cmd = f"-f list_nodes_full {self.PROVIDER}" list_nodes = self.run_cloud(cmd) self.assertIn("state:", [i.strip() for i in list_nodes]) @@ -102,7 +103,7 @@ class ProfitBricksTest(CloudTest): Tests the return of running the --list-locations command for ProfitBricks """ - cmd = "--list-locations {}".format(self.PROVIDER) + cmd = f"--list-locations {self.PROVIDER}" list_locations = self.run_cloud(cmd) self.assertIn("de/fkb", [i.strip() for i in list_locations]) @@ -119,7 +120,7 @@ class ProfitBricksTest(CloudTest): """ # check if instance with salt installed returned ret_str = self.run_cloud( - "-p profitbricks-test {}".format(self.instance_name), timeout=TIMEOUT + f"-p profitbricks-test {self.instance_name}", timeout=TIMEOUT ) self.assertInstanceExists(ret_str) diff --git a/tests/integration/cloud/clouds/test_tencentcloud.py b/tests/integration/cloud/clouds/test_tencentcloud.py index ce995c44ff1..85bac333b57 100644 --- a/tests/integration/cloud/clouds/test_tencentcloud.py +++ b/tests/integration/cloud/clouds/test_tencentcloud.py @@ -68,12 +68,12 @@ class TencentCloudTest(ShellCase): [ i.strip() for i in self.run_cloud( - "-p tencentcloud-test {}".format(INSTANCE_NAME), timeout=500 + f"-p tencentcloud-test {INSTANCE_NAME}", timeout=500 ) ], ) except AssertionError: - self.run_cloud("-d {} --assume-yes".format(INSTANCE_NAME), timeout=500) + self.run_cloud(f"-d {INSTANCE_NAME} --assume-yes", timeout=500) raise # delete the instance @@ -81,9 +81,7 @@ class TencentCloudTest(ShellCase): INSTANCE_NAME + ":", [ i.strip() - for i in self.run_cloud( - "-d {} --assume-yes".format(INSTANCE_NAME), timeout=500 - ) + for i in self.run_cloud(f"-d {INSTANCE_NAME} --assume-yes", timeout=500) ], ) @@ -92,8 +90,8 @@ class TencentCloudTest(ShellCase): Clean up after tests """ query = self.run_cloud("--query") - ret_str = " {}:".format(INSTANCE_NAME) + ret_str = f" {INSTANCE_NAME}:" # if test instance is still present, delete it if ret_str in query: - self.run_cloud("-d {} --assume-yes".format(INSTANCE_NAME), timeout=500) + self.run_cloud(f"-d {INSTANCE_NAME} --assume-yes", timeout=500) diff --git a/tests/integration/cloud/clouds/test_virtualbox.py b/tests/integration/cloud/clouds/test_virtualbox.py index ad69aa249c2..8b3d8b26dfb 100644 --- a/tests/integration/cloud/clouds/test_virtualbox.py +++ b/tests/integration/cloud/clouds/test_virtualbox.py @@ -63,9 +63,7 @@ class VirtualboxProviderTest(VirtualboxCloudTestCase): @return: @rtype: dict """ - output = self.run_cloud( - "-d {} --assume-yes --log-level=debug".format(machine_name) - ) + output = self.run_cloud(f"-d {machine_name} --assume-yes --log-level=debug") return output.get(CONFIG_NAME, {}).get(PROVIDER_NAME, {}) def setUp(self): @@ -130,7 +128,7 @@ class VirtualboxProviderTest(VirtualboxCloudTestCase): Simply create a machine and make sure it was created """ machines = self.run_cloud( - "-p {} {} --log-level=debug".format(PROFILE_NAME, INSTANCE_NAME) + f"-p {PROFILE_NAME} {INSTANCE_NAME} --log-level=debug" ) self.assertIn(INSTANCE_NAME, machines.keys()) @@ -231,7 +229,7 @@ class VirtualboxProviderHeavyTests(VirtualboxCloudTestCase): try: socket.inet_pton(socket.AF_INET6, ip_str) except Exception: # pylint: disable=broad-except - self.fail("{} is not a valid IP address".format(ip_str)) + self.fail(f"{ip_str} is not a valid IP address") def setUp(self): """ @@ -295,7 +293,7 @@ class VirtualboxProviderHeavyTests(VirtualboxCloudTestCase): def test_deploy(self): machines = self.run_cloud( - "-p {} {} --log-level=debug".format(DEPLOY_PROFILE_NAME, INSTANCE_NAME) + f"-p {DEPLOY_PROFILE_NAME} {INSTANCE_NAME} --log-level=debug" ) self.assertIn(INSTANCE_NAME, machines.keys()) machine = machines[INSTANCE_NAME] diff --git a/tests/integration/cloud/clouds/test_vmware.py b/tests/integration/cloud/clouds/test_vmware.py index 1e82566fc21..b997951c330 100644 --- a/tests/integration/cloud/clouds/test_vmware.py +++ b/tests/integration/cloud/clouds/test_vmware.py @@ -39,7 +39,7 @@ class VMWareTest(CloudTest): ] ret_val = self.run_cloud( - "-p vmware-test {}".format(self.instance_name), timeout=TIMEOUT + f"-p vmware-test {self.instance_name}", timeout=TIMEOUT ) disk_datastore_str = " [{}] {}/Hard disk 2-flat.vmdk".format( disk_datastore, self.instance_name @@ -50,7 +50,7 @@ class VMWareTest(CloudTest): self.assertIn( disk_datastore_str, ret_val, - msg="Hard Disk 2 did not use the Datastore {} ".format(disk_datastore), + msg=f"Hard Disk 2 did not use the Datastore {disk_datastore} ", ) self.assertDestroyInstance() @@ -61,7 +61,7 @@ class VMWareTest(CloudTest): """ # create the instance ret_val = self.run_cloud( - "-p vmware-test {} --no-deploy".format(self.instance_name), timeout=TIMEOUT + f"-p vmware-test {self.instance_name} --no-deploy", timeout=TIMEOUT ) # check if instance returned with salt installed @@ -90,7 +90,7 @@ class VMWareTest(CloudTest): ) # create the instance ret_val = self.run_cloud( - "-p {} {}".format(profile_name, self.instance_name), timeout=TIMEOUT + f"-p {profile_name} {self.instance_name}", timeout=TIMEOUT ) # check if instance returned with salt installed self.assertInstanceExists(ret_val) @@ -109,7 +109,7 @@ class VMWareTest(CloudTest): handler = TstSuiteLoggingHandler(format=log_format, level=logging.INFO) with handler: ret_val = self.run_cloud( - "-p {} {}".format(profile_name, self.instance_name), timeout=TIMEOUT + f"-p {profile_name} {self.instance_name}", timeout=TIMEOUT ) # This sometimes times out before it get's an IP, so we check the logs if ret_val == []: diff --git a/tests/integration/cloud/clouds/test_vultrpy.py b/tests/integration/cloud/clouds/test_vultrpy.py index a25b4502dae..fb81d427bd7 100644 --- a/tests/integration/cloud/clouds/test_vultrpy.py +++ b/tests/integration/cloud/clouds/test_vultrpy.py @@ -17,7 +17,7 @@ class VultrTest(CloudTest): """ Tests the return of running the --list-images command for Vultr """ - image_list = self.run_cloud("--list-images {}".format(self.PROVIDER)) + image_list = self.run_cloud(f"--list-images {self.PROVIDER}") self.assertIn("Debian 10 x64 (buster)", [i.strip() for i in image_list]) @@ -25,14 +25,14 @@ class VultrTest(CloudTest): """ Tests the return of running the --list-locations command for Vultr """ - location_list = self.run_cloud("--list-locations {}".format(self.PROVIDER)) + location_list = self.run_cloud(f"--list-locations {self.PROVIDER}") self.assertIn("New Jersey", [i.strip() for i in location_list]) def test_list_sizes(self): """ Tests the return of running the --list-sizes command for Vultr """ - size_list = self.run_cloud("--list-sizes {}".format(self.PROVIDER)) + size_list = self.run_cloud(f"--list-sizes {self.PROVIDER}") self.assertIn( "2048 MB RAM,55 GB SSD,2.00 TB BW", [i.strip() for i in size_list] ) @@ -84,7 +84,7 @@ class VultrTest(CloudTest): """ # check if instance with salt installed returned ret_val = self.run_cloud( - "-p vultr-test {}".format(self.instance_name), timeout=TIMEOUT + 300 + f"-p vultr-test {self.instance_name}", timeout=TIMEOUT + 300 ) self.assertInstanceExists(ret_val) diff --git a/tests/integration/cloud/helpers/cloud_test_base.py b/tests/integration/cloud/helpers/cloud_test_base.py index 48e44a6f0fa..2848db25ed0 100644 --- a/tests/integration/cloud/helpers/cloud_test_base.py +++ b/tests/integration/cloud/helpers/cloud_test_base.py @@ -2,7 +2,6 @@ Tests for the Openstack Cloud Provider """ - import logging import os import shutil @@ -116,7 +115,7 @@ class CloudTest(ShellCase): instance_name = self.instance_name log.debug('Deleting instance "%s"', instance_name) delete_str = self.run_cloud( - "-d {} --assume-yes --out=yaml".format(instance_name), timeout=timeout + f"-d {instance_name} --assume-yes --out=yaml", timeout=timeout ) if delete_str: delete = safe_load("\n".join(delete_str)) @@ -160,7 +159,7 @@ class CloudTest(ShellCase): subclass = self.__class__.__name__.strip("Test") # Use the first three letters of the subclass, fill with '-' if too short self._instance_name = random_string( - "cloud-test-{:-<3}-".format(subclass[:3]), uppercase=False + f"cloud-test-{subclass[:3]:-<3}-", uppercase=False ).lower() return self._instance_name diff --git a/tests/integration/cloud/helpers/virtualbox.py b/tests/integration/cloud/helpers/virtualbox.py index 202ad639b75..8efcea0f84c 100644 --- a/tests/integration/cloud/helpers/virtualbox.py +++ b/tests/integration/cloud/helpers/virtualbox.py @@ -59,7 +59,7 @@ class VirtualboxCloudTestCase(ShellCase): @return: @rtype: dict """ - arg_str = "--out=json {}".format(arg_str) + arg_str = f"--out=json {arg_str}" log.debug("running salt-cloud with %s", arg_str) output = self.run_script( "salt-cloud", arg_str, catch_stderr, timeout=timeout, config_dir=config_dir @@ -97,9 +97,7 @@ class VirtualboxCloudTestCase(ShellCase): args = [] # Args converted in the form of key1='value1' ... keyN='valueN' if kw_function_args: - args = [ - "{}='{}'".format(key, value) for key, value in kw_function_args.items() - ] + args = [f"{key}='{value}'" for key, value in kw_function_args.items()] output = self.run_cloud( "-f {} {} {}".format(function, CONFIG_NAME, " ".join(args)), **kwargs @@ -118,7 +116,5 @@ class VirtualboxCloudTestCase(ShellCase): @rtype: dict """ - output = self.run_cloud( - "-a {} {} --assume-yes".format(action, instance_name), **kwargs - ) + output = self.run_cloud(f"-a {action} {instance_name} --assume-yes", **kwargs) return output.get(CONFIG_NAME, {}).get(PROVIDER_NAME, {}) diff --git a/tests/integration/cloud/test_cloud.py b/tests/integration/cloud/test_cloud.py index 29bd820da7b..960ed317539 100644 --- a/tests/integration/cloud/test_cloud.py +++ b/tests/integration/cloud/test_cloud.py @@ -1,6 +1,7 @@ """ Integration tests for functions located in the salt.cloud.__init__.py file. """ + import pytest import salt.cloud @@ -23,7 +24,7 @@ class CloudClientTestCase(CloudTest): # Use a --list-images salt-cloud call to see if the DigitalOcean provider is # configured correctly before running any tests. - images = self.run_cloud("--list-images {}".format(self.PROVIDER)) + images = self.run_cloud(f"--list-images {self.PROVIDER}") if self.image_name not in [i.strip() for i in images]: self.skipTest( diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 1e1baf6134a..13ded49f4a6 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -4,6 +4,7 @@ Integration tests PyTest configuration/fixtures """ + import logging import pathlib diff --git a/tests/integration/files/extension_modules/pillar/ext_pillar_opts.py b/tests/integration/files/extension_modules/pillar/ext_pillar_opts.py index 19d4d4e9420..37d8e0d2450 100644 --- a/tests/integration/files/extension_modules/pillar/ext_pillar_opts.py +++ b/tests/integration/files/extension_modules/pillar/ext_pillar_opts.py @@ -6,7 +6,6 @@ Returns a hash of the name of the pillar module as defined in _virtual__ with the value __opts__ """ - import logging # Set up logging diff --git a/tests/integration/files/file/base/_modules/runtests_decorators.py b/tests/integration/files/file/base/_modules/runtests_decorators.py index a005b32a1bc..0365a0b655e 100644 --- a/tests/integration/files/file/base/_modules/runtests_decorators.py +++ b/tests/integration/files/file/base/_modules/runtests_decorators.py @@ -15,9 +15,9 @@ EXIT_CODE_CMD = STATE_BASE_DIR / "exit_code.cmd" def _exit_code(code): if os.name == "nt": - cmd = "cmd /c {} {}".format(EXIT_CODE_CMD, code) + cmd = f"cmd /c {EXIT_CODE_CMD} {code}" else: - cmd = "/usr/bin/env sh {} {}".format(EXIT_CODE_SH, code) + cmd = f"/usr/bin/env sh {EXIT_CODE_SH} {code}" return cmd diff --git a/tests/integration/files/file/base/_modules/runtests_helpers.py b/tests/integration/files/file/base/_modules/runtests_helpers.py index 3ee0e2da5f3..a38dd1835cf 100644 --- a/tests/integration/files/file/base/_modules/runtests_helpers.py +++ b/tests/integration/files/file/base/_modules/runtests_helpers.py @@ -6,7 +6,6 @@ ~~~~~~~~~~~~~~~~~~~ """ - import logging import os import sys diff --git a/tests/integration/files/file/base/buildout/var/tb/2/bootstrap.py b/tests/integration/files/file/base/buildout/var/tb/2/bootstrap.py index 257cc5642cb..b8ba90e4d14 100644 --- a/tests/integration/files/file/base/buildout/var/tb/2/bootstrap.py +++ b/tests/integration/files/file/base/buildout/var/tb/2/bootstrap.py @@ -1 +1,2 @@ +# pylint: skip-file foo diff --git a/tests/integration/files/returners/noop_returner.py b/tests/integration/files/returners/noop_returner.py index 0201e5076b9..c6a34f975c2 100644 --- a/tests/integration/files/returners/noop_returner.py +++ b/tests/integration/files/returners/noop_returner.py @@ -5,7 +5,6 @@ noop_returner A returner that does nothing which is used to test the salt-master `event_return` functionality """ - import logging import salt.utils.jid diff --git a/tests/integration/grains/test_core.py b/tests/integration/grains/test_core.py index e45836e4ad2..59b84456938 100644 --- a/tests/integration/grains/test_core.py +++ b/tests/integration/grains/test_core.py @@ -1,6 +1,7 @@ """ Test the core grains """ + import pytest import salt.loader diff --git a/tests/integration/grains/test_custom.py b/tests/integration/grains/test_custom.py index 17a09a4797e..d99e88d1902 100644 --- a/tests/integration/grains/test_custom.py +++ b/tests/integration/grains/test_custom.py @@ -2,7 +2,6 @@ Test the core grains """ - import pytest from tests.support.case import ModuleCase diff --git a/tests/integration/loader/test_ext_grains.py b/tests/integration/loader/test_ext_grains.py index af98e544f65..242519aa3f4 100644 --- a/tests/integration/loader/test_ext_grains.py +++ b/tests/integration/loader/test_ext_grains.py @@ -5,7 +5,6 @@ Test Salt's loader regarding external grains """ - import os import time diff --git a/tests/integration/minion/test_timeout.py b/tests/integration/minion/test_timeout.py index 8ceb66c4a5d..ccb3bf76a92 100644 --- a/tests/integration/minion/test_timeout.py +++ b/tests/integration/minion/test_timeout.py @@ -2,7 +2,6 @@ Tests for various minion timeouts """ - import os import sys @@ -31,16 +30,16 @@ class MinionTimeoutTestCase(ShellCase): else: popen_kwargs = None ret = self.run_salt( - "minion test.sleep {}".format(sleep_length), + f"minion test.sleep {sleep_length}", timeout=90, catch_stderr=True, popen_kwargs=popen_kwargs, ) self.assertTrue( isinstance(ret[0], list), - "Return is not a list. Minion may have returned error: {}".format(ret), + f"Return is not a list. Minion may have returned error: {ret}", ) - self.assertEqual(len(ret[0]), 2, "Standard out wrong length {}".format(ret)) + self.assertEqual(len(ret[0]), 2, f"Standard out wrong length {ret}") self.assertTrue( "True" in ret[0][1], "Minion did not return True after {} seconds. ret={}".format( diff --git a/tests/integration/modules/test_boto_iam.py b/tests/integration/modules/test_boto_iam.py index 01f15d76edd..667395083b6 100644 --- a/tests/integration/modules/test_boto_iam.py +++ b/tests/integration/modules/test_boto_iam.py @@ -1,6 +1,7 @@ """ Validate the boto_iam module """ + import pytest from tests.support.case import ModuleCase diff --git a/tests/integration/modules/test_boto_sns.py b/tests/integration/modules/test_boto_sns.py index fd4313a3344..52125593715 100644 --- a/tests/integration/modules/test_boto_sns.py +++ b/tests/integration/modules/test_boto_sns.py @@ -1,6 +1,7 @@ """ Validate the boto_sns module """ + import re import pytest @@ -99,7 +100,7 @@ class BotoSNSTest(ModuleCase): ) def _get_arn(self, name): - return "arn:aws:sns:us-east-1:{}:{}".format(self.account_id, name) + return f"arn:aws:sns:us-east-1:{self.account_id}:{name}" @property def account_id(self): diff --git a/tests/integration/modules/test_cmdmod.py b/tests/integration/modules/test_cmdmod.py index 800111174f0..c13d31b527b 100644 --- a/tests/integration/modules/test_cmdmod.py +++ b/tests/integration/modules/test_cmdmod.py @@ -56,7 +56,7 @@ class CMDModuleTest(ModuleCase): self.assertTrue(self.run_function("cmd.run", ["echo $SHELL"])) self.assertEqual( self.run_function( - "cmd.run", ["echo $SHELL", "shell={}".format(shell)], python_shell=True + "cmd.run", ["echo $SHELL", f"shell={shell}"], python_shell=True ).rstrip(), shell, ) @@ -108,7 +108,7 @@ class CMDModuleTest(ModuleCase): self.assertEqual( self.run_function( "cmd.run_stderr", - ['echo "cheese" 1>&2', "shell={}".format(shell)], + ['echo "cheese" 1>&2', f"shell={shell}"], python_shell=True, ).rstrip(), "cheese" if not salt.utils.platform.is_windows() else '"cheese"', @@ -126,7 +126,7 @@ class CMDModuleTest(ModuleCase): ret = self.run_function( "cmd.run_all", - ['echo "cheese" 1>&2', "shell={}".format(shell)], + ['echo "cheese" 1>&2', f"shell={shell}"], python_shell=True, ) self.assertTrue("pid" in ret) @@ -194,7 +194,7 @@ class CMDModuleTest(ModuleCase): expected_stderr = "No such file or directory" ret = self.run_function( "cmd.run_all", - ["{} {}".format(func, random_file)], + [f"{func} {random_file}"], success_stderr=[expected_stderr], python_shell=True, ) @@ -394,7 +394,7 @@ class CMDModuleTest(ModuleCase): result = self.run_function( "cmd.run_all", [cmd], runas=RUNTIME_VARS.RUNNING_TESTS_USER ) - errmsg = "The command returned: {}".format(result) + errmsg = f"The command returned: {result}" self.assertEqual(result["retcode"], 0, errmsg) self.assertEqual(result["stdout"], expected_result, errmsg) @@ -505,7 +505,7 @@ class CMDModuleTest(ModuleCase): out = self.run_function( "cmd.run", ["env"], runas=self.runas_usr ).splitlines() - self.assertIn("USER={}".format(self.runas_usr), out) + self.assertIn(f"USER={self.runas_usr}", out) @pytest.mark.skip_if_binaries_missing("sleep", reason="sleep cmd not installed") def test_timeout(self): diff --git a/tests/integration/modules/test_git.py b/tests/integration/modules/test_git.py index f0d26a59a92..8bc2eee57f3 100644 --- a/tests/integration/modules/test_git.py +++ b/tests/integration/modules/test_git.py @@ -38,7 +38,7 @@ def _git_version(): stdout=subprocess.PIPE, check=False, shell=False, - universal_newlines=True, + text=True, ) # On macOS, the git version is displayed in a different format # git version 2.21.1 (Apple Git-122.3) @@ -81,9 +81,7 @@ class GitModuleTest(ModuleCase): dir_path.mkdir(parents=True, exist_ok=True) for filename in self.files: with salt.utils.files.fopen(str(dir_path / filename), "wb") as fp_: - fp_.write( - "This is a test file named {}.".format(filename).encode("utf-8") - ) + fp_.write(f"This is a test file named {filename}.".encode()) # Navigate to the root of the repo to init, stage, and commit with pytest.helpers.change_cwd(self.repo): # Initialize a new git repository @@ -152,13 +150,9 @@ class GitModuleTest(ModuleCase): files_relpath = [os.path.join(newdir, x) for x in self.files] for path in files: with salt.utils.files.fopen(path, "wb") as fp_: - fp_.write( - "This is a test file with relative path {}.\n".format(path).encode( - "utf-8" - ) - ) + fp_.write(f"This is a test file with relative path {path}.\n".encode()) ret = self.run_function("git.add", [self.repo, newdir]) - res = "\n".join(sorted("add '{}'".format(x) for x in files_relpath)) + res = "\n".join(sorted(f"add '{x}'" for x in files_relpath)) if salt.utils.platform.is_windows(): res = res.replace("\\", "/") self.assertEqual(ret, res) @@ -173,11 +167,11 @@ class GitModuleTest(ModuleCase): with salt.utils.files.fopen(file_path, "w") as fp_: fp_.write( salt.utils.stringutils.to_str( - "This is a test file named {}.\n".format(filename) + f"This is a test file named {filename}.\n" ) ) ret = self.run_function("git.add", [self.repo, filename]) - self.assertEqual(ret, "add '{}'".format(filename)) + self.assertEqual(ret, f"add '{filename}'") @pytest.mark.slow_test def test_archive(self): @@ -411,7 +405,7 @@ class GitModuleTest(ModuleCase): "git.config_set", ["foo.single"], value=cfg_global["foo.single"][0], - **{"global": True} + **{"global": True}, ), cfg_global["foo.single"], ) @@ -431,7 +425,7 @@ class GitModuleTest(ModuleCase): "git.config_set", ["foo.multi"], multivar=cfg_global["foo.multi"], - **{"global": True} + **{"global": True}, ), cfg_global["foo.multi"], ) @@ -482,7 +476,7 @@ class GitModuleTest(ModuleCase): "git.config_get_regexp", ["foo.(single|multi)"], cwd=self.repo, - **{"global": True} + **{"global": True}, ), cfg_global, ) @@ -503,7 +497,7 @@ class GitModuleTest(ModuleCase): ["foo.multi"], value_regex="a", cwd=self.repo, - **{"global": True} + **{"global": True}, ), {"foo.multi": [x for x in cfg_global["foo.multi"] if "a" in x]}, ) @@ -586,7 +580,7 @@ class GitModuleTest(ModuleCase): else: self.assertEqual( self.run_function("git.init", [new_repo]).lower(), - "Initialized empty Git repository in {}/.git/".format(new_repo).lower(), + f"Initialized empty Git repository in {new_repo}/.git/".lower(), ) shutil.rmtree(new_repo) @@ -840,7 +834,7 @@ class GitModuleTest(ModuleCase): with salt.utils.files.fopen(os.path.join(self.repo, filename), "w") as fp_: fp_.write( salt.utils.stringutils.to_str( - "This is a new file named {}.".format(filename) + f"This is a new file named {filename}." ) ) # Stage the new file so it shows up as a 'new' file @@ -853,7 +847,7 @@ class GitModuleTest(ModuleCase): with salt.utils.files.fopen(os.path.join(self.repo, filename), "w") as fp_: fp_.write( salt.utils.stringutils.to_str( - "This is a new file named {}.".format(filename) + f"This is a new file named {filename}." ) ) self.assertEqual(self.run_function("git.status", [self.repo]), changes) diff --git a/tests/integration/modules/test_groupadd.py b/tests/integration/modules/test_groupadd.py index 58c1c88e204..60ae68e5d20 100644 --- a/tests/integration/modules/test_groupadd.py +++ b/tests/integration/modules/test_groupadd.py @@ -217,7 +217,7 @@ class GroupModuleTest(ModuleCase): self.run_function("group.add", [self._group], gid=self._gid) self.run_function("user.add", [self._user]) self.run_function("user.add", [self._user1]) - m = "{},{}".format(self._user, self._user1) + m = f"{self._user},{self._user1}" ret = self.run_function("group.members", [self._group, m]) self.assertTrue(ret) group_info = self.run_function("group.info", [self._group]) diff --git a/tests/integration/modules/test_linux_shadow.py b/tests/integration/modules/test_linux_shadow.py index aaea75d8e45..c922cb2f618 100644 --- a/tests/integration/modules/test_linux_shadow.py +++ b/tests/integration/modules/test_linux_shadow.py @@ -27,7 +27,7 @@ class ShadowModuleTest(ModuleCase): """ self._password = self.run_function("shadow.gen_password", ["Password1234"]) if "ERROR" in self._password: - self.fail("Failed to generate password: {}".format(self._password)) + self.fail(f"Failed to generate password: {self._password}") super().setUp() self._no_user = random_string("tu-", uppercase=False) self._test_user = random_string("tu-", uppercase=False) diff --git a/tests/integration/modules/test_lxc.py b/tests/integration/modules/test_lxc.py index b2f9b7945da..08f8cd3c14a 100644 --- a/tests/integration/modules/test_lxc.py +++ b/tests/integration/modules/test_lxc.py @@ -90,11 +90,11 @@ class LXCModuleTest(ModuleCase): start=False, ) - f = "/var/lib/lxc/{}/config".format(self.prefix) + f = f"/var/lib/lxc/{self.prefix}/config" conf = self.run_function("lxc.read_conf", [f]) # Due to a segfault in lxc-destroy caused by invalid configs, # truncate the config. - self.run_function("cmd.run", ["truncate -s 0 {}".format(f)]) + self.run_function("cmd.run", [f"truncate -s 0 {f}"]) self.assertEqual(conf.get("lxc.network.type"), "macvlan") diff --git a/tests/integration/modules/test_macdefaults.py b/tests/integration/modules/test_macdefaults.py index da7a6ef854d..bdd74901628 100644 --- a/tests/integration/modules/test_macdefaults.py +++ b/tests/integration/modules/test_macdefaults.py @@ -1,6 +1,7 @@ """ Validate the mac-defaults module """ + import pytest from tests.support.case import ModuleCase diff --git a/tests/integration/modules/test_mine.py b/tests/integration/modules/test_mine.py index c5e4bef5cc4..88a1d8b3a2c 100644 --- a/tests/integration/modules/test_mine.py +++ b/tests/integration/modules/test_mine.py @@ -46,13 +46,13 @@ class MineTest(ModuleCase, ShellCase): # sub_minion should be able to view test.arg data sub_min_ret = self.run_call( - "mine.get {} test.arg".format(self.tgt), + f"mine.get {self.tgt} test.arg", config_dir=RUNTIME_VARS.TMP_SUB_MINION_CONF_DIR, ) assert " - isn't" in sub_min_ret # minion should not be able to view test.arg data - min_ret = self.run_call("mine.get {} test.arg".format(self.tgt)) + min_ret = self.run_call(f"mine.get {self.tgt} test.arg") assert " - isn't" not in min_ret @pytest.mark.slow_test @@ -68,9 +68,9 @@ class MineTest(ModuleCase, ShellCase): allow_tgt="sub_minion", minion_tgt=minion, ) - min_ret = self.run_call("mine.get {} {}".format(self.tgt, mine_name)) + min_ret = self.run_call(f"mine.get {self.tgt} {mine_name}") sub_ret = self.run_call( - "mine.get {} {}".format(self.tgt, mine_name), + f"mine.get {self.tgt} {mine_name}", config_dir=RUNTIME_VARS.TMP_SUB_MINION_CONF_DIR, ) @@ -94,9 +94,9 @@ class MineTest(ModuleCase, ShellCase): allow_tgt_type="compound", minion_tgt=minion, ) - min_ret = self.run_call("mine.get {} {}".format(self.tgt, mine_name)) + min_ret = self.run_call(f"mine.get {self.tgt} {mine_name}") sub_ret = self.run_call( - "mine.get {} {}".format(self.tgt, mine_name), + f"mine.get {self.tgt} {mine_name}", config_dir=RUNTIME_VARS.TMP_SUB_MINION_CONF_DIR, ) @@ -119,9 +119,9 @@ class MineTest(ModuleCase, ShellCase): allow_tgt="doesnotexist", minion_tgt=minion, ) - min_ret = self.run_call("mine.get {} {}".format(self.tgt, mine_name)) + min_ret = self.run_call(f"mine.get {self.tgt} {mine_name}") sub_ret = self.run_call( - "mine.get {} {}".format(self.tgt, mine_name), + f"mine.get {self.tgt} {mine_name}", config_dir=RUNTIME_VARS.TMP_SUB_MINION_CONF_DIR, ) diff --git a/tests/integration/modules/test_mysql.py b/tests/integration/modules/test_mysql.py index 826a91df78c..fe769b129a6 100644 --- a/tests/integration/modules/test_mysql.py +++ b/tests/integration/modules/test_mysql.py @@ -72,14 +72,14 @@ class MysqlModuleDbTest(ModuleCase, SaltReturnAssertsMixin): """ ret = self.run_function("mysql.db_create", name=db_name, **kwargs) self.assertEqual( - True, ret, "Problem while creating db for db name: '{}'".format(db_name) + True, ret, f"Problem while creating db for db name: '{db_name}'" ) # test db exists ret = self.run_function("mysql.db_exists", name=db_name, **kwargs) self.assertEqual( True, ret, - "Problem while testing db exists for db name: '{}'".format(db_name), + f"Problem while testing db exists for db name: '{db_name}'", ) # List db names to ensure db is created with the right utf8 string ret = self.run_function("mysql.db_list", **kwargs) @@ -115,7 +115,7 @@ class MysqlModuleDbTest(ModuleCase, SaltReturnAssertsMixin): # Now remove database ret = self.run_function("mysql.db_remove", name=db_name, **kwargs) self.assertEqual( - True, ret, "Problem while removing db for db name: '{}'".format(db_name) + True, ret, f"Problem while removing db for db name: '{db_name}'" ) @pytest.mark.destructive_test @@ -694,7 +694,7 @@ class MysqlModuleUserTest(ModuleCase, SaltReturnAssertsMixin): password=None, new_password=None, new_password_hash=None, - **kwargs + **kwargs, ): """ Perform some tests around creation of the given user @@ -760,7 +760,7 @@ class MysqlModuleUserTest(ModuleCase, SaltReturnAssertsMixin): ) if not isinstance(ret, dict): raise AssertionError( - "Unexpected result while retrieving user_info for '{}'".format(user) + f"Unexpected result while retrieving user_info for '{user}'" ) self.assertEqual(ret["Host"], host) self.assertEqual(ret["Password"], check_hash) @@ -1489,7 +1489,7 @@ class MysqlModuleUserGrantTest(ModuleCase, SaltReturnAssertsMixin): user=user, grant_option=grant_option, escape=escape, - **kwargs + **kwargs, ) self.assertEqual( True, @@ -1505,7 +1505,7 @@ class MysqlModuleUserGrantTest(ModuleCase, SaltReturnAssertsMixin): user=user, grant_option=grant_option, escape=escape, - **kwargs + **kwargs, ) self.assertEqual( True, diff --git a/tests/integration/modules/test_test.py b/tests/integration/modules/test_test.py index f9849e3a48c..06f9d23341c 100644 --- a/tests/integration/modules/test_test.py +++ b/tests/integration/modules/test_test.py @@ -82,7 +82,10 @@ class TestModuleTest(ModuleCase, AdaptedConfigurationTestCaseMixin): test.collatz """ self.assertEqual( - self.run_function("test.collatz", ["40"],)[ + self.run_function( + "test.collatz", + ["40"], + )[ 0 ][-1], 2, diff --git a/tests/integration/modules/test_timezone.py b/tests/integration/modules/test_timezone.py index 8d7180cbd13..3af9bf628ec 100644 --- a/tests/integration/modules/test_timezone.py +++ b/tests/integration/modules/test_timezone.py @@ -3,6 +3,7 @@ Integration tests for timezone module Linux and Solaris are supported """ + import pytest from tests.support.case import ModuleCase diff --git a/tests/integration/pillar/test_git_pillar.py b/tests/integration/pillar/test_git_pillar.py index 68c14daaa15..89835a069f8 100644 --- a/tests/integration/pillar/test_git_pillar.py +++ b/tests/integration/pillar/test_git_pillar.py @@ -686,7 +686,7 @@ class GitPythonMixin: @pytest.mark.skipif( - not HAS_GITPYTHON, reason="GitPython >= {} required".format(GITPYTHON_MINVER) + not HAS_GITPYTHON, reason=f"GitPython >= {GITPYTHON_MINVER} required" ) @pytest.mark.usefixtures("ssh_pillar_tests_prep") @pytest.mark.destructive_test @@ -704,7 +704,7 @@ class TestGitPythonSSH(GitPillarSSHTestBase, GitPythonMixin): @pytest.mark.skipif( - not HAS_GITPYTHON, reason="GitPython >= {} required".format(GITPYTHON_MINVER) + not HAS_GITPYTHON, reason=f"GitPython >= {GITPYTHON_MINVER} required" ) @pytest.mark.usefixtures("webserver_pillar_tests_prep") class TestGitPythonHTTP(GitPillarHTTPTestBase, GitPythonMixin): @@ -714,7 +714,7 @@ class TestGitPythonHTTP(GitPillarHTTPTestBase, GitPythonMixin): @pytest.mark.skipif( - not HAS_GITPYTHON, reason="GitPython >= {} required".format(GITPYTHON_MINVER) + not HAS_GITPYTHON, reason=f"GitPython >= {GITPYTHON_MINVER} required" ) @pytest.mark.usefixtures("webserver_pillar_tests_prep_authenticated") class TestGitPythonAuthenticatedHTTP(TestGitPythonHTTP, GitPythonMixin): diff --git a/tests/integration/runners/test_runner_returns.py b/tests/integration/runners/test_runner_returns.py index 849c7aa1e4d..a2ecaf5a51b 100644 --- a/tests/integration/runners/test_runner_returns.py +++ b/tests/integration/runners/test_runner_returns.py @@ -129,7 +129,7 @@ class RunnerReturnsTest(ShellCase): else: user = RUNTIME_VARS.RUNNING_TESTS_USER if salt.utils.platform.is_windows(): - user = "sudo_{}\\{}".format(socket.gethostname(), user) + user = f"sudo_{socket.gethostname()}\\{user}" self.assertEqual( deserialized, { diff --git a/tests/integration/shell/test_master_tops.py b/tests/integration/shell/test_master_tops.py index 27625a4ff60..ac419de96b6 100644 --- a/tests/integration/shell/test_master_tops.py +++ b/tests/integration/shell/test_master_tops.py @@ -3,7 +3,6 @@ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ - import pytest from tests.support.case import ShellCase diff --git a/tests/integration/shell/test_spm.py b/tests/integration/shell/test_spm.py index 991e335e29c..156497cdec4 100644 --- a/tests/integration/shell/test_spm.py +++ b/tests/integration/shell/test_spm.py @@ -41,9 +41,9 @@ class SPMTest(ShellCase, SPMCase): spm_file = os.path.join(config["spm_build_dir"], "apache-201506-2.spm") - build = self.run_spm("build {} -c {}".format(self.formula_dir, self._tmp_spm)) + build = self.run_spm(f"build {self.formula_dir} -c {self._tmp_spm}") - install = self.run_spm("install {} -c {} -y".format(spm_file, self._tmp_spm)) + install = self.run_spm(f"install {spm_file} -c {self._tmp_spm} -y") self.assertTrue( os.path.exists(os.path.join(config["formula_path"], "apache", "apache.sls")) @@ -59,15 +59,15 @@ class SPMTest(ShellCase, SPMCase): spm_file = os.path.join(config["spm_build_dir"], "apache-201506-2.spm") - build = self.run_spm("build {} -c {}".format(self.formula_dir, self._tmp_spm)) + build = self.run_spm(f"build {self.formula_dir} -c {self._tmp_spm}") - install = self.run_spm("install {} -c {} -y".format(spm_file, self._tmp_spm)) + install = self.run_spm(f"install {spm_file} -c {self._tmp_spm} -y") self.assertTrue( os.path.exists(os.path.join(config["formula_path"], "apache", "apache.sls")) ) # check if it forces the install after its already been installed it - install = self.run_spm("install {} -c {} -y -f".format(spm_file, self._tmp_spm)) + install = self.run_spm(f"install {spm_file} -c {self._tmp_spm} -y -f") self.assertEqual(["... installing apache"], install) diff --git a/tests/integration/spm/test_install.py b/tests/integration/spm/test_install.py index c73f6639230..bd4d3617694 100644 --- a/tests/integration/spm/test_install.py +++ b/tests/integration/spm/test_install.py @@ -1,6 +1,7 @@ """ Tests for the spm install utility """ + import os import pytest diff --git a/tests/integration/states/test_boto_sns.py b/tests/integration/states/test_boto_sns.py index c40adbdba5f..f3a255047f9 100644 --- a/tests/integration/states/test_boto_sns.py +++ b/tests/integration/states/test_boto_sns.py @@ -1,6 +1,7 @@ """ Tests for the boto_sns state """ + import re import pytest @@ -44,9 +45,7 @@ class BotoSNSTest(ModuleCase, SaltReturnAssertsMixin): ret = self.run_state("boto_sns.present", name=self.topic_name) self.assertSaltTrueReturn(ret) self.assertInSaltReturn(self.topic_name, ret, "name") - self.assertInSaltComment( - "AWS SNS topic {} created.".format(self.topic_name), ret - ) + self.assertInSaltComment(f"AWS SNS topic {self.topic_name} created.", ret) self.assertSaltStateChangesEqual( ret, {"old": None, "new": {"topic": self.topic_name, "subscriptions": []}} ) @@ -130,9 +129,7 @@ class BotoSNSTest(ModuleCase, SaltReturnAssertsMixin): self.assertSaltTrueReturn(ret) self.assertInSaltReturn(self.topic_name, ret, "name") - self.assertInSaltComment( - "AWS SNS topic {} present.".format(self.topic_name), ret - ) + self.assertInSaltComment(f"AWS SNS topic {self.topic_name} present.", ret) self.assertInSaltComment( "AWS SNS subscription https:https://www.example.com/sns/endpoint already" " set on topic {}.".format(self.topic_name), @@ -234,7 +231,7 @@ class BotoSNSTest(ModuleCase, SaltReturnAssertsMixin): self.assertSaltNoneReturn(ret) self.assertInSaltReturn(self.topic_name, ret, "name") self.assertInSaltComment( - "AWS SNS topic {} is set to be created.".format(self.topic_name), ret + f"AWS SNS topic {self.topic_name} is set to be created.", ret ) self.assertSaltStateChangesEqual(ret, {}) ret = self.run_function("boto_sns.exists", name=self.topic_name) @@ -270,7 +267,7 @@ class BotoSNSTest(ModuleCase, SaltReturnAssertsMixin): self.assertSaltTrueReturn(ret) self.assertInSaltReturn(self.topic_name, ret, "name") self.assertInSaltComment( - "AWS SNS topic {} does not exist.".format(self.topic_name), ret + f"AWS SNS topic {self.topic_name} does not exist.", ret ) self.assertSaltStateChangesEqual(ret, {}) @@ -280,7 +277,7 @@ class BotoSNSTest(ModuleCase, SaltReturnAssertsMixin): self.assertSaltTrueReturn(ret) self.assertInSaltReturn(self.topic_name, ret, "name") self.assertInSaltComment( - "AWS SNS topic {} does not exist.".format(self.topic_name), ret + f"AWS SNS topic {self.topic_name} does not exist.", ret ) self.assertSaltStateChangesEqual( ret, {"new": None, "old": {"topic": self.topic_name}} @@ -292,7 +289,7 @@ class BotoSNSTest(ModuleCase, SaltReturnAssertsMixin): self.assertSaltNoneReturn(ret) self.assertInSaltReturn(self.topic_name, ret, "name") self.assertInSaltComment( - "AWS SNS topic {} is set to be removed.".format(self.topic_name), ret + f"AWS SNS topic {self.topic_name} is set to be removed.", ret ) self.assertSaltStateChangesEqual(ret, {}) ret = self.run_function("boto_sns.exists", name=self.topic_name) diff --git a/tests/integration/states/test_compiler.py b/tests/integration/states/test_compiler.py index ea64759e26d..257655fae91 100644 --- a/tests/integration/states/test_compiler.py +++ b/tests/integration/states/test_compiler.py @@ -2,7 +2,6 @@ tests for host state """ - from tests.support.case import ModuleCase diff --git a/tests/integration/states/test_git.py b/tests/integration/states/test_git.py index dba4340dabd..19cb08f12d2 100644 --- a/tests/integration/states/test_git.py +++ b/tests/integration/states/test_git.py @@ -237,7 +237,7 @@ class GitTest(ModuleCase, SaltReturnAssertsMixin): name=TEST_REPO, rev="develop", target=target, - unless="test -e {}".format(target), + unless=f"test -e {target}", submodules=True, ) self.assertSaltTrueReturn(ret) @@ -495,7 +495,7 @@ class GitTest(ModuleCase, SaltReturnAssertsMixin): assert ret["result"] # Now remove the tag - self.run_function("git.push", [admin_dir, "origin", ":{}".format(tag1)]) + self.run_function("git.push", [admin_dir, "origin", f":{tag1}"]) # Add and push another tag self.run_function("git.tag", [admin_dir, tag2]) self.run_function("git.push", [admin_dir, "origin", tag2]) @@ -541,29 +541,29 @@ class GitTest(ModuleCase, SaltReturnAssertsMixin): ret = self.run_state("git.cloned", name=TEST_REPO, target=target, test=True) ret = ret[next(iter(ret))] assert ret["result"] is None - assert ret["changes"] == {"new": "{} => {}".format(TEST_REPO, target)} - assert ret["comment"] == "{} would be cloned to {}".format(TEST_REPO, target) + assert ret["changes"] == {"new": f"{TEST_REPO} => {target}"} + assert ret["comment"] == f"{TEST_REPO} would be cloned to {target}" # Now actually run the state ret = self.run_state("git.cloned", name=TEST_REPO, target=target) ret = ret[next(iter(ret))] assert ret["result"] is True - assert ret["changes"] == {"new": "{} => {}".format(TEST_REPO, target)} - assert ret["comment"] == "{} cloned to {}".format(TEST_REPO, target) + assert ret["changes"] == {"new": f"{TEST_REPO} => {target}"} + assert ret["comment"] == f"{TEST_REPO} cloned to {target}" # Run the state again to test idempotence ret = self.run_state("git.cloned", name=TEST_REPO, target=target) ret = ret[next(iter(ret))] assert ret["result"] is True assert not ret["changes"] - assert ret["comment"] == "Repository already exists at {}".format(target) + assert ret["comment"] == f"Repository already exists at {target}" # Run the state again to test idempotence (test mode) ret = self.run_state("git.cloned", name=TEST_REPO, target=target, test=True) ret = ret[next(iter(ret))] assert not ret["changes"] assert ret["result"] is True - assert ret["comment"] == "Repository already exists at {}".format(target) + assert ret["comment"] == f"Repository already exists at {target}" @with_tempdir(create=False) @pytest.mark.slow_test @@ -581,7 +581,7 @@ class GitTest(ModuleCase, SaltReturnAssertsMixin): ) ret = ret[next(iter(ret))] assert ret["result"] is None - assert ret["changes"] == {"new": "{} => {}".format(TEST_REPO, target)} + assert ret["changes"] == {"new": f"{TEST_REPO} => {target}"} assert ret["comment"] == "{} would be cloned to {} with branch '{}'".format( TEST_REPO, target, old_branch ) @@ -592,7 +592,7 @@ class GitTest(ModuleCase, SaltReturnAssertsMixin): ) ret = ret[next(iter(ret))] assert ret["result"] is True - assert ret["changes"] == {"new": "{} => {}".format(TEST_REPO, target)} + assert ret["changes"] == {"new": f"{TEST_REPO} => {target}"} assert ret["comment"] == "{} cloned to {} with branch '{}'".format( TEST_REPO, target, old_branch ) @@ -630,7 +630,7 @@ class GitTest(ModuleCase, SaltReturnAssertsMixin): ret = ret[next(iter(ret))] assert ret["result"] is None assert ret["changes"] == {"branch": {"old": old_branch, "new": new_branch}} - assert ret["comment"] == "Branch would be changed to '{}'".format(new_branch) + assert ret["comment"] == f"Branch would be changed to '{new_branch}'" # Now really change the branch ret = self.run_state( @@ -639,7 +639,7 @@ class GitTest(ModuleCase, SaltReturnAssertsMixin): ret = ret[next(iter(ret))] assert ret["result"] is True assert ret["changes"] == {"branch": {"old": old_branch, "new": new_branch}} - assert ret["comment"] == "Branch changed to '{}'".format(new_branch) + assert ret["comment"] == f"Branch changed to '{new_branch}'" # Change back to original branch. This tests that we don't attempt to # checkout a new branch (i.e. git checkout -b) for a branch that exists @@ -650,7 +650,7 @@ class GitTest(ModuleCase, SaltReturnAssertsMixin): ret = ret[next(iter(ret))] assert ret["result"] is True assert ret["changes"] == {"branch": {"old": new_branch, "new": old_branch}} - assert ret["comment"] == "Branch changed to '{}'".format(old_branch) + assert ret["comment"] == f"Branch changed to '{old_branch}'" # Test switching to a nonexistent branch. This should fail. ret = self.run_state( @@ -659,9 +659,7 @@ class GitTest(ModuleCase, SaltReturnAssertsMixin): ret = ret[next(iter(ret))] assert ret["result"] is False assert not ret["changes"] - assert ret["comment"].startswith( - "Failed to change branch to '{}':".format(bad_branch) - ) + assert ret["comment"].startswith(f"Failed to change branch to '{bad_branch}':") @with_tempdir(create=False) @ensure_min_git(min_version="1.7.10") @@ -739,7 +737,7 @@ class GitTest(ModuleCase, SaltReturnAssertsMixin): name="user.name", value="foo bar", repo=name, - **{"global": False} + **{"global": False}, ) self.assertSaltTrueReturn(ret) @@ -966,7 +964,7 @@ class LocalRepoGitTest(ModuleCase, SaltReturnAssertsMixin): ) self.assertEqual( ret[next(iter(ret))]["changes"], - {"new": "{} => {}".format(self.repo, self.target)}, + {"new": f"{self.repo} => {self.target}"}, ) # Run git.latest state again. This should fail again, with a different diff --git a/tests/integration/states/test_handle_iorder.py b/tests/integration/states/test_handle_iorder.py index 39a5e88fe32..7bdd4a0d0df 100644 --- a/tests/integration/states/test_handle_iorder.py +++ b/tests/integration/states/test_handle_iorder.py @@ -2,7 +2,6 @@ tests for host state """ - from tests.support.case import ModuleCase diff --git a/tests/integration/states/test_host.py b/tests/integration/states/test_host.py index f80ed37416f..e351f52fc35 100644 --- a/tests/integration/states/test_host.py +++ b/tests/integration/states/test_host.py @@ -50,4 +50,4 @@ class HostTest(ModuleCase, SaltReturnAssertsMixin): self.assertSaltTrueReturn(ret) with salt.utils.files.fopen(self.hosts_file) as fp_: output = salt.utils.stringutils.to_unicode(fp_.read()) - self.assertIn("{}\t\t{}".format(ip, name), output) + self.assertIn(f"{ip}\t\t{name}", output) diff --git a/tests/integration/states/test_lxd_image.py b/tests/integration/states/test_lxd_image.py index 374aac57762..b0ab485bdf3 100644 --- a/tests/integration/states/test_lxd_image.py +++ b/tests/integration/states/test_lxd_image.py @@ -1,6 +1,7 @@ """ Integration tests for the lxd states """ + import pytest import salt.modules.lxd diff --git a/tests/integration/states/test_lxd_profile.py b/tests/integration/states/test_lxd_profile.py index cfcc24d968d..e6df9db2ef8 100644 --- a/tests/integration/states/test_lxd_profile.py +++ b/tests/integration/states/test_lxd_profile.py @@ -1,6 +1,7 @@ """ Integration tests for the lxd states """ + import pytest import salt.modules.lxd diff --git a/tests/integration/states/test_reg.py b/tests/integration/states/test_reg.py index 94f17d8dad4..2fca4c52b18 100644 --- a/tests/integration/states/test_reg.py +++ b/tests/integration/states/test_reg.py @@ -43,7 +43,7 @@ class RegTest(ModuleCase, SaltReturnAssertsMixin): # Does the state return the correct data ret = self.run_state( "reg.present", - name="HKLM\\{}".format(FAKE_KEY), + name=f"HKLM\\{FAKE_KEY}", vname="test_reg_sz", vdata="fake string data", ) @@ -52,7 +52,7 @@ class RegTest(ModuleCase, SaltReturnAssertsMixin): "Added": { "Entry": "test_reg_sz", "Inheritance": True, - "Key": "HKLM\\{}".format(FAKE_KEY), + "Key": f"HKLM\\{FAKE_KEY}", "Owner": None, "Perms": {"Deny": None, "Grant": None}, "Value": "fake string data", @@ -83,7 +83,7 @@ class RegTest(ModuleCase, SaltReturnAssertsMixin): # Does the state return the correct data ret = self.run_state( "reg.present", - name="HKLM\\{}".format(FAKE_KEY), + name=f"HKLM\\{FAKE_KEY}", vname="test_reg_sz", vdata=UNICODE_VALUE, ) @@ -92,7 +92,7 @@ class RegTest(ModuleCase, SaltReturnAssertsMixin): "Added": { "Entry": "test_reg_sz", "Inheritance": True, - "Key": "HKLM\\{}".format(FAKE_KEY), + "Key": f"HKLM\\{FAKE_KEY}", "Owner": None, "Perms": {"Deny": None, "Grant": None}, "Value": UNICODE_VALUE, @@ -122,14 +122,14 @@ class RegTest(ModuleCase, SaltReturnAssertsMixin): # default type is 'REG_SZ' # Does the state return the correct data ret = self.run_state( - "reg.present", name="HKLM\\{}".format(FAKE_KEY), vdata=UNICODE_VALUE + "reg.present", name=f"HKLM\\{FAKE_KEY}", vdata=UNICODE_VALUE ) expected = { "reg": { "Added": { "Entry": "(Default)", "Inheritance": True, - "Key": "HKLM\\{}".format(FAKE_KEY), + "Key": f"HKLM\\{FAKE_KEY}", "Owner": None, "Perms": {"Deny": None, "Grant": None}, "Value": UNICODE_VALUE, @@ -161,7 +161,7 @@ class RegTest(ModuleCase, SaltReturnAssertsMixin): # Does the state return the correct data ret = self.run_state( "reg.present", - name="HKLM\\{}".format(FAKE_KEY), + name=f"HKLM\\{FAKE_KEY}", vname=UNICODE_VALUE_NAME, vdata="fake string data", ) @@ -170,7 +170,7 @@ class RegTest(ModuleCase, SaltReturnAssertsMixin): "Added": { "Entry": UNICODE_VALUE_NAME, "Inheritance": True, - "Key": "HKLM\\{}".format(FAKE_KEY), + "Key": f"HKLM\\{FAKE_KEY}", "Owner": None, "Perms": {"Deny": None, "Grant": None}, "Value": "fake string data", @@ -203,7 +203,7 @@ class RegTest(ModuleCase, SaltReturnAssertsMixin): # Does the state return the correct data ret = self.run_state( "reg.present", - name="HKLM\\{}".format(FAKE_KEY), + name=f"HKLM\\{FAKE_KEY}", vname="test_reg_binary", vtype="REG_BINARY", vdata=test_data, @@ -213,7 +213,7 @@ class RegTest(ModuleCase, SaltReturnAssertsMixin): "Added": { "Entry": "test_reg_binary", "Inheritance": True, - "Key": "HKLM\\{}".format(FAKE_KEY), + "Key": f"HKLM\\{FAKE_KEY}", "Owner": None, "Perms": {"Deny": None, "Grant": None}, "Value": test_data, @@ -244,7 +244,7 @@ class RegTest(ModuleCase, SaltReturnAssertsMixin): # Does the state return the correct data ret = self.run_state( "reg.present", - name="HKLM\\{}".format(FAKE_KEY), + name=f"HKLM\\{FAKE_KEY}", vname="test_reg_multi_sz", vtype="REG_MULTI_SZ", vdata=["item1", "item2"], @@ -254,7 +254,7 @@ class RegTest(ModuleCase, SaltReturnAssertsMixin): "Added": { "Entry": "test_reg_multi_sz", "Inheritance": True, - "Key": "HKLM\\{}".format(FAKE_KEY), + "Key": f"HKLM\\{FAKE_KEY}", "Owner": None, "Perms": {"Deny": None, "Grant": None}, "Value": ["item1", "item2"], @@ -285,7 +285,7 @@ class RegTest(ModuleCase, SaltReturnAssertsMixin): # Does the state return the correct data ret = self.run_state( "reg.present", - name="HKLM\\{}".format(FAKE_KEY), + name=f"HKLM\\{FAKE_KEY}", vname="test_reg_sz", vdata="fake string data", use_32bit_registry=True, @@ -296,7 +296,7 @@ class RegTest(ModuleCase, SaltReturnAssertsMixin): "Added": { "Entry": "test_reg_sz", "Inheritance": True, - "Key": "HKLM\\{}".format(FAKE_KEY), + "Key": f"HKLM\\{FAKE_KEY}", "Owner": None, "Perms": {"Deny": None, "Grant": None}, "Value": "fake string data", diff --git a/tests/integration/states/test_ssh_known_hosts.py b/tests/integration/states/test_ssh_known_hosts.py index d5e7b8b25bb..3486d0cfd1b 100644 --- a/tests/integration/states/test_ssh_known_hosts.py +++ b/tests/integration/states/test_ssh_known_hosts.py @@ -86,16 +86,14 @@ class SSHKnownHostsStateTest(ModuleCase, SaltReturnAssertsMixin): try: self.assertNotIn(ret, ("", None)) except AssertionError: - raise AssertionError("Salt return '{}' is in ('', None).".format(ret)) + raise AssertionError(f"Salt return '{ret}' is in ('', None).") ret = self.run_function( "ssh.get_known_host_entries", ["root", GITHUB_IP], config=self.known_hosts )[0] try: self.assertNotIn(ret, ("", None, {})) except AssertionError: - raise AssertionError( - "Salt return '{}' is in ('', None,".format(ret) + " {})" - ) + raise AssertionError(f"Salt return '{ret}' is in ('', None," + " {})") @pytest.mark.slow_test def test_present_fail(self): @@ -117,9 +115,7 @@ class SSHKnownHostsStateTest(ModuleCase, SaltReturnAssertsMixin): known_hosts = os.path.join(RUNTIME_VARS.FILES, "ssh", "known_hosts") shutil.copyfile(known_hosts, self.known_hosts) if not os.path.isfile(self.known_hosts): - self.skipTest( - "Unable to copy {} to {}".format(known_hosts, self.known_hosts) - ) + self.skipTest(f"Unable to copy {known_hosts} to {self.known_hosts}") kwargs = {"name": "github.com", "user": "root", "config": self.known_hosts} # test first diff --git a/tests/integration/states/test_x509.py b/tests/integration/states/test_x509.py index 6337df80ccd..228afce78f8 100644 --- a/tests/integration/states/test_x509.py +++ b/tests/integration/states/test_x509.py @@ -214,7 +214,7 @@ class x509Test(ModuleCase, SaltReturnAssertsMixin): assert "Revoked Certificates" in ret[key]["changes"]["New"] self.assertEqual( ret[key]["changes"]["Old"], - "{}/pki/ca.crl does not exist.".format(RUNTIME_VARS.TMP), + f"{RUNTIME_VARS.TMP}/pki/ca.crl does not exist.", ) @pytest.mark.slow_test @@ -261,7 +261,7 @@ c9bcgp7D7xD+TxWWNj4CSXEccJgGr91StV+gFg4ARQ== assert "Revoked Certificates" in ret[key]["changes"]["New"] self.assertEqual( ret[key]["changes"]["Old"], - "{}/pki/ca.crl is not a valid CRL.".format(RUNTIME_VARS.TMP), + f"{RUNTIME_VARS.TMP}/pki/ca.crl is not a valid CRL.", ) def test_cert_issue_not_before_not_after(self): @@ -321,7 +321,7 @@ c9bcgp7D7xD+TxWWNj4CSXEccJgGr91StV+gFg4ARQ== @with_tempfile(suffix=".crt", create=False) @with_tempfile(suffix=".key", create=False) def test_issue_41858(self, keyfile, crtfile): - ret_key = "x509_|-test_crt_|-{}_|-certificate_managed".format(crtfile) + ret_key = f"x509_|-test_crt_|-{crtfile}_|-certificate_managed" signing_policy = "no_such_policy" ret = self.run_function( "state.apply", @@ -351,7 +351,7 @@ c9bcgp7D7xD+TxWWNj4CSXEccJgGr91StV+gFg4ARQ== @with_tempfile(suffix=".crt", create=False) @with_tempfile(suffix=".key", create=False) def test_compound_match_minion_have_correct_grain_value(self, keyfile, crtfile): - ret_key = "x509_|-test_crt_|-{}_|-certificate_managed".format(crtfile) + ret_key = f"x509_|-test_crt_|-{crtfile}_|-certificate_managed" signing_policy = "compound_match" ret = self.run_function( "state.apply", @@ -385,7 +385,7 @@ c9bcgp7D7xD+TxWWNj4CSXEccJgGr91StV+gFg4ARQ== minion_tgt="sub_minion", ) - ret_key = "x509_|-test_crt_|-{}_|-certificate_managed".format(crtfile) + ret_key = f"x509_|-test_crt_|-{crtfile}_|-certificate_managed" signing_policy = "compound_match" self.run_function( "state.apply", @@ -418,7 +418,7 @@ c9bcgp7D7xD+TxWWNj4CSXEccJgGr91StV+gFg4ARQ== ["x509.self_signed"], pillar={"keyfile": keyfile, "crtfile": crtfile}, ) - key = "x509_|-self_signed_cert_|-{}_|-certificate_managed".format(crtfile) + key = f"x509_|-self_signed_cert_|-{crtfile}_|-certificate_managed" self.assertIn("New", first_run[key]["changes"]["Certificate"]) self.assertEqual( "Certificate is valid and up to date", @@ -461,7 +461,7 @@ c9bcgp7D7xD+TxWWNj4CSXEccJgGr91StV+gFg4ARQ== "days_remaining": 10, }, ) - key = "x509_|-self_signed_cert_|-{}_|-certificate_managed".format(crtfile) + key = f"x509_|-self_signed_cert_|-{crtfile}_|-certificate_managed" self.assertEqual( "Certificate is valid and up to date", first_run[key]["changes"]["Status"]["New"], @@ -522,7 +522,7 @@ c9bcgp7D7xD+TxWWNj4CSXEccJgGr91StV+gFg4ARQ== "subjectAltName": "DNS:alt.service.local", }, ) - key = "x509_|-self_signed_cert_|-{}_|-certificate_managed".format(crtfile) + key = f"x509_|-self_signed_cert_|-{crtfile}_|-certificate_managed" self.assertEqual( "Certificate is valid and up to date", first_run[key]["changes"]["Status"]["New"], @@ -612,7 +612,7 @@ c9bcgp7D7xD+TxWWNj4CSXEccJgGr91StV+gFg4ARQ== ["x509.self_signed_different_properties"], pillar={"keyfile": keyfile, "crtfile": crtfile, "fileMode": "0755"}, ) - key = "x509_|-self_signed_cert_|-{}_|-certificate_managed".format(crtfile) + key = f"x509_|-self_signed_cert_|-{crtfile}_|-certificate_managed" self.assertEqual( "Certificate is valid and up to date", first_run[key]["changes"]["Status"]["New"], @@ -657,7 +657,7 @@ c9bcgp7D7xD+TxWWNj4CSXEccJgGr91StV+gFg4ARQ== pillar={"keyfile": keyfile, "crtfile": bad_crtfile}, ) - key = "x509_|-self_signed_cert_|-{}_|-certificate_managed".format(bad_crtfile) + key = f"x509_|-self_signed_cert_|-{bad_crtfile}_|-certificate_managed" self.assertFalse(ret[key]["result"], "State should have failed.") self.assertEqual({}, ret[key]["changes"]) self.assertFalse( diff --git a/tests/integration/utils/test_idem.py b/tests/integration/utils/test_idem.py index c2b57b1ec14..eb2fcd83254 100644 --- a/tests/integration/utils/test_idem.py +++ b/tests/integration/utils/test_idem.py @@ -1,6 +1,7 @@ """ Test utility methods that the idem module and state share """ + from contextlib import contextmanager import pytest diff --git a/tests/integration/utils/test_smb.py b/tests/integration/utils/test_smb.py index 5f7db744242..8ef792d6340 100644 --- a/tests/integration/utils/test_smb.py +++ b/tests/integration/utils/test_smb.py @@ -1,6 +1,7 @@ """ Test utility methods that communicate with SMB shares. """ + import getpass import logging import os diff --git a/tests/integration/utils/test_win_runas.py b/tests/integration/utils/test_win_runas.py index 41d4169d945..bd498c2f622 100644 --- a/tests/integration/utils/test_win_runas.py +++ b/tests/integration/utils/test_win_runas.py @@ -92,7 +92,7 @@ class _ServiceManager(win32serviceutil.ServiceFramework): logger.exception(msg) exc_info = sys.exc_info() tb = traceback.format_tb(exc_info[2]) - servicemanager.LogErrorMsg("{} {} {}".format(msg, exc_info[1], tb)) + servicemanager.LogErrorMsg(f"{msg} {exc_info[1]} {tb}") @property def timeout_ms(self): @@ -118,7 +118,7 @@ class _ServiceManager(win32serviceutil.ServiceFramework): servicemanager.PYS_SERVICE_STARTED, (self._svc_name_, ""), ) - self.log_info("Starting Service {}".format(self._svc_name_)) + self.log_info(f"Starting Service {self._svc_name_}") monitor_thread = threading.Thread(target=self.target_thread) monitor_thread.start() while self.active: @@ -362,7 +362,7 @@ class RunAsTest(ModuleCase): "cmd.exe", "/C", "winrs", - "/r:{}".format(self.hostname), + f"/r:{self.hostname}", "python", RUNAS_PATH, ] @@ -390,7 +390,7 @@ class RunAsTest(ModuleCase): "cmd.exe", "/C", "winrs", - "/r:{}".format(self.hostname), + f"/r:{self.hostname}", "python", RUNAS_PATH, ] @@ -423,7 +423,7 @@ class RunAsTest(ModuleCase): "cmd.exe", "/C", "winrs", - "/r:{}".format(self.hostname), + f"/r:{self.hostname}", "python", RUNAS_PATH, ] @@ -455,7 +455,7 @@ class RunAsTest(ModuleCase): "cmd.exe", "/C", "winrs", - "/r:{}".format(self.hostname), + f"/r:{self.hostname}", "python", RUNAS_PATH, ] @@ -477,7 +477,7 @@ class RunAsTest(ModuleCase): "cmd.exe", "/C", "winrs", - "/r:{}".format(self.hostname), + f"/r:{self.hostname}", "python", RUNAS_PATH, ] @@ -499,7 +499,7 @@ class RunAsTest(ModuleCase): "cmd.exe", "/C", "winrs", - "/r:{}".format(self.hostname), + f"/r:{self.hostname}", "python", RUNAS_PATH, ] @@ -521,7 +521,7 @@ class RunAsTest(ModuleCase): "cmd.exe", "/C", "winrs", - "/r:{}".format(self.hostname), + f"/r:{self.hostname}", "python", RUNAS_PATH, ] @@ -552,7 +552,7 @@ class RunAsTest(ModuleCase): "-ComputerName", self.hostname, "-ScriptBlock", - "{{ python.exe {} }}".format(RUNAS_PATH), + f"{{ python.exe {RUNAS_PATH} }}", ] ) self.assertEqual(ret, 1) @@ -580,7 +580,7 @@ class RunAsTest(ModuleCase): "-ComputerName", self.hostname, "-ScriptBlock", - "{{ python.exe {} }}".format(RUNAS_PATH), + f"{{ python.exe {RUNAS_PATH} }}", ] ) self.assertEqual(ret, 1) @@ -611,7 +611,7 @@ class RunAsTest(ModuleCase): ) with salt.utils.files.fopen(RUNAS_PATH, "w") as fp: fp.write(runaspy) - cmd = "python.exe {}; exit $LASTEXITCODE".format(RUNAS_PATH) + cmd = f"python.exe {RUNAS_PATH}; exit $LASTEXITCODE" ret = subprocess.call(psrp_wrap.format(self.hostname, cmd), shell=True) # nosec self.assertEqual(ret, 0) @@ -639,7 +639,7 @@ class RunAsTest(ModuleCase): ) with salt.utils.files.fopen(RUNAS_PATH, "w") as fp: fp.write(runaspy) - cmd = "python.exe {}; exit $LASTEXITCODE".format(RUNAS_PATH) + cmd = f"python.exe {RUNAS_PATH}; exit $LASTEXITCODE" ret = subprocess.call(psrp_wrap.format(self.hostname, cmd), shell=True) # nosec self.assertEqual(ret, 0) diff --git a/tests/minionswarm.py b/tests/minionswarm.py index cb3cb0aa38d..2ace3c7a7d5 100644 --- a/tests/minionswarm.py +++ b/tests/minionswarm.py @@ -207,7 +207,7 @@ class Swarm: if not os.path.exists(path): os.makedirs(path) - print("Creating shared pki keys for the swarm on: {}".format(path)) + print(f"Creating shared pki keys for the swarm on: {path}") subprocess.call( "salt-key -c {0} --gen-keys minion --gen-keys-dir {0} " "--log-file {1} --user {2}".format( @@ -260,7 +260,7 @@ class Swarm: Clean up the config files """ for path in self.confs: - pidfile = "{}.pid".format(path) + pidfile = f"{path}.pid" try: try: with salt.utils.files.fopen(pidfile) as fp_: @@ -287,7 +287,7 @@ class MinionSwarm(Swarm): """ self.prep_configs() for path in self.confs: - cmd = "salt-minion -c {} --pid-file {}".format(path, "{}.pid".format(path)) + cmd = "salt-minion -c {} --pid-file {}".format(path, f"{path}.pid") if self.opts["foreground"]: cmd += " -l debug &" else: @@ -392,9 +392,7 @@ class MasterSwarm(Swarm): """ Do the master start """ - cmd = "salt-master -c {} --pid-file {}".format( - self.conf, "{}.pid".format(self.conf) - ) + cmd = "salt-master -c {} --pid-file {}".format(self.conf, f"{self.conf}.pid") if self.opts["foreground"]: cmd += " -l debug &" else: diff --git a/tests/modparser.py b/tests/modparser.py index 978b3ad7836..7e7882b1b9c 100644 --- a/tests/modparser.py +++ b/tests/modparser.py @@ -46,7 +46,7 @@ def mod_data(opts, full): try: finder.load_file(full) except ImportError as exc: - print("ImportError - {} (Reason: {})".format(full, exc), file=sys.stderr) + print(f"ImportError - {full} (Reason: {exc})", file=sys.stderr) return ret for name, mod in finder.modules.items(): basemod = name.split(".")[0] diff --git a/tests/packdump.py b/tests/packdump.py index d25b5454e73..e9b7b70096a 100644 --- a/tests/packdump.py +++ b/tests/packdump.py @@ -1,6 +1,7 @@ """ Simple script to dump the contents of msgpack files to the terminal """ + # pylint: disable=resource-leakage import os diff --git a/tests/pytests/conftest.py b/tests/pytests/conftest.py index ba3defb6cc8..a1cdac8c2be 100644 --- a/tests/pytests/conftest.py +++ b/tests/pytests/conftest.py @@ -2,6 +2,7 @@ tests.pytests.conftest ~~~~~~~~~~~~~~~~~~~~~~ """ + import asyncio import functools import inspect @@ -648,6 +649,7 @@ def io_loop(): # <---- Async Test Fixtures ------------------------------------------------------------------------------------------ + # ----- Helpers -----------------------------------------------------------------------------------------------------> @pytest.helpers.proxy.register def delta_proxy_minion_ids(): diff --git a/tests/pytests/functional/cache/helpers.py b/tests/pytests/functional/cache/helpers.py index cd90f0fefc7..49ddf32e406 100644 --- a/tests/pytests/functional/cache/helpers.py +++ b/tests/pytests/functional/cache/helpers.py @@ -138,7 +138,7 @@ def run_common_cache_tests(subtests, cache): ): with patch.dict( cache.modules._dict, - {"{}.updated".format(cache.driver): MagicMock(side_effect=SaltCacheError)}, + {f"{cache.driver}.updated": MagicMock(side_effect=SaltCacheError)}, ), pytest.raises(SaltCacheError): cache.updated(bank="kaboom", key="oops") diff --git a/tests/pytests/functional/cli/test_batch.py b/tests/pytests/functional/cli/test_batch.py index c82a0ef0a51..599ac70bccf 100644 --- a/tests/pytests/functional/cli/test_batch.py +++ b/tests/pytests/functional/cli/test_batch.py @@ -2,6 +2,7 @@ tests.pytests.functional.cli.test_batch ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ + import salt.cli.batch import salt.config import salt.utils.jid diff --git a/tests/pytests/functional/cli/test_salt_cloud.py b/tests/pytests/functional/cli/test_salt_cloud.py index 0b661490bfe..4bd33bdc6c9 100644 --- a/tests/pytests/functional/cli/test_salt_cloud.py +++ b/tests/pytests/functional/cli/test_salt_cloud.py @@ -2,6 +2,7 @@ tests.pytests.integration.cli.test_salt_cloud ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ + import pytest pytest.importorskip("libcloud", reason="salt-cloud requires >= libcloud 0.11.4") diff --git a/tests/pytests/functional/formulas/test_docker.py b/tests/pytests/functional/formulas/test_docker.py index f48f03f5faa..d6b95c9df9d 100644 --- a/tests/pytests/functional/formulas/test_docker.py +++ b/tests/pytests/functional/formulas/test_docker.py @@ -1,6 +1,7 @@ """ Tests using docker formula """ + import pytest diff --git a/tests/pytests/functional/formulas/test_nginx.py b/tests/pytests/functional/formulas/test_nginx.py index f1d86091185..0cd8324893c 100644 --- a/tests/pytests/functional/formulas/test_nginx.py +++ b/tests/pytests/functional/formulas/test_nginx.py @@ -1,6 +1,7 @@ """ Tests using nginx formula """ + import pytest pytestmark = [ diff --git a/tests/pytests/functional/formulas/test_sudoers.py b/tests/pytests/functional/formulas/test_sudoers.py index 015d3a13472..caeace8d853 100644 --- a/tests/pytests/functional/formulas/test_sudoers.py +++ b/tests/pytests/functional/formulas/test_sudoers.py @@ -1,6 +1,7 @@ """ Tests using sudoers formula """ + import pytest diff --git a/tests/pytests/functional/formulas/test_vim.py b/tests/pytests/functional/formulas/test_vim.py index 2f0448e76d6..83d2354dff0 100644 --- a/tests/pytests/functional/formulas/test_vim.py +++ b/tests/pytests/functional/formulas/test_vim.py @@ -1,6 +1,7 @@ """ Tests using vim formula """ + import pytest diff --git a/tests/pytests/functional/loader/test_loaded_base_name.py b/tests/pytests/functional/loader/test_loaded_base_name.py index 56c2892c8d6..ff68ff72350 100644 --- a/tests/pytests/functional/loader/test_loaded_base_name.py +++ b/tests/pytests/functional/loader/test_loaded_base_name.py @@ -10,7 +10,7 @@ from salt.loader.lazy import LazyLoader @pytest.fixture(scope="module") def loaded_base_name(): - return random_string("{}.".format(__name__), digits=False, uppercase=False) + return random_string(f"{__name__}.", digits=False, uppercase=False) @pytest.fixture(scope="module") diff --git a/tests/pytests/functional/log_handlers/test_logstash_mod.py b/tests/pytests/functional/log_handlers/test_logstash_mod.py index dfc45a75824..426ad3a51dd 100644 --- a/tests/pytests/functional/log_handlers/test_logstash_mod.py +++ b/tests/pytests/functional/log_handlers/test_logstash_mod.py @@ -36,10 +36,10 @@ def zmq_server(): context = zmq.Context() server = context.socket(zmq.SUB) port = ports.get_unused_localhost_port() - handler = ZMQLogstashHander("tcp://127.0.0.1:{}".format(port)) + handler = ZMQLogstashHander(f"tcp://127.0.0.1:{port}") try: server.setsockopt(zmq.SUBSCRIBE, b"") - server.bind("tcp://127.0.0.1:{}".format(port)) + server.bind(f"tcp://127.0.0.1:{port}") logger.setLevel(logging.DEBUG) logger.addHandler(handler) diff --git a/tests/pytests/functional/modules/cmd/test_powershell.py b/tests/pytests/functional/modules/cmd/test_powershell.py index 62b17665640..f072a967e81 100644 --- a/tests/pytests/functional/modules/cmd/test_powershell.py +++ b/tests/pytests/functional/modules/cmd/test_powershell.py @@ -87,7 +87,7 @@ def test_cmd_run_all_powershell_string(): def test_cmd_run_encoded_cmd(shell): cmd = "Write-Output 'encoded command'" - cmd = "$ProgressPreference='SilentlyContinue'; {}".format(cmd) + cmd = f"$ProgressPreference='SilentlyContinue'; {cmd}" cmd_utf16 = cmd.encode("utf-16-le") encoded_cmd = base64.standard_b64encode(cmd_utf16) encoded_cmd = salt.utils.stringutils.to_str(encoded_cmd) @@ -97,7 +97,7 @@ def test_cmd_run_encoded_cmd(shell): def test_cmd_run_all_encoded_cmd(shell): cmd = "Write-Output 'encoded command'" - cmd = "$ProgressPreference='SilentlyContinue'; {}".format(cmd) + cmd = f"$ProgressPreference='SilentlyContinue'; {cmd}" cmd_utf16 = cmd.encode("utf-16-le") encoded_cmd = base64.standard_b64encode(cmd_utf16) encoded_cmd = salt.utils.stringutils.to_str(encoded_cmd) diff --git a/tests/pytests/functional/modules/cmd/test_runas.py b/tests/pytests/functional/modules/cmd/test_runas.py index 0d4cc020124..f226900de69 100644 --- a/tests/pytests/functional/modules/cmd/test_runas.py +++ b/tests/pytests/functional/modules/cmd/test_runas.py @@ -22,5 +22,5 @@ def configure_loader_modules(): @pytest.mark.skip_if_not_root def test_run_as(account): ret = cmdmod.run("id", runas=account.username) - assert "gid={}".format(account.info.gid) in ret - assert "uid={}".format(account.info.uid) in ret + assert f"gid={account.info.gid}" in ret + assert f"uid={account.info.uid}" in ret diff --git a/tests/pytests/functional/modules/file/test_replace.py b/tests/pytests/functional/modules/file/test_replace.py index 3be41d0661d..416ddfb1945 100644 --- a/tests/pytests/functional/modules/file/test_replace.py +++ b/tests/pytests/functional/modules/file/test_replace.py @@ -1,6 +1,7 @@ """ Tests for file.rename function """ + import os import shutil @@ -46,7 +47,7 @@ def multiline_file(tmp_path_factory, multiline_string): def test_no_backup(file, multiline_file): # Backup file should NOT be created - bak_file = "{}.bak".format(multiline_file) + bak_file = f"{multiline_file}.bak" assert "Salticus" not in multiline_file.read_text() file.replace(str(multiline_file), "Etiam", "Salticus", backup=False) assert "Salticus" in multiline_file.read_text() @@ -55,7 +56,7 @@ def test_no_backup(file, multiline_file): def test_backup(file, multiline_file): # Should create a backup file. This is basically the default - bak_file = "{}.bak".format(multiline_file) + bak_file = f"{multiline_file}.bak" file.replace(str(multiline_file), "Etiam", "Salticus") assert "Salticus" in multiline_file.read_text() assert os.path.exists(bak_file) diff --git a/tests/pytests/functional/modules/file/test_rmdir.py b/tests/pytests/functional/modules/file/test_rmdir.py index 0dd6bc0476b..cca9d273496 100644 --- a/tests/pytests/functional/modules/file/test_rmdir.py +++ b/tests/pytests/functional/modules/file/test_rmdir.py @@ -33,12 +33,7 @@ def nested_empty_dirs(tmp_path): for root in range(1, num_root + 1): for mid in range(1, num_mid + 1): for last in range(1, num_last + 1): - nest = ( - tmp_path - / "root{}".format(root) - / "mid{}".format(mid) - / "last{}".format(last) - ) + nest = tmp_path / f"root{root}" / f"mid{mid}" / f"last{last}" nest.mkdir(parents=True, exist_ok=True) if last % 2: now = time.time() @@ -55,12 +50,7 @@ def nested_dirs_with_files(tmp_path): for root in range(1, num_root + 1): for mid in range(1, num_mid + 1): for last in range(1, num_last + 1): - nest = ( - tmp_path - / "root{}".format(root) - / "mid{}".format(mid) - / "last{}".format(last) - ) + nest = tmp_path / f"root{root}" / f"mid{mid}" / f"last{last}" nest.mkdir(parents=True, exist_ok=True) if last % 2: last_file = nest / "stuff.txt" diff --git a/tests/pytests/functional/modules/file/test_symlink.py b/tests/pytests/functional/modules/file/test_symlink.py index 24e110dc41f..6d40d6e9160 100644 --- a/tests/pytests/functional/modules/file/test_symlink.py +++ b/tests/pytests/functional/modules/file/test_symlink.py @@ -116,7 +116,7 @@ def test_symlink_target_relative_path(file, source): Test symlink when the target file is a relative path Should throw a SaltInvocationError """ - target = "..{}symlink.lnk".format(os.path.sep) + target = f"..{os.path.sep}symlink.lnk" with pytest.raises(SaltInvocationError) as exc: file.symlink(str(source), str(target)) assert "Link path must be absolute" in exc.value.message diff --git a/tests/pytests/functional/modules/state/test_jinja_filters.py b/tests/pytests/functional/modules/state/test_jinja_filters.py index 0fd44dba74c..7a72ba7f530 100644 --- a/tests/pytests/functional/modules/state/test_jinja_filters.py +++ b/tests/pytests/functional/modules/state/test_jinja_filters.py @@ -1,6 +1,7 @@ """ Testing Jinja filters availablilty via state system """ + import logging import os diff --git a/tests/pytests/functional/modules/test_archive.py b/tests/pytests/functional/modules/test_archive.py index 60f06aef71f..1ec0a4e092f 100644 --- a/tests/pytests/functional/modules/test_archive.py +++ b/tests/pytests/functional/modules/test_archive.py @@ -1,6 +1,7 @@ """ Tests for the archive state """ + import os import pathlib import shutil @@ -45,7 +46,7 @@ class Archive: @src.default def _src(self): - return self.path / "{}_src_dir".format(self.fmt) + return self.path / f"{self.fmt}_src_dir" @src_file.default def _src_file(self): @@ -53,11 +54,11 @@ class Archive: @archive.default def _archive(self): - return self.path / "archive.{}".format(self.fmt) + return self.path / f"archive.{self.fmt}" @dst.default def _dst(self): - return self.path / "{}_dst_dir".format(self.fmt) + return self.path / f"{self.fmt}_dst_dir" @filename.default def _filename(self): @@ -150,7 +151,7 @@ def archive(modules): def unicode_filename_ids(value): - return "unicode_filename={}".format(value) + return f"unicode_filename={value}" @pytest.fixture(params=[True, False], ids=unicode_filename_ids) diff --git a/tests/pytests/functional/modules/test_dockermod.py b/tests/pytests/functional/modules/test_dockermod.py index 3c7bb25e461..7d66379de0c 100644 --- a/tests/pytests/functional/modules/test_dockermod.py +++ b/tests/pytests/functional/modules/test_dockermod.py @@ -1,6 +1,7 @@ """ Integration tests for the docker_container states """ + import logging import pytest diff --git a/tests/pytests/functional/modules/test_etcd_mod.py b/tests/pytests/functional/modules/test_etcd_mod.py index e1e1b552df2..6ec3017e94d 100644 --- a/tests/pytests/functional/modules/test_etcd_mod.py +++ b/tests/pytests/functional/modules/test_etcd_mod.py @@ -65,10 +65,9 @@ def test_basic_operations(subtests, profile_name, prefix): assert etcd_mod.get_(prefix, recurse=True, profile=profile_name) is None with subtests.test("We should be able to set and retrieve simple values"): - etcd_mod.set_("{}/1".format(prefix), "one", profile=profile_name) + etcd_mod.set_(f"{prefix}/1", "one", profile=profile_name) assert ( - etcd_mod.get_("{}/1".format(prefix), recurse=False, profile=profile_name) - == "one" + etcd_mod.get_(f"{prefix}/1", recurse=False, profile=profile_name) == "one" ) with subtests.test("We should be able to update and retrieve those values"): @@ -85,8 +84,8 @@ def test_basic_operations(subtests, profile_name, prefix): with subtests.test("We should be list all top level values at a directory"): expected = { prefix: { - "{}/1".format(prefix): "not one", - "{}/2/".format(prefix): {}, + f"{prefix}/1": "not one", + f"{prefix}/2/": {}, }, } assert etcd_mod.ls_(path=prefix, profile=profile_name) == expected @@ -98,7 +97,7 @@ def test_basic_operations(subtests, profile_name, prefix): "4": "two-four", }, } - etcd_mod.rm_("{}/1".format(prefix), profile=profile_name) + etcd_mod.rm_(f"{prefix}/1", profile=profile_name) assert etcd_mod.tree(path=prefix, profile=profile_name) == updated with subtests.test("updates should be able to be caught by waiting in read"): @@ -106,16 +105,16 @@ def test_basic_operations(subtests, profile_name, prefix): def wait_func(return_list): return_list.append( - etcd_mod.watch("{}/1".format(prefix), timeout=30, profile=profile_name) + etcd_mod.watch(f"{prefix}/1", timeout=30, profile=profile_name) ) wait_thread = threading.Thread(target=wait_func, args=(return_list,)) wait_thread.start() time.sleep(1) - etcd_mod.set_("{}/1".format(prefix), "one", profile=profile_name) + etcd_mod.set_(f"{prefix}/1", "one", profile=profile_name) wait_thread.join() modified = return_list.pop() - assert modified["key"] == "{}/1".format(prefix) + assert modified["key"] == f"{prefix}/1" assert modified["value"] == "one" @@ -126,22 +125,22 @@ def test_with_missing_profile(subtests, prefix, etcd_version, etcd_port): if etcd_version in (EtcdVersion.v2, EtcdVersion.v3_v2_mode) and etcd_port != 2379: # Only need to run this once with subtests.test("Test no profile and bad connection in get_"): - assert etcd_mod.get_("{}/1".format(prefix)) is None + assert etcd_mod.get_(f"{prefix}/1") is None with subtests.test("Test no profile and bad connection in set_"): - assert etcd_mod.set_("{}/1".format(prefix), "lol") is None + assert etcd_mod.set_(f"{prefix}/1", "lol") is None with subtests.test("Test no profile and bad connection in update"): - assert etcd_mod.update({"{}/1".format(prefix): "SIUUU"}) is None + assert etcd_mod.update({f"{prefix}/1": "SIUUU"}) is None with subtests.test("Test no profile and bad connection in watch"): - assert etcd_mod.watch("{}/1".format(prefix)) is None + assert etcd_mod.watch(f"{prefix}/1") is None with subtests.test("Test no profile and bad connection in ls_"): assert etcd_mod.ls_() is None with subtests.test("Test no profile and bad connection in rm"): - assert etcd_mod.rm_("{}/1".format(prefix)) is None + assert etcd_mod.rm_(f"{prefix}/1") is None with subtests.test("Test no profile and bad connection in tree"): assert etcd_mod.tree() is None diff --git a/tests/pytests/functional/modules/test_mac_pkgutil.py b/tests/pytests/functional/modules/test_mac_pkgutil.py index 397bb895871..6b9233c2ecd 100644 --- a/tests/pytests/functional/modules/test_mac_pkgutil.py +++ b/tests/pytests/functional/modules/test_mac_pkgutil.py @@ -1,6 +1,7 @@ """ integration tests for mac_pkgutil """ + import shutil import pytest diff --git a/tests/pytests/functional/modules/test_mysql.py b/tests/pytests/functional/modules/test_mysql.py index d920bbdbc03..c82bba30193 100644 --- a/tests/pytests/functional/modules/test_mysql.py +++ b/tests/pytests/functional/modules/test_mysql.py @@ -1,6 +1,7 @@ """ Test Salt MySQL module across various MySQL variants """ + import logging import time diff --git a/tests/pytests/functional/modules/test_network.py b/tests/pytests/functional/modules/test_network.py index 702373c15ae..ab6aef879e5 100644 --- a/tests/pytests/functional/modules/test_network.py +++ b/tests/pytests/functional/modules/test_network.py @@ -1,6 +1,7 @@ """ Validate network module """ + import pytest pytestmark = [ @@ -76,6 +77,4 @@ def test_network_nslookup(network, url): if out in val: exp_out.remove(out) if exp_out: - pytest.fail( - "Failed to find the {} key(s) on the returned data: {}".format(exp_out, ret) - ) + pytest.fail(f"Failed to find the {exp_out} key(s) on the returned data: {ret}") diff --git a/tests/pytests/functional/modules/test_opkg.py b/tests/pytests/functional/modules/test_opkg.py index 091db51ef03..243011d5e73 100644 --- a/tests/pytests/functional/modules/test_opkg.py +++ b/tests/pytests/functional/modules/test_opkg.py @@ -63,7 +63,7 @@ def test_conf_d_path_exists_with_files(tmp_path): conf_d_path = tmp_path / "conf.d.path" conf_d_path.mkdir(parents=True, exist_ok=True) file_one = conf_d_path / "file_one" - expected_md5sum = "d41d8cd98f00b204e9800998ecf8427e {}\n".format(file_one) + expected_md5sum = f"d41d8cd98f00b204e9800998ecf8427e {file_one}\n" expected_timestamp = "10000\n" file_one.touch() os.utime(str(file_one), (int(expected_timestamp), int(expected_timestamp))) diff --git a/tests/pytests/functional/modules/test_system.py b/tests/pytests/functional/modules/test_system.py index 2dabaaebfad..e5ae735fdd3 100644 --- a/tests/pytests/functional/modules/test_system.py +++ b/tests/pytests/functional/modules/test_system.py @@ -178,7 +178,7 @@ def test_get_system_date_time(setup_teardown_vars, system, fmt_str): t1 = datetime.datetime.now() res = system.get_system_date_time() t2 = datetime.datetime.strptime(res, fmt_str) - msg = "Difference in times is too large. Now: {} Fake: {}".format(t1, t2) + msg = f"Difference in times is too large. Now: {t1} Fake: {t2}" assert _same_times(t1, t2, seconds_diff=3), msg @@ -189,7 +189,7 @@ def test_get_system_date_time_utc(setup_teardown_vars, system, fmt_str): t1 = datetime.datetime.utcnow() res = system.get_system_date_time("+0000") t2 = datetime.datetime.strptime(res, fmt_str) - msg = "Difference in times is too large. Now: {} Fake: {}".format(t1, t2) + msg = f"Difference in times is too large. Now: {t1} Fake: {t2}" assert _same_times(t1, t2, seconds_diff=3), msg diff --git a/tests/pytests/functional/modules/test_win_dsc.py b/tests/pytests/functional/modules/test_win_dsc.py index 76255968631..c496d1857c9 100644 --- a/tests/pytests/functional/modules/test_win_dsc.py +++ b/tests/pytests/functional/modules/test_win_dsc.py @@ -167,7 +167,7 @@ def test_compile_config_missing(dsc): path = "C:\\Path\\not\\exists.ps1" with pytest.raises(salt.exceptions.CommandExecutionError) as exc: dsc.compile_config(path=path) - assert exc.value.message == "{} not found".format(path) + assert exc.value.message == f"{path} not found" @pytest.mark.destructive_test @@ -204,7 +204,7 @@ def test_apply_config_missing(dsc): path = "C:\\Path\\not\\exists" with pytest.raises(salt.exceptions.CommandExecutionError) as exc: dsc.apply_config(path=path) - assert exc.value.message == "{} not found".format(path) + assert exc.value.message == f"{path} not found" @pytest.mark.destructive_test diff --git a/tests/pytests/functional/modules/test_win_shortcut.py b/tests/pytests/functional/modules/test_win_shortcut.py index 292f439536b..604a7efa6b2 100644 --- a/tests/pytests/functional/modules/test_win_shortcut.py +++ b/tests/pytests/functional/modules/test_win_shortcut.py @@ -1,6 +1,7 @@ """ Tests for win_shortcut execution module """ + import os import shutil import subprocess @@ -127,7 +128,7 @@ def tmp_share(): remove_cmd = [ "powershell", "-command", - '"Remove-SmbShare -Name {} -Force" | Out-Null'.format(share_name), + f'"Remove-SmbShare -Name {share_name} -Force" | Out-Null', ] subprocess.run(create_cmd, check=True) @@ -342,7 +343,7 @@ def test_create_lnk_smb_issue_61170(shortcut, tmp_dir, tmp_share): hot_key="Alt+Ctrl+C", icon_index=0, icon_location=r"C:\Windows\notepad.exe", - target=r"\\localhost\{}".format(tmp_share), + target=rf"\\localhost\{tmp_share}", window_style="Normal", working_dir=r"C:\Windows", ) @@ -354,7 +355,7 @@ def test_create_lnk_smb_issue_61170(shortcut, tmp_dir, tmp_share): "icon_index": 0, "icon_location": r"C:\Windows\notepad.exe", "path": test_link, - "target": r"\\localhost\{}".format(tmp_share), + "target": rf"\\localhost\{tmp_share}", "window_style": "Normal", "working_dir": r"C:\Windows", } @@ -449,7 +450,7 @@ def test_create_backup(shortcut, tmp_lnk): } result = shortcut.get(path=str(tmp_lnk)) assert result == expected - assert len(list(tmp_lnk.parent.glob("{}-*.lnk".format(tmp_lnk.stem)))) == 1 + assert len(list(tmp_lnk.parent.glob(f"{tmp_lnk.stem}-*.lnk"))) == 1 def test_create_make_dirs(shortcut, tmp_dir): diff --git a/tests/pytests/functional/modules/win_file/test_check_perms.py b/tests/pytests/functional/modules/win_file/test_check_perms.py index 7b829b35eed..f2196185904 100644 --- a/tests/pytests/functional/modules/win_file/test_check_perms.py +++ b/tests/pytests/functional/modules/win_file/test_check_perms.py @@ -1,6 +1,7 @@ """ Tests for win_file execution module """ + import pytest import salt.modules.win_file as win_file diff --git a/tests/pytests/functional/modules/win_file/test_remove.py b/tests/pytests/functional/modules/win_file/test_remove.py index 6cc26686f5a..d9e92411ca2 100644 --- a/tests/pytests/functional/modules/win_file/test_remove.py +++ b/tests/pytests/functional/modules/win_file/test_remove.py @@ -1,6 +1,7 @@ """ Tests for win_file execution module """ + import pytest import salt.modules.win_file as win_file diff --git a/tests/pytests/functional/modules/win_file/test_stat.py b/tests/pytests/functional/modules/win_file/test_stat.py index 0ff78e85fb7..a09d7d43aa9 100644 --- a/tests/pytests/functional/modules/win_file/test_stat.py +++ b/tests/pytests/functional/modules/win_file/test_stat.py @@ -1,6 +1,7 @@ """ Tests for win_file execution module """ + import pytest import salt.modules.win_file as win_file diff --git a/tests/pytests/functional/modules/win_lgpo/test_audit_settings_module.py b/tests/pytests/functional/modules/win_lgpo/test_audit_settings_module.py index 2830c7a7d27..978fe1e4c44 100644 --- a/tests/pytests/functional/modules/win_lgpo/test_audit_settings_module.py +++ b/tests/pytests/functional/modules/win_lgpo/test_audit_settings_module.py @@ -42,7 +42,7 @@ def clean_adv_audit(): # - C:\Windows\System32\GroupPolicy\Machine\Microsoft\Windows NT\Audit win_dir = os.environ.get("WINDIR") audit_csv_files = [ - r"{}\security\audit\audit.csv".format(win_dir), + rf"{win_dir}\security\audit\audit.csv", r"{}\System32\GroupPolicy\Machine\Microsoft\Windows NT\Audit\audit.csv".format( win_dir ), diff --git a/tests/pytests/functional/netapi/rest_cherrypy/test_auth.py b/tests/pytests/functional/netapi/rest_cherrypy/test_auth.py index bd348430bf2..0e4ae4e6841 100644 --- a/tests/pytests/functional/netapi/rest_cherrypy/test_auth.py +++ b/tests/pytests/functional/netapi/rest_cherrypy/test_auth.py @@ -56,7 +56,7 @@ async def test_good_login(http_client, auth_creds, content_type_map, client_conf cookies = response.headers["Set-Cookie"] response_obj = salt.utils.json.loads(response.body)["return"][0] token = response_obj["token"] - assert "session_id={}".format(token) in cookies + assert f"session_id={token}" in cookies perms = response_obj["perms"] perms_config = client_config["external_auth"]["auto"][auth_creds["username"]] assert set(perms) == set(perms_config) diff --git a/tests/pytests/functional/netapi/rest_cherrypy/test_external_auth_syntax.py b/tests/pytests/functional/netapi/rest_cherrypy/test_external_auth_syntax.py index 7344adb383d..073d0b390e2 100644 --- a/tests/pytests/functional/netapi/rest_cherrypy/test_external_auth_syntax.py +++ b/tests/pytests/functional/netapi/rest_cherrypy/test_external_auth_syntax.py @@ -14,7 +14,7 @@ pytestmark = [ ACCOUNT_USERNAME = "saltdev-syntax" -ACCOUNT_GROUP_NAME = "{}-group".format(ACCOUNT_USERNAME) +ACCOUNT_GROUP_NAME = f"{ACCOUNT_USERNAME}-group" @attr.s(frozen=True, slots=True) @@ -32,7 +32,7 @@ class ExternalAuthConfig: return { "*": ["grains.*"], ACCOUNT_USERNAME: ["@wheel"], - "{}%".format(ACCOUNT_GROUP_NAME): ["@runner"], + f"{ACCOUNT_GROUP_NAME}%": ["@runner"], } @pam.default @@ -72,14 +72,14 @@ def external_auth_ids(value): # By Group ExternalAuthConfig( eauth="pam", - pam_key="{}%".format(ACCOUNT_GROUP_NAME), + pam_key=f"{ACCOUNT_GROUP_NAME}%", pam_config=["grains.*"], expected_perms=["grains.*"], fixture_id="by-group-pam", ), ExternalAuthConfig( eauth="auto", - pam_key="{}%".format(ACCOUNT_GROUP_NAME), + pam_key=f"{ACCOUNT_GROUP_NAME}%", pam_config=["@wheel", "grains.*"], expected_perms=["@wheel", "grains.*"], fixture_id="by-group-auto", @@ -147,14 +147,14 @@ def external_auth_ids(value): # By group, by wheel ExternalAuthConfig( eauth="pam", - pam_key="{}%".format(ACCOUNT_GROUP_NAME), + pam_key=f"{ACCOUNT_GROUP_NAME}%", pam_config=["@wheel"], expected_perms=["@wheel"], fixture_id="by-group-by-@wheel-pam", ), ExternalAuthConfig( eauth="auto", - pam_key="{}%".format(ACCOUNT_GROUP_NAME), + pam_key=f"{ACCOUNT_GROUP_NAME}%", pam_config=["@wheel"], expected_perms=["@wheel", "grains.*"], fixture_id="by-group-by-@wheel-auto", @@ -162,14 +162,14 @@ def external_auth_ids(value): # By group, by runner ExternalAuthConfig( eauth="pam", - pam_key="{}%".format(ACCOUNT_GROUP_NAME), + pam_key=f"{ACCOUNT_GROUP_NAME}%", pam_config=["@runner"], expected_perms=["@runner"], fixture_id="by-group-by-@runner-pam", ), ExternalAuthConfig( eauth="auto", - pam_key="{}%".format(ACCOUNT_GROUP_NAME), + pam_key=f"{ACCOUNT_GROUP_NAME}%", pam_config=["@runner"], expected_perms=["@wheel", "grains.*"], fixture_id="by-group-by-@runner-auto", @@ -177,14 +177,14 @@ def external_auth_ids(value): # By group, by jobs ExternalAuthConfig( eauth="pam", - pam_key="{}%".format(ACCOUNT_GROUP_NAME), + pam_key=f"{ACCOUNT_GROUP_NAME}%", pam_config=["@jobs"], expected_perms=["@jobs"], fixture_id="by-group-by-@jobs-pam", ), ExternalAuthConfig( eauth="auto", - pam_key="{}%".format(ACCOUNT_GROUP_NAME), + pam_key=f"{ACCOUNT_GROUP_NAME}%", pam_config=["@jobs"], expected_perms=["@wheel", "grains.*"], fixture_id="by-group-by-@jobs-auto", diff --git a/tests/pytests/functional/netapi/rest_tornado/test_auth_handler.py b/tests/pytests/functional/netapi/rest_tornado/test_auth_handler.py index d3f42af9621..5c276ce6400 100644 --- a/tests/pytests/functional/netapi/rest_tornado/test_auth_handler.py +++ b/tests/pytests/functional/netapi/rest_tornado/test_auth_handler.py @@ -47,7 +47,7 @@ async def test_login( assert response.code == 200 response_obj = salt.utils.json.loads(response.body)["return"][0] token = response_obj["token"] - assert "session_id={}".format(token) in cookies + assert f"session_id={token}" in cookies perms = response_obj["perms"] perms_config = client_config["external_auth"]["auto"][auth_creds["username"]] assert set(perms) == set(perms_config) @@ -67,7 +67,7 @@ async def test_login( assert response.code == 200 response_obj = salt.utils.json.loads(response.body)["return"][0] token = response_obj["token"] - assert "session_id={}".format(token) in cookies + assert f"session_id={token}" in cookies perms = response_obj["perms"] perms_config = client_config["external_auth"]["auto"][auth_creds["username"]] assert set(perms) == set(perms_config) @@ -87,7 +87,7 @@ async def test_login( assert response.code == 200 response_obj = salt.utils.json.loads(response.body)["return"][0] token = response_obj["token"] - assert "session_id={}".format(token) in cookies + assert f"session_id={token}" in cookies perms = response_obj["perms"] perms_config = client_config["external_auth"]["auto"][auth_creds["username"]] assert set(perms) == set(perms_config) diff --git a/tests/pytests/functional/netapi/rest_tornado/test_auth_handler_pam.py b/tests/pytests/functional/netapi/rest_tornado/test_auth_handler_pam.py index b2c514e9586..e16320ea898 100644 --- a/tests/pytests/functional/netapi/rest_tornado/test_auth_handler_pam.py +++ b/tests/pytests/functional/netapi/rest_tornado/test_auth_handler_pam.py @@ -55,7 +55,7 @@ async def test_login( assert response.code == 200 response_obj = salt.utils.json.loads(response.body)["return"][0] token = response_obj["token"] - assert "session_id={}".format(token) in cookies + assert f"session_id={token}" in cookies perms = response_obj["perms"] perms_config = client_config["external_auth"][eauth][username] assert set(perms) == set(perms_config) @@ -75,7 +75,7 @@ async def test_login( assert response.code == 200 response_obj = salt.utils.json.loads(response.body)["return"][0] token = response_obj["token"] - assert "session_id={}".format(token) in cookies + assert f"session_id={token}" in cookies perms = response_obj["perms"] perms_config = client_config["external_auth"][eauth][username] assert set(perms) == set(perms_config) @@ -95,7 +95,7 @@ async def test_login( assert response.code == 200 response_obj = salt.utils.json.loads(response.body)["return"][0] token = response_obj["token"] - assert "session_id={}".format(token) in cookies + assert f"session_id={token}" in cookies perms = response_obj["perms"] perms_config = client_config["external_auth"][eauth][username] assert set(perms) == set(perms_config) diff --git a/tests/pytests/functional/netapi/rest_tornado/test_base_api_handler.py b/tests/pytests/functional/netapi/rest_tornado/test_base_api_handler.py index a8c4b762f6e..6794b081f47 100644 --- a/tests/pytests/functional/netapi/rest_tornado/test_base_api_handler.py +++ b/tests/pytests/functional/netapi/rest_tornado/test_base_api_handler.py @@ -95,7 +95,7 @@ async def test_token(http_client): # send a token as a cookie response = await http_client.fetch( - "/", headers={"Cookie": "{}=foo".format(saltnado.AUTH_COOKIE_NAME)} + "/", headers={"Cookie": f"{saltnado.AUTH_COOKIE_NAME}=foo"} ) token = salt.utils.json.loads(response.body)["token"] assert token == "foo" @@ -105,7 +105,7 @@ async def test_token(http_client): "/", headers={ saltnado.AUTH_TOKEN_HEADER: "foo", - "Cookie": "{}=bar".format(saltnado.AUTH_COOKIE_NAME), + "Cookie": f"{saltnado.AUTH_COOKIE_NAME}=bar", }, ) token = salt.utils.json.loads(response.body)["token"] diff --git a/tests/pytests/functional/netapi/rest_tornado/test_external_auth_syntax.py b/tests/pytests/functional/netapi/rest_tornado/test_external_auth_syntax.py index 4bdd3279ed1..fb0455152c4 100644 --- a/tests/pytests/functional/netapi/rest_tornado/test_external_auth_syntax.py +++ b/tests/pytests/functional/netapi/rest_tornado/test_external_auth_syntax.py @@ -15,7 +15,7 @@ pytestmark = [ ACCOUNT_USERNAME = "saltdev-syntax" -ACCOUNT_GROUP_NAME = "{}-group".format(ACCOUNT_USERNAME) +ACCOUNT_GROUP_NAME = f"{ACCOUNT_USERNAME}-group" @attr.s(frozen=True, slots=True) @@ -33,7 +33,7 @@ class ExternalAuthConfig: return { "*": ["grains.*"], ACCOUNT_USERNAME: ["@wheel"], - "{}%".format(ACCOUNT_GROUP_NAME): ["@runner"], + f"{ACCOUNT_GROUP_NAME}%": ["@runner"], } @pam.default @@ -73,14 +73,14 @@ def external_auth_ids(value): # By Group ExternalAuthConfig( eauth="pam", - pam_key="{}%".format(ACCOUNT_GROUP_NAME), + pam_key=f"{ACCOUNT_GROUP_NAME}%", pam_config=["grains.*"], expected_perms=["grains.*"], fixture_id="by-group-pam", ), ExternalAuthConfig( eauth="auto", - pam_key="{}%".format(ACCOUNT_GROUP_NAME), + pam_key=f"{ACCOUNT_GROUP_NAME}%", pam_config=["@wheel", "grains.*"], expected_perms=["@wheel", "grains.*"], fixture_id="by-group-auto", @@ -148,14 +148,14 @@ def external_auth_ids(value): # By group, by wheel ExternalAuthConfig( eauth="pam", - pam_key="{}%".format(ACCOUNT_GROUP_NAME), + pam_key=f"{ACCOUNT_GROUP_NAME}%", pam_config=["@wheel"], expected_perms=["@wheel"], fixture_id="by-group-by-@wheel-pam", ), ExternalAuthConfig( eauth="auto", - pam_key="{}%".format(ACCOUNT_GROUP_NAME), + pam_key=f"{ACCOUNT_GROUP_NAME}%", pam_config=["@wheel"], expected_perms=["@wheel", "grains.*"], fixture_id="by-group-by-@wheel-auto", @@ -163,14 +163,14 @@ def external_auth_ids(value): # By group, by runner ExternalAuthConfig( eauth="pam", - pam_key="{}%".format(ACCOUNT_GROUP_NAME), + pam_key=f"{ACCOUNT_GROUP_NAME}%", pam_config=["@runner"], expected_perms=["@runner"], fixture_id="by-group-by-@runner-pam", ), ExternalAuthConfig( eauth="auto", - pam_key="{}%".format(ACCOUNT_GROUP_NAME), + pam_key=f"{ACCOUNT_GROUP_NAME}%", pam_config=["@runner"], expected_perms=["@wheel", "grains.*"], fixture_id="by-group-by-@runner-auto", @@ -178,14 +178,14 @@ def external_auth_ids(value): # By group, by jobs ExternalAuthConfig( eauth="pam", - pam_key="{}%".format(ACCOUNT_GROUP_NAME), + pam_key=f"{ACCOUNT_GROUP_NAME}%", pam_config=["@jobs"], expected_perms=["@jobs"], fixture_id="by-group-by-@jobs-pam", ), ExternalAuthConfig( eauth="auto", - pam_key="{}%".format(ACCOUNT_GROUP_NAME), + pam_key=f"{ACCOUNT_GROUP_NAME}%", pam_config=["@jobs"], expected_perms=["@wheel", "grains.*"], fixture_id="by-group-by-@jobs-auto", diff --git a/tests/pytests/functional/pillar/test_gpg.py b/tests/pytests/functional/pillar/test_gpg.py index 2c7166795bb..6e633127caa 100644 --- a/tests/pytests/functional/pillar/test_gpg.py +++ b/tests/pytests/functional/pillar/test_gpg.py @@ -264,7 +264,7 @@ def gpg_homedir(salt_master, test_key): stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True, - universal_newlines=True, + text=True, ) ret = ProcessResult( returncode=proc.returncode, @@ -280,7 +280,7 @@ def gpg_homedir(salt_master, test_key): stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True, - universal_newlines=True, + text=True, input=test_key, ) ret = ProcessResult( @@ -303,7 +303,7 @@ def gpg_homedir(salt_master, test_key): stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True, - universal_newlines=True, + text=True, input="KILLAGENT", ) ret = ProcessResult( diff --git a/tests/pytests/functional/sdb/test_etcd_db.py b/tests/pytests/functional/sdb/test_etcd_db.py index eb3ebba6448..b10588320a7 100644 --- a/tests/pytests/functional/sdb/test_etcd_db.py +++ b/tests/pytests/functional/sdb/test_etcd_db.py @@ -43,10 +43,7 @@ def test_basic_operations(etcd_profile, prefix, profile_name): Ensure we can do the basic CRUD operations available in sdb.etcd_db """ assert ( - etcd_db.set_("{}/1".format(prefix), "one", profile=etcd_profile[profile_name]) - == "one" - ) - etcd_db.delete("{}/1".format(prefix), profile=etcd_profile[profile_name]) - assert ( - etcd_db.get("{}/1".format(prefix), profile=etcd_profile[profile_name]) is None + etcd_db.set_(f"{prefix}/1", "one", profile=etcd_profile[profile_name]) == "one" ) + etcd_db.delete(f"{prefix}/1", profile=etcd_profile[profile_name]) + assert etcd_db.get(f"{prefix}/1", profile=etcd_profile[profile_name]) is None diff --git a/tests/pytests/functional/states/cmd/test_runas.py b/tests/pytests/functional/states/cmd/test_runas.py index 75ce883a05c..5ab0169ffa1 100644 --- a/tests/pytests/functional/states/cmd/test_runas.py +++ b/tests/pytests/functional/states/cmd/test_runas.py @@ -13,5 +13,5 @@ def account(): def test_runas_id(cmd, account): ret = cmd.run("id", runas=account.username) assert ret.result is True - assert "uid={}".format(account.info.uid) in ret.changes["stdout"] - assert "gid={}".format(account.info.gid) in ret.changes["stdout"] + assert f"uid={account.info.uid}" in ret.changes["stdout"] + assert f"gid={account.info.gid}" in ret.changes["stdout"] diff --git a/tests/pytests/functional/states/file/test_append.py b/tests/pytests/functional/states/file/test_append.py index 874d5d20714..6eeab13e287 100644 --- a/tests/pytests/functional/states/file/test_append.py +++ b/tests/pytests/functional/states/file/test_append.py @@ -94,7 +94,7 @@ def test_issue_2379_file_append(modules, tmp_path): ) # create the sls template template_lines = [ - "{}:".format(tmp_file), + f"{tmp_file}:", " file.append:", " - text: PermitRootLogin yes", ] diff --git a/tests/pytests/functional/states/file/test_blockreplace.py b/tests/pytests/functional/states/file/test_blockreplace.py index 2e93a7a7324..6920fa27ac9 100644 --- a/tests/pytests/functional/states/file/test_blockreplace.py +++ b/tests/pytests/functional/states/file/test_blockreplace.py @@ -118,7 +118,7 @@ class BlockreplaceParts: def strip_ending_linebreak_ids(value): - return "strip_ending_linebreak={}".format(value) + return f"strip_ending_linebreak={value}" @pytest.mark.parametrize( @@ -478,7 +478,7 @@ def test_append_no_append_newline(file, tmp_path, strip_ending_linebreak): def line_breaks_ids(value): - return "line_breaks={}".format(value) + return f"line_breaks={value}" @pytest.mark.parametrize("line_breaks", ("windows", "posix"), ids=line_breaks_ids) diff --git a/tests/pytests/functional/states/file/test_cached.py b/tests/pytests/functional/states/file/test_cached.py index 1b052382071..130dd213d5a 100644 --- a/tests/pytests/functional/states/file/test_cached.py +++ b/tests/pytests/functional/states/file/test_cached.py @@ -22,7 +22,7 @@ def test_cached_test_true(): source_hash = secrets.token_hex(nbytes=32) expected = { "changes": {}, - "comment": "File will be cached: {}".format(name), + "comment": f"File will be cached: {name}", "name": name, "result": None, } @@ -41,7 +41,7 @@ def test_cached_present_test_true(): source_hash = secrets.token_hex(nbytes=32) expected = { "changes": {}, - "comment": "File already cached: {}".format(name), + "comment": f"File already cached: {name}", "name": name, "result": None, } @@ -62,7 +62,7 @@ def test_cached_present_different_hash_test_true(): existing_hash = secrets.token_hex(nbytes=32) expected = { "changes": {}, - "comment": "Hashes don't match.\nFile will be cached: {}".format(name), + "comment": f"Hashes don't match.\nFile will be cached: {name}", "name": name, "result": None, } @@ -82,7 +82,7 @@ def test_cached_present_no_source_hash_test_true(): existing_hash = secrets.token_hex(nbytes=32) expected = { "changes": {}, - "comment": "No hash found. File will be cached: {}".format(name), + "comment": f"No hash found. File will be cached: {name}", "name": name, "result": None, } diff --git a/tests/pytests/functional/states/file/test_comment.py b/tests/pytests/functional/states/file/test_comment.py index b7a7c8a7c95..cd825d75d83 100644 --- a/tests/pytests/functional/states/file/test_comment.py +++ b/tests/pytests/functional/states/file/test_comment.py @@ -1,6 +1,7 @@ """ Tests for file.comment state function """ + import re import pytest diff --git a/tests/pytests/functional/states/file/test_managed.py b/tests/pytests/functional/states/file/test_managed.py index 013935d3a70..76b139c7988 100644 --- a/tests/pytests/functional/states/file/test_managed.py +++ b/tests/pytests/functional/states/file/test_managed.py @@ -778,7 +778,6 @@ def test_issue_8947_utf8_sls(modules, tmp_path, state_tree, subtests): @pytest.mark.skip_if_not_root @pytest.mark.skip_on_windows(reason="Windows does not support setuid. Skipping.") def test_owner_after_setuid(file, modules, tmp_path, state_file_account): - """ Test to check file user/group after setting setuid or setgid. Because Python os.chown() does reset the setuid/setgid to 0. diff --git a/tests/pytests/functional/states/file/test_patch.py b/tests/pytests/functional/states/file/test_patch.py index 6dc0e0349ab..3c28eabea60 100644 --- a/tests/pytests/functional/states/file/test_patch.py +++ b/tests/pytests/functional/states/file/test_patch.py @@ -291,7 +291,7 @@ def test_patch_single_file_failure(file, tmp_path, files, patches): assert_fpath = f".*{reject_file.name}" else: assert_fpath = reject_file - assert re.search("saving rejects to (file )?{}".format(assert_fpath), ret.comment) + assert re.search(f"saving rejects to (file )?{assert_fpath}", ret.comment) @pytest.mark.skip_on_freebsd( @@ -324,7 +324,7 @@ def test_patch_directory_failure(file, tmp_path, files, patches): assert_fpath = f".*{reject_file.name}" else: assert_fpath = reject_file - assert re.search("saving rejects to (file )?{}".format(assert_fpath), ret.comment) + assert re.search(f"saving rejects to (file )?{assert_fpath}", ret.comment) def test_patch_single_file_remote_source(file, files, patches, subtests): diff --git a/tests/pytests/functional/states/file/test_pruned.py b/tests/pytests/functional/states/file/test_pruned.py index 80d4f94b6c2..544f92f210a 100644 --- a/tests/pytests/functional/states/file/test_pruned.py +++ b/tests/pytests/functional/states/file/test_pruned.py @@ -26,12 +26,7 @@ def nested_empty_dirs(tmp_path): for root in range(1, num_root + 1): for mid in range(1, num_mid + 1): for last in range(1, num_last + 1): - nest = ( - tmp_path - / "root{}".format(root) - / "mid{}".format(mid) - / "last{}".format(last) - ) + nest = tmp_path / f"root{root}" / f"mid{mid}" / f"last{last}" nest.mkdir(parents=True, exist_ok=True) yield str(tmp_path) @@ -44,12 +39,7 @@ def nested_dirs_with_files(tmp_path): for root in range(1, num_root + 1): for mid in range(1, num_mid + 1): for last in range(1, num_last + 1): - nest = ( - tmp_path - / "root{}".format(root) - / "mid{}".format(mid) - / "last{}".format(last) - ) + nest = tmp_path / f"root{root}" / f"mid{mid}" / f"last{last}" nest.mkdir(parents=True, exist_ok=True) if last % 2: last_file = nest / "stuff.txt" @@ -62,7 +52,7 @@ def test_pruned_failure(file, single_dir_with_file): assert ret.result is False assert not ret.changes["deleted"] assert len(ret.changes["errors"]) == 1 - assert ret.comment == "Failed to remove directory {}".format(single_dir_with_file) + assert ret.comment == f"Failed to remove directory {single_dir_with_file}" def test_pruned_success_recurse_and_deleted(file, nested_empty_dirs): diff --git a/tests/pytests/functional/states/file/test_recurse.py b/tests/pytests/functional/states/file/test_recurse.py index 5b58127fc7a..c735d5128da 100644 --- a/tests/pytests/functional/states/file/test_recurse.py +++ b/tests/pytests/functional/states/file/test_recurse.py @@ -180,9 +180,7 @@ def test_recurse_issue_34945(file, tmp_path, state_tree): name = tmp_path / issue_dir - ret = file.recurse( - name=str(name), source="salt://{}".format(issue_dir), dir_mode=dir_mode - ) + ret = file.recurse(name=str(name), source=f"salt://{issue_dir}", dir_mode=dir_mode) assert ret.result is True assert name.is_dir() assert src_dir.stat().st_mode != name.stat().st_mode @@ -222,7 +220,7 @@ def test_issue_2726_mode_kwarg(modules, tmp_path, state_tree): # Let's test for the wrong usage approach bad_mode_kwarg_testfile = dir1 / "bad_mode_kwarg" / "testfile" bad_template = [ - "{}:".format(bad_mode_kwarg_testfile), + f"{bad_mode_kwarg_testfile}:", " file.recurse:", " - source: salt://testfile", " - mode: 644", @@ -242,7 +240,7 @@ def test_issue_2726_mode_kwarg(modules, tmp_path, state_tree): # Now, the correct usage approach good_mode_kwargs_testfile = dir2 / "good_mode_kwargs" / "testappend" good_template = [ - "{}:".format(good_mode_kwargs_testfile), + f"{good_mode_kwargs_testfile}:", " file.recurse:", " - source: salt://testappend", " - dir_mode: 744", diff --git a/tests/pytests/functional/states/file/test_rename.py b/tests/pytests/functional/states/file/test_rename.py index db293d16277..1aa4fc77b68 100644 --- a/tests/pytests/functional/states/file/test_rename.py +++ b/tests/pytests/functional/states/file/test_rename.py @@ -1,6 +1,7 @@ """ Tests for file.rename state function """ + # nox -e pytest-zeromq-3.8(coverage=False) -- -vvv --run-slow --run-destructive tests\pytests\functional\states\file\test_rename.py import pytest diff --git a/tests/pytests/functional/states/file/test_replace.py b/tests/pytests/functional/states/file/test_replace.py index 22dab816804..48442bfb3e6 100644 --- a/tests/pytests/functional/states/file/test_replace.py +++ b/tests/pytests/functional/states/file/test_replace.py @@ -86,9 +86,9 @@ def test_replace_issue_18612_prepend(file, tmp_path): ) # ensure, the resulting file contains the expected lines - assert path_test.read_text() == "en_US.UTF-8\n{}".format(contents) + assert path_test.read_text() == f"en_US.UTF-8\n{contents}" - backup_file = path_test.with_name("{}.bak".format(path_test.name)) + backup_file = path_test.with_name(f"{path_test.name}.bak") assert backup_file.is_file() assert backup_file.read_text() == contents @@ -127,9 +127,9 @@ def test_replace_issue_18612_append(file, tmp_path): ) # ensure, the resulting file contains the expected lines - assert path_test.read_text() == "{}\nen_US.UTF-8\n".format(contents) + assert path_test.read_text() == f"{contents}\nen_US.UTF-8\n" - backup_file = path_test.with_name("{}.bak".format(path_test.name)) + backup_file = path_test.with_name(f"{path_test.name}.bak") assert backup_file.is_file() assert backup_file.read_text() == contents @@ -171,9 +171,9 @@ def test_replace_issue_18612_append_not_found_content(file, tmp_path): ) # ensure, the resulting file contains the expected lines - assert path_test.read_text() == "{}\n{}\n".format(contents, not_found_content) + assert path_test.read_text() == f"{contents}\n{not_found_content}\n" - backup_file = path_test.with_name("{}.bak".format(path_test.name)) + backup_file = path_test.with_name(f"{path_test.name}.bak") assert backup_file.is_file() assert backup_file.read_text() == contents @@ -215,7 +215,7 @@ def test_replace_issue_18612_change_mid_line_with_comment(file, tmp_path): # ensure, the resulting file contains the expected lines assert path_test.read_text() == contents.replace("#foo=bar", "foo=salt") - backup_file = path_test.with_name("{}.bak".format(path_test.name)) + backup_file = path_test.with_name(f"{path_test.name}.bak") assert backup_file.is_file() assert backup_file.read_text() == contents @@ -273,7 +273,7 @@ def test_replace_issue_18841_no_changes(file, tmp_path): assert path_test.read_text() == contents # ensure no backup file was created - backup_file = path_test.with_name("{}.bak".format(path_test.name)) + backup_file = path_test.with_name(f"{path_test.name}.bak") assert backup_file.is_file() is False # ensure the file's mtime didn't change @@ -328,7 +328,7 @@ def test_replace_issue_18841_omit_backup(file, tmp_path): assert path_test.read_text() == contents # ensure no backup file was created - backup_file = path_test.with_name("{}.bak".format(path_test.name)) + backup_file = path_test.with_name(f"{path_test.name}.bak") assert backup_file.is_file() is False # ensure the file's mtime didn't change diff --git a/tests/pytests/functional/states/file/test_symlink.py b/tests/pytests/functional/states/file/test_symlink.py index cabd1d43e83..1ad85efac2c 100644 --- a/tests/pytests/functional/states/file/test_symlink.py +++ b/tests/pytests/functional/states/file/test_symlink.py @@ -20,7 +20,7 @@ def test_symlink(file, tmp_path): "name": str(symlink), "changes": {"new": str(symlink)}, "result": True, - "comment": "Created new symlink {} -> {}".format(symlink, target), + "comment": f"Created new symlink {symlink} -> {target}", } assert ret.filtered == expected assert symlink.exists() diff --git a/tests/pytests/functional/states/rabbitmq/conftest.py b/tests/pytests/functional/states/rabbitmq/conftest.py index d8ccc1761b8..cc667939f5f 100644 --- a/tests/pytests/functional/states/rabbitmq/conftest.py +++ b/tests/pytests/functional/states/rabbitmq/conftest.py @@ -16,10 +16,10 @@ class RabbitMQImage: @container_id.default def _default_container_id(self): - return random_string("{}-{}-".format(self.name, self.tag)) + return random_string(f"{self.name}-{self.tag}-") def __str__(self): - return "{}:{}".format(self.name, self.tag) + return f"{self.name}:{self.tag}" @attr.s(kw_only=True, slots=True) @@ -42,7 +42,7 @@ def get_test_versions(): def get_test_version_id(value): - return "container={}".format(value) + return f"container={value}" @pytest.fixture(scope="package", params=get_test_versions(), ids=get_test_version_id) diff --git a/tests/pytests/functional/states/test_chocolatey_1_2_1.py b/tests/pytests/functional/states/test_chocolatey_1_2_1.py index 9dcc186636a..0e9972df17e 100644 --- a/tests/pytests/functional/states/test_chocolatey_1_2_1.py +++ b/tests/pytests/functional/states/test_chocolatey_1_2_1.py @@ -1,6 +1,7 @@ """ Functional tests for chocolatey state """ + import os import pathlib diff --git a/tests/pytests/functional/states/test_chocolatey_latest.py b/tests/pytests/functional/states/test_chocolatey_latest.py index 9d329d5fc59..41ba0df5b38 100644 --- a/tests/pytests/functional/states/test_chocolatey_latest.py +++ b/tests/pytests/functional/states/test_chocolatey_latest.py @@ -1,6 +1,7 @@ """ Functional tests for chocolatey state """ + import os import pathlib diff --git a/tests/pytests/functional/states/test_docker_network.py b/tests/pytests/functional/states/test_docker_network.py index 16a78b13a4a..3890bd7ef06 100644 --- a/tests/pytests/functional/states/test_docker_network.py +++ b/tests/pytests/functional/states/test_docker_network.py @@ -33,7 +33,7 @@ class Network: self._rand_indexes = random.sample( range(2, self.net.num_addresses - 1), self.net.num_addresses - 3 ) - self.ip_arg = "ipv{}_address".format(self.net.version) + self.ip_arg = f"ipv{self.net.version}_address" except KeyError: # No explicit subnet passed self.net = self.ip_arg = None @@ -47,12 +47,13 @@ class Network: ) def arg_map(self, arg_name): - return { + ret = { "ipv4_address": "IPv4Address", "ipv6_address": "IPv6Address", "links": "Links", "aliases": "Aliases", - }[arg_name] + } + return ret[arg_name] @property def subnet(self): @@ -165,7 +166,7 @@ def test_absent(docker_network, existing_network): assert ret.changes assert ret.changes == {"removed": True} assert ret.comment - assert ret.comment == "Removed network '{}'".format(existing_network.name) + assert ret.comment == f"Removed network '{existing_network.name}'" def test_absent_with_disconnected_container( @@ -185,7 +186,7 @@ def test_absent_when_not_present(network, docker_network): ret = docker_network.absent(name=net.name) assert ret.result is True assert not ret.changes - assert ret.comment == "Network '{}' already absent".format(net.name) + assert ret.comment == f"Network '{net.name}' already absent" def test_present(docker, network, docker_network): @@ -194,7 +195,7 @@ def test_present(docker, network, docker_network): assert ret.result is True assert ret.changes assert ret.changes == {"created": True} - assert ret.comment == "Network '{}' created".format(net.name) + assert ret.comment == f"Network '{net.name}' created" # Now check to see that the network actually exists. If it doesn't, # this next function call will raise an exception. @@ -207,7 +208,7 @@ def test_present_with_containers(network, docker, docker_network, container): assert ret.result is True assert ret.changes assert ret.changes == {"created": True, "connected": [container.name]} - assert ret.comment == "Network '{}' created".format(net.name) + assert ret.comment == f"Network '{net.name}' created" # Now check to see that the network actually exists. If it doesn't, # this next function call will raise an exception. @@ -224,7 +225,7 @@ def test_present_with_reconnect(network, docker, docker_network, container, reco assert ret.result is True assert ret.changes assert ret.changes == {"created": True} - assert ret.comment == "Network '{}' created".format(net.name) + assert ret.comment == f"Network '{net.name}' created" # Connect the container docker.connect_container_to_network(container.name, net.name) diff --git a/tests/pytests/functional/states/test_etcd_mod.py b/tests/pytests/functional/states/test_etcd_mod.py index 5a862b4c7bc..abe76fd6030 100644 --- a/tests/pytests/functional/states/test_etcd_mod.py +++ b/tests/pytests/functional/states/test_etcd_mod.py @@ -69,59 +69,53 @@ def test_basic_operations(subtests, profile_name, prefix, etcd_version): """ with subtests.test("Removing a non-existent key should not explode"): expected = { - "name": "{}/2/3".format(prefix), + "name": f"{prefix}/2/3", "comment": "Key does not exist", "result": True, "changes": {}, } - assert etcd_state.rm("{}/2/3".format(prefix), profile=profile_name) == expected + assert etcd_state.rm(f"{prefix}/2/3", profile=profile_name) == expected with subtests.test("We should be able to set a value"): expected = { - "name": "{}/1".format(prefix), + "name": f"{prefix}/1", "comment": "New key created", "result": True, - "changes": {"{}/1".format(prefix): "one"}, + "changes": {f"{prefix}/1": "one"}, } - assert ( - etcd_state.set_("{}/1".format(prefix), "one", profile=profile_name) - == expected - ) + assert etcd_state.set_(f"{prefix}/1", "one", profile=profile_name) == expected with subtests.test( "We should be able to create an empty directory and set values in it" ): if etcd_version in (EtcdVersion.v2, EtcdVersion.v3_v2_mode): expected = { - "name": "{}/2".format(prefix), + "name": f"{prefix}/2", "comment": "New directory created", "result": True, - "changes": {"{}/2".format(prefix): "Created"}, + "changes": {f"{prefix}/2": "Created"}, } - assert ( - etcd_state.directory("{}/2".format(prefix), profile=profile_name) - == expected - ) + assert etcd_state.directory(f"{prefix}/2", profile=profile_name) == expected expected = { - "name": "{}/2/3".format(prefix), + "name": f"{prefix}/2/3", "comment": "New key created", "result": True, - "changes": {"{}/2/3".format(prefix): "two-three"}, + "changes": {f"{prefix}/2/3": "two-three"}, } assert ( - etcd_state.set_("{}/2/3".format(prefix), "two-three", profile=profile_name) + etcd_state.set_(f"{prefix}/2/3", "two-three", profile=profile_name) == expected ) with subtests.test("We should be able to remove an existing key"): expected = { - "name": "{}/2/3".format(prefix), + "name": f"{prefix}/2/3", "comment": "Key removed", "result": True, - "changes": {"{}/2/3".format(prefix): "Deleted"}, + "changes": {f"{prefix}/2/3": "Deleted"}, } - assert etcd_state.rm("{}/2/3".format(prefix), profile=profile_name) == expected + assert etcd_state.rm(f"{prefix}/2/3", profile=profile_name) == expected def test_with_missing_profile(subtests, prefix, etcd_version, etcd_port): @@ -131,16 +125,16 @@ def test_with_missing_profile(subtests, prefix, etcd_version, etcd_port): if etcd_version in (EtcdVersion.v2, EtcdVersion.v3_v2_mode) and etcd_port != 2379: # Only need to run this once with subtests.test("Test no profile and bad connection in set_"): - ret = etcd_state.set_("{}/1".format(prefix), "one") + ret = etcd_state.set_(f"{prefix}/1", "one") assert not ret["result"] assert ret["comment"] == etcd_state.NO_PROFILE_MSG with subtests.test("Test no profile and bad connection in directory"): - ret = etcd_state.directory("{}/2".format(prefix)) + ret = etcd_state.directory(f"{prefix}/2") assert not ret["result"] assert ret["comment"] == etcd_state.NO_PROFILE_MSG with subtests.test("Test no profile and bad connection in rm"): - ret = etcd_state.rm("{}/2/3".format(prefix)) + ret = etcd_state.rm(f"{prefix}/2/3") assert not ret["result"] assert ret["comment"] == etcd_state.NO_PROFILE_MSG diff --git a/tests/pytests/functional/states/test_mysql.py b/tests/pytests/functional/states/test_mysql.py index 355f2cc1eba..1f14d8d8ed2 100644 --- a/tests/pytests/functional/states/test_mysql.py +++ b/tests/pytests/functional/states/test_mysql.py @@ -1,6 +1,7 @@ """ Test Salt MySQL state module across various MySQL variants """ + import logging import time diff --git a/tests/pytests/functional/states/test_svn.py b/tests/pytests/functional/states/test_svn.py index 5ad09ad37e2..a1f85eee92d 100644 --- a/tests/pytests/functional/states/test_svn.py +++ b/tests/pytests/functional/states/test_svn.py @@ -1,6 +1,7 @@ """ Tests for the SVN state """ + import logging import pytest @@ -133,7 +134,7 @@ def no_test_latest_existing_repo(svn, svn_mod, repo_url, repo_revision, repo_tar assert ret.result is True assert ret.changes assert "revision" in ret.changes - assert ret.changes["revision"] == "{} => {}".format(current_rev, repo_revision) + assert ret.changes["revision"] == f"{current_rev} => {repo_revision}" assert repo_target.joinpath(".svn").is_dir() diff --git a/tests/pytests/functional/states/test_win_certutil.py b/tests/pytests/functional/states/test_win_certutil.py index 92d238b3f4a..6b3d58b19c6 100644 --- a/tests/pytests/functional/states/test_win_certutil.py +++ b/tests/pytests/functional/states/test_win_certutil.py @@ -1,6 +1,7 @@ """ Tests for win_certutil state module """ + import pytest import salt.utils.files diff --git a/tests/pytests/functional/states/test_x509_v2.py b/tests/pytests/functional/states/test_x509_v2.py index 3cd09d7d840..01c877fceda 100644 --- a/tests/pytests/functional/states/test_x509_v2.py +++ b/tests/pytests/functional/states/test_x509_v2.py @@ -572,9 +572,9 @@ def existing_cert(x509, cert_args, ca_key, rsa_privkey, request): ca_key, encoding=cert_args.get("encoding", "pem"), passphrase=cert_args.get("pkcs12_passphrase"), - subject=subject - if "signing_policy" not in cert_args - else "CN=from_signing_policy", + subject=( + subject if "signing_policy" not in cert_args else "CN=from_signing_policy" + ), ) yield cert_args["name"] diff --git a/tests/pytests/functional/states/test_zookeeper.py b/tests/pytests/functional/states/test_zookeeper.py index e735fdd1cf0..77a50cc0b72 100644 --- a/tests/pytests/functional/states/test_zookeeper.py +++ b/tests/pytests/functional/states/test_zookeeper.py @@ -23,7 +23,7 @@ pytestmark = [ def minion_config_overrides(zookeeper_port): zookeeper_grains = { "prod": { - "hosts": "localhost:{}".format(zookeeper_port), + "hosts": f"localhost:{zookeeper_port}", "default_acl": [ { "username": "daniel", @@ -38,7 +38,7 @@ def minion_config_overrides(zookeeper_port): "username": "daniel", "password": "test", }, - "hosts": "localhost:{}".format(zookeeper_port), + "hosts": f"localhost:{zookeeper_port}", "default_acl": [ { "username": "daniel", diff --git a/tests/pytests/functional/states/win_lgpo/test_audit_settings_state.py b/tests/pytests/functional/states/win_lgpo/test_audit_settings_state.py index 6f45461618d..f7590e48938 100644 --- a/tests/pytests/functional/states/win_lgpo/test_audit_settings_state.py +++ b/tests/pytests/functional/states/win_lgpo/test_audit_settings_state.py @@ -77,7 +77,7 @@ def clean_adv_audit(): # - C:\Windows\System32\GroupPolicy\Machine\Microsoft\Windows NT\Audit win_dir = os.environ.get("WINDIR") audit_csv_files = [ - r"{}\security\audit\audit.csv".format(win_dir), + rf"{win_dir}\security\audit\audit.csv", r"{}\System32\GroupPolicy\Machine\Microsoft\Windows NT\Audit\audit.csv".format( win_dir ), diff --git a/tests/pytests/functional/transport/ipc/test_client.py b/tests/pytests/functional/transport/ipc/test_client.py index 20bc43aa064..51efbe2b5e2 100644 --- a/tests/pytests/functional/transport/ipc/test_client.py +++ b/tests/pytests/functional/transport/ipc/test_client.py @@ -110,7 +110,7 @@ async def test_basic_send(channel): async def test_send_many(channel): msgs = [] for i in range(0, 1000): - msgs.append("test_many_send_{}".format(i)) + msgs.append(f"test_many_send_{i}") for msg in msgs: await channel.send(msg) diff --git a/tests/pytests/functional/transport/server/test_request_server.py b/tests/pytests/functional/transport/server/test_request_server.py index 773de615e4d..fe271f1b403 100644 --- a/tests/pytests/functional/transport/server/test_request_server.py +++ b/tests/pytests/functional/transport/server/test_request_server.py @@ -10,9 +10,9 @@ async def test_request_server( minion_opts["transport"] = master_opts["transport"] = transport # Needed by tcp transport's RequestClient - minion_opts[ - "master_uri" - ] = f"tcp://{master_opts['interface']}:{master_opts['ret_port']}" + minion_opts["master_uri"] = ( + f"tcp://{master_opts['interface']}:{master_opts['ret_port']}" + ) req_server = salt.transport.request_server(master_opts) req_server.pre_fork(process_manager) diff --git a/tests/pytests/functional/transport/tcp/test_pub_server.py b/tests/pytests/functional/transport/tcp/test_pub_server.py index e4ec44fb856..5b9ef4b6196 100644 --- a/tests/pytests/functional/transport/tcp/test_pub_server.py +++ b/tests/pytests/functional/transport/tcp/test_pub_server.py @@ -1,5 +1,4 @@ import os -import threading import time import tornado.gen diff --git a/tests/pytests/functional/utils/functools/test_namespaced_function.py b/tests/pytests/functional/utils/functools/test_namespaced_function.py index 88b92637804..283a722a87c 100644 --- a/tests/pytests/functional/utils/functools/test_namespaced_function.py +++ b/tests/pytests/functional/utils/functools/test_namespaced_function.py @@ -11,7 +11,7 @@ log = logging.getLogger(__name__) def preserve_context_ids(value): - return "preserve_context={}".format(value) + return f"preserve_context={value}" @pytest.fixture(params=[True, False], ids=preserve_context_ids) diff --git a/tests/pytests/functional/utils/test_etcd_util.py b/tests/pytests/functional/utils/test_etcd_util.py index 9c8f9764f72..e665d0b2856 100644 --- a/tests/pytests/functional/utils/test_etcd_util.py +++ b/tests/pytests/functional/utils/test_etcd_util.py @@ -66,23 +66,23 @@ def test_simple_operations(etcd_client, prefix): """ Verify basic functionality in order to justify use of the cleanup fixture. """ - assert not etcd_client.get("{}/mtg/ambush".format(prefix)) - assert etcd_client.set("{}/mtg/ambush".format(prefix), "viper") == "viper" - assert etcd_client.get("{}/mtg/ambush".format(prefix)) == "viper" - assert etcd_client.set("{}/mtg/counter".format(prefix), "spell") == "spell" - assert etcd_client.tree("{}/mtg".format(prefix)) == { + assert not etcd_client.get(f"{prefix}/mtg/ambush") + assert etcd_client.set(f"{prefix}/mtg/ambush", "viper") == "viper" + assert etcd_client.get(f"{prefix}/mtg/ambush") == "viper" + assert etcd_client.set(f"{prefix}/mtg/counter", "spell") == "spell" + assert etcd_client.tree(f"{prefix}/mtg") == { "ambush": "viper", "counter": "spell", } - assert etcd_client.ls("{}/mtg".format(prefix)) == { - "{}/mtg".format(prefix): { - "{}/mtg/ambush".format(prefix): "viper", - "{}/mtg/counter".format(prefix): "spell", + assert etcd_client.ls(f"{prefix}/mtg") == { + f"{prefix}/mtg": { + f"{prefix}/mtg/ambush": "viper", + f"{prefix}/mtg/counter": "spell", }, } - assert etcd_client.delete("{}/mtg/ambush".format(prefix)) - assert etcd_client.delete("{}/mtg".format(prefix), recurse=True) - assert not etcd_client.get("{}/mtg".format(prefix), recurse=True) + assert etcd_client.delete(f"{prefix}/mtg/ambush") + assert etcd_client.delete(f"{prefix}/mtg", recurse=True) + assert not etcd_client.get(f"{prefix}/mtg", recurse=True) def test_simple_operations_with_raw_keys_and_values( @@ -94,23 +94,23 @@ def test_simple_operations_with_raw_keys_and_values( modified_opts[profile_name]["etcd.raw_keys"] = True modified_opts[profile_name]["etcd.raw_values"] = True etcd_client = get_conn(modified_opts, profile=profile_name) - assert not etcd_client.get("{}/mtg/ambush".format(prefix)) - assert etcd_client.set("{}/mtg/ambush".format(prefix), "viper") == b"viper" - assert etcd_client.get("{}/mtg/ambush".format(prefix)) == b"viper" - assert etcd_client.set("{}/mtg/counter".format(prefix), "spell") == b"spell" - assert etcd_client.tree("{}/mtg".format(prefix)) == { + assert not etcd_client.get(f"{prefix}/mtg/ambush") + assert etcd_client.set(f"{prefix}/mtg/ambush", "viper") == b"viper" + assert etcd_client.get(f"{prefix}/mtg/ambush") == b"viper" + assert etcd_client.set(f"{prefix}/mtg/counter", "spell") == b"spell" + assert etcd_client.tree(f"{prefix}/mtg") == { b"ambush": b"viper", b"counter": b"spell", } - assert etcd_client.ls("{}/mtg".format(prefix)) == { - "{}/mtg".format(prefix).encode("UTF-8"): { - "{}/mtg/ambush".format(prefix).encode("UTF-8"): b"viper", - "{}/mtg/counter".format(prefix).encode("UTF-8"): b"spell", + assert etcd_client.ls(f"{prefix}/mtg") == { + f"{prefix}/mtg".encode(): { + f"{prefix}/mtg/ambush".encode(): b"viper", + f"{prefix}/mtg/counter".encode(): b"spell", }, } - assert etcd_client.delete("{}/mtg/ambush".format(prefix)) - assert etcd_client.delete("{}/mtg".format(prefix), recurse=True) - assert not etcd_client.get("{}/mtg".format(prefix), recurse=True) + assert etcd_client.delete(f"{prefix}/mtg/ambush") + assert etcd_client.delete(f"{prefix}/mtg", recurse=True) + assert not etcd_client.get(f"{prefix}/mtg", recurse=True) def test_get(subtests, etcd_client, prefix): @@ -120,14 +120,14 @@ def test_get(subtests, etcd_client, prefix): # Test general get case with key=value with subtests.test("inserted keys should be able to be retrieved"): - etcd_client.set("{}/get-test/key".format(prefix), "value") - assert etcd_client.get("{}/get-test/key".format(prefix)) == "value" + etcd_client.set(f"{prefix}/get-test/key", "value") + assert etcd_client.get(f"{prefix}/get-test/key") == "value" # Test with recurse=True. with subtests.test("keys should be able to be retrieved recursively"): - etcd_client.set("{}/get-test/key2/subkey".format(prefix), "subvalue") - etcd_client.set("{}/get-test/key2/subkey2/1".format(prefix), "subvalue1") - etcd_client.set("{}/get-test/key2/subkey2/2".format(prefix), "subvalue2") + etcd_client.set(f"{prefix}/get-test/key2/subkey", "subvalue") + etcd_client.set(f"{prefix}/get-test/key2/subkey2/1", "subvalue1") + etcd_client.set(f"{prefix}/get-test/key2/subkey2/2", "subvalue2") expected = { "subkey": "subvalue", @@ -137,24 +137,22 @@ def test_get(subtests, etcd_client, prefix): }, } - assert ( - etcd_client.get("{}/get-test/key2".format(prefix), recurse=True) == expected - ) + assert etcd_client.get(f"{prefix}/get-test/key2", recurse=True) == expected def test_read(subtests, etcd_client, prefix, etcd_version): """ Test that we are able to read and wait. """ - etcd_client.set("{}/read/1".format(prefix), "one") - etcd_client.set("{}/read/2".format(prefix), "two") - etcd_client.set("{}/read/3/4".format(prefix), "three/four") + etcd_client.set(f"{prefix}/read/1", "one") + etcd_client.set(f"{prefix}/read/2", "two") + etcd_client.set(f"{prefix}/read/3/4", "three/four") # Simple read test with subtests.test( "reading a newly inserted and existent key should return that key" ): - result = etcd_client.read("{}/read/1".format(prefix)) + result = etcd_client.read(f"{prefix}/read/1") assert result if etcd_version in (EtcdVersion.v2, EtcdVersion.v3_v2_mode): assert result.value == "one" @@ -171,10 +169,10 @@ def test_read(subtests, etcd_client, prefix, etcd_version): "2": "two", "3": {"4": "three/four"}, }, - path="{}/read".format(prefix), + path=f"{prefix}/read", ) - result = etcd_client.read("{}/read".format(prefix), recurse=True) + result = etcd_client.read(f"{prefix}/read", recurse=True) assert result if etcd_version in (EtcdVersion.v2, EtcdVersion.v3_v2_mode): assert result.children @@ -187,7 +185,7 @@ def test_read(subtests, etcd_client, prefix, etcd_version): result_dict[child.key] = child.value else: for child in result: - if child.key != "{}/read".format(prefix): + if child.key != f"{prefix}/read": result_dict[child.key] = child.value assert result_dict == expected @@ -197,16 +195,16 @@ def test_read(subtests, etcd_client, prefix, etcd_version): def wait_func(return_list): return_list.append( - etcd_client.read("{}/read/1".format(prefix), wait=True, timeout=30) + etcd_client.read(f"{prefix}/read/1", wait=True, timeout=30) ) wait_thread = threading.Thread(target=wait_func, args=(return_list,)) wait_thread.start() time.sleep(1) - etcd_client.set("{}/read/1".format(prefix), "not one") + etcd_client.set(f"{prefix}/read/1", "not one") wait_thread.join() modified = return_list.pop() - assert modified.key == "{}/read/1".format(prefix) + assert modified.key == f"{prefix}/read/1" assert modified.value == "not one" # Wait for an update using recursive @@ -215,18 +213,16 @@ def test_read(subtests, etcd_client, prefix, etcd_version): def wait_func_2(return_list): return_list.append( - etcd_client.read( - "{}/read".format(prefix), wait=True, timeout=30, recurse=True - ) + etcd_client.read(f"{prefix}/read", wait=True, timeout=30, recurse=True) ) wait_thread = threading.Thread(target=wait_func_2, args=(return_list,)) wait_thread.start() time.sleep(1) - etcd_client.set("{}/read/1".format(prefix), "one again!") + etcd_client.set(f"{prefix}/read/1", "one again!") wait_thread.join() modified = return_list.pop() - assert modified.key == "{}/read/1".format(prefix) + assert modified.key == f"{prefix}/read/1" assert modified.value == "one again!" # Wait for an update after last modification @@ -242,7 +238,7 @@ def test_read(subtests, etcd_client, prefix, etcd_version): def wait_func_3(return_list): return_list.append( etcd_client.read( - "{}/read/1".format(prefix), + f"{prefix}/read/1", wait=True, timeout=30, start_revision=last_modified + 1, @@ -252,10 +248,10 @@ def test_read(subtests, etcd_client, prefix, etcd_version): wait_thread = threading.Thread(target=wait_func_3, args=(return_list,)) wait_thread.start() time.sleep(1) - etcd_client.set("{}/read/1".format(prefix), "one") + etcd_client.set(f"{prefix}/read/1", "one") wait_thread.join() modified = return_list.pop() - assert modified.key == "{}/read/1".format(prefix) + assert modified.key == f"{prefix}/read/1" assert modified.value == "one" # Wait for an update after last modification, recursively @@ -269,7 +265,7 @@ def test_read(subtests, etcd_client, prefix, etcd_version): def wait_func_4(return_list): return_list.append( etcd_client.read( - "{}/read".format(prefix), + f"{prefix}/read", wait=True, timeout=30, recurse=True, @@ -280,10 +276,10 @@ def test_read(subtests, etcd_client, prefix, etcd_version): wait_thread = threading.Thread(target=wait_func_4, args=(return_list,)) wait_thread.start() time.sleep(1) - etcd_client.set("{}/read/1".format(prefix), "one") + etcd_client.set(f"{prefix}/read/1", "one") wait_thread.join() modified = return_list.pop() - assert modified.key == "{}/read/1".format(prefix) + assert modified.key == f"{prefix}/read/1" assert modified.value == "one" @@ -291,19 +287,19 @@ def test_update(subtests, etcd_client, prefix): """ Ensure that we can update fields """ - etcd_client.set("{}/read/1".format(prefix), "one") - etcd_client.set("{}/read/2".format(prefix), "two") - etcd_client.set("{}/read/3/4".format(prefix), "three/four") + etcd_client.set(f"{prefix}/read/1", "one") + etcd_client.set(f"{prefix}/read/2", "two") + etcd_client.set(f"{prefix}/read/3/4", "three/four") # Update existent fields with subtests.test("update should work on already existent field"): updated = { - "{}/read/1".format(prefix): "not one", - "{}/read/2".format(prefix): "not two", + f"{prefix}/read/1": "not one", + f"{prefix}/read/2": "not two", } assert etcd_client.update(updated) == updated - assert etcd_client.get("{}/read/1".format(prefix)) == "not one" - assert etcd_client.get("{}/read/2".format(prefix)) == "not two" + assert etcd_client.get(f"{prefix}/read/1") == "not one" + assert etcd_client.get(f"{prefix}/read/2") == "not two" # Update non-existent fields with subtests.test("update should work on non-existent fields"): @@ -319,10 +315,10 @@ def test_update(subtests, etcd_client, prefix): } assert etcd_client.update(updated) == etcd_client._flatten(updated) - assert etcd_client.get("{}/read-2".format(prefix)) == "read-2" - assert etcd_client.get("{}/read-3".format(prefix)) == "read-3" + assert etcd_client.get(f"{prefix}/read-2") == "read-2" + assert etcd_client.get(f"{prefix}/read-3") == "read-3" assert ( - etcd_client.get("{}/read-4".format(prefix), recurse=True) + etcd_client.get(f"{prefix}/read-4", recurse=True) == updated[prefix]["read-4"] ) @@ -332,15 +328,12 @@ def test_update(subtests, etcd_client, prefix): "2": "path updated two", } expected_return = { - "{}/read/1".format(prefix): "path updated one", - "{}/read/2".format(prefix): "path updated two", + f"{prefix}/read/1": "path updated one", + f"{prefix}/read/2": "path updated two", } - assert ( - etcd_client.update(updated, path="{}/read".format(prefix)) - == expected_return - ) - assert etcd_client.get("{}/read/1".format(prefix)) == "path updated one" - assert etcd_client.get("{}/read/2".format(prefix)) == "path updated two" + assert etcd_client.update(updated, path=f"{prefix}/read") == expected_return + assert etcd_client.get(f"{prefix}/read/1") == "path updated one" + assert etcd_client.get(f"{prefix}/read/2") == "path updated two" def test_write_file(subtests, etcd_client, prefix): @@ -350,28 +343,23 @@ def test_write_file(subtests, etcd_client, prefix): with subtests.test( "we should be able to write a single value for a non-existent key" ): - assert ( - etcd_client.write_file("{}/write/key_1".format(prefix), "value_1") - == "value_1" - ) - assert etcd_client.get("{}/write/key_1".format(prefix)) == "value_1" + assert etcd_client.write_file(f"{prefix}/write/key_1", "value_1") == "value_1" + assert etcd_client.get(f"{prefix}/write/key_1") == "value_1" with subtests.test("we should be able to write a single value for an existent key"): assert ( - etcd_client.write_file("{}/write/key_1".format(prefix), "new_value_1") + etcd_client.write_file(f"{prefix}/write/key_1", "new_value_1") == "new_value_1" ) - assert etcd_client.get("{}/write/key_1".format(prefix)) == "new_value_1" + assert etcd_client.get(f"{prefix}/write/key_1") == "new_value_1" with subtests.test("we should be able to write a single value with a ttl"): assert ( - etcd_client.write_file( - "{}/write/ttl_key".format(prefix), "new_value_2", ttl=5 - ) + etcd_client.write_file(f"{prefix}/write/ttl_key", "new_value_2", ttl=5) == "new_value_2" ) time.sleep(10) - assert etcd_client.get("{}/write/ttl_key".format(prefix)) is None + assert etcd_client.get(f"{prefix}/write/ttl_key") is None def test_write_directory(subtests, etcd_client, prefix, etcd_version): @@ -382,19 +370,19 @@ def test_write_directory(subtests, etcd_client, prefix, etcd_version): pytest.skip("write_directory is not defined for etcd v3") with subtests.test("we should be able to create a non-existent directory"): - assert etcd_client.write_directory("{}/write_dir/dir1".format(prefix), None) - assert etcd_client.get("{}/write_dir/dir1".format(prefix)) is None + assert etcd_client.write_directory(f"{prefix}/write_dir/dir1", None) + assert etcd_client.get(f"{prefix}/write_dir/dir1") is None with subtests.test("writing an already existent directory should return True"): - assert etcd_client.write_directory("{}/write_dir/dir1".format(prefix), None) - assert etcd_client.get("{}/write_dir/dir1".format(prefix)) is None + assert etcd_client.write_directory(f"{prefix}/write_dir/dir1", None) + assert etcd_client.get(f"{prefix}/write_dir/dir1") is None with subtests.test("we should be able to write to a new directory"): assert ( - etcd_client.write_file("{}/write_dir/dir1/key1".format(prefix), "value1") + etcd_client.write_file(f"{prefix}/write_dir/dir1/key1", "value1") == "value1" ) - assert etcd_client.get("{}/write_dir/dir1/key1".format(prefix)) == "value1" + assert etcd_client.get(f"{prefix}/write_dir/dir1/key1") == "value1" def test_ls(subtests, etcd_client, prefix): @@ -402,25 +390,25 @@ def test_ls(subtests, etcd_client, prefix): Test listing top level contents """ with subtests.test("ls on a non-existent directory should return an empty dict"): - assert not etcd_client.ls("{}/ls".format(prefix)) + assert not etcd_client.ls(f"{prefix}/ls") with subtests.test( "ls should list the top level keys and values at the given path" ): - etcd_client.set("{}/ls/1".format(prefix), "one") - etcd_client.set("{}/ls/2".format(prefix), "two") - etcd_client.set("{}/ls/3/4".format(prefix), "three/four") + etcd_client.set(f"{prefix}/ls/1", "one") + etcd_client.set(f"{prefix}/ls/2", "two") + etcd_client.set(f"{prefix}/ls/3/4", "three/four") # If it's a dir, it's suffixed with a slash expected = { - "{}/ls".format(prefix): { - "{}/ls/1".format(prefix): "one", - "{}/ls/2".format(prefix): "two", - "{}/ls/3/".format(prefix): {}, + f"{prefix}/ls": { + f"{prefix}/ls/1": "one", + f"{prefix}/ls/2": "two", + f"{prefix}/ls/3/": {}, }, } - assert etcd_client.ls("{}/ls".format(prefix)) == expected + assert etcd_client.ls(f"{prefix}/ls") == expected @pytest.mark.parametrize("func", ("rm", "delete")) @@ -431,18 +419,18 @@ def test_rm_and_delete(subtests, etcd_client, prefix, func, etcd_version): func = getattr(etcd_client, func) with subtests.test("removing a non-existent key should do nothing"): - assert func("{}/rm/key1".format(prefix)) is None + assert func(f"{prefix}/rm/key1") is None with subtests.test("we should be able to remove an existing key"): - etcd_client.set("{}/rm/key1".format(prefix), "value1") - assert func("{}/rm/key1".format(prefix)) - assert etcd_client.get("{}/rm/key1".format(prefix)) is None + etcd_client.set(f"{prefix}/rm/key1", "value1") + assert func(f"{prefix}/rm/key1") + assert etcd_client.get(f"{prefix}/rm/key1") is None with subtests.test("we should be able to remove an empty directory"): if etcd_version == EtcdVersion.v2: - etcd_client.write_directory("{}/rm/dir1".format(prefix), None) - assert func("{}/rm/dir1".format(prefix), recurse=True) - assert etcd_client.get("{}/rm/dir1".format(prefix), recurse=True) is None + etcd_client.write_directory(f"{prefix}/rm/dir1", None) + assert func(f"{prefix}/rm/dir1", recurse=True) + assert etcd_client.get(f"{prefix}/rm/dir1", recurse=True) is None with subtests.test("we should be able to remove a directory with keys"): updated = { @@ -454,11 +442,11 @@ def test_rm_and_delete(subtests, etcd_client, prefix, func, etcd_version): }, } } - etcd_client.update(updated, path="{}/rm".format(prefix)) + etcd_client.update(updated, path=f"{prefix}/rm") - assert func("{}/rm/dir1".format(prefix), recurse=True) - assert etcd_client.get("{}/rm/dir1".format(prefix), recurse=True) is None - assert etcd_client.get("{}/rm/dir1/rm-1".format(prefix), recurse=True) is None + assert func(f"{prefix}/rm/dir1", recurse=True) + assert etcd_client.get(f"{prefix}/rm/dir1", recurse=True) is None + assert etcd_client.get(f"{prefix}/rm/dir1/rm-1", recurse=True) is None with subtests.test("removing a directory without recursion should do nothing"): updated = { @@ -470,14 +458,11 @@ def test_rm_and_delete(subtests, etcd_client, prefix, func, etcd_version): }, } } - etcd_client.update(updated, path="{}/rm".format(prefix)) + etcd_client.update(updated, path=f"{prefix}/rm") - assert func("{}/rm/dir1".format(prefix)) is None - assert ( - etcd_client.get("{}/rm/dir1".format(prefix), recurse=True) - == updated["dir1"] - ) - assert etcd_client.get("{}/rm/dir1/rm-1".format(prefix)) == "value-1" + assert func(f"{prefix}/rm/dir1") is None + assert etcd_client.get(f"{prefix}/rm/dir1", recurse=True) == updated["dir1"] + assert etcd_client.get(f"{prefix}/rm/dir1/rm-1") == "value-1" def test_tree(subtests, etcd_client, prefix, etcd_version): @@ -488,16 +473,16 @@ def test_tree(subtests, etcd_client, prefix, etcd_version): assert etcd_client.tree(prefix) is None with subtests.test("the tree of an file should be {key: value}"): - etcd_client.set("{}/1".format(prefix), "one") - assert etcd_client.tree("{}/1".format(prefix)) == {"1": "one"} + etcd_client.set(f"{prefix}/1", "one") + assert etcd_client.tree(f"{prefix}/1") == {"1": "one"} with subtests.test("the tree of an empty directory should be empty"): if etcd_version == EtcdVersion.v2: - etcd_client.write_directory("{}/2".format(prefix), None) - assert etcd_client.tree("{}/2".format(prefix)) == {} + etcd_client.write_directory(f"{prefix}/2", None) + assert etcd_client.tree(f"{prefix}/2") == {} with subtests.test("we should be able to recieve the tree of a directory"): - etcd_client.set("{}/3/4".format(prefix), "three/four") + etcd_client.set(f"{prefix}/3/4", "three/four") expected = { "1": "one", "2": {}, @@ -508,11 +493,11 @@ def test_tree(subtests, etcd_client, prefix, etcd_version): assert etcd_client.tree(prefix) == expected with subtests.test("we should be able to recieve the tree of an outer directory"): - etcd_client.set("{}/5/6/7".format(prefix), "five/six/seven") + etcd_client.set(f"{prefix}/5/6/7", "five/six/seven") expected = { "6": {"7": "five/six/seven"}, } - assert etcd_client.tree("{}/5".format(prefix)) == expected + assert etcd_client.tree(f"{prefix}/5") == expected def test_watch(subtests, etcd_client, prefix): @@ -523,32 +508,30 @@ def test_watch(subtests, etcd_client, prefix): "4": "three/four", }, } - etcd_client.update(updated, path="{}/watch".format(prefix)) + etcd_client.update(updated, path=f"{prefix}/watch") with subtests.test("watching an invalid key should timeout and return None"): - assert etcd_client.watch("{}/invalid".format(prefix), timeout=3) is None + assert etcd_client.watch(f"{prefix}/invalid", timeout=3) is None with subtests.test( "watching an valid key with no changes should timeout and return None" ): - assert etcd_client.watch("{}/watch/1".format(prefix), timeout=3) is None + assert etcd_client.watch(f"{prefix}/watch/1", timeout=3) is None # Wait for an update with subtests.test("updates should be able to be caught by waiting in read"): return_list = [] def wait_func(return_list): - return_list.append( - etcd_client.watch("{}/watch/1".format(prefix), timeout=30) - ) + return_list.append(etcd_client.watch(f"{prefix}/watch/1", timeout=30)) wait_thread = threading.Thread(target=wait_func, args=(return_list,)) wait_thread.start() time.sleep(1) - etcd_client.set("{}/watch/1".format(prefix), "not one") + etcd_client.set(f"{prefix}/watch/1", "not one") wait_thread.join() modified = return_list.pop() - assert modified["key"] == "{}/watch/1".format(prefix) + assert modified["key"] == f"{prefix}/watch/1" assert modified["value"] == "not one" # Wait for an update using recursive @@ -557,16 +540,16 @@ def test_watch(subtests, etcd_client, prefix): def wait_func_2(return_list): return_list.append( - etcd_client.watch("{}/watch".format(prefix), timeout=30, recurse=True) + etcd_client.watch(f"{prefix}/watch", timeout=30, recurse=True) ) wait_thread = threading.Thread(target=wait_func_2, args=(return_list,)) wait_thread.start() time.sleep(1) - etcd_client.set("{}/watch/1".format(prefix), "one again!") + etcd_client.set(f"{prefix}/watch/1", "one again!") wait_thread.join() modified = return_list.pop() - assert modified["key"] == "{}/watch/1".format(prefix) + assert modified["key"] == f"{prefix}/watch/1" assert modified["value"] == "one again!" # Wait for an update after last modification @@ -579,7 +562,7 @@ def test_watch(subtests, etcd_client, prefix): def wait_func_3(return_list): return_list.append( etcd_client.watch( - "{}/watch/1".format(prefix), + f"{prefix}/watch/1", timeout=30, start_revision=last_modified + 1, ) @@ -588,10 +571,10 @@ def test_watch(subtests, etcd_client, prefix): wait_thread = threading.Thread(target=wait_func_3, args=(return_list,)) wait_thread.start() time.sleep(1) - etcd_client.set("{}/watch/1".format(prefix), "one") + etcd_client.set(f"{prefix}/watch/1", "one") wait_thread.join() modified = return_list.pop() - assert modified["key"] == "{}/watch/1".format(prefix) + assert modified["key"] == f"{prefix}/watch/1" assert modified["value"] == "one" # Wait for an update after last modification, recursively @@ -602,7 +585,7 @@ def test_watch(subtests, etcd_client, prefix): def wait_func_4(return_list): return_list.append( etcd_client.watch( - "{}/watch".format(prefix), + f"{prefix}/watch", timeout=30, recurse=True, start_revision=last_modified + 1, @@ -612,8 +595,8 @@ def test_watch(subtests, etcd_client, prefix): wait_thread = threading.Thread(target=wait_func_4, args=(return_list,)) wait_thread.start() time.sleep(1) - etcd_client.set("{}/watch/1".format(prefix), "one") + etcd_client.set(f"{prefix}/watch/1", "one") wait_thread.join() modified = return_list.pop() - assert modified["key"] == "{}/watch/1".format(prefix) + assert modified["key"] == f"{prefix}/watch/1" assert modified["value"] == "one" diff --git a/tests/pytests/functional/utils/test_jinja.py b/tests/pytests/functional/utils/test_jinja.py index 98070c9909b..9623e198b5d 100644 --- a/tests/pytests/functional/utils/test_jinja.py +++ b/tests/pytests/functional/utils/test_jinja.py @@ -17,8 +17,8 @@ def test_utils_jinja_cache_removed_file_from_root(temp_salt_minion, tmp_path): cache_root = tmp_path / "cache" cache_root.mkdir(parents=True, exist_ok=True) filename = "jinja_cache" - sls_file = file_root / "{}.sls".format(filename) - jinja_file = file_root / "{}.jinja".format(filename) + sls_file = file_root / f"{filename}.sls" + jinja_file = file_root / f"{filename}.jinja" sls_file.write_text("{% include '" + filename + ".jinja' %}") jinja_file.write_text("{% set this = 'that' %}") diff --git a/tests/pytests/functional/utils/test_process.py b/tests/pytests/functional/utils/test_process.py index 6c420b95f48..bbb83638761 100644 --- a/tests/pytests/functional/utils/test_process.py +++ b/tests/pytests/functional/utils/test_process.py @@ -4,6 +4,7 @@ tests.pytests.functional.utils.test_process Test salt's process utility module """ + import pytest import salt.utils.process diff --git a/tests/pytests/functional/utils/win_dacl/test_get_name.py b/tests/pytests/functional/utils/win_dacl/test_get_name.py index 8ea5d7614e4..f35c1336ec4 100644 --- a/tests/pytests/functional/utils/win_dacl/test_get_name.py +++ b/tests/pytests/functional/utils/win_dacl/test_get_name.py @@ -4,6 +4,7 @@ tests.pytests.unit.utils.win_dacl.test_get_name Test the get_name function in the win_dacl utility module """ + import pytest import salt.exceptions diff --git a/tests/pytests/functional/utils/win_dacl/test_get_sid.py b/tests/pytests/functional/utils/win_dacl/test_get_sid.py index e2e09f6dea6..4560713dad5 100644 --- a/tests/pytests/functional/utils/win_dacl/test_get_sid.py +++ b/tests/pytests/functional/utils/win_dacl/test_get_sid.py @@ -4,6 +4,7 @@ tests.pytests.unit.utils.win_dacl.test_get_sid Test the get_sid function in the win_dacl utility module """ + import pytest import salt.utils.win_dacl diff --git a/tests/pytests/functional/utils/win_dacl/test_get_sid_string.py b/tests/pytests/functional/utils/win_dacl/test_get_sid_string.py index adde42501ae..bea9240f75e 100644 --- a/tests/pytests/functional/utils/win_dacl/test_get_sid_string.py +++ b/tests/pytests/functional/utils/win_dacl/test_get_sid_string.py @@ -4,6 +4,7 @@ tests.pytests.unit.utils.win_dacl.test_get_sid_string Test the get_sid_string function in the win_dacl utility module """ + import pytest import salt.utils.win_dacl diff --git a/tests/pytests/integration/_logging/test_multiple_processes_logging.py b/tests/pytests/integration/_logging/test_multiple_processes_logging.py index 57a9beca3f9..b9457bad656 100644 --- a/tests/pytests/integration/_logging/test_multiple_processes_logging.py +++ b/tests/pytests/integration/_logging/test_multiple_processes_logging.py @@ -48,7 +48,7 @@ def logging_master(salt_factories): def matches(logging_master): return [ # Each of these is a separate process started by the master - "*|PID:{}|*".format(logging_master.process_pid), + f"*|PID:{logging_master.process_pid}|*", "*|MWorker-*|*", "*|Maintenance|*", "*|ReqServer|*", diff --git a/tests/pytests/integration/cli/test_batch.py b/tests/pytests/integration/cli/test_batch.py index 70d66d99598..32ae60346f4 100644 --- a/tests/pytests/integration/cli/test_batch.py +++ b/tests/pytests/integration/cli/test_batch.py @@ -24,7 +24,7 @@ def test_batch_run(salt_cli, run_timeout, salt_sub_minion): """ Tests executing a simple batch command to help catch regressions """ - ret = "Executing run on [{}]".format(repr(salt_sub_minion.id)) + ret = f"Executing run on [{repr(salt_sub_minion.id)}]" cmd = salt_cli.run( "test.echo", "batch testing", @@ -59,8 +59,8 @@ def test_batch_run_grains_targeting( Tests executing a batch command using a percentage divisor as well as grains targeting. """ - sub_min_ret = "Executing run on [{}]".format(repr(salt_sub_minion.id)) - min_ret = "Executing run on [{}]".format(repr(salt_minion.id)) + sub_min_ret = f"Executing run on [{repr(salt_sub_minion.id)}]" + min_ret = f"Executing run on [{repr(salt_minion.id)}]" cmd = salt_cli.run( "-C", "-b 25%", diff --git a/tests/pytests/integration/cli/test_salt.py b/tests/pytests/integration/cli/test_salt.py index 231e8b7dc4b..24b79a11b35 100644 --- a/tests/pytests/integration/cli/test_salt.py +++ b/tests/pytests/integration/cli/test_salt.py @@ -1,6 +1,7 @@ """ :codeauthor: Thayne Harbaugh (tharbaug@adobe.com) """ + import logging import os import shutil diff --git a/tests/pytests/integration/cli/test_salt_cp.py b/tests/pytests/integration/cli/test_salt_cp.py index 9c303e7c9b4..ce01de43437 100644 --- a/tests/pytests/integration/cli/test_salt_cp.py +++ b/tests/pytests/integration/cli/test_salt_cp.py @@ -3,7 +3,6 @@ tests.integration.shell.cp ~~~~~~~~~~~~~~~~~~~~~~~~~~ """ - import logging import os import pathlib diff --git a/tests/pytests/integration/cli/test_salt_deltaproxy.py b/tests/pytests/integration/cli/test_salt_deltaproxy.py index 3457a972aec..1d8eea0e997 100644 --- a/tests/pytests/integration/cli/test_salt_deltaproxy.py +++ b/tests/pytests/integration/cli/test_salt_deltaproxy.py @@ -1,6 +1,7 @@ """ :codeauthor: Gareth J. Greenaway (ggreenaway@vmware.com) """ + import logging import random @@ -177,7 +178,9 @@ def test_exit_status_correct_usage( f"{proxy_two}.sls", dummy_proxy_two_pillar_file, ) - with top_tempfile, controlproxy_tempfile, dummy_proxy_one_tempfile, dummy_proxy_two_tempfile: + with ( + top_tempfile + ), controlproxy_tempfile, dummy_proxy_one_tempfile, dummy_proxy_two_tempfile: factory = salt_master.salt_proxy_minion_daemon( proxy_minion_id, defaults=config_defaults, @@ -404,7 +407,11 @@ def test_invalid_connection( broken_proxy_two_tempfile = salt_master.pillar_tree.base.temp_file( f"{broken_proxy_two}.sls", broken_proxy_two_pillar_file ) - with top_tempfile, controlproxy_tempfile, dummy_proxy_one_tempfile, broken_proxy_one_tempfile, broken_proxy_two_tempfile: + with ( + top_tempfile + ), ( + controlproxy_tempfile + ), dummy_proxy_one_tempfile, broken_proxy_one_tempfile, broken_proxy_two_tempfile: factory = salt_master.salt_proxy_minion_daemon( proxy_minion_id, defaults=config_defaults, @@ -533,7 +540,11 @@ def ping(): custom_proxy_module = salt_master.state_tree.base.temp_file( "_proxy/custom_dummy.py", module_contents ) - with top_tempfile, controlproxy_tempfile, dummy_proxy_one_tempfile, dummy_proxy_two_tempfile, custom_proxy_module: + with ( + top_tempfile + ), ( + controlproxy_tempfile + ), dummy_proxy_one_tempfile, dummy_proxy_two_tempfile, custom_proxy_module: factory = salt_master.salt_proxy_minion_daemon( proxy_minion_id, defaults=config_defaults, @@ -666,7 +677,11 @@ def ping(): custom_proxy_module = salt_master.state_tree.base.temp_file( "_proxy/custom_dummy.py", module_contents ) - with top_tempfile, controlproxy_tempfile, dummy_proxy_one_tempfile, dummy_proxy_two_tempfile, custom_proxy_module: + with ( + top_tempfile + ), ( + controlproxy_tempfile + ), dummy_proxy_one_tempfile, dummy_proxy_two_tempfile, custom_proxy_module: factory = salt_master.salt_proxy_minion_daemon( proxy_minion_id, defaults=config_defaults, diff --git a/tests/pytests/integration/cluster/test_basic_cluster.py b/tests/pytests/integration/cluster/test_basic_cluster.py index 663a4a465db..1879d1c8425 100644 --- a/tests/pytests/integration/cluster/test_basic_cluster.py +++ b/tests/pytests/integration/cluster/test_basic_cluster.py @@ -1,6 +1,7 @@ """ Cluster integration tests. """ + import salt.utils.event diff --git a/tests/pytests/integration/grains/test_grains.py b/tests/pytests/integration/grains/test_grains.py index f83db6a97b8..6d374021caa 100644 --- a/tests/pytests/integration/grains/test_grains.py +++ b/tests/pytests/integration/grains/test_grains.py @@ -1,6 +1,7 @@ """ Grains include tests """ + import os diff --git a/tests/pytests/integration/master/test_payload.py b/tests/pytests/integration/master/test_payload.py index 692005b5692..9d663ac34ee 100644 --- a/tests/pytests/integration/master/test_payload.py +++ b/tests/pytests/integration/master/test_payload.py @@ -1,6 +1,7 @@ """ Tests for payload """ + import pytest diff --git a/tests/pytests/integration/minion/test_return_retries.py b/tests/pytests/integration/minion/test_return_retries.py index 058cfdc32be..be7885e7b44 100644 --- a/tests/pytests/integration/minion/test_return_retries.py +++ b/tests/pytests/integration/minion/test_return_retries.py @@ -108,7 +108,9 @@ def test_pillar_timeout(salt_master_factory, tmp_path): ) cli = master.salt_cli() sls_tempfile = master.state_tree.base.temp_file(f"{sls_name}.sls", sls_contents) - with master.started(), minion1.started(), minion2.started(), minion3.started(), minion4.started(), sls_tempfile: + with master.started(), minion1.started(), minion2.started(), minion3.started(), minion4.started(), ( + sls_tempfile + ): cmd = 'import time; time.sleep(6); print(\'{"foo": "bang"}\');\n' with salt.utils.files.fopen(tmp_path / "script.py", "w") as fp: fp.write(cmd) diff --git a/tests/pytests/integration/modules/grains/test_module.py b/tests/pytests/integration/modules/grains/test_module.py index cbbb149d2ad..bb977af9183 100644 --- a/tests/pytests/integration/modules/grains/test_module.py +++ b/tests/pytests/integration/modules/grains/test_module.py @@ -2,7 +2,6 @@ Test the grains module """ - import logging import time diff --git a/tests/pytests/integration/modules/saltutil/test_modules.py b/tests/pytests/integration/modules/saltutil/test_modules.py index 9d10189bb30..d35cb735f2e 100644 --- a/tests/pytests/integration/modules/saltutil/test_modules.py +++ b/tests/pytests/integration/modules/saltutil/test_modules.py @@ -2,7 +2,6 @@ Integration tests for the saltutil module. """ - import pytest pytestmark = [ diff --git a/tests/pytests/integration/modules/saltutil/test_pillar.py b/tests/pytests/integration/modules/saltutil/test_pillar.py index 7eb51605604..c1e451772c3 100644 --- a/tests/pytests/integration/modules/saltutil/test_pillar.py +++ b/tests/pytests/integration/modules/saltutil/test_pillar.py @@ -2,7 +2,6 @@ Integration tests for the saltutil module. """ - import logging import time diff --git a/tests/pytests/integration/modules/saltutil/test_wheel.py b/tests/pytests/integration/modules/saltutil/test_wheel.py index 51164c62399..3ddb95c2dc3 100644 --- a/tests/pytests/integration/modules/saltutil/test_wheel.py +++ b/tests/pytests/integration/modules/saltutil/test_wheel.py @@ -2,7 +2,6 @@ Integration tests for the saltutil module. """ - import pathlib import shutil diff --git a/tests/pytests/integration/modules/state/test_state_test.py b/tests/pytests/integration/modules/state/test_state_test.py index 40049e9a6b6..776350af1d9 100644 --- a/tests/pytests/integration/modules/state/test_state_test.py +++ b/tests/pytests/integration/modules/state/test_state_test.py @@ -173,7 +173,7 @@ def test_state_sls_id_test_true_post_run(salt_call_cli, testfile_path): assert ret.returncode == 0 assert testfile_path.exists() for val in ret.data.values(): - assert val["comment"] == "File {} updated".format(testfile_path) + assert val["comment"] == f"File {testfile_path} updated" assert val["changes"]["diff"] == "New file" ret = salt_call_cli.run("state.sls", "sls-id-test", test=True) @@ -195,7 +195,7 @@ def test_state_sls_id_test_false_pillar_true(salt_call_cli, testfile_path): ret = salt_call_cli.run("state.sls", "sls-id-test", test=False) assert ret.returncode == 0 for val in ret.data.values(): - assert val["comment"] == "File {} updated".format(testfile_path) + assert val["comment"] == f"File {testfile_path} updated" assert val["changes"]["diff"] == "New file" diff --git a/tests/pytests/integration/modules/test_beacons.py b/tests/pytests/integration/modules/test_beacons.py index 1a1ae274854..7908f4db609 100644 --- a/tests/pytests/integration/modules/test_beacons.py +++ b/tests/pytests/integration/modules/test_beacons.py @@ -1,6 +1,7 @@ """ :codeauthor: Justin Anderson """ + import pathlib import shutil diff --git a/tests/pytests/integration/modules/test_event.py b/tests/pytests/integration/modules/test_event.py index 172b2ab445b..b6ea0a2d1cb 100644 --- a/tests/pytests/integration/modules/test_event.py +++ b/tests/pytests/integration/modules/test_event.py @@ -2,6 +2,7 @@ tests.pytests.integration.modules.test_event ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ + import time import pytest diff --git a/tests/pytests/integration/modules/test_file.py b/tests/pytests/integration/modules/test_file.py index 1489269a93f..f68031b67e7 100644 --- a/tests/pytests/integration/modules/test_file.py +++ b/tests/pytests/integration/modules/test_file.py @@ -1,6 +1,7 @@ """ Tests for the file state """ + import os import pytest @@ -110,7 +111,7 @@ def test_manage_file_verify_ssl( ) if not verify_ssl: assert ret.data["changes"] == {"diff": "New file", "mode": "0000"} - assert ret.data["comment"] == "File {} updated".format(test_file) + assert ret.data["comment"] == f"File {test_file} updated" else: assert "SSL: CERTIFICATE_VERIFY_FAILED" in ret.stderr diff --git a/tests/pytests/integration/modules/test_idem.py b/tests/pytests/integration/modules/test_idem.py index 90e319cab0d..9ddc3eb4412 100644 --- a/tests/pytests/integration/modules/test_idem.py +++ b/tests/pytests/integration/modules/test_idem.py @@ -1,6 +1,7 @@ """ Integration tests for the idem execution module """ + from contextlib import contextmanager import pytest diff --git a/tests/pytests/integration/modules/test_rpmbuild_pkgbuild.py b/tests/pytests/integration/modules/test_rpmbuild_pkgbuild.py index e4bc54b56e5..c9eaa3284b2 100644 --- a/tests/pytests/integration/modules/test_rpmbuild_pkgbuild.py +++ b/tests/pytests/integration/modules/test_rpmbuild_pkgbuild.py @@ -270,7 +270,7 @@ def gpg_agent(request, gpghome): shell=True, stdout=subprocess.PIPE, check=True, - universal_newlines=True, + text=True, ) if tuple(int(p) for p in gpg_version_proc.stdout.split(".")) >= (2, 1): kill_option_supported = True @@ -286,7 +286,7 @@ def gpg_agent(request, gpghome): ["pidof", "gpg-agent"], check=True, stdout=subprocess.PIPE, - universal_newlines=True, + text=True, ) except subprocess.CalledProcessError as exc: # Not running @@ -314,7 +314,7 @@ def gpg_agent(request, gpghome): ) ) subprocess.run( # nosec - "{}; {}".format(gpg_agent_cmd, echo_gpg_tty_cmd), shell=True, check=True + f"{gpg_agent_cmd}; {echo_gpg_tty_cmd}", shell=True, check=True ) yield finally: @@ -327,7 +327,7 @@ def gpg_agent(request, gpghome): ["pidof", "gpg-agent"], check=True, stdout=subprocess.PIPE, - universal_newlines=True, + text=True, ) except subprocess.CalledProcessError as exc: # Not running diff --git a/tests/pytests/integration/modules/test_state.py b/tests/pytests/integration/modules/test_state.py index c9804afb6a9..847a71df62c 100644 --- a/tests/pytests/integration/modules/test_state.py +++ b/tests/pytests/integration/modules/test_state.py @@ -24,7 +24,7 @@ def test_logging_and_state_output_order(salt_master, salt_minion, salt_cli, tmp_ target_path ) sls_tempfile = salt_master.state_tree.base.temp_file( - "{}.sls".format(sls_name), sls_contents + f"{sls_name}.sls", sls_contents ) with sls_tempfile: # Get the command line to use @@ -40,7 +40,7 @@ def test_logging_and_state_output_order(salt_master, salt_minion, salt_cli, tmp_ stderr=subprocess.STDOUT, check=False, shell=False, - universal_newlines=True, + text=True, ) assert ret.stdout assert not ret.stderr @@ -53,7 +53,7 @@ def test_logging_and_state_output_order(salt_master, salt_minion, salt_cli, tmp_ # This output order should not match and should trigger a _pytest.outcomes.Failed exception matcher.fnmatch_lines( [ - '"{}":*'.format(salt_minion.id), + f'"{salt_minion.id}":*', '"file_*', "*Reading configuration from*", ] @@ -66,7 +66,7 @@ def test_logging_and_state_output_order(salt_master, salt_minion, salt_cli, tmp_ # Confirm we have logging going on... "*Reading configuration from*", # And that after logging, we have the state output - '"{}":*'.format(salt_minion.id), + f'"{salt_minion.id}":*', '"file_*', ] ) diff --git a/tests/pytests/integration/modules/test_useradd.py b/tests/pytests/integration/modules/test_useradd.py index 6b180d89df6..25c2d7090da 100644 --- a/tests/pytests/integration/modules/test_useradd.py +++ b/tests/pytests/integration/modules/test_useradd.py @@ -1,6 +1,7 @@ """ Integration tests for modules/useradd.py and modules/win_useradd.py """ + import pytest from saltfactories.utils import random_string diff --git a/tests/pytests/integration/modules/test_virt.py b/tests/pytests/integration/modules/test_virt.py index 8f1c71e2238..2ce6eed7357 100644 --- a/tests/pytests/integration/modules/test_virt.py +++ b/tests/pytests/integration/modules/test_virt.py @@ -1,6 +1,7 @@ """ Validate the virt module """ + import logging from numbers import Number from xml.etree import ElementTree diff --git a/tests/pytests/integration/netapi/rest_cherrypy/test_arg_kwarg.py b/tests/pytests/integration/netapi/rest_cherrypy/test_arg_kwarg.py index 65e12a082d6..9db103d7a19 100644 --- a/tests/pytests/integration/netapi/rest_cherrypy/test_arg_kwarg.py +++ b/tests/pytests/integration/netapi/rest_cherrypy/test_arg_kwarg.py @@ -48,7 +48,7 @@ async def test_accepts_arg_kwarg_keys( arg = _low.pop("arg") body = urllib.parse.urlencode(_low) for _arg in arg: - body += "&arg={}".format(_arg) + body += f"&arg={_arg}" response = await http_client.fetch( "/", method="POST", @@ -70,7 +70,7 @@ async def test_accepts_arg_kwarg_keys( _low = low2.copy() arg = _low.pop("arg") body = urllib.parse.urlencode(_low) - body += "&arg={}".format(arg) + body += f"&arg={arg}" response = await http_client.fetch( "/", method="POST", diff --git a/tests/pytests/integration/netapi/rest_cherrypy/test_auth.py b/tests/pytests/integration/netapi/rest_cherrypy/test_auth.py index ce11207d2c1..0c46316eafe 100644 --- a/tests/pytests/integration/netapi/rest_cherrypy/test_auth.py +++ b/tests/pytests/integration/netapi/rest_cherrypy/test_auth.py @@ -54,7 +54,7 @@ async def test_good_login(http_client, auth_creds, content_type_map, client_conf cookies = response.headers["Set-Cookie"] response_obj = salt.utils.json.loads(response.body)["return"][0] token = response_obj["token"] - assert "session_id={}".format(token) in cookies + assert f"session_id={token}" in cookies perms = response_obj["perms"] perms_config = client_config["external_auth"]["auto"][auth_creds["username"]] assert set(perms) == set(perms_config) diff --git a/tests/pytests/integration/netapi/rest_tornado/test_jobs_api_handler.py b/tests/pytests/integration/netapi/rest_tornado/test_jobs_api_handler.py index 80cc53453f2..b47875b7410 100644 --- a/tests/pytests/integration/netapi/rest_tornado/test_jobs_api_handler.py +++ b/tests/pytests/integration/netapi/rest_tornado/test_jobs_api_handler.py @@ -37,7 +37,7 @@ async def test_get(http_client, subtests): # test with a specific JID passed in jid = next(iter(response_obj.keys())) response = await http_client.fetch( - "/jobs/{}".format(jid), + f"/jobs/{jid}", method="GET", follow_redirects=False, ) diff --git a/tests/pytests/integration/pillar/cache/test_pillar_cache.py b/tests/pytests/integration/pillar/cache/test_pillar_cache.py index d54bbfa082f..86f0d49d39b 100644 --- a/tests/pytests/integration/pillar/cache/test_pillar_cache.py +++ b/tests/pytests/integration/pillar/cache/test_pillar_cache.py @@ -1,6 +1,7 @@ """ Pillar cache tests """ + import pytest diff --git a/tests/pytests/integration/pillar/test_pillar_include.py b/tests/pytests/integration/pillar/test_pillar_include.py index 63a76599660..dfabd4cb99f 100644 --- a/tests/pytests/integration/pillar/test_pillar_include.py +++ b/tests/pytests/integration/pillar/test_pillar_include.py @@ -1,6 +1,7 @@ """ Pillar include tests """ + import pytest @@ -83,8 +84,16 @@ def pillar_include_tree(base_env_pillar_tree_root_dir, salt_minion, salt_call_cl "glob-include-b.sls", glob_include_b_pillar_file, base_env_pillar_tree_root_dir ) try: - with top_tempfile, include_tempfile, include_a_tempfile, include_b_tempfile, include_c_tempfile, include_d_tempfile: - with glob_include_tempfile, glob_include_a_tempfile, glob_include_b_tempfile: + with ( + top_tempfile + ), ( + include_tempfile + ), ( + include_a_tempfile + ), include_b_tempfile, include_c_tempfile, include_d_tempfile: + with ( + glob_include_tempfile + ), glob_include_a_tempfile, glob_include_b_tempfile: ret = salt_call_cli.run("saltutil.refresh_pillar", wait=True) assert ret.returncode == 0 assert ret.data is True diff --git a/tests/pytests/integration/proxy/conftest.py b/tests/pytests/integration/proxy/conftest.py index d924f4eba8a..6c2abb2688b 100644 --- a/tests/pytests/integration/proxy/conftest.py +++ b/tests/pytests/integration/proxy/conftest.py @@ -78,18 +78,24 @@ def deltaproxy_pillar_tree(request, salt_master, salt_delta_proxy_factory): "controlproxy.sls", controlproxy_pillar_file ) dummy_proxy_one_tempfile = salt_master.pillar_tree.base.temp_file( - "{}.sls".format(proxy_one), dummy_proxy_pillar_file + f"{proxy_one}.sls", dummy_proxy_pillar_file ) dummy_proxy_two_tempfile = salt_master.pillar_tree.base.temp_file( - "{}.sls".format(proxy_two), dummy_proxy_pillar_file + f"{proxy_two}.sls", dummy_proxy_pillar_file ) dummy_proxy_three_tempfile = salt_master.pillar_tree.base.temp_file( - "{}.sls".format(proxy_three), dummy_proxy_pillar_file + f"{proxy_three}.sls", dummy_proxy_pillar_file ) dummy_proxy_four_tempfile = salt_master.pillar_tree.base.temp_file( - "{}.sls".format(proxy_four), dummy_proxy_pillar_file + f"{proxy_four}.sls", dummy_proxy_pillar_file ) - with top_tempfile, controlproxy_tempfile, dummy_proxy_one_tempfile, dummy_proxy_two_tempfile, dummy_proxy_three_tempfile, dummy_proxy_four_tempfile: + with ( + top_tempfile + ), ( + controlproxy_tempfile + ), ( + dummy_proxy_one_tempfile + ), dummy_proxy_two_tempfile, dummy_proxy_three_tempfile, dummy_proxy_four_tempfile: yield diff --git a/tests/pytests/integration/proxy/test_deltaproxy.py b/tests/pytests/integration/proxy/test_deltaproxy.py index 48f23b18d68..c95c43f17bf 100644 --- a/tests/pytests/integration/proxy/test_deltaproxy.py +++ b/tests/pytests/integration/proxy/test_deltaproxy.py @@ -1,6 +1,7 @@ """ Simple Smoke Tests for Connected Proxy Minion """ + import logging import pytest diff --git a/tests/pytests/integration/proxy/test_shell.py b/tests/pytests/integration/proxy/test_shell.py index 44a0e137f75..fec736d7063 100644 --- a/tests/pytests/integration/proxy/test_shell.py +++ b/tests/pytests/integration/proxy/test_shell.py @@ -1,6 +1,7 @@ """ Simple Smoke Tests for Connected Proxy Minion """ + import logging import random diff --git a/tests/pytests/integration/proxy/test_simple.py b/tests/pytests/integration/proxy/test_simple.py index f3d26834ef9..048138e43e5 100644 --- a/tests/pytests/integration/proxy/test_simple.py +++ b/tests/pytests/integration/proxy/test_simple.py @@ -1,6 +1,7 @@ """ Simple Smoke Tests for Connected Proxy Minion """ + import logging import pytest diff --git a/tests/pytests/integration/runners/state/orchestrate/test_events.py b/tests/pytests/integration/runners/state/orchestrate/test_events.py index 4f0ecccb406..072317d4423 100644 --- a/tests/pytests/integration/runners/state/orchestrate/test_events.py +++ b/tests/pytests/integration/runners/state/orchestrate/test_events.py @@ -1,6 +1,7 @@ """ Tests for orchestration events """ + import concurrent.futures import functools import json diff --git a/tests/pytests/integration/runners/test_match.py b/tests/pytests/integration/runners/test_match.py index 3f7ebb2f09b..7a76ff59efe 100644 --- a/tests/pytests/integration/runners/test_match.py +++ b/tests/pytests/integration/runners/test_match.py @@ -1,6 +1,7 @@ """ Integration tests for the match runner """ + import logging import pytest diff --git a/tests/pytests/integration/sdb/test_vault.py b/tests/pytests/integration/sdb/test_vault.py index 047de78b01e..f5a4cf57870 100644 --- a/tests/pytests/integration/sdb/test_vault.py +++ b/tests/pytests/integration/sdb/test_vault.py @@ -1,6 +1,7 @@ """ Integration tests for the vault modules """ + import logging import pytest diff --git a/tests/pytests/integration/ssh/state/test_with_import_dir.py b/tests/pytests/integration/ssh/state/test_with_import_dir.py index 4048545bfc2..cc15dac1f2f 100644 --- a/tests/pytests/integration/ssh/state/test_with_import_dir.py +++ b/tests/pytests/integration/ssh/state/test_with_import_dir.py @@ -3,6 +3,7 @@ Verify salt-ssh can use imported map files in states when the map files are in another directory outside of sls files importing them. """ + import pytest pytestmark = [ diff --git a/tests/pytests/integration/ssh/test_jinja_mods.py b/tests/pytests/integration/ssh/test_jinja_mods.py index d730af16d02..aa745c7cdcd 100644 --- a/tests/pytests/integration/ssh/test_jinja_mods.py +++ b/tests/pytests/integration/ssh/test_jinja_mods.py @@ -21,7 +21,7 @@ def test_echo(salt_ssh_cli, base_env_state_tree_root_dir): echo=echo ) state_tempfile = pytest.helpers.temp_file( - "{}.sls".format(name), state_file, base_env_state_tree_root_dir + f"{name}.sls", state_file, base_env_state_tree_root_dir ) with state_tempfile: diff --git a/tests/pytests/integration/ssh/test_log.py b/tests/pytests/integration/ssh/test_log.py index e87c4a8581f..cc851407521 100644 --- a/tests/pytests/integration/ssh/test_log.py +++ b/tests/pytests/integration/ssh/test_log.py @@ -1,6 +1,7 @@ """ Integration tests for salt-ssh logging """ + import logging import time diff --git a/tests/pytests/integration/ssh/test_py_versions.py b/tests/pytests/integration/ssh/test_py_versions.py index 52ab819e808..cacd2ba97cb 100644 --- a/tests/pytests/integration/ssh/test_py_versions.py +++ b/tests/pytests/integration/ssh/test_py_versions.py @@ -1,6 +1,7 @@ """ Integration tests for salt-ssh py_versions """ + import logging import socket import time diff --git a/tests/pytests/integration/ssh/test_ssh_setup.py b/tests/pytests/integration/ssh/test_ssh_setup.py index 00e7e6394ff..2b68f5c4a48 100644 --- a/tests/pytests/integration/ssh/test_ssh_setup.py +++ b/tests/pytests/integration/ssh/test_ssh_setup.py @@ -1,6 +1,7 @@ """ Integration tests for salt-ssh py_versions """ + import logging import os import signal diff --git a/tests/pytests/integration/states/test_beacon.py b/tests/pytests/integration/states/test_beacon.py index 5d6737e6a18..5aefa6ecf2b 100644 --- a/tests/pytests/integration/states/test_beacon.py +++ b/tests/pytests/integration/states/test_beacon.py @@ -1,6 +1,7 @@ """ Integration tests for the beacon states """ + import logging import pytest diff --git a/tests/pytests/integration/states/test_file.py b/tests/pytests/integration/states/test_file.py index 4b286a854f4..1233b0b2998 100644 --- a/tests/pytests/integration/states/test_file.py +++ b/tests/pytests/integration/states/test_file.py @@ -1,6 +1,7 @@ """ Tests for the file state """ + import logging import os import pathlib @@ -656,7 +657,9 @@ def test_patch_single_file_failure( math_tempfile = pytest.helpers.temp_file(math_file, content[1], tmp_path) reject_tempfile = pytest.helpers.temp_file("reject.txt", "", tmp_path) - with sls_tempfile, sls_reject_tempfile, numbers_tempfile, math_tempfile, reject_tempfile: + with ( + sls_tempfile + ), sls_reject_tempfile, numbers_tempfile, math_tempfile, reject_tempfile: # Empty the file to ensure that the patch doesn't apply cleanly with salt.utils.files.fopen(numbers_file, "w"): pass @@ -729,7 +732,9 @@ def test_patch_directory_failure( math_tempfile = pytest.helpers.temp_file(math_file, content[1], tmp_path) reject_tempfile = pytest.helpers.temp_file("reject.txt", "", tmp_path) - with sls_tempfile, sls_reject_tempfile, numbers_tempfile, math_tempfile, reject_tempfile: + with ( + sls_tempfile + ), sls_reject_tempfile, numbers_tempfile, math_tempfile, reject_tempfile: # Empty the file to ensure that the patch doesn't apply cleanly with salt.utils.files.fopen(math_file, "w"): pass diff --git a/tests/pytests/integration/states/test_idem.py b/tests/pytests/integration/states/test_idem.py index feab60d4951..86d253036e7 100644 --- a/tests/pytests/integration/states/test_idem.py +++ b/tests/pytests/integration/states/test_idem.py @@ -1,6 +1,7 @@ """ Tests for the idem state """ + import tempfile from contextlib import contextmanager @@ -62,5 +63,5 @@ def test_bad_state(salt_call_cli): parent = ret.data["idem_|-idem_bad_test_|-idem_bad_test_|-state"] assert parent["result"] is False - assert "SLS ref {} did not resolve to a file".format(bad_sls) == parent["comment"] + assert f"SLS ref {bad_sls} did not resolve to a file" == parent["comment"] assert not parent["sub_state_run"] diff --git a/tests/pytests/integration/states/test_include.py b/tests/pytests/integration/states/test_include.py index 62ee7efeaf8..829ccddd130 100644 --- a/tests/pytests/integration/states/test_include.py +++ b/tests/pytests/integration/states/test_include.py @@ -1,6 +1,7 @@ """ Integration tests for the jinja includes in states """ + import logging import pytest diff --git a/tests/pytests/integration/utils/test_templates.py b/tests/pytests/integration/utils/test_templates.py index 241bd8f58d8..595dcebe0ac 100644 --- a/tests/pytests/integration/utils/test_templates.py +++ b/tests/pytests/integration/utils/test_templates.py @@ -1,6 +1,7 @@ """ Tests for the templates utils """ + import os import pytest @@ -25,7 +26,7 @@ def test_issue_60083( {{ pillar|json }} """ sls_tempfile = pytest.helpers.temp_file( - "{}.sls".format(sls_name), sls_contents, base_env_state_tree_root_dir + f"{sls_name}.sls", sls_contents, base_env_state_tree_root_dir ) with sls_tempfile: # , issue_50221_ext_pillar_tempfile: ret = salt_call_cli.run( @@ -60,7 +61,7 @@ def test_issue_62372( {{ my_list | random_shuffle(seed="static") }} """ sls_tempfile = pytest.helpers.temp_file( - "{}.sls".format(sls_name), sls_contents, base_env_state_tree_root_dir + f"{sls_name}.sls", sls_contents, base_env_state_tree_root_dir ) with sls_tempfile: ret = salt_call_cli.run( diff --git a/tests/pytests/integration/wheel/test_pillar_roots.py b/tests/pytests/integration/wheel/test_pillar_roots.py index df6bb578550..c107f1646b3 100644 --- a/tests/pytests/integration/wheel/test_pillar_roots.py +++ b/tests/pytests/integration/wheel/test_pillar_roots.py @@ -37,7 +37,7 @@ def test_write_subdir(client, salt_master): def test_cvr_2021_25282(client, pillar_file_path): ret = client.cmd( "pillar_roots.write", - kwarg={"data": "foo", "path": "../{}".format(pillar_file_path.name)}, + kwarg={"data": "foo", "path": f"../{pillar_file_path.name}"}, ) assert not pillar_file_path.parent.parent.joinpath(pillar_file_path.name).is_file() assert ret.find("Invalid path") != -1 @@ -46,7 +46,7 @@ def test_cvr_2021_25282(client, pillar_file_path): def test_cvr_2021_25282_subdir(client, pillar_file_path): ret = client.cmd( "pillar_roots.write", - kwarg={"data": "foo", "path": "../../{}".format(pillar_file_path.name)}, + kwarg={"data": "foo", "path": f"../../{pillar_file_path.name}"}, ) assert not pillar_file_path.parent.parent.parent.joinpath( pillar_file_path.name diff --git a/tests/pytests/pkg/conftest.py b/tests/pytests/pkg/conftest.py index 048ad7a238d..20d71f14228 100644 --- a/tests/pytests/pkg/conftest.py +++ b/tests/pytests/pkg/conftest.py @@ -373,12 +373,12 @@ def salt_minion(salt_factories, salt_master, install_salt): "open_mode": True, } if platform.is_windows(): - config_overrides[ - "winrepo_dir" - ] = rf"{salt_factories.root_dir}\srv\salt\win\repo" - config_overrides[ - "winrepo_dir_ng" - ] = rf"{salt_factories.root_dir}\srv\salt\win\repo_ng" + config_overrides["winrepo_dir"] = ( + rf"{salt_factories.root_dir}\srv\salt\win\repo" + ) + config_overrides["winrepo_dir_ng"] = ( + rf"{salt_factories.root_dir}\srv\salt\win\repo_ng" + ) config_overrides["winrepo_source_dir"] = r"salt://win/repo_ng" if install_salt.classic and platform.is_windows(): diff --git a/tests/pytests/pkg/download/test_pkg_download.py b/tests/pytests/pkg/download/test_pkg_download.py index a71d4b038e9..d25db84383f 100644 --- a/tests/pytests/pkg/download/test_pkg_download.py +++ b/tests/pytests/pkg/download/test_pkg_download.py @@ -1,6 +1,7 @@ """ Test Salt Pkg Downloads """ + import contextlib import logging import os diff --git a/tests/pytests/scenarios/blackout/conftest.py b/tests/pytests/scenarios/blackout/conftest.py index 09cee10db66..dd025aa0d74 100644 --- a/tests/pytests/scenarios/blackout/conftest.py +++ b/tests/pytests/scenarios/blackout/conftest.py @@ -76,7 +76,7 @@ class BlackoutPillar: ) else: pytest.fail( - "Minion did not refresh pillar after {} seconds".format(timeout) + f"Minion did not refresh pillar after {timeout} seconds" ) time.sleep(sleep) diff --git a/tests/pytests/scenarios/blackout/test_minion_blackout.py b/tests/pytests/scenarios/blackout/test_minion_blackout.py index 581ad2b135b..ed5fca72c48 100644 --- a/tests/pytests/scenarios/blackout/test_minion_blackout.py +++ b/tests/pytests/scenarios/blackout/test_minion_blackout.py @@ -2,7 +2,6 @@ Tests for minion blackout """ - import logging import pytest diff --git a/tests/pytests/scenarios/cluster/test_cluster.py b/tests/pytests/scenarios/cluster/test_cluster.py index 35899a2a1e9..5f81f30b09a 100644 --- a/tests/pytests/scenarios/cluster/test_cluster.py +++ b/tests/pytests/scenarios/cluster/test_cluster.py @@ -1,6 +1,7 @@ """ Cluster scinarios. """ + import os import pathlib import time @@ -27,9 +28,9 @@ def test_cluster_key_rotation( cluster_master_3, ): config = cluster_minion_1.config.copy() - config[ - "master_uri" - ] = f"tcp://{master.config['interface']}:{master.config['ret_port']}" + config["master_uri"] = ( + f"tcp://{master.config['interface']}:{master.config['ret_port']}" + ) auth = salt.crypt.SAuth(config) auth.authenticate() assert "aes" in auth._creds @@ -64,9 +65,9 @@ def test_cluster_key_rotation( cluster_master_3, ): config = cluster_minion_1.config.copy() - config[ - "master_uri" - ] = f"tcp://{master.config['interface']}:{master.config['ret_port']}" + config["master_uri"] = ( + f"tcp://{master.config['interface']}:{master.config['ret_port']}" + ) auth = salt.crypt.SAuth(config) auth.authenticate() assert "aes" in auth._creds diff --git a/tests/pytests/scenarios/compat/conftest.py b/tests/pytests/scenarios/compat/conftest.py index 29d58354abc..e42c4c9259a 100644 --- a/tests/pytests/scenarios/compat/conftest.py +++ b/tests/pytests/scenarios/compat/conftest.py @@ -4,6 +4,7 @@ Salt Compatibility PyTest Fixtures """ + import logging import os import shutil @@ -61,7 +62,7 @@ def host_docker_network_ip_address(docker_client): ipam_pools=[{"subnet": network_subnet, "gateway": network_gateway}], ) assert isinstance(ret, dict), ret - assert ret["result"], "Failed to create docker network: {}".format(ret) + assert ret["result"], f"Failed to create docker network: {ret}" yield network_gateway finally: sminion.states.docker_network.absent(network_name) diff --git a/tests/pytests/scenarios/compat/test_with_versions.py b/tests/pytests/scenarios/compat/test_with_versions.py index ecb3a73de1a..cc61a01f509 100644 --- a/tests/pytests/scenarios/compat/test_with_versions.py +++ b/tests/pytests/scenarios/compat/test_with_versions.py @@ -4,6 +4,7 @@ Test current salt master with older salt minions """ + import logging import pathlib diff --git a/tests/pytests/scenarios/failover/multimaster/conftest.py b/tests/pytests/scenarios/failover/multimaster/conftest.py index 3a2c941a200..970c1e59137 100644 --- a/tests/pytests/scenarios/failover/multimaster/conftest.py +++ b/tests/pytests/scenarios/failover/multimaster/conftest.py @@ -91,8 +91,8 @@ def salt_mm_failover_minion_1(salt_mm_failover_master_1, salt_mm_failover_master mm_master_2_addr = salt_mm_failover_master_2.config["interface"] config_overrides = { "master": [ - "{}:{}".format(mm_master_1_addr, mm_master_1_port), - "{}:{}".format(mm_master_2_addr, mm_master_2_port), + f"{mm_master_1_addr}:{mm_master_1_port}", + f"{mm_master_2_addr}:{mm_master_2_port}", ], "publish_port": salt_mm_failover_master_1.config["publish_port"], "master_type": "failover", @@ -129,8 +129,8 @@ def salt_mm_failover_minion_2(salt_mm_failover_master_1, salt_mm_failover_master # We put the second master first in the list so it has the right startup checks every time. config_overrides = { "master": [ - "{}:{}".format(mm_master_2_addr, mm_master_2_port), - "{}:{}".format(mm_master_1_addr, mm_master_1_port), + f"{mm_master_2_addr}:{mm_master_2_port}", + f"{mm_master_1_addr}:{mm_master_1_port}", ], "publish_port": salt_mm_failover_master_1.config["publish_port"], "master_type": "failover", @@ -174,7 +174,7 @@ def run_salt_cmds(): for minion in list(minions_to_check): try: ret = cli.run( - "--timeout={}".format(timeout), + f"--timeout={timeout}", "test.ping", minion_tgt=minion, ) diff --git a/tests/pytests/scenarios/failover/multimaster/test_failover_master.py b/tests/pytests/scenarios/failover/multimaster/test_failover_master.py index 6efecfb8334..f661e9ab9a4 100644 --- a/tests/pytests/scenarios/failover/multimaster/test_failover_master.py +++ b/tests/pytests/scenarios/failover/multimaster/test_failover_master.py @@ -28,8 +28,8 @@ def test_pki(salt_mm_failover_master_1, salt_mm_failover_master_2, caplog): mm_master_2_addr = salt_mm_failover_master_2.config["interface"] config_overrides = { "master": [ - "{}:{}".format(mm_master_1_addr, mm_master_1_port), - "{}:{}".format(mm_master_2_addr, mm_master_2_port), + f"{mm_master_1_addr}:{mm_master_1_port}", + f"{mm_master_2_addr}:{mm_master_2_port}", ], "publish_port": salt_mm_failover_master_1.config["publish_port"], "master_type": "failover", @@ -94,7 +94,7 @@ def test_failover_to_second_master( event_patterns = [ ( salt_mm_failover_master_2.id, - "salt/minion/{}/start".format(salt_mm_failover_minion_1.id), + f"salt/minion/{salt_mm_failover_minion_1.id}/start", ) ] @@ -184,19 +184,19 @@ def test_minions_alive_with_no_master( event_patterns = [ ( salt_mm_failover_master_1.id, - "salt/minion/{}/start".format(salt_mm_failover_minion_1.id), + f"salt/minion/{salt_mm_failover_minion_1.id}/start", ), ( salt_mm_failover_master_1.id, - "salt/minion/{}/start".format(salt_mm_failover_minion_2.id), + f"salt/minion/{salt_mm_failover_minion_2.id}/start", ), ( salt_mm_failover_master_2.id, - "salt/minion/{}/start".format(salt_mm_failover_minion_1.id), + f"salt/minion/{salt_mm_failover_minion_1.id}/start", ), ( salt_mm_failover_master_2.id, - "salt/minion/{}/start".format(salt_mm_failover_minion_2.id), + f"salt/minion/{salt_mm_failover_minion_2.id}/start", ), ] events = event_listener.wait_for_events( @@ -208,7 +208,7 @@ def test_minions_alive_with_no_master( assert len(events.matches) >= 2 expected_tags = { - "salt/minion/{}/start".format(salt_mm_failover_minion_1.id), - "salt/minion/{}/start".format(salt_mm_failover_minion_2.id), + f"salt/minion/{salt_mm_failover_minion_1.id}/start", + f"salt/minion/{salt_mm_failover_minion_2.id}/start", } assert {event.tag for event in events} == expected_tags diff --git a/tests/pytests/scenarios/multimaster/conftest.py b/tests/pytests/scenarios/multimaster/conftest.py index ff230a2b46e..1bfc830cb00 100644 --- a/tests/pytests/scenarios/multimaster/conftest.py +++ b/tests/pytests/scenarios/multimaster/conftest.py @@ -91,8 +91,8 @@ def salt_mm_minion_1(salt_mm_master_1, salt_mm_master_2): mm_master_2_addr = salt_mm_master_2.config["interface"] config_overrides = { "master": [ - "{}:{}".format(mm_master_1_addr, mm_master_1_port), - "{}:{}".format(mm_master_2_addr, mm_master_2_port), + f"{mm_master_1_addr}:{mm_master_1_port}", + f"{mm_master_2_addr}:{mm_master_2_port}", ], "test.foo": "baz", } @@ -118,8 +118,8 @@ def salt_mm_minion_2(salt_mm_master_1, salt_mm_master_2): mm_master_2_addr = salt_mm_master_2.config["interface"] config_overrides = { "master": [ - "{}:{}".format(mm_master_1_addr, mm_master_1_port), - "{}:{}".format(mm_master_2_addr, mm_master_2_port), + f"{mm_master_1_addr}:{mm_master_1_port}", + f"{mm_master_2_addr}:{mm_master_2_port}", ], "test.foo": "baz", } @@ -157,7 +157,7 @@ def run_salt_cmds(): for cli in list(clis_to_check[minion]): try: ret = cli.run( - "--timeout={}".format(timeout), + f"--timeout={timeout}", "test.ping", minion_tgt=minion, _timeout=2 * timeout, diff --git a/tests/pytests/scenarios/multimaster/test_multimaster.py b/tests/pytests/scenarios/multimaster/test_multimaster.py index 8f8c8cf9055..a40e7a39622 100644 --- a/tests/pytests/scenarios/multimaster/test_multimaster.py +++ b/tests/pytests/scenarios/multimaster/test_multimaster.py @@ -110,7 +110,7 @@ def test_minion_reconnection_attempts( assert salt_mm_minion_2.is_running() start_events = event_listener.wait_for_events( - [(salt_mm_master_1.id, "salt/minion/{}/start".format(salt_mm_minion_1.id))], + [(salt_mm_master_1.id, f"salt/minion/{salt_mm_minion_1.id}/start")], timeout=60, after_time=start_time, ) @@ -123,7 +123,7 @@ def test_minion_reconnection_attempts( start_time = time.time() start_events = event_listener.wait_for_events( - [(salt_mm_master_2.id, "salt/minion/{}/start".format(salt_mm_minion_1.id))], + [(salt_mm_master_2.id, f"salt/minion/{salt_mm_minion_1.id}/start")], timeout=60, after_time=start_time, ) diff --git a/tests/pytests/scenarios/performance/conftest.py b/tests/pytests/scenarios/performance/conftest.py index 2485cf51fd3..89c92bb599e 100644 --- a/tests/pytests/scenarios/performance/conftest.py +++ b/tests/pytests/scenarios/performance/conftest.py @@ -1,6 +1,7 @@ """ Salt performance tests """ + import logging import shutil diff --git a/tests/pytests/scenarios/setup/test_install.py b/tests/pytests/scenarios/setup/test_install.py index 9c506b56cab..5953a9640c5 100644 --- a/tests/pytests/scenarios/setup/test_install.py +++ b/tests/pytests/scenarios/setup/test_install.py @@ -1,6 +1,7 @@ """ Tests for building and installing salt """ + import json import logging import os diff --git a/tests/pytests/scenarios/setup/test_man.py b/tests/pytests/scenarios/setup/test_man.py index 28f0d6285a3..92b91e8e6d0 100644 --- a/tests/pytests/scenarios/setup/test_man.py +++ b/tests/pytests/scenarios/setup/test_man.py @@ -59,7 +59,7 @@ def test_man_pages(virtualenv, src_dir): venv.venv_python, "setup.py", "install", - "--root={}".format(rootdir), + f"--root={rootdir}", cwd=src_dir, ) diff --git a/tests/pytests/unit/auth/test_ldap.py b/tests/pytests/unit/auth/test_ldap.py index fe973701af3..6a43bb350d0 100644 --- a/tests/pytests/unit/auth/test_ldap.py +++ b/tests/pytests/unit/auth/test_ldap.py @@ -1,6 +1,7 @@ """ Unit tests for salt.auth.ldap """ + import pytest import salt.auth.ldap diff --git a/tests/pytests/unit/beacons/test_adb.py b/tests/pytests/unit/beacons/test_adb.py index 0d9ee99ee6a..945e782093b 100644 --- a/tests/pytests/unit/beacons/test_adb.py +++ b/tests/pytests/unit/beacons/test_adb.py @@ -4,6 +4,7 @@ ADB beacon test cases """ + import pytest import salt.beacons.adb as adb diff --git a/tests/pytests/unit/beacons/test_avahi_announce.py b/tests/pytests/unit/beacons/test_avahi_announce.py index 2eb95a35a2f..bd7359dcd58 100644 --- a/tests/pytests/unit/beacons/test_avahi_announce.py +++ b/tests/pytests/unit/beacons/test_avahi_announce.py @@ -4,6 +4,7 @@ Avahi announce beacon test cases """ + import pytest import salt.beacons.avahi_announce as avahi_announce diff --git a/tests/pytests/unit/beacons/test_bonjour_announce.py b/tests/pytests/unit/beacons/test_bonjour_announce.py index c5551edebfd..25df0ffbd13 100644 --- a/tests/pytests/unit/beacons/test_bonjour_announce.py +++ b/tests/pytests/unit/beacons/test_bonjour_announce.py @@ -4,6 +4,7 @@ Bonjour announce beacon test cases """ + import pytest import salt.beacons.bonjour_announce as bonjour_announce diff --git a/tests/pytests/unit/beacons/test_btmp.py b/tests/pytests/unit/beacons/test_btmp.py index 6ea03fbfdbd..1ae0d2cf23e 100644 --- a/tests/pytests/unit/beacons/test_btmp.py +++ b/tests/pytests/unit/beacons/test_btmp.py @@ -232,7 +232,7 @@ def test_match_group(): with patch("time.time", MagicMock(return_value=1506121200)): with patch("struct.unpack", MagicMock(return_value=pack)): with patch( - "{}.info".format(groupadd), + f"{groupadd}.info", new=MagicMock(return_value=mock_group_info), ): config = [ diff --git a/tests/pytests/unit/beacons/test_diskusage.py b/tests/pytests/unit/beacons/test_diskusage.py index e37863cd733..94fff2fa918 100644 --- a/tests/pytests/unit/beacons/test_diskusage.py +++ b/tests/pytests/unit/beacons/test_diskusage.py @@ -4,6 +4,7 @@ Disk usage beacon test cases """ + from collections import namedtuple import pytest diff --git a/tests/pytests/unit/beacons/test_glxinfo.py b/tests/pytests/unit/beacons/test_glxinfo.py index b556c2cafa9..4888c6301d2 100644 --- a/tests/pytests/unit/beacons/test_glxinfo.py +++ b/tests/pytests/unit/beacons/test_glxinfo.py @@ -4,6 +4,7 @@ glxinfo beacon test cases """ + import pytest import salt.beacons.glxinfo as glxinfo diff --git a/tests/pytests/unit/beacons/test_haproxy.py b/tests/pytests/unit/beacons/test_haproxy.py index 33197cb1414..dc0c961d547 100644 --- a/tests/pytests/unit/beacons/test_haproxy.py +++ b/tests/pytests/unit/beacons/test_haproxy.py @@ -4,6 +4,7 @@ HAProxy beacon test cases """ + import pytest import salt.beacons.haproxy as haproxy diff --git a/tests/pytests/unit/beacons/test_load.py b/tests/pytests/unit/beacons/test_load.py index a0a28428e4b..0f57465cfe3 100644 --- a/tests/pytests/unit/beacons/test_load.py +++ b/tests/pytests/unit/beacons/test_load.py @@ -4,6 +4,7 @@ Load beacon test cases """ + import pytest import salt.beacons.load as load diff --git a/tests/pytests/unit/beacons/test_log_beacon.py b/tests/pytests/unit/beacons/test_log_beacon.py index f0dc61865cb..18184936d9d 100644 --- a/tests/pytests/unit/beacons/test_log_beacon.py +++ b/tests/pytests/unit/beacons/test_log_beacon.py @@ -4,6 +4,7 @@ log beacon test cases """ + import pytest import salt.beacons.log_beacon as log_beacon diff --git a/tests/pytests/unit/beacons/test_memusage.py b/tests/pytests/unit/beacons/test_memusage.py index bab3d5321e2..6f172c9c1d8 100644 --- a/tests/pytests/unit/beacons/test_memusage.py +++ b/tests/pytests/unit/beacons/test_memusage.py @@ -4,6 +4,7 @@ Memory usage beacon test cases """ + from collections import namedtuple import pytest diff --git a/tests/pytests/unit/beacons/test_network_info.py b/tests/pytests/unit/beacons/test_network_info.py index 2f356f41ac0..5ea31605484 100644 --- a/tests/pytests/unit/beacons/test_network_info.py +++ b/tests/pytests/unit/beacons/test_network_info.py @@ -4,6 +4,7 @@ Network info beacon test cases """ + from collections import namedtuple import pytest diff --git a/tests/pytests/unit/beacons/test_ps.py b/tests/pytests/unit/beacons/test_ps.py index 2d1df7ff15d..da6baa2bc0b 100644 --- a/tests/pytests/unit/beacons/test_ps.py +++ b/tests/pytests/unit/beacons/test_ps.py @@ -4,6 +4,7 @@ ps usage beacon test cases """ + import pytest import salt.beacons.ps as ps diff --git a/tests/pytests/unit/beacons/test_swapusage.py b/tests/pytests/unit/beacons/test_swapusage.py index 5ffed290bf8..39070ce49bf 100644 --- a/tests/pytests/unit/beacons/test_swapusage.py +++ b/tests/pytests/unit/beacons/test_swapusage.py @@ -4,6 +4,7 @@ Swap usage beacon test cases """ + from collections import namedtuple import pytest diff --git a/tests/pytests/unit/beacons/test_wtmp.py b/tests/pytests/unit/beacons/test_wtmp.py index 3788ef05cb5..cd0c9d1df6f 100644 --- a/tests/pytests/unit/beacons/test_wtmp.py +++ b/tests/pytests/unit/beacons/test_wtmp.py @@ -236,7 +236,7 @@ def test_match_group(): with patch("time.time", MagicMock(return_value=1506121200)): with patch("struct.unpack", MagicMock(return_value=pack)): with patch( - "{}.info".format(groupadd), + f"{groupadd}.info", new=MagicMock(return_value=mock_group_info), ): config = [ diff --git a/tests/pytests/unit/cache/test_localfs.py b/tests/pytests/unit/cache/test_localfs.py index cda71066368..e5f7c6cc30b 100644 --- a/tests/pytests/unit/cache/test_localfs.py +++ b/tests/pytests/unit/cache/test_localfs.py @@ -1,6 +1,7 @@ """ Validate the functions in the localfs cache """ + import errno import shutil diff --git a/tests/pytests/unit/cache/test_memcache.py b/tests/pytests/unit/cache/test_memcache.py index d8a074c5c35..7a1d9374335 100644 --- a/tests/pytests/unit/cache/test_memcache.py +++ b/tests/pytests/unit/cache/test_memcache.py @@ -1,6 +1,7 @@ """ Validate Cache class methods """ + import pytest import salt.cache diff --git a/tests/pytests/unit/cache/test_mysql_cache.py b/tests/pytests/unit/cache/test_mysql_cache.py index 9d1bcf72c75..930a191e3fa 100644 --- a/tests/pytests/unit/cache/test_mysql_cache.py +++ b/tests/pytests/unit/cache/test_mysql_cache.py @@ -2,7 +2,6 @@ unit tests for the mysql_cache cache """ - import logging import pytest diff --git a/tests/pytests/unit/client/ssh/wrapper/test_config.py b/tests/pytests/unit/client/ssh/wrapper/test_config.py index 64e89c762ad..a708b925fdf 100644 --- a/tests/pytests/unit/client/ssh/wrapper/test_config.py +++ b/tests/pytests/unit/client/ssh/wrapper/test_config.py @@ -3,7 +3,6 @@ This tests the SSH wrapper module. """ - import fnmatch import pytest diff --git a/tests/pytests/unit/client/ssh/wrapper/test_cp.py b/tests/pytests/unit/client/ssh/wrapper/test_cp.py index 58f8334721c..77f8ebb0878 100644 --- a/tests/pytests/unit/client/ssh/wrapper/test_cp.py +++ b/tests/pytests/unit/client/ssh/wrapper/test_cp.py @@ -6,6 +6,7 @@ tests.pytests.unit.fileclient.test_fileclient_cache. + additional ones below """ + import errno import logging import os diff --git a/tests/pytests/unit/cloud/clouds/test_digitalocean.py b/tests/pytests/unit/cloud/clouds/test_digitalocean.py index 68990adf8ac..0b3316675b0 100644 --- a/tests/pytests/unit/cloud/clouds/test_digitalocean.py +++ b/tests/pytests/unit/cloud/clouds/test_digitalocean.py @@ -5,7 +5,6 @@ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ - import logging import pytest diff --git a/tests/pytests/unit/cloud/clouds/test_hetzner.py b/tests/pytests/unit/cloud/clouds/test_hetzner.py index cfe5bb4e85e..c423d83dbca 100644 --- a/tests/pytests/unit/cloud/clouds/test_hetzner.py +++ b/tests/pytests/unit/cloud/clouds/test_hetzner.py @@ -490,9 +490,9 @@ def test_destroy(): connect.return_value.servers.get_by_name.return_value = None hetzner.destroy("myvm", "action") - server = ( - connect.return_value.servers.get_by_name.return_value - ) = MagicMock() + server = connect.return_value.servers.get_by_name.return_value = ( + MagicMock() + ) # Stop the server before shutdown but failed hetzner.destroy("myvm", "action") @@ -531,9 +531,9 @@ def test_resize(): hetzner.resize("myvm", kwargs, "action") - server = ( - connect.return_value.servers.get_by_name.return_value - ) = MagicMock() + server = connect.return_value.servers.get_by_name.return_value = ( + MagicMock() + ) # Invalid server size with pytest.raises(SaltCloudException): diff --git a/tests/pytests/unit/cloud/clouds/test_proxmox.py b/tests/pytests/unit/cloud/clouds/test_proxmox.py index 1d1823a8035..8aba387c372 100644 --- a/tests/pytests/unit/cloud/clouds/test_proxmox.py +++ b/tests/pytests/unit/cloud/clouds/test_proxmox.py @@ -156,14 +156,14 @@ def test__reconfigure_clone_params(): "onboot": "0", "sshkeys": "ssh-rsa ABCDEF user@host\n", } - query_calls = [call("get", "nodes/myhost/qemu/{}/config".format(vmid))] + query_calls = [call("get", f"nodes/myhost/qemu/{vmid}/config")] for key, value in properties.items(): if key == "sshkeys": value = urllib.parse.quote(value, safe="") query_calls.append( call( "post", - "nodes/myhost/qemu/{}/config".format(vmid), + f"nodes/myhost/qemu/{vmid}/config", {key: value}, ) ) @@ -346,7 +346,7 @@ def test_find_agent_ips(): # CASE 1: Test ipv4 and ignore_cidr result = proxmox._find_agent_ip(vm_, ANY) mock_query.assert_any_call( - "get", "nodes/myhost/qemu/{}/agent/network-get-interfaces".format(ANY) + "get", f"nodes/myhost/qemu/{ANY}/agent/network-get-interfaces" ) assert result == "2.3.4.5" @@ -356,7 +356,7 @@ def test_find_agent_ips(): vm_["protocol"] = "ipv6" result = proxmox._find_agent_ip(vm_, ANY) mock_query.assert_any_call( - "get", "nodes/myhost/qemu/{}/agent/network-get-interfaces".format(ANY) + "get", f"nodes/myhost/qemu/{ANY}/agent/network-get-interfaces" ) assert result == "2001::1:2" @@ -515,6 +515,6 @@ def test_creation_failure_logging(caplog): break if missing: raise AssertionError( - "Did not find error messages: {}".format(sorted(list(missing))) + f"Did not find error messages: {sorted(list(missing))}" ) return diff --git a/tests/pytests/unit/cloud/clouds/test_saltify.py b/tests/pytests/unit/cloud/clouds/test_saltify.py index 8dd0359185a..851c05d0f80 100644 --- a/tests/pytests/unit/cloud/clouds/test_saltify.py +++ b/tests/pytests/unit/cloud/clouds/test_saltify.py @@ -1,6 +1,7 @@ """ :codeauthor: Alexander Schwartz """ + import pytest import salt.client diff --git a/tests/pytests/unit/cloud/clouds/test_vultrpy.py b/tests/pytests/unit/cloud/clouds/test_vultrpy.py index a388ba7f2a5..2945588280d 100644 --- a/tests/pytests/unit/cloud/clouds/test_vultrpy.py +++ b/tests/pytests/unit/cloud/clouds/test_vultrpy.py @@ -96,7 +96,9 @@ def test_create_firewall_ssh(): patch_show = patch("salt.cloud.clouds.vultrpy.show_instance", MagicMock()) - with patch_scripts, patch_firewall, patch_keys, patch_vultrid, patch_query, patch_show: + with ( + patch_scripts + ), patch_firewall, patch_keys, patch_vultrid, patch_query, patch_show: vultr.create(kwargs) query_ret = mock_query.call_args.kwargs["data"] assert "SSHKEYID=key1%2Ckey2%2Ckey3" in query_ret @@ -143,7 +145,9 @@ def test_create_firewall_doesnotexist(caplog): patch_show = patch("salt.cloud.clouds.vultrpy.show_instance", MagicMock()) - with patch_scripts, patch_firewall, patch_keys, patch_vultrid, patch_query, patch_show: + with ( + patch_scripts + ), patch_firewall, patch_keys, patch_vultrid, patch_query, patch_show: with caplog.at_level(logging.INFO): ret = vultr.create(kwargs) assert ( @@ -193,7 +197,9 @@ def test_create_ssh_key_ids_doesnotexist(caplog): patch_show = patch("salt.cloud.clouds.vultrpy.show_instance", MagicMock()) - with patch_scripts, patch_firewall, patch_keys, patch_vultrid, patch_query, patch_show: + with ( + patch_scripts + ), patch_firewall, patch_keys, patch_vultrid, patch_query, patch_show: with caplog.at_level(logging.INFO): ret = vultr.create(kwargs) assert ( diff --git a/tests/pytests/unit/config/schemas/test_ssh.py b/tests/pytests/unit/config/schemas/test_ssh.py index 93692edabd4..5616c341a15 100644 --- a/tests/pytests/unit/config/schemas/test_ssh.py +++ b/tests/pytests/unit/config/schemas/test_ssh.py @@ -146,7 +146,7 @@ def test_config_validate(): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - pytest.fail("ValidationError raised: {}".format(exc)) + pytest.fail(f"ValidationError raised: {exc}") try: jsonschema.validate( @@ -155,7 +155,7 @@ def test_config_validate(): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - pytest.fail("ValidationError raised: {}".format(exc)) + pytest.fail(f"ValidationError raised: {exc}") try: jsonschema.validate( @@ -164,7 +164,7 @@ def test_config_validate(): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - pytest.fail("ValidationError raised: {}".format(exc)) + pytest.fail(f"ValidationError raised: {exc}") try: jsonschema.validate( @@ -173,7 +173,7 @@ def test_config_validate(): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - pytest.fail("ValidationError raised: {}".format(exc)) + pytest.fail(f"ValidationError raised: {exc}") try: jsonschema.validate( @@ -188,7 +188,7 @@ def test_config_validate(): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - pytest.fail("ValidationError raised: {}".format(exc)) + pytest.fail(f"ValidationError raised: {exc}") try: jsonschema.validate( @@ -202,7 +202,7 @@ def test_config_validate(): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - pytest.fail("ValidationError raised: {}".format(exc)) + pytest.fail(f"ValidationError raised: {exc}") with pytest.raises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate( @@ -259,7 +259,7 @@ def test_roster_config_validate(): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - pytest.fail("ValidationError raised: {}".format(exc)) + pytest.fail(f"ValidationError raised: {exc}") with pytest.raises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate( diff --git a/tests/pytests/unit/config/test__validate_opts.py b/tests/pytests/unit/config/test__validate_opts.py index 741631e6f81..f07a60c3c1f 100644 --- a/tests/pytests/unit/config/test__validate_opts.py +++ b/tests/pytests/unit/config/test__validate_opts.py @@ -1,6 +1,7 @@ """ Test config option type enforcement """ + import pytest import salt.config diff --git a/tests/pytests/unit/crypt/test_crypt.py b/tests/pytests/unit/crypt/test_crypt.py index 098c42d0dd9..6062dd0c44d 100644 --- a/tests/pytests/unit/crypt/test_crypt.py +++ b/tests/pytests/unit/crypt/test_crypt.py @@ -4,6 +4,7 @@ tests.pytests.unit.test_crypt Unit tests for salt's crypt module """ + import uuid import pytest diff --git a/tests/pytests/unit/engines/test_engines.py b/tests/pytests/unit/engines/test_engines.py index aaf8280a74d..f83ced785b0 100644 --- a/tests/pytests/unit/engines/test_engines.py +++ b/tests/pytests/unit/engines/test_engines.py @@ -8,7 +8,7 @@ from tests.support.mock import MagicMock, patch def kwargs(): opts = {"__role": "minion"} name = "foobar" - fun = "{}.start".format(name) + fun = f"{name}.start" config = funcs = runners = proxy = {} return dict( opts=opts, diff --git a/tests/pytests/unit/engines/test_libvirt_events.py b/tests/pytests/unit/engines/test_libvirt_events.py index 382ec311732..a83a1948fac 100644 --- a/tests/pytests/unit/engines/test_libvirt_events.py +++ b/tests/pytests/unit/engines/test_libvirt_events.py @@ -1,6 +1,7 @@ """ unit tests for the libvirt_events engine """ + import pytest import salt.engines.libvirt_events as libvirt_events diff --git a/tests/pytests/unit/engines/test_slack.py b/tests/pytests/unit/engines/test_slack.py index c375e903b7b..b3269a6f2a5 100644 --- a/tests/pytests/unit/engines/test_slack.py +++ b/tests/pytests/unit/engines/test_slack.py @@ -1,6 +1,7 @@ """ unit tests for the slack engine """ + import pytest import salt.engines.slack as slack diff --git a/tests/pytests/unit/engines/test_slack_bolt_engine.py b/tests/pytests/unit/engines/test_slack_bolt_engine.py index e537a859550..1d2e30a045b 100644 --- a/tests/pytests/unit/engines/test_slack_bolt_engine.py +++ b/tests/pytests/unit/engines/test_slack_bolt_engine.py @@ -1,6 +1,7 @@ """ unit tests for the slack engine """ + import pytest import salt.engines.slack_bolt_engine as slack_bolt_engine @@ -327,7 +328,13 @@ def test_run_commands_from_slack_async(slack_client): # # test with control as True and fire_all as False # - with patch_slack_client_run_until, patch_slack_client_run_command_async, patch_slack_client_get_jobs_from_runner, patch_app_client_files_upload as app_client_files_upload, patch_app_client_chat_postMessage as app_client_chat_postMessage: + with ( + patch_slack_client_run_until + ), ( + patch_slack_client_run_command_async + ), ( + patch_slack_client_get_jobs_from_runner + ), patch_app_client_files_upload as app_client_files_upload, patch_app_client_chat_postMessage as app_client_chat_postMessage: slack_client.run_commands_from_slack_async( message_generator=message_generator, fire_all=False, @@ -389,7 +396,15 @@ def test_run_commands_from_slack_async(slack_client): }, ) ] - with patch_slack_client_run_until, patch_slack_client_run_command_async, patch_slack_client_get_jobs_from_runner, patch_event_send, patch_app_client_files_upload as app_client_files_upload, patch_app_client_chat_postMessage as app_client_chat_postMessage: + with ( + patch_slack_client_run_until + ), ( + patch_slack_client_run_command_async + ), ( + patch_slack_client_get_jobs_from_runner + ), ( + patch_event_send + ), patch_app_client_files_upload as app_client_files_upload, patch_app_client_chat_postMessage as app_client_chat_postMessage: slack_client.run_commands_from_slack_async( message_generator=message_generator, fire_all=True, @@ -509,6 +524,8 @@ def test_run_command_async(slack_client): }, ) ] - with patch_runner_client, patch_runner_client_asynchronous as runner_client_asynchronous: + with ( + patch_runner_client + ), patch_runner_client_asynchronous as runner_client_asynchronous: ret = slack_client.run_command_async(msg) runner_client_asynchronous.assert_has_calls(expected_calls) diff --git a/tests/pytests/unit/engines/test_sqs_events.py b/tests/pytests/unit/engines/test_sqs_events.py index 894d1d6f652..28fb75f8f89 100644 --- a/tests/pytests/unit/engines/test_sqs_events.py +++ b/tests/pytests/unit/engines/test_sqs_events.py @@ -1,6 +1,7 @@ """ unit tests for the sqs_events engine """ + import pytest import salt.engines.sqs_events as sqs_events diff --git a/tests/pytests/unit/fileclient/test_fileclient.py b/tests/pytests/unit/fileclient/test_fileclient.py index 395695b69ad..94512e50633 100644 --- a/tests/pytests/unit/fileclient/test_fileclient.py +++ b/tests/pytests/unit/fileclient/test_fileclient.py @@ -1,6 +1,7 @@ """ Tests for the salt fileclient """ + import errno import logging import os diff --git a/tests/pytests/unit/fileserver/gitfs/test_gitfs_config.py b/tests/pytests/unit/fileserver/gitfs/test_gitfs_config.py index 209e659c6dd..9b5d10590dc 100644 --- a/tests/pytests/unit/fileserver/gitfs/test_gitfs_config.py +++ b/tests/pytests/unit/fileserver/gitfs/test_gitfs_config.py @@ -27,7 +27,7 @@ except (ImportError, AttributeError): pytestmark = [ pytest.mark.skipif( - not HAS_GITPYTHON, reason="GitPython >= {} required".format(GITPYTHON_MINVER) + not HAS_GITPYTHON, reason=f"GitPython >= {GITPYTHON_MINVER} required" ) ] diff --git a/tests/pytests/unit/grains/test_core.py b/tests/pytests/unit/grains/test_core.py index 0b686fcb05d..68a2c2f347a 100644 --- a/tests/pytests/unit/grains/test_core.py +++ b/tests/pytests/unit/grains/test_core.py @@ -1780,9 +1780,9 @@ def test_lxc_virtual(): os.path, "isfile", MagicMock( - side_effect=lambda x: True - if x in ("/proc/1/cgroup", "/proc/1/environ") - else False + side_effect=lambda x: ( + True if x in ("/proc/1/cgroup", "/proc/1/environ") else False + ) ), ), patch("salt.utils.files.fopen", mock_open(read_data=file_contents)), patch.dict( core.__salt__, {"cmd.run_all": MagicMock()} @@ -1828,9 +1828,11 @@ def test_container_inside_virtual_machine(): os.path, "isfile", MagicMock( - side_effect=lambda x: True - if x in ("/proc/cpuinfo", "/proc/1/cgroup", "/proc/1/environ") - else False + side_effect=lambda x: ( + True + if x in ("/proc/cpuinfo", "/proc/1/cgroup", "/proc/1/environ") + else False + ) ), ), patch("salt.utils.files.fopen", mock_open(read_data=file_contents)), patch.dict( core.__salt__, {"cmd.run_all": MagicMock()} @@ -3601,8 +3603,8 @@ def test_linux_devicetree_data(test_input, expected): raise FileNotFoundError() m = MagicMock() - m.__enter__.return_value.read = ( - lambda: test_input.get(filename) # pylint: disable=W0640 + m.__enter__.return_value.read = lambda: ( + test_input.get(filename) # pylint: disable=W0640 if filename in test_input # pylint: disable=W0640 else _raise_fnfe() ) diff --git a/tests/pytests/unit/grains/test_esxi.py b/tests/pytests/unit/grains/test_esxi.py index 29be04bc56e..e158b2b3843 100644 --- a/tests/pytests/unit/grains/test_esxi.py +++ b/tests/pytests/unit/grains/test_esxi.py @@ -4,7 +4,6 @@ :codeauthor: :email:`Gareth J. Greenaway ` """ - import logging import pytest diff --git a/tests/pytests/unit/loader/test_context.py b/tests/pytests/unit/loader/test_context.py index 9815f443f25..64b36411f4b 100644 --- a/tests/pytests/unit/loader/test_context.py +++ b/tests/pytests/unit/loader/test_context.py @@ -1,6 +1,7 @@ """ Tests for salt.loader.context """ + import copy import salt.loader.context diff --git a/tests/pytests/unit/loader/test_lazy.py b/tests/pytests/unit/loader/test_lazy.py index 571f458b360..8e461b454b4 100644 --- a/tests/pytests/unit/loader/test_lazy.py +++ b/tests/pytests/unit/loader/test_lazy.py @@ -1,6 +1,7 @@ """ Tests for salt.loader.lazy """ + import sys import pytest diff --git a/tests/pytests/unit/loader/test_loader.py b/tests/pytests/unit/loader/test_loader.py index 3c26b435c8c..e7359c6a74a 100644 --- a/tests/pytests/unit/loader/test_loader.py +++ b/tests/pytests/unit/loader/test_loader.py @@ -4,6 +4,7 @@ tests.pytests.unit.loader.test_loader Unit tests for salt's loader """ + import os import shutil import textwrap diff --git a/tests/pytests/unit/log_handlers/test_sentry_mod.py b/tests/pytests/unit/log_handlers/test_sentry_mod.py index 4c2d174b710..e011719ca84 100644 --- a/tests/pytests/unit/log_handlers/test_sentry_mod.py +++ b/tests/pytests/unit/log_handlers/test_sentry_mod.py @@ -1,6 +1,7 @@ """ Tests for salt.log_handlers.sentry_mod """ + import pytest import salt.log_handlers.sentry_mod diff --git a/tests/pytests/unit/modules/dockermod/test_module.py b/tests/pytests/unit/modules/dockermod/test_module.py index abfd101540d..e311032f229 100644 --- a/tests/pytests/unit/modules/dockermod/test_module.py +++ b/tests/pytests/unit/modules/dockermod/test_module.py @@ -319,24 +319,26 @@ def test_update_mine(): """ def config_get_disabled(val, default): - return { + ret = { "base_url": docker_mod.NOTSET, "version": docker_mod.NOTSET, "docker.url": docker_mod.NOTSET, "docker.version": docker_mod.NOTSET, "docker.machine": docker_mod.NOTSET, "docker.update_mine": False, - }[val] + } + return ret[val] def config_get_enabled(val, default): - return { + ret = { "base_url": docker_mod.NOTSET, "version": docker_mod.NOTSET, "docker.url": docker_mod.NOTSET, "docker.version": docker_mod.NOTSET, "docker.machine": docker_mod.NOTSET, "docker.update_mine": True, - }[val] + } + return ret[val] mine_mock = Mock() dunder_salt = { @@ -937,19 +939,21 @@ def test_compare_container_image_id_resolution(): """ def _inspect_container_effect(id_): - return { + ret = { "container1": { "Config": {"Image": "realimage:latest"}, "HostConfig": {}, }, "container2": {"Config": {"Image": "image_id"}, "HostConfig": {}}, - }[id_] + } + return ret[id_] def _inspect_image_effect(id_): - return { + ret = { "realimage:latest": {"Id": "image_id"}, "image_id": {"Id": "image_id"}, - }[id_] + } + return ret[id_] inspect_container_mock = MagicMock(side_effect=_inspect_container_effect) inspect_image_mock = MagicMock(side_effect=_inspect_image_effect) @@ -967,7 +971,7 @@ def test_compare_container_ulimits_order(): """ def _inspect_container_effect(id_): - return { + ret = { "container1": { "Config": {}, "HostConfig": { @@ -986,7 +990,8 @@ def test_compare_container_ulimits_order(): ] }, }, - }[id_] + } + return ret[id_] inspect_container_mock = MagicMock(side_effect=_inspect_container_effect) @@ -1004,7 +1009,7 @@ def test_compare_container_env_order(): """ def _inspect_container_effect(id_): - return { + ret = { "container1": { "Config": {}, "HostConfig": {"Env": ["FOO=bar", "HELLO=world"]}, @@ -1013,7 +1018,8 @@ def test_compare_container_env_order(): "Config": {}, "HostConfig": {"Env": ["HELLO=world", "FOO=bar"]}, }, - }[id_] + } + return ret[id_] inspect_container_mock = MagicMock(side_effect=_inspect_container_effect) diff --git a/tests/pytests/unit/modules/file/test_file_chattr.py b/tests/pytests/unit/modules/file/test_file_chattr.py index b97dcf946f4..edee87b8093 100644 --- a/tests/pytests/unit/modules/file/test_file_chattr.py +++ b/tests/pytests/unit/modules/file/test_file_chattr.py @@ -221,7 +221,7 @@ def test_check_perms_should_report_attrs_new_and_old_if_they_changed(): ) ).strip() else: - assert False, "not sure how to handle {}".format(cmd) + assert False, f"not sure how to handle {cmd}" patch_run = patch.dict( filemod.__salt__, diff --git a/tests/pytests/unit/modules/file/test_file_check.py b/tests/pytests/unit/modules/file/test_file_check.py index ce86acd7fcc..76d8a0cecae 100644 --- a/tests/pytests/unit/modules/file/test_file_check.py +++ b/tests/pytests/unit/modules/file/test_file_check.py @@ -88,7 +88,7 @@ def test_check_managed_follow_symlinks(a_link, tfile): a_link, tfile, None, None, user, None, lperms, None, None, None, None, None ) assert ret is True - assert comments == "The file {} is in the correct state".format(a_link) + assert comments == f"The file {a_link} is in the correct state" ret, comments = filemod.check_managed( a_link, tfile, None, None, user, None, "0644", None, None, None, None, None @@ -113,7 +113,7 @@ def test_check_managed_follow_symlinks(a_link, tfile): follow_symlinks=True, ) assert ret is True - assert comments == "The file {} is in the correct state".format(a_link) + assert comments == f"The file {a_link} is in the correct state" @pytest.mark.skip_on_windows(reason="os.symlink is not available on Windows") diff --git a/tests/pytests/unit/modules/file/test_file_grep.py b/tests/pytests/unit/modules/file/test_file_grep.py index b3f57e0505f..8f362c0896b 100644 --- a/tests/pytests/unit/modules/file/test_file_grep.py +++ b/tests/pytests/unit/modules/file/test_file_grep.py @@ -117,7 +117,7 @@ def test_grep_query_too_many_opts(multiline_file): def test_grep_query_exists_wildcard(multiline_file): - _file = "{}*".format(multiline_file) + _file = f"{multiline_file}*" result = filemod.grep(_file, "Lorem ipsum") assert result, None @@ -127,7 +127,7 @@ def test_grep_query_exists_wildcard(multiline_file): def test_grep_file_not_exists_wildcard(multiline_file): - _file = "{}-junk*".format(multiline_file) + _file = f"{multiline_file}-junk*" result = filemod.grep(_file, "Lorem ipsum") assert result, None diff --git a/tests/pytests/unit/modules/file/test_file_line.py b/tests/pytests/unit/modules/file/test_file_line.py index 80030e1417d..17f08cdf371 100644 --- a/tests/pytests/unit/modules/file/test_file_line.py +++ b/tests/pytests/unit/modules/file/test_file_line.py @@ -965,7 +965,7 @@ def test_delete_line_in_empty_file(anyattr, mode): ) warning_call = _log.warning.call_args_list[0][0] warning_log_msg = warning_call[0] % warning_call[1:] - assert "Cannot find text to {}".format(mode) in warning_log_msg + assert f"Cannot find text to {mode}" in warning_log_msg @pytest.mark.parametrize("mode", ["delete", "replace"]) @@ -1149,7 +1149,7 @@ def test_line_insert_multi_line_content_after_unicode(tempfile_name, get_body): See issue #48113 :return: """ - file_content = "This is a line{}This is another line".format(os.linesep) + file_content = f"This is a line{os.linesep}This is another line" file_modified = salt.utils.stringutils.to_str( "This is a line{}" "This is another line{}" @@ -1588,7 +1588,7 @@ def test_line_insert_ensure_beforeafter_twolines(tempfile_name, get_body): isfile_mock = MagicMock( side_effect=lambda x: True if x == tempfile_name else DEFAULT ) - for (_after, _before) in [(after, before), ("NAME_.*", "SKEL_.*")]: + for _after, _before in [(after, before), ("NAME_.*", "SKEL_.*")]: with patch("os.path.isfile", isfile_mock), patch( "os.stat", MagicMock(return_value=DummyStat()) ), patch("salt.utils.files.fopen", mock_open(read_data=file_content)), patch( @@ -1640,7 +1640,7 @@ def test_line_insert_ensure_beforeafter_twolines_exists(tempfile_name): isfile_mock = MagicMock( side_effect=lambda x: True if x == tempfile_name else DEFAULT ) - for (_after, _before) in [(after, before), ("NAME_.*", "SKEL_.*")]: + for _after, _before in [(after, before), ("NAME_.*", "SKEL_.*")]: with patch("os.path.isfile", isfile_mock), patch( "os.stat", MagicMock(return_value=DummyStat()) ), patch("salt.utils.files.fopen", mock_open(read_data=file_content)), patch( @@ -1677,7 +1677,7 @@ def test_line_insert_ensure_beforeafter_rangelines(): file_content.split(os.linesep)[0], file_content.split(os.linesep)[-1], ) - for (_after, _before) in [(after, before), ("NAME_.*", "SKEL_.*")]: + for _after, _before in [(after, before), ("NAME_.*", "SKEL_.*")]: with patch("os.path.realpath", MagicMock(wraps=lambda x: x)), patch( "os.path.isfile", MagicMock(return_value=True) ), patch("os.stat", MagicMock()), patch( diff --git a/tests/pytests/unit/modules/file/test_file_module.py b/tests/pytests/unit/modules/file/test_file_module.py index 34fe4fa210d..38de2811aba 100644 --- a/tests/pytests/unit/modules/file/test_file_module.py +++ b/tests/pytests/unit/modules/file/test_file_module.py @@ -183,7 +183,7 @@ def test_sed_limit_escaped(sed_content, subdir): path = tfile.name before = "/var/lib/foo" after = "" - limit = "^{}".format(before) + limit = f"^{before}" filemod.sed(path, before, after, limit=limit) @@ -506,12 +506,13 @@ def test_get_diff(): mockself.path = path def readlines(mockself): # pylint: disable=unused-argument - return { + ret = { "text1": text1.encode("utf8"), "text2": text2.encode("utf8"), "binary1": binary1, "binary2": binary2, - }[mockself.path].splitlines(True) + } + return ret[mockself.path].splitlines(True) def __enter__(mockself): return mockself diff --git a/tests/pytests/unit/modules/napalm/test_bgp.py b/tests/pytests/unit/modules/napalm/test_bgp.py index e9dcb21ecf5..48a7105342d 100644 --- a/tests/pytests/unit/modules/napalm/test_bgp.py +++ b/tests/pytests/unit/modules/napalm/test_bgp.py @@ -2,7 +2,6 @@ :codeauthor: :email:`Anthony Shaw ` """ - import pytest import salt.modules.napalm_bgp as napalm_bgp diff --git a/tests/pytests/unit/modules/napalm/test_mod.py b/tests/pytests/unit/modules/napalm/test_mod.py index 306a9840a46..5b693c2de2a 100644 --- a/tests/pytests/unit/modules/napalm/test_mod.py +++ b/tests/pytests/unit/modules/napalm/test_mod.py @@ -1,6 +1,7 @@ """ :codeauthor: :email:`David Murphy ` """ + import logging import pytest diff --git a/tests/pytests/unit/modules/napalm/test_network.py b/tests/pytests/unit/modules/napalm/test_network.py index 4dfaf8af447..2ce2d6e621b 100644 --- a/tests/pytests/unit/modules/napalm/test_network.py +++ b/tests/pytests/unit/modules/napalm/test_network.py @@ -2,7 +2,6 @@ :codeauthor: Anthony Shaw """ - import pytest import salt.modules.napalm_network as napalm_network diff --git a/tests/pytests/unit/modules/napalm/test_route.py b/tests/pytests/unit/modules/napalm/test_route.py index 06ccf0ec618..b72130c14de 100644 --- a/tests/pytests/unit/modules/napalm/test_route.py +++ b/tests/pytests/unit/modules/napalm/test_route.py @@ -10,7 +10,7 @@ from tests.support.mock import MagicMock, patch def mock_net_load(template, *args, **kwargs): - raise ValueError("incorrect template {}".format(template)) + raise ValueError(f"incorrect template {template}") @pytest.fixture diff --git a/tests/pytests/unit/modules/napalm/test_snmp.py b/tests/pytests/unit/modules/napalm/test_snmp.py index 67d25850f3a..5166372ca68 100644 --- a/tests/pytests/unit/modules/napalm/test_snmp.py +++ b/tests/pytests/unit/modules/napalm/test_snmp.py @@ -2,7 +2,6 @@ :codeauthor: :email:`Anthony Shaw ` """ - import pytest import salt.modules.napalm_network as napalm_network diff --git a/tests/pytests/unit/modules/napalm/test_users.py b/tests/pytests/unit/modules/napalm/test_users.py index b76010e76f1..f55a649aa7b 100644 --- a/tests/pytests/unit/modules/napalm/test_users.py +++ b/tests/pytests/unit/modules/napalm/test_users.py @@ -2,7 +2,6 @@ :codeauthor: :email:`Anthony Shaw ` """ - import pytest import salt.modules.napalm_network as napalm_network diff --git a/tests/pytests/unit/modules/test_acme.py b/tests/pytests/unit/modules/test_acme.py index 2d7aa6d2883..aa56dc59813 100644 --- a/tests/pytests/unit/modules/test_acme.py +++ b/tests/pytests/unit/modules/test_acme.py @@ -2,7 +2,6 @@ :codeauthor: Herbert Buurman """ - import datetime import os import textwrap diff --git a/tests/pytests/unit/modules/test_aixpkg.py b/tests/pytests/unit/modules/test_aixpkg.py index 7e9b21afb7f..bb56173bd34 100644 --- a/tests/pytests/unit/modules/test_aixpkg.py +++ b/tests/pytests/unit/modules/test_aixpkg.py @@ -1283,7 +1283,7 @@ fake_info Not found on the installation media """ fileset_pkg_name = "/cecc/repos/aix72/TL3/BASE/installp/ppc/info_fake" - fileset_pkg_base_name = os.path.basename("{}".format(fileset_pkg_name)) + fileset_pkg_base_name = os.path.basename(f"{fileset_pkg_name}") dnf_installp_call = MagicMock( side_effect=[ {"retcode": 1, "stdout": "", "stderr": info_fake_dnf_error}, @@ -1347,8 +1347,8 @@ def test_remove_dnf(): ) list_pkgs_mock = MagicMock( side_effect=[ - {"{}".format(pkg_name): "{}".format(pkg_name_version)}, - {"{}".format(pkg_name): ""}, + {f"{pkg_name}": f"{pkg_name_version}"}, + {f"{pkg_name}": ""}, ] ) @@ -1357,21 +1357,19 @@ def test_remove_dnf(): aixpkg.__salt__, {"cmd.run_all": dnf_call, "config.get": MagicMock(return_value=False)}, ), patch.object(aixpkg, "list_pkgs", list_pkgs_mock): - result = aixpkg.remove("{}".format(pkg_name)) + result = aixpkg.remove(f"{pkg_name}") dnf_call.assert_any_call( - ["/usr/bin/lslpp", "-Lc", "{}".format(pkg_name)], + ["/usr/bin/lslpp", "-Lc", f"{pkg_name}"], python_shell=False, ) libpath_env = {"LIBPATH": "/opt/freeware/lib:/usr/lib"} dnf_call.assert_any_call( - "/opt/freeware/bin/dnf -y remove {}".format(pkg_name), + f"/opt/freeware/bin/dnf -y remove {pkg_name}", env=libpath_env, ignore_retcode=True, python_shell=False, ) - expected = { - "{}".format(pkg_name): {"old": "{}".format(pkg_name_version), "new": ""} - } + expected = {f"{pkg_name}": {"old": f"{pkg_name_version}", "new": ""}} assert result == expected @@ -1468,8 +1466,8 @@ bos.adt.insttools 7.2.2.0 ROOT APPLY SUCCESS ) list_pkgs_mock = MagicMock( side_effect=[ - {"{}".format(fileset_base_name): "{}".format(fileset_pkg_name_version)}, - {"{}".format(fileset_base_name): ""}, + {f"{fileset_base_name}": f"{fileset_pkg_name_version}"}, + {f"{fileset_base_name}": ""}, ] ) @@ -1478,20 +1476,20 @@ bos.adt.insttools 7.2.2.0 ROOT APPLY SUCCESS aixpkg.__salt__, {"cmd.run_all": dnf_call, "config.get": MagicMock(return_value=False)}, ), patch.object(aixpkg, "list_pkgs", list_pkgs_mock): - result = aixpkg.remove("{}".format(fileset_pkg_name)) + result = aixpkg.remove(f"{fileset_pkg_name}") dnf_call.assert_any_call( - ["/usr/bin/lslpp", "-Lc", "{}".format(fileset_pkg_name)], + ["/usr/bin/lslpp", "-Lc", f"{fileset_pkg_name}"], python_shell=False, ) libpath_env = {"LIBPATH": "/opt/freeware/lib:/usr/lib"} test_name = os.path.basename(fileset_pkg_name) dnf_call.assert_any_call( - ["/usr/sbin/installp", "-u", "{}".format(fileset_base_name)], + ["/usr/sbin/installp", "-u", f"{fileset_base_name}"], python_shell=False, ) expected = { - "{}".format(fileset_base_name): { - "old": "{}".format(fileset_pkg_name_version), + f"{fileset_base_name}": { + "old": f"{fileset_pkg_name_version}", "new": "", } } @@ -1530,15 +1528,13 @@ lslpp: Fileset info_fake not installed. ), patch.object(aixpkg, "list_pkgs", list_pkgs_mock): expected = { "changes": {}, - "errors": [ - "/usr/bin/lslpp: Fileset {} not installed.".format(fileset_pkg_name) - ], + "errors": [f"/usr/bin/lslpp: Fileset {fileset_pkg_name} not installed."], } with pytest.raises(CommandExecutionError) as exc_info: result = aixpkg.remove(fileset_pkg_name) assert exc_info.value.info == expected, exc_info.value.info assert lslpp_call.call_count == 1 lslpp_call.assert_any_call( - ["/usr/bin/lslpp", "-Lc", "{}".format(fileset_pkg_name)], + ["/usr/bin/lslpp", "-Lc", f"{fileset_pkg_name}"], python_shell=False, ) diff --git a/tests/pytests/unit/modules/test_at.py b/tests/pytests/unit/modules/test_at.py index 0a44d83beea..da5be7f4b0e 100644 --- a/tests/pytests/unit/modules/test_at.py +++ b/tests/pytests/unit/modules/test_at.py @@ -4,7 +4,6 @@ TestCase for the salt.modules.at module """ - import pytest import salt.modules.at as at diff --git a/tests/pytests/unit/modules/test_augeas_cfg.py b/tests/pytests/unit/modules/test_augeas_cfg.py index 0720b6b25b9..dd197555665 100644 --- a/tests/pytests/unit/modules/test_augeas_cfg.py +++ b/tests/pytests/unit/modules/test_augeas_cfg.py @@ -3,6 +3,7 @@ Test cases for salt.modules.augeas_cfg """ + import pytest import salt.modules.augeas_cfg as augeas_cfg diff --git a/tests/pytests/unit/modules/test_bigip.py b/tests/pytests/unit/modules/test_bigip.py index 3e24ad9df4a..2fc8cb44c50 100644 --- a/tests/pytests/unit/modules/test_bigip.py +++ b/tests/pytests/unit/modules/test_bigip.py @@ -4,6 +4,7 @@ tests.unit.modules.test_bigip Unit tests for the bigip module """ + import logging import pytest diff --git a/tests/pytests/unit/modules/test_bluez_bluetooth.py b/tests/pytests/unit/modules/test_bluez_bluetooth.py index e7b832e613f..d3bab5ba043 100644 --- a/tests/pytests/unit/modules/test_bluez_bluetooth.py +++ b/tests/pytests/unit/modules/test_bluez_bluetooth.py @@ -2,7 +2,6 @@ :codeauthor: Rahul Handay """ - import pytest import salt.modules.bluez_bluetooth as bluez diff --git a/tests/pytests/unit/modules/test_boto_dynamodb.py b/tests/pytests/unit/modules/test_boto_dynamodb.py index f5b983e13f0..0a2fe186a1c 100644 --- a/tests/pytests/unit/modules/test_boto_dynamodb.py +++ b/tests/pytests/unit/modules/test_boto_dynamodb.py @@ -2,7 +2,6 @@ Test cases for salt.modules.boto_dynamodb """ - import pytest import salt.modules.boto_dynamodb as boto_dynamodb diff --git a/tests/pytests/unit/modules/test_bower.py b/tests/pytests/unit/modules/test_bower.py index df33182ab1a..537fb08fbaa 100644 --- a/tests/pytests/unit/modules/test_bower.py +++ b/tests/pytests/unit/modules/test_bower.py @@ -2,7 +2,6 @@ :codeauthor: Alexander Pyatkin """ - import pytest import salt.modules.bower as bower diff --git a/tests/pytests/unit/modules/test_bridge.py b/tests/pytests/unit/modules/test_bridge.py index f68ffbce2d7..7595e4263ee 100644 --- a/tests/pytests/unit/modules/test_bridge.py +++ b/tests/pytests/unit/modules/test_bridge.py @@ -2,7 +2,6 @@ :codeauthor: Rupesh Tare """ - import pytest import salt.modules.bridge as bridge diff --git a/tests/pytests/unit/modules/test_cassandra_cql.py b/tests/pytests/unit/modules/test_cassandra_cql.py index 6b39d2f0cc4..c07b78ce158 100644 --- a/tests/pytests/unit/modules/test_cassandra_cql.py +++ b/tests/pytests/unit/modules/test_cassandra_cql.py @@ -2,7 +2,6 @@ Test case for the cassandra_cql module """ - import logging import ssl @@ -86,7 +85,7 @@ def test_version(caplog): with pytest.raises(CommandExecutionError) as err: with patch.object(cassandra_cql, "cql_query", mock_cql_query): version = cassandra_cql.version() - assert "{}".format(err.value) == "" + assert f"{err.value}" == "" assert "Could not get Cassandra version." in caplog.text for record in caplog.records: assert record.levelname == "CRITICAL" diff --git a/tests/pytests/unit/modules/test_chocolatey.py b/tests/pytests/unit/modules/test_chocolatey.py index ac2c7341045..8dd630793f1 100644 --- a/tests/pytests/unit/modules/test_chocolatey.py +++ b/tests/pytests/unit/modules/test_chocolatey.py @@ -1,6 +1,7 @@ """ Test for the chocolatey module """ + import os import pytest diff --git a/tests/pytests/unit/modules/test_chroot.py b/tests/pytests/unit/modules/test_chroot.py index d44bfed9303..b1e9beb674e 100644 --- a/tests/pytests/unit/modules/test_chroot.py +++ b/tests/pytests/unit/modules/test_chroot.py @@ -159,7 +159,7 @@ def test_call_fails_salt_thin(): salt_mock["cmd.run_chroot"].assert_called_with( "/chroot", [ - "python{}".format(sys.version_info[0]), + f"python{sys.version_info[0]}", "/tmp01/salt-call", "--metadata", "--local", @@ -207,7 +207,7 @@ def test_call_success(): salt_mock["cmd.run_chroot"].assert_called_with( "/chroot", [ - "python{}".format(sys.version_info[0]), + f"python{sys.version_info[0]}", "/tmp01/salt-call", "--metadata", "--local", @@ -257,7 +257,7 @@ def test_call_success_parameters(): salt_mock["cmd.run_chroot"].assert_called_with( "/chroot", [ - "python{}".format(sys.version_info[0]), + f"python{sys.version_info[0]}", "/tmp01/salt-call", "--metadata", "--local", diff --git a/tests/pytests/unit/modules/test_composer.py b/tests/pytests/unit/modules/test_composer.py index 74d828aee6a..c0f5f552f2a 100644 --- a/tests/pytests/unit/modules/test_composer.py +++ b/tests/pytests/unit/modules/test_composer.py @@ -2,7 +2,6 @@ :codeauthor: Rupesh Tare """ - import pytest import salt.modules.composer as composer diff --git a/tests/pytests/unit/modules/test_config.py b/tests/pytests/unit/modules/test_config.py index c522dc7897c..122d41b9291 100644 --- a/tests/pytests/unit/modules/test_config.py +++ b/tests/pytests/unit/modules/test_config.py @@ -2,7 +2,6 @@ Test cases for salt.modules.config """ - import fnmatch import pytest diff --git a/tests/pytests/unit/modules/test_consul.py b/tests/pytests/unit/modules/test_consul.py index 52f1c8ece2e..311c48d05a4 100644 --- a/tests/pytests/unit/modules/test_consul.py +++ b/tests/pytests/unit/modules/test_consul.py @@ -2,7 +2,6 @@ Test case for the consul execution module """ - import logging import pytest @@ -1148,11 +1147,11 @@ def test_catalog_register(): token=token, node=node, address=address, - **nodemeta_kwargs + **nodemeta_kwargs, ) expected = { "data": {"Address": address, "Node": node, "NodeMeta": nodemeta}, - "message": "Catalog registration for {} successful.".format(node), + "message": f"Catalog registration for {node} successful.", "res": True, } @@ -1198,7 +1197,7 @@ def test_catalog_deregister(): checkid=checkid, ) expected = { - "message": "Catalog item {} removed.".format(node), + "message": f"Catalog item {node} removed.", "res": True, } @@ -1604,7 +1603,7 @@ def test_acl_create(): with patch.object(salt.utils.http, "query", return_value=mock_http_result): with patch.dict(consul.__salt__, {"config.get": mock_url}): result = consul.acl_create(consul_url=consul_url, token=token, name=name) - expected = {"message": "ACL {} created.".format(name), "res": True} + expected = {"message": f"ACL {name} created.", "res": True} assert expected == result @@ -1653,7 +1652,7 @@ def test_acl_update(): result = consul.acl_update( consul_url=consul_url, token=token, name=name, id=aclid ) - expected = {"message": "ACL {} created.".format(name), "res": True} + expected = {"message": f"ACL {name} created.", "res": True} assert expected == result @@ -1693,7 +1692,7 @@ def test_acl_delete(): result = consul.acl_delete( consul_url=consul_url, token=token, name=name, id=aclid ) - expected = {"message": "ACL {} deleted.".format(aclid), "res": True} + expected = {"message": f"ACL {aclid} deleted.", "res": True} assert expected == result @@ -1775,7 +1774,7 @@ def test_acl_clone(): ) expected = { "ID": aclid, - "message": "ACL {} cloned.".format(name), + "message": f"ACL {name} cloned.", "res": True, } assert expected == result @@ -1845,7 +1844,7 @@ def test_event_fire(): result = consul.event_fire(consul_url=consul_url, token=token, name=name) expected = { "data": "test", - "message": "Event {} fired.".format(name), + "message": f"Event {name} fired.", "res": True, } assert expected == result diff --git a/tests/pytests/unit/modules/test_cp.py b/tests/pytests/unit/modules/test_cp.py index 8fa0fd0d44b..8618a6bf74f 100644 --- a/tests/pytests/unit/modules/test_cp.py +++ b/tests/pytests/unit/modules/test_cp.py @@ -2,7 +2,6 @@ :codeauthor: jmoney """ - import pytest import salt.channel.client diff --git a/tests/pytests/unit/modules/test_daemontools.py b/tests/pytests/unit/modules/test_daemontools.py index 3a5e51fcba4..a5cbed24568 100644 --- a/tests/pytests/unit/modules/test_daemontools.py +++ b/tests/pytests/unit/modules/test_daemontools.py @@ -2,7 +2,6 @@ :codeauthor: Rupesh Tare """ - import os import pytest diff --git a/tests/pytests/unit/modules/test_data.py b/tests/pytests/unit/modules/test_data.py index c4d3f918c79..11b8568082d 100644 --- a/tests/pytests/unit/modules/test_data.py +++ b/tests/pytests/unit/modules/test_data.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import pytest import salt.modules.data as data diff --git a/tests/pytests/unit/modules/test_deb_apache.py b/tests/pytests/unit/modules/test_deb_apache.py index 1608321f107..d78f17c5d60 100644 --- a/tests/pytests/unit/modules/test_deb_apache.py +++ b/tests/pytests/unit/modules/test_deb_apache.py @@ -2,7 +2,6 @@ :codeauthor: Jayesh Kariya """ - import pytest import salt.modules.deb_apache as deb_apache diff --git a/tests/pytests/unit/modules/test_devinfo.py b/tests/pytests/unit/modules/test_devinfo.py index d3895e53246..ccca1486e86 100644 --- a/tests/pytests/unit/modules/test_devinfo.py +++ b/tests/pytests/unit/modules/test_devinfo.py @@ -42,10 +42,13 @@ def test_devices(): "E": {"ID_BUS": "ata"}, } - with patch.dict( - devinfo.__salt__, - {"udev.info": lambda d: {"sda": hd, "sdb": usb, "sr0": cdrom}[d]}, - ), patch.dict(devinfo.__grains__, {"disks": ["sda", "sdb", "sr0"]}): + def udev_info(key): + devices = {"sda": hd, "sdb": usb, "sr0": cdrom} + return devices[key] + + with patch.dict(devinfo.__salt__, {"udev.info": udev_info}), patch.dict( + devinfo.__grains__, {"disks": ["sda", "sdb", "sr0"]} + ): assert devinfo.filter_({"e.id_bus": "ata"}, {}) == ["sda", "sr0"] assert devinfo.filter_({"e.id_bus": "usb"}, {}) == ["sdb"] assert devinfo.filter_({"e.id_bus": "ata"}, {"s": ["cdrom"]}) == ["sda"] diff --git a/tests/pytests/unit/modules/test_devmap.py b/tests/pytests/unit/modules/test_devmap.py index f7fc9f09ea1..405eccac1b4 100644 --- a/tests/pytests/unit/modules/test_devmap.py +++ b/tests/pytests/unit/modules/test_devmap.py @@ -2,7 +2,6 @@ :codeauthor: Rupesh Tare """ - import os.path import pytest diff --git a/tests/pytests/unit/modules/test_dig.py b/tests/pytests/unit/modules/test_dig.py index dcc0acc8295..0d39a20e73c 100644 --- a/tests/pytests/unit/modules/test_dig.py +++ b/tests/pytests/unit/modules/test_dig.py @@ -2,7 +2,6 @@ Test cases for salt.modules.dig """ - import pytest import salt.modules.dig as dig diff --git a/tests/pytests/unit/modules/test_disk.py b/tests/pytests/unit/modules/test_disk.py index 58d8cbc305c..ca35852e06e 100644 --- a/tests/pytests/unit/modules/test_disk.py +++ b/tests/pytests/unit/modules/test_disk.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import pytest import salt.modules.disk as disk @@ -274,7 +275,7 @@ def test_fstype(): """ device = "/dev/sdX1" fs_type = "ext4" - mock = MagicMock(return_value="FSTYPE\n{}".format(fs_type)) + mock = MagicMock(return_value=f"FSTYPE\n{fs_type}") with patch.dict(disk.__grains__, {"kernel": "Linux"}), patch.dict( disk.__salt__, {"cmd.run": mock} ), patch("salt.utils.path.which", MagicMock(return_value=True)): @@ -291,7 +292,7 @@ def test_resize2fs(): "salt.utils.path.which", MagicMock(return_value=True) ): disk.resize2fs(device) - mock.assert_called_once_with("resize2fs {}".format(device), python_shell=False) + mock.assert_called_once_with(f"resize2fs {device}", python_shell=False) @pytest.mark.skip_on_windows(reason="Skip on Windows") diff --git a/tests/pytests/unit/modules/test_djangomod.py b/tests/pytests/unit/modules/test_djangomod.py index f3a22dd8052..f3fb1ed884e 100644 --- a/tests/pytests/unit/modules/test_djangomod.py +++ b/tests/pytests/unit/modules/test_djangomod.py @@ -3,6 +3,7 @@ Test cases for salt.modules.djangomod """ + import pytest import salt.modules.djangomod as djangomod diff --git a/tests/pytests/unit/modules/test_dpkg_lowpkg.py b/tests/pytests/unit/modules/test_dpkg_lowpkg.py index 41bd615ff29..625015b7590 100644 --- a/tests/pytests/unit/modules/test_dpkg_lowpkg.py +++ b/tests/pytests/unit/modules/test_dpkg_lowpkg.py @@ -4,7 +4,6 @@ Test cases for salt.modules.dpkg """ - import logging import os diff --git a/tests/pytests/unit/modules/test_drac.py b/tests/pytests/unit/modules/test_drac.py index 2a8da5a23f6..9d684797e0c 100644 --- a/tests/pytests/unit/modules/test_drac.py +++ b/tests/pytests/unit/modules/test_drac.py @@ -2,7 +2,6 @@ :codeauthor: Rupesh Tare """ - import pytest import salt.modules.drac as drac diff --git a/tests/pytests/unit/modules/test_drbd.py b/tests/pytests/unit/modules/test_drbd.py index ce9625c2d0c..c4686093a5a 100644 --- a/tests/pytests/unit/modules/test_drbd.py +++ b/tests/pytests/unit/modules/test_drbd.py @@ -4,7 +4,6 @@ Test cases for salt.modules.drbd """ - import pytest import salt.modules.drbd as drbd diff --git a/tests/pytests/unit/modules/test_etcd_mod.py b/tests/pytests/unit/modules/test_etcd_mod.py index 1c43772524d..d4b26a8486f 100644 --- a/tests/pytests/unit/modules/test_etcd_mod.py +++ b/tests/pytests/unit/modules/test_etcd_mod.py @@ -9,7 +9,6 @@ :codeauthor: Jayesh Kariya """ - import pytest import salt.modules.etcd_mod as etcd_mod diff --git a/tests/pytests/unit/modules/test_extfs.py b/tests/pytests/unit/modules/test_extfs.py index 4099f21b2ff..ce36373ef0b 100644 --- a/tests/pytests/unit/modules/test_extfs.py +++ b/tests/pytests/unit/modules/test_extfs.py @@ -2,7 +2,6 @@ :codeauthor: Jayesh Kariya """ - import pytest import salt.modules.extfs as extfs diff --git a/tests/pytests/unit/modules/test_genesis.py b/tests/pytests/unit/modules/test_genesis.py index 7a3b1632843..2bb81bf67f5 100644 --- a/tests/pytests/unit/modules/test_genesis.py +++ b/tests/pytests/unit/modules/test_genesis.py @@ -1,6 +1,7 @@ """ :codeauthor: Rupesh Tare """ + import pytest import salt.modules.genesis as genesis diff --git a/tests/pytests/unit/modules/test_gentoo_service.py b/tests/pytests/unit/modules/test_gentoo_service.py index 1d7e8eca7f9..31df975cb53 100644 --- a/tests/pytests/unit/modules/test_gentoo_service.py +++ b/tests/pytests/unit/modules/test_gentoo_service.py @@ -2,7 +2,6 @@ Test cases for salt.modules.gentoo_service """ - import pytest import salt.modules.gentoo_service as gentoo_service diff --git a/tests/pytests/unit/modules/test_git.py b/tests/pytests/unit/modules/test_git.py index 9d7c9ae9fc7..4da79b7bd55 100644 --- a/tests/pytests/unit/modules/test_git.py +++ b/tests/pytests/unit/modules/test_git.py @@ -2,7 +2,6 @@ :codeauthor: Erik Johnson """ - import copy import logging import os @@ -88,9 +87,11 @@ def test_list_worktrees(worktree_info, worktree_root): return "worktree {}\nHEAD {}\n{}\n".format( path, worktree_info[path]["HEAD"], - "branch {}".format(worktree_info[path]["branch"]) - if worktree_info[path]["branch"] != "detached" - else "detached", + ( + "branch {}".format(worktree_info[path]["branch"]) + if worktree_info[path]["branch"] != "detached" + else "detached" + ), ) # Build dict for _cmd_run_side_effect below. Start with the output from diff --git a/tests/pytests/unit/modules/test_glassfish.py b/tests/pytests/unit/modules/test_glassfish.py index 159d00cbb16..0362d23fc8d 100644 --- a/tests/pytests/unit/modules/test_glassfish.py +++ b/tests/pytests/unit/modules/test_glassfish.py @@ -4,6 +4,7 @@ tests.unit.modules.test_glassfish Unit tests for the glassfish module """ + import logging import pytest diff --git a/tests/pytests/unit/modules/test_glusterfs.py b/tests/pytests/unit/modules/test_glusterfs.py index be0d5b04462..8fab4a942a0 100644 --- a/tests/pytests/unit/modules/test_glusterfs.py +++ b/tests/pytests/unit/modules/test_glusterfs.py @@ -5,7 +5,6 @@ Test cases for salt.modules.glusterfs """ - import pytest import salt.modules.glusterfs as glusterfs diff --git a/tests/pytests/unit/modules/test_grub_legacy.py b/tests/pytests/unit/modules/test_grub_legacy.py index 47ec919939c..4d0feae6f4b 100644 --- a/tests/pytests/unit/modules/test_grub_legacy.py +++ b/tests/pytests/unit/modules/test_grub_legacy.py @@ -4,7 +4,6 @@ Test cases for salt.modules.grub_legacy """ - import errno import pytest diff --git a/tests/pytests/unit/modules/test_hadoop.py b/tests/pytests/unit/modules/test_hadoop.py index 37416403274..fad51b9b6e6 100644 --- a/tests/pytests/unit/modules/test_hadoop.py +++ b/tests/pytests/unit/modules/test_hadoop.py @@ -4,7 +4,6 @@ Test cases for salt.modules.hadoop """ - import pytest import salt.modules.hadoop as hadoop diff --git a/tests/pytests/unit/modules/test_haproxyconn.py b/tests/pytests/unit/modules/test_haproxyconn.py index 7834818fbea..51d39fc7d3b 100644 --- a/tests/pytests/unit/modules/test_haproxyconn.py +++ b/tests/pytests/unit/modules/test_haproxyconn.py @@ -4,7 +4,6 @@ Test cases for salt.modules.haproxyconn """ - import pytest import salt.modules.haproxyconn as haproxyconn diff --git a/tests/pytests/unit/modules/test_hashutil.py b/tests/pytests/unit/modules/test_hashutil.py index 57a237bad66..cf1527e624e 100644 --- a/tests/pytests/unit/modules/test_hashutil.py +++ b/tests/pytests/unit/modules/test_hashutil.py @@ -2,7 +2,6 @@ Test cases for salt.modules.hashutil """ - import pytest import salt.modules.hashutil as hashutil diff --git a/tests/pytests/unit/modules/test_helm.py b/tests/pytests/unit/modules/test_helm.py index 8286f4af27a..776ed45734e 100644 --- a/tests/pytests/unit/modules/test_helm.py +++ b/tests/pytests/unit/modules/test_helm.py @@ -2,7 +2,6 @@ Test cases for salt.modules.helm """ - import pytest import salt.modules.helm as helm diff --git a/tests/pytests/unit/modules/test_hg.py b/tests/pytests/unit/modules/test_hg.py index 314b48b2c8e..c942066fe9a 100644 --- a/tests/pytests/unit/modules/test_hg.py +++ b/tests/pytests/unit/modules/test_hg.py @@ -4,7 +4,6 @@ Test cases for salt.modules.hg """ - import pytest import salt.modules.hg as hg @@ -97,17 +96,17 @@ def test_status_multiple(): """ Test for Status to a given repository (cwd is list) """ + + def side_effect(*_, **kwargs): + if kwargs["cwd"] == "dir 0": + return "A file 0\n" + if kwargs["cwd"] == "dir 1": + return "M file 1" + with patch.dict( hg.__salt__, { - "cmd.run_stdout": MagicMock( - side_effect=( - lambda *args, **kwargs: { - "dir 0": "A file 0\n", - "dir 1": "M file 1", - }[kwargs["cwd"]] - ) - ) + "cmd.run_stdout": MagicMock(side_effect=side_effect), }, ): assert hg.status(["dir 0", "dir 1"]) == { diff --git a/tests/pytests/unit/modules/test_http.py b/tests/pytests/unit/modules/test_http.py index 7e2c33dc4c6..16aa8a72a99 100644 --- a/tests/pytests/unit/modules/test_http.py +++ b/tests/pytests/unit/modules/test_http.py @@ -4,7 +4,6 @@ Test cases for salt.modules.http """ - import pytest import salt.modules.http as http diff --git a/tests/pytests/unit/modules/test_ilo.py b/tests/pytests/unit/modules/test_ilo.py index 0df13c8be7d..3328856e577 100644 --- a/tests/pytests/unit/modules/test_ilo.py +++ b/tests/pytests/unit/modules/test_ilo.py @@ -4,7 +4,6 @@ Test cases for salt.modules.ilo """ - import tempfile import pytest diff --git a/tests/pytests/unit/modules/test_incron.py b/tests/pytests/unit/modules/test_incron.py index 9f241d570f1..cae619a6968 100644 --- a/tests/pytests/unit/modules/test_incron.py +++ b/tests/pytests/unit/modules/test_incron.py @@ -4,7 +4,6 @@ Test cases for salt.modules.incron """ - import pytest import salt.modules.incron as incron diff --git a/tests/pytests/unit/modules/test_ini_manage.py b/tests/pytests/unit/modules/test_ini_manage.py index 27f8d46eac6..499bae71e06 100644 --- a/tests/pytests/unit/modules/test_ini_manage.py +++ b/tests/pytests/unit/modules/test_ini_manage.py @@ -437,9 +437,7 @@ def test_unicode_set_option(encoding, linesep, ini_file, unicode_content): assert ini.get_option(str(ini_file), "Ascii", "ay", encoding=encoding) == "Aymar" # Check new section and option added - assert ( - ini.get_option(str(ini_file), "Юникод", "dv", encoding=encoding) == "ދިވެހިބަސް" - ) + assert ini.get_option(str(ini_file), "Юникод", "dv", encoding=encoding) == "ދިވެހިބަސް" @pytest.mark.parametrize("linesep", ["\r", "\n", "\r\n"]) @@ -478,9 +476,12 @@ def test_unicode_remove_option(encoding, linesep, ini_file, unicode_content): ini_file.write_bytes(content) assert ( - ini.remove_option(str(ini_file), "Юникод", "繁體中文", encoding=encoding) == "zh_TW" + ini.remove_option(str(ini_file), "Юникод", "繁體中文", encoding=encoding) + == "zh_TW" + ) + assert ( + ini.get_option(str(ini_file), "Юникод", "繁體中文", encoding=encoding) is None ) - assert ini.get_option(str(ini_file), "Юникод", "繁體中文", encoding=encoding) is None @pytest.mark.parametrize("linesep", ["\r", "\n", "\r\n"]) diff --git a/tests/pytests/unit/modules/test_introspect.py b/tests/pytests/unit/modules/test_introspect.py index caf9db42eee..287829af22c 100644 --- a/tests/pytests/unit/modules/test_introspect.py +++ b/tests/pytests/unit/modules/test_introspect.py @@ -4,7 +4,6 @@ Test cases for salt.modules.introspect """ - import pytest import salt.modules.introspect as introspect @@ -33,8 +32,8 @@ def test_running_service_owners(): ) ret = { "Error": { - "Unsupported File Module": "{}".format(err2), - "Unsupported Package Manager": "{}".format(err1), + "Unsupported File Module": f"{err2}", + "Unsupported Package Manager": f"{err1}", } } assert introspect.running_service_owners() == ret @@ -65,8 +64,8 @@ def test_enabled_service_owners(): ) ret = { "Error": { - "Unsupported Service Manager": "{}".format(err2), - "Unsupported Package Manager": "{}".format(err1), + "Unsupported Service Manager": f"{err2}", + "Unsupported Package Manager": f"{err1}", } } assert introspect.enabled_service_owners() == ret diff --git a/tests/pytests/unit/modules/test_ipset.py b/tests/pytests/unit/modules/test_ipset.py index e0f486300f3..83d07f1d4ef 100644 --- a/tests/pytests/unit/modules/test_ipset.py +++ b/tests/pytests/unit/modules/test_ipset.py @@ -1,6 +1,7 @@ """ :codeauthor: Rupesh Tare """ + import pytest import salt.modules.ipset as ipset diff --git a/tests/pytests/unit/modules/test_iptables.py b/tests/pytests/unit/modules/test_iptables.py index 63943462429..27fc171c86c 100644 --- a/tests/pytests/unit/modules/test_iptables.py +++ b/tests/pytests/unit/modules/test_iptables.py @@ -433,9 +433,7 @@ def test_check(): mock_rule = "m state --state RELATED,ESTABLISHED -j ACCEPT" mock_chain = "INPUT" mock_uuid = 31337 - mock_cmd_rule = MagicMock( - return_value="-A {}\n-A {}".format(mock_chain, hex(mock_uuid)) - ) + mock_cmd_rule = MagicMock(return_value=f"-A {mock_chain}\n-A {hex(mock_uuid)}") mock_cmd_nooutput = MagicMock(return_value="") mock_has = MagicMock(return_value=True) mock_not = MagicMock(return_value=False) diff --git a/tests/pytests/unit/modules/test_junos.py b/tests/pytests/unit/modules/test_junos.py index c29e70a4295..cfc792f5dd3 100644 --- a/tests/pytests/unit/modules/test_junos.py +++ b/tests/pytests/unit/modules/test_junos.py @@ -1,6 +1,7 @@ """ :codeauthor: Rajvi Dhimar """ + import os import pytest diff --git a/tests/pytests/unit/modules/test_key.py b/tests/pytests/unit/modules/test_key.py index bfc9442a103..726d7db44ca 100644 --- a/tests/pytests/unit/modules/test_key.py +++ b/tests/pytests/unit/modules/test_key.py @@ -4,7 +4,6 @@ Test cases for salt.modules.key """ - import os.path import pytest diff --git a/tests/pytests/unit/modules/test_keyboard.py b/tests/pytests/unit/modules/test_keyboard.py index d88f52bd6d6..ceb0d7effe0 100644 --- a/tests/pytests/unit/modules/test_keyboard.py +++ b/tests/pytests/unit/modules/test_keyboard.py @@ -2,7 +2,6 @@ :codeauthor: Jayesh Kariya """ - import pytest import salt.modules.keyboard as keyboard diff --git a/tests/pytests/unit/modules/test_kmod.py b/tests/pytests/unit/modules/test_kmod.py index c75c17caf59..313c6dd7121 100644 --- a/tests/pytests/unit/modules/test_kmod.py +++ b/tests/pytests/unit/modules/test_kmod.py @@ -93,9 +93,7 @@ def test_load(): assert [mod] == kmod.load(mod, True) with patch.dict(kmod.__salt__, {"cmd.run_all": mock_run_all_1}): - assert "Error loading module {}: {}".format(mod, err_msg) == kmod.load( - mod - ) + assert f"Error loading module {mod}: {err_msg}" == kmod.load(mod) def test_is_loaded(): diff --git a/tests/pytests/unit/modules/test_kubeadm.py b/tests/pytests/unit/modules/test_kubeadm.py index 252a89da2f9..a4c1d2fc449 100644 --- a/tests/pytests/unit/modules/test_kubeadm.py +++ b/tests/pytests/unit/modules/test_kubeadm.py @@ -2,7 +2,6 @@ Test cases for salt.modules.kubeadm """ - import pytest import salt.modules.kubeadm as kubeadm diff --git a/tests/pytests/unit/modules/test_launchctl_service.py b/tests/pytests/unit/modules/test_launchctl_service.py index bda0137189b..afb0920476a 100644 --- a/tests/pytests/unit/modules/test_launchctl_service.py +++ b/tests/pytests/unit/modules/test_launchctl_service.py @@ -4,7 +4,6 @@ Test cases for salt.modules.launchctl """ - import pytest import salt.modules.launchctl_service as launchctl diff --git a/tests/pytests/unit/modules/test_ldapmod.py b/tests/pytests/unit/modules/test_ldapmod.py index 751625eb992..9b8207ed5bf 100644 --- a/tests/pytests/unit/modules/test_ldapmod.py +++ b/tests/pytests/unit/modules/test_ldapmod.py @@ -4,7 +4,6 @@ Test cases for salt.modules.ldapmod """ - import time import pytest diff --git a/tests/pytests/unit/modules/test_linux_lvm.py b/tests/pytests/unit/modules/test_linux_lvm.py index 848a57040a1..2b45072876a 100644 --- a/tests/pytests/unit/modules/test_linux_lvm.py +++ b/tests/pytests/unit/modules/test_linux_lvm.py @@ -4,7 +4,6 @@ TestCase for the salt.modules.linux_lvm module """ - import os.path import pytest @@ -371,7 +370,7 @@ def test_lvcreate_extra_arguments_no_parameter(): assert linux_lvm.lvcreate(None, None, None, 1, **extra_args) == { "Output from lvcreate": 'Logical volume "None" created.' } - expected_args = ["--{}".format(arg) for arg in extra_args] + expected_args = [f"--{arg}" for arg in extra_args] processed_extra_args = mock.call_args.args[0][-(len(extra_args) + 1) : -1] assert all([arg in expected_args for arg in processed_extra_args]) diff --git a/tests/pytests/unit/modules/test_linux_shadow.py b/tests/pytests/unit/modules/test_linux_shadow.py index 5d977fc5212..0c742672750 100644 --- a/tests/pytests/unit/modules/test_linux_shadow.py +++ b/tests/pytests/unit/modules/test_linux_shadow.py @@ -1,6 +1,7 @@ """ :codeauthor: Erik Johnson """ + import types import pytest diff --git a/tests/pytests/unit/modules/test_locate.py b/tests/pytests/unit/modules/test_locate.py index f74853a10bc..f4e5b2fb822 100644 --- a/tests/pytests/unit/modules/test_locate.py +++ b/tests/pytests/unit/modules/test_locate.py @@ -4,7 +4,6 @@ Test cases for salt.modules.locate """ - import pytest import salt.modules.locate as locate diff --git a/tests/pytests/unit/modules/test_logadm.py b/tests/pytests/unit/modules/test_logadm.py index 7926252d025..fd5e61ba30f 100644 --- a/tests/pytests/unit/modules/test_logadm.py +++ b/tests/pytests/unit/modules/test_logadm.py @@ -4,7 +4,6 @@ Test cases for salt.modules.logadm """ - import pytest import salt.modules.logadm as logadm diff --git a/tests/pytests/unit/modules/test_logrotate.py b/tests/pytests/unit/modules/test_logrotate.py index 86caa5e58ad..03872c4cf06 100644 --- a/tests/pytests/unit/modules/test_logrotate.py +++ b/tests/pytests/unit/modules/test_logrotate.py @@ -4,7 +4,6 @@ Test cases for salt.modules.logrotate """ - import pytest import salt.modules.logrotate as logrotate diff --git a/tests/pytests/unit/modules/test_lvs.py b/tests/pytests/unit/modules/test_lvs.py index 58ba24a4160..513046787f0 100644 --- a/tests/pytests/unit/modules/test_lvs.py +++ b/tests/pytests/unit/modules/test_lvs.py @@ -4,7 +4,6 @@ Test cases for salt.modules.lvs """ - import pytest import salt.modules.lvs as lvs diff --git a/tests/pytests/unit/modules/test_mac_assistive.py b/tests/pytests/unit/modules/test_mac_assistive.py index 40841f516f2..b670991681c 100644 --- a/tests/pytests/unit/modules/test_mac_assistive.py +++ b/tests/pytests/unit/modules/test_mac_assistive.py @@ -49,7 +49,7 @@ def tcc_db_path(tmp_path, macos_version): # .schema # # Copy/Paste the output of that to this test. - pytest.fail("Don't know how to handle {}".format(macos_version)) + pytest.fail(f"Don't know how to handle {macos_version}") conn = sqlite3.connect(str(db)) with conn: for stmt in schema.splitlines(): diff --git a/tests/pytests/unit/modules/test_mac_brew_pkg.py b/tests/pytests/unit/modules/test_mac_brew_pkg.py index e824ba175df..6cd46f1ebb5 100644 --- a/tests/pytests/unit/modules/test_mac_brew_pkg.py +++ b/tests/pytests/unit/modules/test_mac_brew_pkg.py @@ -1,6 +1,7 @@ """ :codeauthor: Nicole Thomas """ + import os import textwrap diff --git a/tests/pytests/unit/modules/test_mac_service.py b/tests/pytests/unit/modules/test_mac_service.py index c657ea893c5..91578d946cf 100644 --- a/tests/pytests/unit/modules/test_mac_service.py +++ b/tests/pytests/unit/modules/test_mac_service.py @@ -2,7 +2,6 @@ :codeauthor: Megan Wilhite """ - import pytest import salt.modules.mac_service as mac_service diff --git a/tests/pytests/unit/modules/test_mac_shadow.py b/tests/pytests/unit/modules/test_mac_shadow.py index fa294b6651d..94d3c36b046 100644 --- a/tests/pytests/unit/modules/test_mac_shadow.py +++ b/tests/pytests/unit/modules/test_mac_shadow.py @@ -1,6 +1,7 @@ """ Unit Tests for the mac_desktop execution module. """ + from datetime import datetime import pytest diff --git a/tests/pytests/unit/modules/test_mandrill.py b/tests/pytests/unit/modules/test_mandrill.py index c1930d470e3..4f1c62e4673 100644 --- a/tests/pytests/unit/modules/test_mandrill.py +++ b/tests/pytests/unit/modules/test_mandrill.py @@ -2,7 +2,6 @@ Tests for the Mandrill execution module. """ - import pytest import salt.modules.mandrill as mandrill diff --git a/tests/pytests/unit/modules/test_match.py b/tests/pytests/unit/modules/test_match.py index 3a942dec752..6f159c0e8a5 100644 --- a/tests/pytests/unit/modules/test_match.py +++ b/tests/pytests/unit/modules/test_match.py @@ -2,7 +2,6 @@ :codeauthor: Oleg Lipovchenko """ - import pytest import salt.loader @@ -145,7 +144,7 @@ def test_watch_for_opts_mismatch_compound_match(minion_id): and use it instead of `__opts__`. If sometime in the future we update the matchers and use `__opts__` directly this breaks proxy matching. """ - assert compound_match.match("L@{}".format(minion_id)) + assert compound_match.match(f"L@{minion_id}") assert compound_match.match("L@rest03", {"id": "rest03"}) assert not compound_match.match("L@rest03") diff --git a/tests/pytests/unit/modules/test_mdadm_raid.py b/tests/pytests/unit/modules/test_mdadm_raid.py index f496339b738..ebbf9cecc25 100644 --- a/tests/pytests/unit/modules/test_mdadm_raid.py +++ b/tests/pytests/unit/modules/test_mdadm_raid.py @@ -5,6 +5,7 @@ tests.unit.modules.mdadm_test ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ + import re import pytest diff --git a/tests/pytests/unit/modules/test_mine.py b/tests/pytests/unit/modules/test_mine.py index 9fdfecbd0c1..2f06c1c27d8 100644 --- a/tests/pytests/unit/modules/test_mine.py +++ b/tests/pytests/unit/modules/test_mine.py @@ -3,7 +3,6 @@ :codeauthor: Herbert Buurman """ - import pytest import salt.modules.mine as mine @@ -24,7 +23,7 @@ class FakeCache: return self.data.get((bank, key), {}) def debug(self): - print("{}:FakeCache dump:\n{}".format(__name__, self.data)) + print(f"{__name__}:FakeCache dump:\n{self.data}") @pytest.fixture diff --git a/tests/pytests/unit/modules/test_mongodb.py b/tests/pytests/unit/modules/test_mongodb.py index b8b011dfdac..37bf432af25 100644 --- a/tests/pytests/unit/modules/test_mongodb.py +++ b/tests/pytests/unit/modules/test_mongodb.py @@ -112,7 +112,9 @@ def test_version(): mongodb.__salt__, {"config.option": config_option_mock} ) - with patch_mongo_client, patch_pymongo_command, patch_pymongo_database, patch_salt_dict: + with ( + patch_mongo_client + ), patch_pymongo_command, patch_pymongo_database, patch_salt_dict: ret = mongodb.version() assert ret == "6.0.2" @@ -139,7 +141,9 @@ def test_db_list(): mongodb.__salt__, {"config.option": config_option_mock} ) - with patch_list_db_names, patch_mongo_client, patch_pymongo_database, patch_salt_dict: + with ( + patch_list_db_names + ), patch_mongo_client, patch_pymongo_database, patch_salt_dict: ret = mongodb.db_list() assert ret == ["admin", "config", "local"] @@ -167,7 +171,9 @@ def test_db_exists(): mongodb.__salt__, {"config.option": config_option_mock} ) - with patch_list_db_names, patch_mongo_client, patch_pymongo_database, patch_salt_dict: + with ( + patch_list_db_names + ), patch_mongo_client, patch_pymongo_database, patch_salt_dict: ret = mongodb.db_exists("admin") assert ret @@ -215,7 +221,9 @@ def test_user_list(): mongodb.__salt__, {"config.option": config_option_mock} ) - with patch_mongo_client, patch_pymongo_database, patch_pymongo_command, patch_salt_dict: + with ( + patch_mongo_client + ), patch_pymongo_database, patch_pymongo_command, patch_salt_dict: ret = mongodb.user_list() expected = [ { @@ -318,7 +326,9 @@ def test_user_create(): mongodb.__salt__, {"config.option": config_option_mock} ) - with patch_mongo_client, patch_pymongo_database, patch_salt_dict, patch_pymongo_command: + with ( + patch_mongo_client + ), patch_pymongo_database, patch_salt_dict, patch_pymongo_command: ret = mongodb.user_create("test_user", "test_password") assert ret @@ -344,7 +354,9 @@ def test_user_create_exception(): mongodb.__salt__, {"config.option": config_option_mock} ) - with patch_mongo_client, patch_pymongo_database, patch_salt_dict, patch_pymongo_command: + with ( + patch_mongo_client + ), patch_pymongo_database, patch_salt_dict, patch_pymongo_command: ret = mongodb.user_create("test_user", "test_password") assert not ret @@ -370,7 +382,9 @@ def test_user_remove(): mongodb.__salt__, {"config.option": config_option_mock} ) - with patch_mongo_client, patch_pymongo_database, patch_salt_dict, patch_pymongo_command: + with ( + patch_mongo_client + ), patch_pymongo_database, patch_salt_dict, patch_pymongo_command: ret = mongodb.user_remove("test_user") assert ret @@ -396,7 +410,9 @@ def test_user_remove_exception(): mongodb.__salt__, {"config.option": config_option_mock} ) - with patch_mongo_client, patch_pymongo_database, patch_salt_dict, patch_pymongo_command: + with ( + patch_mongo_client + ), patch_pymongo_database, patch_salt_dict, patch_pymongo_command: ret = mongodb.user_remove("test_user") assert not ret @@ -446,7 +462,9 @@ def test_user_roles_exists(): mongodb.__salt__, {"config.option": config_option_mock} ) - with patch_mongo_client, patch_pymongo_database, patch_salt_dict, patch_pymongo_command: + with ( + patch_mongo_client + ), patch_pymongo_database, patch_salt_dict, patch_pymongo_command: ret = mongodb.user_roles_exists("test_user", '["read"]', "admin") assert ret @@ -471,7 +489,9 @@ def test_user_grant_roles(): mongodb.__salt__, {"config.option": config_option_mock} ) - with patch_mongo_client, patch_pymongo_database, patch_salt_dict, patch_pymongo_command: + with ( + patch_mongo_client + ), patch_pymongo_database, patch_salt_dict, patch_pymongo_command: ret = mongodb.user_grant_roles( "test_user", '[{"role": "readWrite", "db": "admin" }]', "admin" ) @@ -498,7 +518,9 @@ def test_user_revoke_roles(): mongodb.__salt__, {"config.option": config_option_mock} ) - with patch_mongo_client, patch_pymongo_database, patch_salt_dict, patch_pymongo_command: + with ( + patch_mongo_client + ), patch_pymongo_database, patch_salt_dict, patch_pymongo_command: ret = mongodb.user_revoke_roles( "test_user", '[{"role": "readWrite", "db": "admin" }]', "admin" ) @@ -525,7 +547,9 @@ def test_collection_create(): mongodb.__salt__, {"config.option": config_option_mock} ) - with patch_mongo_client, patch_pymongo_database, patch_salt_dict, patch_pymongo_command: + with ( + patch_mongo_client + ), patch_pymongo_database, patch_salt_dict, patch_pymongo_command: ret = mongodb.collection_create("test_collection") assert ret @@ -552,7 +576,9 @@ def test_collections_list(): mongodb.__salt__, {"config.option": config_option_mock} ) - with patch_mongo_client, patch_pymongo_database, patch_salt_dict, patch_pymongo_list_collection_names: + with ( + patch_mongo_client + ), patch_pymongo_database, patch_salt_dict, patch_pymongo_list_collection_names: ret = mongodb.collections_list() assert ret == ["system.users", "mycollection", "system.version"] @@ -579,7 +605,9 @@ def test_insert(): patch_pymongo_database = patch("pymongo.database.Database", pymongo_database_mock) patch_pymongo_collection = patch.object(mongodb, "getattr", pymongo_collection_mock) - with patch_mongo_client, patch_salt_dict, patch_pymongo_database, patch_pymongo_collection: + with ( + patch_mongo_client + ), patch_salt_dict, patch_pymongo_database, patch_pymongo_collection: patch_pymongo_collection_insert = patch.object( MockPyMongoCollection, "insert_many", diff --git a/tests/pytests/unit/modules/test_monit.py b/tests/pytests/unit/modules/test_monit.py index 092782bc1dd..7e16f1eca69 100644 --- a/tests/pytests/unit/modules/test_monit.py +++ b/tests/pytests/unit/modules/test_monit.py @@ -2,7 +2,6 @@ :codeauthor: Rupesh Tare """ - import pytest import salt.modules.monit as monit diff --git a/tests/pytests/unit/modules/test_mysql.py b/tests/pytests/unit/modules/test_mysql.py index 001655c8fd1..7e2bb5928b3 100644 --- a/tests/pytests/unit/modules/test_mysql.py +++ b/tests/pytests/unit/modules/test_mysql.py @@ -6,7 +6,6 @@ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ - import logging import pytest @@ -861,7 +860,7 @@ def _test_call(function, expected_sql, *args, **kwargs): .execute("{}".format(expected_sql["sql"]), expected_sql["sql_args"]) ) else: - calls = call().cursor().execute("{}".format(expected_sql)) + calls = call().cursor().execute(f"{expected_sql}") connect_mock.assert_has_calls((calls,), True) diff --git a/tests/pytests/unit/modules/test_nacl.py b/tests/pytests/unit/modules/test_nacl.py index 915e2c5e3dd..2906ebc5419 100644 --- a/tests/pytests/unit/modules/test_nacl.py +++ b/tests/pytests/unit/modules/test_nacl.py @@ -1,6 +1,7 @@ """ Unit tests for the salt.modules.nacl module """ + import pytest import salt.utils.stringutils diff --git a/tests/pytests/unit/modules/test_nfs3.py b/tests/pytests/unit/modules/test_nfs3.py index 030e7f6d6f2..ecb16dff4a5 100644 --- a/tests/pytests/unit/modules/test_nfs3.py +++ b/tests/pytests/unit/modules/test_nfs3.py @@ -4,7 +4,6 @@ Test cases for salt.modules.nfs3 """ - import pytest import salt.modules.nfs3 as nfs3 diff --git a/tests/pytests/unit/modules/test_nftables.py b/tests/pytests/unit/modules/test_nftables.py index 423a38c0101..855e7712e7f 100644 --- a/tests/pytests/unit/modules/test_nftables.py +++ b/tests/pytests/unit/modules/test_nftables.py @@ -3,6 +3,7 @@ Test cases for salt.modules.nftables """ + import json import pytest diff --git a/tests/pytests/unit/modules/test_npm.py b/tests/pytests/unit/modules/test_npm.py index 61117ffcc12..53243964953 100644 --- a/tests/pytests/unit/modules/test_npm.py +++ b/tests/pytests/unit/modules/test_npm.py @@ -4,7 +4,6 @@ Test cases for salt.modules.npm """ - import textwrap import pytest diff --git a/tests/pytests/unit/modules/test_openbsdpkg.py b/tests/pytests/unit/modules/test_openbsdpkg.py index 33261be9464..aca6068cc48 100644 --- a/tests/pytests/unit/modules/test_openbsdpkg.py +++ b/tests/pytests/unit/modules/test_openbsdpkg.py @@ -2,7 +2,6 @@ :codeauthor: Eric Radman """ - import pytest import salt.modules.openbsdpkg as openbsdpkg diff --git a/tests/pytests/unit/modules/test_openbsdrcctl_service.py b/tests/pytests/unit/modules/test_openbsdrcctl_service.py index b0f97fa1404..1aa53507562 100644 --- a/tests/pytests/unit/modules/test_openbsdrcctl_service.py +++ b/tests/pytests/unit/modules/test_openbsdrcctl_service.py @@ -28,32 +28,28 @@ def configure_loader_modules(retcode_mock): def test_available(retcode_mock, rcctl): retcode_mock.return_value = 0 assert openbsdrcctl.available("test") is True - retcode_mock.assert_called_with("{} get test".format(rcctl), ignore_retcode=True) + retcode_mock.assert_called_with(f"{rcctl} get test", ignore_retcode=True) retcode_mock.return_value = 2 assert openbsdrcctl.available("test") is False - retcode_mock.assert_called_with("{} get test".format(rcctl), ignore_retcode=True) + retcode_mock.assert_called_with(f"{rcctl} get test", ignore_retcode=True) def test_status(retcode_mock, rcctl): retcode_mock.return_value = 0 assert openbsdrcctl.status("test") is True - retcode_mock.assert_called_with("{} check test".format(rcctl), ignore_retcode=True) + retcode_mock.assert_called_with(f"{rcctl} check test", ignore_retcode=True) retcode_mock.return_value = 2 assert openbsdrcctl.status("test") is False - retcode_mock.assert_called_with("{} check test".format(rcctl), ignore_retcode=True) + retcode_mock.assert_called_with(f"{rcctl} check test", ignore_retcode=True) def test_disabled(retcode_mock, rcctl): retcode_mock.return_value = 0 assert openbsdrcctl.disabled("test") is False - retcode_mock.assert_called_with( - "{} get test status".format(rcctl), ignore_retcode=True - ) + retcode_mock.assert_called_with(f"{rcctl} get test status", ignore_retcode=True) retcode_mock.return_value = 2 assert openbsdrcctl.disabled("test") is True - retcode_mock.assert_called_with( - "{} get test status".format(rcctl), ignore_retcode=True - ) + retcode_mock.assert_called_with(f"{rcctl} get test status", ignore_retcode=True) def test_enabled(retcode_mock, rcctl): @@ -66,12 +62,8 @@ def test_enabled(retcode_mock, rcctl): } with patch.dict(openbsdrcctl.__salt__, salt_mock): assert openbsdrcctl.enabled("test", flags=flags_return) is True - retcode_mock.assert_called_with( - "{} get test status".format(rcctl), ignore_retcode=True - ) + retcode_mock.assert_called_with(f"{rcctl} get test status", ignore_retcode=True) retcode_mock.return_value = 2 stdout_mock.reset_mock() assert openbsdrcctl.enabled("test") is False - retcode_mock.assert_called_with( - "{} get test status".format(rcctl), ignore_retcode=True - ) + retcode_mock.assert_called_with(f"{rcctl} get test status", ignore_retcode=True) diff --git a/tests/pytests/unit/modules/test_oracle.py b/tests/pytests/unit/modules/test_oracle.py index 2e578e6b5db..4aa8318d9b7 100644 --- a/tests/pytests/unit/modules/test_oracle.py +++ b/tests/pytests/unit/modules/test_oracle.py @@ -4,7 +4,6 @@ Test cases for salt.modules.oracle """ - import os import pytest diff --git a/tests/pytests/unit/modules/test_osquery.py b/tests/pytests/unit/modules/test_osquery.py index 98ce22b25e3..20647a6dfc4 100644 --- a/tests/pytests/unit/modules/test_osquery.py +++ b/tests/pytests/unit/modules/test_osquery.py @@ -4,7 +4,6 @@ Test cases for salt.modules.osquery """ - import pytest import salt.modules.osquery as osquery diff --git a/tests/pytests/unit/modules/test_pacmanpkg.py b/tests/pytests/unit/modules/test_pacmanpkg.py index 09a6f6aef16..796624dbeb7 100644 --- a/tests/pytests/unit/modules/test_pacmanpkg.py +++ b/tests/pytests/unit/modules/test_pacmanpkg.py @@ -2,7 +2,6 @@ :codeauthor: Eric Vz """ - import pytest import salt.modules.pacmanpkg as pacman @@ -110,7 +109,7 @@ def test_group_list(): elif cmd == ["pacman", "-Qg"]: return "group-a pkg1\ngroup-b pkg4" else: - return "Untested command ({}, {})!".format(cmd, kwargs) + return f"Untested command ({cmd}, {kwargs})!" cmdmock = MagicMock(side_effect=cmdlist) @@ -137,7 +136,7 @@ def test_group_info(): if cmd == ["pacman", "-Sgg", "testgroup"]: return "testgroup pkg1\ntestgroup pkg2" else: - return "Untested command ({}, {})!".format(cmd, kwargs) + return f"Untested command ({cmd}, {kwargs})!" cmdmock = MagicMock(side_effect=cmdlist) diff --git a/tests/pytests/unit/modules/test_pagerduty.py b/tests/pytests/unit/modules/test_pagerduty.py index 0d4cda95868..f43df961f53 100644 --- a/tests/pytests/unit/modules/test_pagerduty.py +++ b/tests/pytests/unit/modules/test_pagerduty.py @@ -4,7 +4,6 @@ Test cases for salt.modules.pagerduty """ - import pytest import salt.modules.pagerduty as pagerduty diff --git a/tests/pytests/unit/modules/test_pam.py b/tests/pytests/unit/modules/test_pam.py index 0fd8078a560..6f1e7faf661 100644 --- a/tests/pytests/unit/modules/test_pam.py +++ b/tests/pytests/unit/modules/test_pam.py @@ -3,6 +3,7 @@ Test cases for salt.modules.pam """ + import pytest import salt.modules.pam as pam diff --git a/tests/pytests/unit/modules/test_parallels.py b/tests/pytests/unit/modules/test_parallels.py index 2d48ccb6146..22c0b1c87df 100644 --- a/tests/pytests/unit/modules/test_parallels.py +++ b/tests/pytests/unit/modules/test_parallels.py @@ -2,7 +2,6 @@ Test parallels desktop execution module functions """ - import textwrap import pytest @@ -234,12 +233,12 @@ def test_exists(): runas = "macdev" # Validate exists - mock_list = MagicMock(return_value="Name: {}\nState: running".format(name)) + mock_list = MagicMock(return_value=f"Name: {name}\nState: running") with patch.object(parallels, "list_vms", mock_list): assert parallels.exists(name, runas=runas) # Validate not exists - mock_list = MagicMock(return_value="Name: {}\nState: running".format(name)) + mock_list = MagicMock(return_value=f"Name: {name}\nState: running") with patch.object(parallels, "list_vms", mock_list): assert not parallels.exists("winvm", runas=runas) diff --git a/tests/pytests/unit/modules/test_pecl.py b/tests/pytests/unit/modules/test_pecl.py index 65b1235ce18..8113fb4ce64 100644 --- a/tests/pytests/unit/modules/test_pecl.py +++ b/tests/pytests/unit/modules/test_pecl.py @@ -4,7 +4,6 @@ Test cases for salt.modules.pecl """ - import pytest import salt.modules.pecl as pecl diff --git a/tests/pytests/unit/modules/test_pkgutil.py b/tests/pytests/unit/modules/test_pkgutil.py index 627c807d917..5df0044fc30 100644 --- a/tests/pytests/unit/modules/test_pkgutil.py +++ b/tests/pytests/unit/modules/test_pkgutil.py @@ -2,7 +2,6 @@ :codeauthor: Jayesh Kariya """ - import pytest import salt.modules.pkgutil as pkgutil diff --git a/tests/pytests/unit/modules/test_portage_config.py b/tests/pytests/unit/modules/test_portage_config.py index 34b388a8a43..71da51390e2 100644 --- a/tests/pytests/unit/modules/test_portage_config.py +++ b/tests/pytests/unit/modules/test_portage_config.py @@ -4,6 +4,7 @@ pytest.unit.modules.portage_flags ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ + import pytest import salt.modules.portage_config as portage_config @@ -26,7 +27,7 @@ def test_get_config_file_wildcards(): ("cat/pkg::repo", "/etc/portage/package.mask/cat/pkg"), ] - for (atom, expected) in pairs: + for atom, expected in pairs: assert portage_config._get_config_file("mask", atom) == expected diff --git a/tests/pytests/unit/modules/test_postfix.py b/tests/pytests/unit/modules/test_postfix.py index e834b654473..72ed5a8d4b7 100644 --- a/tests/pytests/unit/modules/test_postfix.py +++ b/tests/pytests/unit/modules/test_postfix.py @@ -2,7 +2,6 @@ :codeauthor: Jayesh Kariya """ - import pytest import salt.modules.postfix as postfix diff --git a/tests/pytests/unit/modules/test_poudriere.py b/tests/pytests/unit/modules/test_poudriere.py index 4f069f47715..899d553a6bb 100644 --- a/tests/pytests/unit/modules/test_poudriere.py +++ b/tests/pytests/unit/modules/test_poudriere.py @@ -34,9 +34,9 @@ def test_make_pkgng_aware(): """ temp_dir = os.path.join("tmp", "salt") conf_file = os.path.join("tmp", "salt", "salt-make.conf") - ret1 = "Could not create or find required directory {}".format(temp_dir) - ret2 = "Looks like file {} could not be created".format(conf_file) - ret3 = {"changes": "Created {}".format(conf_file)} + ret1 = f"Could not create or find required directory {temp_dir}" + ret2 = f"Looks like file {conf_file} could not be created" + ret3 = {"changes": f"Created {conf_file}"} mock = MagicMock(return_value=temp_dir) mock_true = MagicMock(return_value=True) with patch.dict( diff --git a/tests/pytests/unit/modules/test_ps.py b/tests/pytests/unit/modules/test_ps.py index 99540b243d2..ba87bdccd4a 100644 --- a/tests/pytests/unit/modules/test_ps.py +++ b/tests/pytests/unit/modules/test_ps.py @@ -85,7 +85,9 @@ def sample_process(): patch_create_time = patch( "psutil._psplatform.Process.create_time", return_value=393829200 ) - with patch_stat_file, patch_status, patch_create_time, patch_exe, patch_oneshot, patch_kinfo: + with ( + patch_stat_file + ), patch_status, patch_create_time, patch_exe, patch_oneshot, patch_kinfo: proc = psutil.Process(pid=42) proc.info = proc.as_dict(("name", "status")) yield proc @@ -1184,7 +1186,9 @@ def test_proc_info(): patch_create_time = patch( "psutil._psplatform.Process.create_time", return_value=393829200 ) - with patch_stat_file, patch_status, patch_create_time, patch_exe, patch_oneshot, patch_kinfo: + with ( + patch_stat_file + ), patch_status, patch_create_time, patch_exe, patch_oneshot, patch_kinfo: if salt.utils.platform.is_windows(): with patch("psutil._pswindows.cext") as mock__psutil_windows: with patch("psutil._pswindows.Process.ppid", return_value=99): diff --git a/tests/pytests/unit/modules/test_publish.py b/tests/pytests/unit/modules/test_publish.py index 38731761a91..5da0902dfa7 100644 --- a/tests/pytests/unit/modules/test_publish.py +++ b/tests/pytests/unit/modules/test_publish.py @@ -2,7 +2,6 @@ :codeauthor: Jayesh Kariya """ - import pytest import salt.modules.publish as publish diff --git a/tests/pytests/unit/modules/test_pw_user.py b/tests/pytests/unit/modules/test_pw_user.py index c527bcbd2df..9b1c86f1039 100644 --- a/tests/pytests/unit/modules/test_pw_user.py +++ b/tests/pytests/unit/modules/test_pw_user.py @@ -2,7 +2,6 @@ :codeauthor: Rupesh Tare """ - import logging import pytest diff --git a/tests/pytests/unit/modules/test_qemu_img.py b/tests/pytests/unit/modules/test_qemu_img.py index b616f6f172b..ed175d33a36 100644 --- a/tests/pytests/unit/modules/test_qemu_img.py +++ b/tests/pytests/unit/modules/test_qemu_img.py @@ -2,7 +2,6 @@ :codeauthor: Rupesh Tare """ - import os import pytest diff --git a/tests/pytests/unit/modules/test_rabbitmq.py b/tests/pytests/unit/modules/test_rabbitmq.py index b9004962b4f..13860cd33f5 100644 --- a/tests/pytests/unit/modules/test_rabbitmq.py +++ b/tests/pytests/unit/modules/test_rabbitmq.py @@ -2,7 +2,6 @@ :codeauthor: Jayesh Kariya """ - import logging import pytest diff --git a/tests/pytests/unit/modules/test_rbenv.py b/tests/pytests/unit/modules/test_rbenv.py index ed0a535ec37..5d36acc2094 100644 --- a/tests/pytests/unit/modules/test_rbenv.py +++ b/tests/pytests/unit/modules/test_rbenv.py @@ -4,7 +4,6 @@ Test cases for salt.modules.rbenv """ - import os import pytest diff --git a/tests/pytests/unit/modules/test_rdp.py b/tests/pytests/unit/modules/test_rdp.py index 682bd752f1b..8815b201737 100644 --- a/tests/pytests/unit/modules/test_rdp.py +++ b/tests/pytests/unit/modules/test_rdp.py @@ -4,7 +4,6 @@ Test cases for salt.modules.rdp """ - import pytest import salt.modules.rdp as rdp diff --git a/tests/pytests/unit/modules/test_reg.py b/tests/pytests/unit/modules/test_reg.py index 480af192086..e28f6db832a 100644 --- a/tests/pytests/unit/modules/test_reg.py +++ b/tests/pytests/unit/modules/test_reg.py @@ -193,7 +193,7 @@ def test_list_keys_non_existing(): """ Test the list_keys function using a non existing registry key """ - expected = (False, "Cannot find key: HKLM\\{}".format(FAKE_KEY)) + expected = (False, f"Cannot find key: HKLM\\{FAKE_KEY}") result = reg.list_keys(hive="HKLM", key=FAKE_KEY) assert result == expected @@ -235,7 +235,7 @@ def test_list_values_non_existing(): """ Test the list_values function using a non existing registry key """ - expected = (False, "Cannot find key: HKLM\\{}".format(FAKE_KEY)) + expected = (False, f"Cannot find key: HKLM\\{FAKE_KEY}") result = reg.list_values(hive="HKLM", key=FAKE_KEY) assert result == expected @@ -312,7 +312,7 @@ def test_read_value_non_existing_key(): Test the read_value function using a non existing registry key """ expected = { - "comment": "Cannot find key: HKLM\\{}".format(FAKE_KEY), + "comment": f"Cannot find key: HKLM\\{FAKE_KEY}", "vdata": None, "vtype": None, "vname": "fake_name", diff --git a/tests/pytests/unit/modules/test_restartcheck.py b/tests/pytests/unit/modules/test_restartcheck.py index 14efa9a7add..2a4c385bd24 100644 --- a/tests/pytests/unit/modules/test_restartcheck.py +++ b/tests/pytests/unit/modules/test_restartcheck.py @@ -217,7 +217,11 @@ def test_when_nilinuxrt_and_not_kernel_modules_changed_or_sysapi_files_changed_a return_value=[], ) - with patch_grains, patch_kernel_versions, patch_salt, patch_sysapi_changed, patch_kernel_mod_changed, patch_del_files: + with ( + patch_grains + ), ( + patch_kernel_versions + ), patch_salt, patch_sysapi_changed, patch_kernel_mod_changed, patch_del_files: actual_result = restartcheck.restartcheck() assert actual_result == expected_result @@ -262,7 +266,11 @@ def test_when_nilinuxrt_and_not_kernel_modules_changed_or_sysapi_files_changed_a return_value=[], ) - with patch_grains, patch_kernel_versions, patch_salt, patch_sysapi_changed, patch_kernel_mod_changed, patch_del_files: + with ( + patch_grains + ), ( + patch_kernel_versions + ), patch_salt, patch_sysapi_changed, patch_kernel_mod_changed, patch_del_files: actual_result = restartcheck.restartcheck() assert actual_result == expected_result @@ -570,14 +578,10 @@ def test_valid_command(): patch_deleted = patch( "salt.modules.restartcheck._deleted_files", - MagicMock( - return_value=[(";touch {};".format(create_file), 123, "/root/ (deleted)")] - ), + MagicMock(return_value=[(f";touch {create_file};", 123, "/root/ (deleted)")]), ) - patch_readlink = patch( - "os.readlink", return_value="/root/;touch {};".format(create_file) - ) + patch_readlink = patch("os.readlink", return_value=f"/root/;touch {create_file};") check_error = True if salt.utils.path.which("repoquery"): @@ -635,7 +639,9 @@ def test_valid_command_b(): patch_popen = patch("subprocess.Popen", popen_mock) patch_grains = patch.dict(restartcheck.__grains__, {"os_family": "RedHat"}) - with patch_kernel, patch_salt, patch_deleted, patch_readlink, patch_grains, patch_popen: + with ( + patch_kernel + ), patch_salt, patch_deleted, patch_readlink, patch_grains, patch_popen: ret = restartcheck.restartcheck() assert "Found 1 processes using old versions of upgraded files" in ret popen_mock.assert_called_with( diff --git a/tests/pytests/unit/modules/test_ret.py b/tests/pytests/unit/modules/test_ret.py index 85c4e539859..25d85beecfa 100644 --- a/tests/pytests/unit/modules/test_ret.py +++ b/tests/pytests/unit/modules/test_ret.py @@ -4,7 +4,6 @@ Test cases for salt.modules.ret """ - import pytest import salt.loader diff --git a/tests/pytests/unit/modules/test_rh_service.py b/tests/pytests/unit/modules/test_rh_service.py index bee9e1e0860..e6373b92e6e 100644 --- a/tests/pytests/unit/modules/test_rh_service.py +++ b/tests/pytests/unit/modules/test_rh_service.py @@ -4,7 +4,6 @@ Test cases for salt.modules.rh_service """ - import textwrap import pytest diff --git a/tests/pytests/unit/modules/test_rvm.py b/tests/pytests/unit/modules/test_rvm.py index 0125d7a42ff..dab57c2a2ff 100644 --- a/tests/pytests/unit/modules/test_rvm.py +++ b/tests/pytests/unit/modules/test_rvm.py @@ -2,7 +2,6 @@ Test cases for salt.modules.rvm """ - import pytest import salt.modules.rvm as rvm diff --git a/tests/pytests/unit/modules/test_s6.py b/tests/pytests/unit/modules/test_s6.py index 7809051f03f..a66fd62018b 100644 --- a/tests/pytests/unit/modules/test_s6.py +++ b/tests/pytests/unit/modules/test_s6.py @@ -4,7 +4,6 @@ Test cases for salt.modules.s6 """ - import os import pytest diff --git a/tests/pytests/unit/modules/test_saltcloudmod.py b/tests/pytests/unit/modules/test_saltcloudmod.py index 54f56552329..53f2f61f77b 100644 --- a/tests/pytests/unit/modules/test_saltcloudmod.py +++ b/tests/pytests/unit/modules/test_saltcloudmod.py @@ -2,7 +2,6 @@ :codeauthor: Rahul Handay """ - import pytest import salt.modules.saltcloudmod as saltcloudmod diff --git a/tests/pytests/unit/modules/test_schedule.py b/tests/pytests/unit/modules/test_schedule.py index 419c4df9c8b..1dbdc529d5a 100644 --- a/tests/pytests/unit/modules/test_schedule.py +++ b/tests/pytests/unit/modules/test_schedule.py @@ -59,7 +59,13 @@ def test_purge(job1): schedule, "list_", MagicMock(return_value=_schedule_data) ) - with patch_makedirs, patch_schedule_opts, patch_schedule_event_fire, patch_schedule_get_event, patch_schedule_connect_pub, patch_schedule_list: + with ( + patch_makedirs + ), ( + patch_schedule_opts + ), ( + patch_schedule_event_fire + ), patch_schedule_get_event, patch_schedule_connect_pub, patch_schedule_list: assert schedule.purge() == { "comment": ["Deleted job: job1 from schedule."], "changes": {"job1": "removed"}, @@ -113,7 +119,11 @@ def test_delete(job1): SaltEvent, "connect_pub", return_value=True ) - with patch_makedirs, patch_schedule_opts, patch_schedule_event_fire, patch_schedule_connect_pub, patch_schedule_get_event: + with ( + patch_makedirs + ), ( + patch_schedule_opts + ), patch_schedule_event_fire, patch_schedule_connect_pub, patch_schedule_get_event: assert schedule.delete("job1") == { "comment": "Job job1 does not exist.", "changes": {}, @@ -268,7 +278,9 @@ def test_add(): SaltEvent, "get_event", return_value={"complete": True, "schedule": {}} ) - with patch_makedirs, patch_schedule_opts, patch_schedule_connect_pub, patch_schedule_event_fire: + with ( + patch_makedirs + ), patch_schedule_opts, patch_schedule_connect_pub, patch_schedule_event_fire: _ret_value = {"complete": True, "schedule": {"job1": {"salt": "salt"}}} patch_schedule_get_event = patch.object( @@ -355,7 +367,11 @@ def test_run_job(job1): return_value={"complete": True, "schedule": {"job1": job1}}, ) - with patch_makedirs, patch_schedule_opts, patch_schedule_event_fire, patch_schedule_connect_pub, patch_schedule_get_event: + with ( + patch_makedirs + ), ( + patch_schedule_opts + ), patch_schedule_event_fire, patch_schedule_connect_pub, patch_schedule_get_event: assert schedule.run_job("job1") == { "comment": "Scheduling Job job1 on minion.", "result": True, @@ -384,7 +400,11 @@ def test_enable_job(): SaltEvent, "connect_pub", return_value=True ) - with patch_makedirs, patch_schedule_opts, patch_schedule_event_fire, patch_schedule_connect_pub, patch_schedule_get_event: + with ( + patch_makedirs + ), ( + patch_schedule_opts + ), patch_schedule_event_fire, patch_schedule_connect_pub, patch_schedule_get_event: assert schedule.enable_job("job1") == { "comment": "Job job1 does not exist.", "changes": {}, @@ -414,7 +434,11 @@ def test_disable_job(): SaltEvent, "connect_pub", return_value=True ) - with patch_makedirs, patch_schedule_opts, patch_schedule_event_fire, patch_schedule_connect_pub, patch_schedule_get_event: + with ( + patch_makedirs + ), ( + patch_schedule_opts + ), patch_schedule_event_fire, patch_schedule_connect_pub, patch_schedule_get_event: assert schedule.disable_job("job1") == { "comment": "Job job1 does not exist.", "changes": {}, @@ -503,7 +527,11 @@ def test_move(job1): return_value={"complete": True, "schedule": {"job1": job1}}, ) - with patch_makedirs, patch_schedule_opts, patch_schedule_event_fire, patch_schedule_connect_pub, patch_schedule_get_event: + with ( + patch_makedirs + ), ( + patch_schedule_opts + ), patch_schedule_event_fire, patch_schedule_connect_pub, patch_schedule_get_event: mock = MagicMock(return_value={}) patch_schedule_publish = patch.dict( schedule.__salt__, {"publish.publish": mock} @@ -545,7 +573,11 @@ def test_move(job1): mock = MagicMock(side_effect=[{}, {"job1": {}}]) - with patch_makedirs, patch_schedule_opts, patch_schedule_event_fire, patch_schedule_connect_pub, patch_schedule_get_event: + with ( + patch_makedirs + ), ( + patch_schedule_opts + ), patch_schedule_event_fire, patch_schedule_connect_pub, patch_schedule_get_event: with patch.dict(schedule.__pillar__, {"schedule": {"job1": job1}}): mock = MagicMock(return_value={}) patch_schedule_publish = patch.dict( @@ -608,7 +640,11 @@ def test_copy(job1): SaltEvent, "connect_pub", return_value=True ) - with patch_makedirs, patch_schedule_opts, patch_schedule_event_fire, patch_schedule_get_event, patch_schedule_connect_pub: + with ( + patch_makedirs + ), ( + patch_schedule_opts + ), patch_schedule_event_fire, patch_schedule_get_event, patch_schedule_connect_pub: mock = MagicMock(return_value={}) patch_schedule_publish = patch.dict( schedule.__salt__, {"publish.publish": mock} @@ -648,7 +684,11 @@ def test_copy(job1): "result": False, } - with patch_makedirs, patch_schedule_opts, patch_schedule_event_fire, patch_schedule_get_event, patch_schedule_connect_pub: + with ( + patch_makedirs + ), ( + patch_schedule_opts + ), patch_schedule_event_fire, patch_schedule_get_event, patch_schedule_connect_pub: mock = MagicMock(return_value={}) patch_schedule_publish = patch.dict( schedule.__salt__, {"publish.publish": mock} @@ -762,7 +802,9 @@ def test_modify(job1): SaltEvent, "connect_pub", return_value=True ) - with patch_makedirs, patch_schedule_opts, patch_schedule_event_fire, patch_schedule_connect_pub: + with ( + patch_makedirs + ), patch_schedule_opts, patch_schedule_event_fire, patch_schedule_connect_pub: _ret_value = {"complete": True, "schedule": {"job1": current_job1}} patch_schedule_get_event = patch.object( @@ -925,7 +967,11 @@ def test_is_enabled(): return_value={"complete": True, "schedule": {"job1": job1}}, ) - with patch_makedirs, patch_schedule_opts, patch_schedule_get_event, patch_schedule_connect_pub, patch_schedule_salt: + with ( + patch_makedirs + ), ( + patch_schedule_opts + ), patch_schedule_get_event, patch_schedule_connect_pub, patch_schedule_salt: ret = schedule.is_enabled("job1") assert ret == job1 @@ -966,7 +1012,11 @@ def test_job_status(): SaltEvent, "connect_pub", return_value=True ) - with patch_makedirs, patch_schedule_opts, patch_schedule_get_event, patch_schedule_connect_pub, patch_schedule_salt: + with ( + patch_makedirs + ), ( + patch_schedule_opts + ), patch_schedule_get_event, patch_schedule_connect_pub, patch_schedule_salt: ret = schedule.job_status("job1") assert ret == { "_last_run": "2021-11-01T12:36:57", @@ -1022,7 +1072,13 @@ def test_list(job1): "os.path.exists", MagicMock(return_value=True) ) - with patch_schedule_opts, patch_schedule_event_fire, patch_schedule_get_event, patch_schedule_connect_pub, patch_schedule_os_path_exists, patch_makedirs: + with ( + patch_schedule_opts + ), ( + patch_schedule_event_fire + ), ( + patch_schedule_get_event + ), patch_schedule_connect_pub, patch_schedule_os_path_exists, patch_makedirs: with patch( "salt.utils.files.fopen", mock_open(read_data=saved_schedule) ) as fopen_mock: @@ -1050,7 +1106,15 @@ def test_list(job1): seconds: 10 """ - with patch_schedule_opts, patch_makedirs, patch_schedule_event_fire, patch_schedule_get_event, patch_schedule_connect_pub, patch_schedule_os_path_exists: + with ( + patch_schedule_opts + ), ( + patch_makedirs + ), ( + patch_schedule_event_fire + ), ( + patch_schedule_get_event + ), patch_schedule_connect_pub, patch_schedule_os_path_exists: with patch("salt.utils.files.fopen", mock_open(read_data="")) as fopen_mock: ret = schedule.list_() assert ret == expected @@ -1082,7 +1146,13 @@ def test_list(job1): seconds: 10 """ - with patch_schedule_opts, patch_schedule_event_fire, patch_schedule_get_event, patch_schedule_connect_pub, patch_schedule_os_path_exists, patch_makedirs: + with ( + patch_schedule_opts + ), ( + patch_schedule_event_fire + ), ( + patch_schedule_get_event + ), patch_schedule_connect_pub, patch_schedule_os_path_exists, patch_makedirs: with patch( "salt.utils.files.fopen", mock_open(read_data=saved_schedule) ) as fopen_mock: @@ -1141,7 +1211,13 @@ def test_list_global_enabled(job1): "os.path.exists", MagicMock(return_value=True) ) - with patch_schedule_opts, patch_schedule_event_fire, patch_schedule_get_event, patch_schedule_connect_pub, patch_schedule_os_path_exists, patch_makedirs: + with ( + patch_schedule_opts + ), ( + patch_schedule_event_fire + ), ( + patch_schedule_get_event + ), patch_schedule_connect_pub, patch_schedule_os_path_exists, patch_makedirs: with patch( "salt.utils.files.fopen", mock_open(read_data=saved_schedule) ) as fopen_mock: @@ -1201,7 +1277,13 @@ def test_list_global_disabled(job1): "os.path.exists", MagicMock(return_value=True) ) - with patch_schedule_opts, patch_schedule_event_fire, patch_schedule_get_event, patch_schedule_connect_pub, patch_schedule_os_path_exists, patch_makedirs: + with ( + patch_schedule_opts + ), ( + patch_schedule_event_fire + ), ( + patch_schedule_get_event + ), patch_schedule_connect_pub, patch_schedule_os_path_exists, patch_makedirs: with patch( "salt.utils.files.fopen", mock_open(read_data=saved_schedule) ) as fopen_mock: diff --git a/tests/pytests/unit/modules/test_sdb.py b/tests/pytests/unit/modules/test_sdb.py index 01d1e1a6273..aa046d7cffe 100644 --- a/tests/pytests/unit/modules/test_sdb.py +++ b/tests/pytests/unit/modules/test_sdb.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import pytest import salt.modules.sdb as sdb diff --git a/tests/pytests/unit/modules/test_serverdensity_device.py b/tests/pytests/unit/modules/test_serverdensity_device.py index 6d79aefa813..5a65012c11e 100644 --- a/tests/pytests/unit/modules/test_serverdensity_device.py +++ b/tests/pytests/unit/modules/test_serverdensity_device.py @@ -4,7 +4,6 @@ TestCase for salt.modules.serverdensity_device """ - import pytest import salt.modules.serverdensity_device as serverdensity_device diff --git a/tests/pytests/unit/modules/test_servicenow.py b/tests/pytests/unit/modules/test_servicenow.py index 1971b63f653..d5e9a96ae13 100644 --- a/tests/pytests/unit/modules/test_servicenow.py +++ b/tests/pytests/unit/modules/test_servicenow.py @@ -4,7 +4,6 @@ TestCase for salt.modules.servicenow """ - import pytest import salt.modules.servicenow as servicenow diff --git a/tests/pytests/unit/modules/test_slackware_service.py b/tests/pytests/unit/modules/test_slackware_service.py index c2cd52e1a5d..93e685a0677 100644 --- a/tests/pytests/unit/modules/test_slackware_service.py +++ b/tests/pytests/unit/modules/test_slackware_service.py @@ -1,6 +1,7 @@ """ :codeauthor: Piter Punk """ + import os import pytest diff --git a/tests/pytests/unit/modules/test_smartos_imgadm.py b/tests/pytests/unit/modules/test_smartos_imgadm.py index 3f9500aaa81..111e28529dc 100644 --- a/tests/pytests/unit/modules/test_smartos_imgadm.py +++ b/tests/pytests/unit/modules/test_smartos_imgadm.py @@ -4,7 +4,6 @@ TestCase for salt.modules.smartos_imgadm module """ - import pytest import salt.modules.smartos_imgadm as imgadm diff --git a/tests/pytests/unit/modules/test_smtp.py b/tests/pytests/unit/modules/test_smtp.py index 983bb209cf2..840b6c08fbb 100644 --- a/tests/pytests/unit/modules/test_smtp.py +++ b/tests/pytests/unit/modules/test_smtp.py @@ -4,7 +4,6 @@ TestCase for salt.modules.smtp """ - import pytest import salt.modules.smtp as smtp diff --git a/tests/pytests/unit/modules/test_status.py b/tests/pytests/unit/modules/test_status.py index e0bb270df66..55632e13c0b 100644 --- a/tests/pytests/unit/modules/test_status.py +++ b/tests/pytests/unit/modules/test_status.py @@ -2,7 +2,6 @@ Test cases for salt.modules.status """ - import os import pytest @@ -150,7 +149,7 @@ def test_uptime_linux(): ), patch( "os.path.exists", MagicMock(return_value=True) ): - proc_uptime = salt.utils.stringutils.to_str("{} {}".format(m.ut, m.idle)) + proc_uptime = salt.utils.stringutils.to_str(f"{m.ut} {m.idle}") with patch("salt.utils.files.fopen", mock_open(read_data=proc_uptime)): ret = status.uptime() diff --git a/tests/pytests/unit/modules/test_suse_ip.py b/tests/pytests/unit/modules/test_suse_ip.py index b6812a0043f..c46764f7066 100644 --- a/tests/pytests/unit/modules/test_suse_ip.py +++ b/tests/pytests/unit/modules/test_suse_ip.py @@ -400,7 +400,7 @@ def _test_mode_0_or_2(mode_num=0): expected = [ "downdelay=200", "miimon=100", - "mode={}".format(mode_num), + f"mode={mode_num}", "use_carrier=0", ] assert bonding_opts == expected, bonding_opts @@ -414,7 +414,7 @@ def _test_mode_0_or_2(mode_num=0): "arp_ip_target=1.2.3.4,5.6.7.8", "downdelay=200", "miimon=100", - "mode={}".format(mode_num), + f"mode={mode_num}", "use_carrier=0", ] assert bonding_opts == expected, bonding_opts @@ -426,7 +426,7 @@ def _test_mode_0_or_2(mode_num=0): expected = [ "arp_interval=300", "arp_ip_target=1.2.3.4,5.6.7.8", - "mode={}".format(mode_num), + f"mode={mode_num}", ] assert bonding_opts == expected, bonding_opts @@ -580,14 +580,12 @@ def test_build_interface_bond_mode_4(): raise else: expected = [ - "ad_select={}".format(ad_select), + f"ad_select={ad_select}", "downdelay=200", "lacp_rate={}".format( "1" if lacp_rate == "fast" - else "0" - if lacp_rate == "slow" - else lacp_rate + else "0" if lacp_rate == "slow" else lacp_rate ), "miimon=100", "mode=4", diff --git a/tests/pytests/unit/modules/test_swift.py b/tests/pytests/unit/modules/test_swift.py index f8c0f313387..3fb5c504df8 100644 --- a/tests/pytests/unit/modules/test_swift.py +++ b/tests/pytests/unit/modules/test_swift.py @@ -4,7 +4,6 @@ Test cases for salt.modules.swift """ - import pytest import salt.modules.swift as swift diff --git a/tests/pytests/unit/modules/test_syslog_ng.py b/tests/pytests/unit/modules/test_syslog_ng.py index d481de33f96..88d403f4c61 100644 --- a/tests/pytests/unit/modules/test_syslog_ng.py +++ b/tests/pytests/unit/modules/test_syslog_ng.py @@ -2,7 +2,6 @@ Test cases for salt.modules.syslog_ng """ - import os from textwrap import dedent diff --git a/tests/pytests/unit/modules/test_system.py b/tests/pytests/unit/modules/test_system.py index d2a8a4ba9a9..c825db51cbc 100644 --- a/tests/pytests/unit/modules/test_system.py +++ b/tests/pytests/unit/modules/test_system.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import pytest import salt.modules.system as system diff --git a/tests/pytests/unit/modules/test_telegram.py b/tests/pytests/unit/modules/test_telegram.py index 568c01002b2..02679df4d1a 100644 --- a/tests/pytests/unit/modules/test_telegram.py +++ b/tests/pytests/unit/modules/test_telegram.py @@ -4,7 +4,6 @@ Test cases for salt.modules.telegram. """ - import pytest import salt.modules.telegram as telegram diff --git a/tests/pytests/unit/modules/test_tls.py b/tests/pytests/unit/modules/test_tls.py index 6ed24dbaf00..8f85c681982 100644 --- a/tests/pytests/unit/modules/test_tls.py +++ b/tests/pytests/unit/modules/test_tls.py @@ -97,8 +97,8 @@ bymYbi0l2pWqQLA2sPoRHNw= @pytest.mark.skip_on_windows(reason="Skipping on Windows per Shane's suggestion") def test_create_ca_permissions_on_cert_and_key(tmp_path, tls_test_data): ca_name = "test_ca" - certp = tmp_path / ca_name / "{}_ca_cert.crt".format(ca_name) - certk = tmp_path / ca_name / "{}_ca_cert.key".format(ca_name) + certp = tmp_path / ca_name / f"{ca_name}_ca_cert.crt" + certk = tmp_path / ca_name / f"{ca_name}_ca_cert.key" mock_opt = MagicMock(return_value=str(tmp_path)) mock_ret = MagicMock(return_value=0) @@ -392,16 +392,12 @@ def test_cert_info(tls_test_data): == str(err) ): log.exception(err) - pytest.skip( - "Encountered an upstream error with PyOpenSSL: {}".format(err) - ) + pytest.skip(f"Encountered an upstream error with PyOpenSSL: {err}") if "'_cffi_backend.CDataGCP' object has no attribute 'object'" == str( err ): log.exception(err) - pytest.skip( - "Encountered an upstream error with PyOpenSSL: {}".format(err) - ) + pytest.skip(f"Encountered an upstream error with PyOpenSSL: {err}") # python-openssl version 0.14, when installed with the "junos-eznc" pip # package, causes an error on this test. Newer versions of PyOpenSSL do not have # this issue. If 0.14 is installed and we hit this error, skip the test. @@ -555,7 +551,7 @@ def test_create_self_signed_cert(tmp_path, tls_test_data): certk = "{}/{}/certs/{}.key".format( ca_path, tls_dir, tls_test_data["create_ca"]["CN"] ) - ret = 'Created Private Key: "{}" Created Certificate: "{}"'.format(certk, certp) + ret = f'Created Private Key: "{certk}" Created Certificate: "{certp}"' mock_opt = MagicMock(return_value=ca_path) with patch.dict(tls.__salt__, {"config.option": mock_opt}), patch.dict( tls.__opts__, {"hash_type": "sha256", "cachedir": ca_path} @@ -580,7 +576,7 @@ def test_recreate_self_signed_cert(tmp_path, tls_test_data): certk = "{}/{}/certs/{}.key".format( ca_path, tls_dir, tls_test_data["create_ca"]["CN"] ) - ret = 'Created Private Key: "{}" Created Certificate: "{}"'.format(certk, certp) + ret = f'Created Private Key: "{certk}" Created Certificate: "{certp}"' mock_opt = MagicMock(return_value=ca_path) with patch.dict(tls.__salt__, {"config.option": mock_opt}), patch.dict( tls.__opts__, {"hash_type": "sha256", "cachedir": ca_path} diff --git a/tests/pytests/unit/modules/test_tomcat.py b/tests/pytests/unit/modules/test_tomcat.py index 869c3f96c85..6658fca0dad 100644 --- a/tests/pytests/unit/modules/test_tomcat.py +++ b/tests/pytests/unit/modules/test_tomcat.py @@ -2,7 +2,6 @@ Tests cases for salt.modules.tomcat """ - import io import urllib.request diff --git a/tests/pytests/unit/modules/test_transactional_update.py b/tests/pytests/unit/modules/test_transactional_update.py index 5d9294c49bd..eb6dfae2868 100644 --- a/tests/pytests/unit/modules/test_transactional_update.py +++ b/tests/pytests/unit/modules/test_transactional_update.py @@ -178,9 +178,11 @@ def test_commands_with_global_params(): "--non-interactive", "--drop-if-no-change", "--no-selfupdate", - cmd.replace("_", ".") - if cmd.startswith("grub") - else cmd.replace("_", "-"), + ( + cmd.replace("_", ".") + if cmd.startswith("grub") + else cmd.replace("_", "-") + ), ] ) diff --git a/tests/pytests/unit/modules/test_tuned.py b/tests/pytests/unit/modules/test_tuned.py index 19692ec9d83..557112a0fe3 100644 --- a/tests/pytests/unit/modules/test_tuned.py +++ b/tests/pytests/unit/modules/test_tuned.py @@ -2,7 +2,6 @@ Test for the salt.modules.tuned """ - import pytest from salt.modules import tuned diff --git a/tests/pytests/unit/modules/test_udev.py b/tests/pytests/unit/modules/test_udev.py index d5dbee9d20f..19e055908ee 100644 --- a/tests/pytests/unit/modules/test_udev.py +++ b/tests/pytests/unit/modules/test_udev.py @@ -4,7 +4,6 @@ Test cases for salt.modules.udev """ - import pytest import salt.modules.udev as udev diff --git a/tests/pytests/unit/modules/test_uptime.py b/tests/pytests/unit/modules/test_uptime.py index 2e129a7c9bb..9857a9959f4 100644 --- a/tests/pytests/unit/modules/test_uptime.py +++ b/tests/pytests/unit/modules/test_uptime.py @@ -2,7 +2,6 @@ Test cases for salt.modules.uptime """ - import pytest import salt.modules.uptime as uptime diff --git a/tests/pytests/unit/modules/test_uwsgi.py b/tests/pytests/unit/modules/test_uwsgi.py index 65d3f75a86a..23e35a2a105 100644 --- a/tests/pytests/unit/modules/test_uwsgi.py +++ b/tests/pytests/unit/modules/test_uwsgi.py @@ -2,7 +2,6 @@ Test cases for salt.modules.uswgi """ - import pytest import salt.modules.uwsgi as uwsgi diff --git a/tests/pytests/unit/modules/test_vagrant.py b/tests/pytests/unit/modules/test_vagrant.py index a6bc3c32cd0..d34c98c1a5e 100644 --- a/tests/pytests/unit/modules/test_vagrant.py +++ b/tests/pytests/unit/modules/test_vagrant.py @@ -2,7 +2,6 @@ TestCase for the salt.modules.vagrant module. """ - import pytest import salt.exceptions diff --git a/tests/pytests/unit/modules/test_vmctl.py b/tests/pytests/unit/modules/test_vmctl.py index e0935924a43..b264d99f1c7 100644 --- a/tests/pytests/unit/modules/test_vmctl.py +++ b/tests/pytests/unit/modules/test_vmctl.py @@ -2,7 +2,6 @@ Test for salt.modules.vmctl """ - import pytest import salt.modules.vmctl as vmctl diff --git a/tests/pytests/unit/modules/test_webutil.py b/tests/pytests/unit/modules/test_webutil.py index d6e9d0b466d..038e4778206 100644 --- a/tests/pytests/unit/modules/test_webutil.py +++ b/tests/pytests/unit/modules/test_webutil.py @@ -4,7 +4,6 @@ Test cases for salt.modules.webutil """ - import pytest import salt.modules.webutil as htpasswd diff --git a/tests/pytests/unit/modules/test_win_autoruns.py b/tests/pytests/unit/modules/test_win_autoruns.py index dd8060eedd8..1261a05c012 100644 --- a/tests/pytests/unit/modules/test_win_autoruns.py +++ b/tests/pytests/unit/modules/test_win_autoruns.py @@ -2,7 +2,6 @@ :codeauthor: Jayesh Kariya """ - import pytest import salt.modules.win_autoruns as win_autoruns diff --git a/tests/pytests/unit/modules/test_win_dns_client.py b/tests/pytests/unit/modules/test_win_dns_client.py index 8dfad4d0127..8e30c1bb58e 100644 --- a/tests/pytests/unit/modules/test_win_dns_client.py +++ b/tests/pytests/unit/modules/test_win_dns_client.py @@ -2,7 +2,6 @@ :codeauthor: Jayesh Kariya """ - import types import pytest diff --git a/tests/pytests/unit/modules/test_win_iis.py b/tests/pytests/unit/modules/test_win_iis.py index f5e37724d24..c2fb37daaba 100644 --- a/tests/pytests/unit/modules/test_win_iis.py +++ b/tests/pytests/unit/modules/test_win_iis.py @@ -2,7 +2,6 @@ Test cases for salt.modules.win_iis """ - import pytest import salt.modules.win_iis as win_iis @@ -602,7 +601,7 @@ def test_get_webconfiguration_settings(): for setting in settings: ps_cmd.extend( [ - "$Property = Get-WebConfigurationProperty -PSPath '{}'".format(name), + f"$Property = Get-WebConfigurationProperty -PSPath '{name}'", "-Name '{name}' -Filter '{filter}' -ErrorAction Stop;".format( filter=setting["filter"], name=setting["name"] ), diff --git a/tests/pytests/unit/modules/test_win_licence.py b/tests/pytests/unit/modules/test_win_licence.py index 2948be088f0..70a6cfbc490 100644 --- a/tests/pytests/unit/modules/test_win_licence.py +++ b/tests/pytests/unit/modules/test_win_licence.py @@ -2,7 +2,6 @@ Test cases for salt.modules.win_licence """ - import pytest import salt.modules.win_license as win_license diff --git a/tests/pytests/unit/modules/test_win_path.py b/tests/pytests/unit/modules/test_win_path.py index 7dad024a878..8b12653feed 100644 --- a/tests/pytests/unit/modules/test_win_path.py +++ b/tests/pytests/unit/modules/test_win_path.py @@ -2,7 +2,6 @@ :codeauthor: Rahul Handay """ - import os import pytest diff --git a/tests/pytests/unit/modules/test_win_pkg.py b/tests/pytests/unit/modules/test_win_pkg.py index 2d8439f9b44..d892e79a21b 100644 --- a/tests/pytests/unit/modules/test_win_pkg.py +++ b/tests/pytests/unit/modules/test_win_pkg.py @@ -1,6 +1,7 @@ """ Tests for the win_pkg module """ + import logging import pytest diff --git a/tests/pytests/unit/modules/test_win_pki.py b/tests/pytests/unit/modules/test_win_pki.py index 128fb14f820..600282e8bd8 100644 --- a/tests/pytests/unit/modules/test_win_pki.py +++ b/tests/pytests/unit/modules/test_win_pki.py @@ -2,7 +2,6 @@ Test cases for salt.modules.win_pki """ - import pytest import salt.modules.win_pki as win_pki diff --git a/tests/pytests/unit/modules/test_win_powercfg.py b/tests/pytests/unit/modules/test_win_powercfg.py index e1cd9426a4c..77475464e47 100644 --- a/tests/pytests/unit/modules/test_win_powercfg.py +++ b/tests/pytests/unit/modules/test_win_powercfg.py @@ -2,7 +2,6 @@ Test cases for salt.modules.win_powercfg """ - import pytest import salt.modules.win_powercfg as powercfg diff --git a/tests/pytests/unit/modules/test_win_psget.py b/tests/pytests/unit/modules/test_win_psget.py index af7737b121f..417106affe8 100644 --- a/tests/pytests/unit/modules/test_win_psget.py +++ b/tests/pytests/unit/modules/test_win_psget.py @@ -2,7 +2,6 @@ Test cases for salt.modules.win_psget """ - import pytest import salt.modules.win_psget as win_psget diff --git a/tests/pytests/unit/modules/test_win_shadow.py b/tests/pytests/unit/modules/test_win_shadow.py index bccb67fe9da..dbac3807172 100644 --- a/tests/pytests/unit/modules/test_win_shadow.py +++ b/tests/pytests/unit/modules/test_win_shadow.py @@ -4,7 +4,6 @@ Test cases for salt.modules.win_shadow """ - import pytest import salt.modules.win_shadow as win_shadow diff --git a/tests/pytests/unit/modules/test_win_snmp.py b/tests/pytests/unit/modules/test_win_snmp.py index 339f834e0d8..bb8370a521a 100644 --- a/tests/pytests/unit/modules/test_win_snmp.py +++ b/tests/pytests/unit/modules/test_win_snmp.py @@ -2,7 +2,6 @@ Test cases for salt.modules.win_snmp """ - import pytest import salt.modules.win_snmp as win_snmp diff --git a/tests/pytests/unit/modules/test_win_system.py b/tests/pytests/unit/modules/test_win_system.py index a33aa3b1002..54eed432995 100644 --- a/tests/pytests/unit/modules/test_win_system.py +++ b/tests/pytests/unit/modules/test_win_system.py @@ -1,6 +1,7 @@ """ :codeauthor: Gareth J. Greenaway """ + import pytest import salt.modules.cmdmod as cmdmod diff --git a/tests/pytests/unit/modules/test_win_task.py b/tests/pytests/unit/modules/test_win_task.py index 6e71612264a..ee61d739b99 100644 --- a/tests/pytests/unit/modules/test_win_task.py +++ b/tests/pytests/unit/modules/test_win_task.py @@ -1,6 +1,7 @@ """ Test the win_task execution module """ + from datetime import datetime import pytest diff --git a/tests/pytests/unit/modules/test_win_timezone.py b/tests/pytests/unit/modules/test_win_timezone.py index 26a867dff85..b32b6a0187b 100644 --- a/tests/pytests/unit/modules/test_win_timezone.py +++ b/tests/pytests/unit/modules/test_win_timezone.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import pytest import salt.modules.win_timezone as win_timezone diff --git a/tests/pytests/unit/modules/test_win_wua.py b/tests/pytests/unit/modules/test_win_wua.py index 234574a015d..ee4db206a03 100644 --- a/tests/pytests/unit/modules/test_win_wua.py +++ b/tests/pytests/unit/modules/test_win_wua.py @@ -1,6 +1,7 @@ """ Test the win_wua execution module """ + import pytest import salt.modules.win_wua as win_wua diff --git a/tests/pytests/unit/modules/test_xapi_virt.py b/tests/pytests/unit/modules/test_xapi_virt.py index 47cdc4b6376..2f854f64cc9 100644 --- a/tests/pytests/unit/modules/test_xapi_virt.py +++ b/tests/pytests/unit/modules/test_xapi_virt.py @@ -4,7 +4,6 @@ Test cases for salt.modules.xapi """ - import pytest import salt.modules.xapi_virt as xapi diff --git a/tests/pytests/unit/modules/test_xfs.py b/tests/pytests/unit/modules/test_xfs.py index 9d1ce9dff34..79ff0dc2f34 100644 --- a/tests/pytests/unit/modules/test_xfs.py +++ b/tests/pytests/unit/modules/test_xfs.py @@ -2,7 +2,6 @@ Test cases for salt.modules.xfs """ - import textwrap import pytest diff --git a/tests/pytests/unit/modules/test_xml.py b/tests/pytests/unit/modules/test_xml.py index 334d2f2b73e..e627a5b6402 100644 --- a/tests/pytests/unit/modules/test_xml.py +++ b/tests/pytests/unit/modules/test_xml.py @@ -2,7 +2,6 @@ Tests for xml module """ - import pytest from salt.modules import xml diff --git a/tests/pytests/unit/modules/test_yumpkg.py b/tests/pytests/unit/modules/test_yumpkg.py index 35f545ad72b..ecdad27ac83 100644 --- a/tests/pytests/unit/modules/test_yumpkg.py +++ b/tests/pytests/unit/modules/test_yumpkg.py @@ -1562,9 +1562,9 @@ def test_remove_with_epoch_and_arch_info(): installed = "8:3.8.12-4.n.el7" list_pkgs_mock = MagicMock( side_effect=lambda **kwargs: { - name_and_arch: [installed] - if kwargs.get("versions_as_list", False) - else installed + name_and_arch: ( + [installed] if kwargs.get("versions_as_list", False) else installed + ) } ) cmd_mock = MagicMock( diff --git a/tests/pytests/unit/modules/test_zenoss.py b/tests/pytests/unit/modules/test_zenoss.py index 3d03f11d770..fb2834cc484 100644 --- a/tests/pytests/unit/modules/test_zenoss.py +++ b/tests/pytests/unit/modules/test_zenoss.py @@ -2,7 +2,6 @@ Test cases for salt.modules.keystone """ - import pytest import salt.modules.config as config diff --git a/tests/pytests/unit/modules/test_zfs.py b/tests/pytests/unit/modules/test_zfs.py index a9d8a3016ec..a60a61f2aa6 100644 --- a/tests/pytests/unit/modules/test_zfs.py +++ b/tests/pytests/unit/modules/test_zfs.py @@ -215,9 +215,9 @@ def test_create_error_missing_parent(utils_patch): ) ret = {} ret["stdout"] = "" - ret[ - "stderr" - ] = "cannot create 'myzpool/mydataset/mysubdataset': parent does not exist" + ret["stderr"] = ( + "cannot create 'myzpool/mydataset/mysubdataset': parent does not exist" + ) ret["retcode"] = 1 mock_cmd = MagicMock(return_value=ret) with patch.dict(zfs.__salt__, {"cmd.run_all": mock_cmd}), patch.dict( diff --git a/tests/pytests/unit/modules/test_znc.py b/tests/pytests/unit/modules/test_znc.py index a28f8f1ca26..1cf491e5b0a 100644 --- a/tests/pytests/unit/modules/test_znc.py +++ b/tests/pytests/unit/modules/test_znc.py @@ -4,7 +4,6 @@ TestCase for salt.modules.znc """ - import pytest import salt.modules.znc as znc diff --git a/tests/pytests/unit/modules/test_zpool.py b/tests/pytests/unit/modules/test_zpool.py index 48fcf9e272c..f3256db0b8c 100644 --- a/tests/pytests/unit/modules/test_zpool.py +++ b/tests/pytests/unit/modules/test_zpool.py @@ -469,9 +469,9 @@ def test_split_not_mirror(utils_patch): """ ret = {} ret["stdout"] = "" - ret[ - "stderr" - ] = "Unable to split datapool: Source pool must be composed only of mirrors" + ret["stderr"] = ( + "Unable to split datapool: Source pool must be composed only of mirrors" + ) ret["retcode"] = 1 mock_cmd = MagicMock(return_value=ret) diff --git a/tests/pytests/unit/modules/test_zypperpkg.py b/tests/pytests/unit/modules/test_zypperpkg.py index 2780524b559..1cb2d34b98a 100644 --- a/tests/pytests/unit/modules/test_zypperpkg.py +++ b/tests/pytests/unit/modules/test_zypperpkg.py @@ -2,7 +2,6 @@ :codeauthor: Gareth J. Greenaway """ - import os import textwrap diff --git a/tests/pytests/unit/modules/virt/conftest.py b/tests/pytests/unit/modules/virt/conftest.py index 03225530056..6e1bfa539b0 100644 --- a/tests/pytests/unit/modules/virt/conftest.py +++ b/tests/pytests/unit/modules/virt/conftest.py @@ -40,7 +40,7 @@ class MappedResultMock(MagicMock): def __init__(self): def mapped_results(*args, **kwargs): if args[0] not in self._instances.keys(): - raise virt.libvirt.libvirtError("Not found: {}".format(args[0])) + raise virt.libvirt.libvirtError(f"Not found: {args[0]}") return self._instances[args[0]] super().__init__(side_effect=mapped_results) @@ -150,8 +150,8 @@ def make_mock_storage_pool(): mocked_pool = mocked_conn.storagePoolLookupByName(name) source_def = source if not source and type == "disk": - source = "".format(name) - pool_path = "/path/to/{}".format(name) + source = f"" + pool_path = f"/path/to/{name}" mocked_pool.XMLDesc.return_value = """ @@ -185,7 +185,7 @@ def make_mock_storage_pool(): for volume in volumes: mocked_pool.storageVolLookupByName.add(volume) mocked_vol = mocked_pool.storageVolLookupByName(volume) - vol_path = "{}/{}".format(pool_path, volume) + vol_path = f"{pool_path}/{volume}" mocked_vol.XMLDesc.return_value = """ diff --git a/tests/pytests/unit/modules/virt/test_domain.py b/tests/pytests/unit/modules/virt/test_domain.py index 1d1a3d1849a..b0cb2f80f82 100644 --- a/tests/pytests/unit/modules/virt/test_domain.py +++ b/tests/pytests/unit/modules/virt/test_domain.py @@ -1941,14 +1941,17 @@ def test_update_disks(make_mock_vm): added_disk_path = os.path.join( virt.__salt__["config.get"]("virt:images"), "my_vm_added.qcow2" ) - assert mock_run.call_args[0][ - 0 - ] == 'qemu-img create -f qcow2 "{}" 2048M'.format(added_disk_path) + assert ( + mock_run.call_args[0][0] + == f'qemu-img create -f qcow2 "{added_disk_path}" 2048M' + ) assert mock_chmod.call_args[0][0] == added_disk_path assert [ - ET.fromstring(disk).find("source").get("file") - if str(disk).find(" -1 - else None + ( + ET.fromstring(disk).find("source").get("file") + if str(disk).find(" -1 + else None + ) for disk in ret["disk"]["attached"] ] == [None, os.path.join(root_dir, "my_vm_added.qcow2")] @@ -2018,9 +2021,11 @@ def test_update_disks_existing_block(make_mock_vm): ], ) assert [ - ET.fromstring(disk).find("source").get("file") - if str(disk).find(" -1 - else None + ( + ET.fromstring(disk).find("source").get("file") + if str(disk).find(" -1 + else None + ) for disk in ret["disk"]["attached"] ] == ["/dev/ssd/data"] diff --git a/tests/pytests/unit/modules/win_lgpo/test_admx_policies.py b/tests/pytests/unit/modules/win_lgpo/test_admx_policies.py index b9da371190b..1e34ffc4612 100644 --- a/tests/pytests/unit/modules/win_lgpo/test_admx_policies.py +++ b/tests/pytests/unit/modules/win_lgpo/test_admx_policies.py @@ -1,6 +1,7 @@ """ :codeauthor: Shane Lee """ + import glob import logging import os diff --git a/tests/pytests/unit/modules/win_lgpo/test_defined_policies.py b/tests/pytests/unit/modules/win_lgpo/test_defined_policies.py index 9acfc0f141c..7b3366eff8c 100644 --- a/tests/pytests/unit/modules/win_lgpo/test_defined_policies.py +++ b/tests/pytests/unit/modules/win_lgpo/test_defined_policies.py @@ -1,6 +1,7 @@ """ This tests policies that are defined in the giant dictionary in the LGPO module """ + import pytest import salt.modules.win_file as win_file diff --git a/tests/pytests/unit/modules/win_lgpo/test_mechanisms.py b/tests/pytests/unit/modules/win_lgpo/test_mechanisms.py index b9d659acb5f..5ce9ce2a4fb 100644 --- a/tests/pytests/unit/modules/win_lgpo/test_mechanisms.py +++ b/tests/pytests/unit/modules/win_lgpo/test_mechanisms.py @@ -1,6 +1,7 @@ """ :codeauthor: Shane Lee """ + import os import pytest diff --git a/tests/pytests/unit/modules/win_lgpo/test_point_print_enabled.py b/tests/pytests/unit/modules/win_lgpo/test_point_print_enabled.py index 88b1c05b4e7..4d39311f8e4 100644 --- a/tests/pytests/unit/modules/win_lgpo/test_point_print_enabled.py +++ b/tests/pytests/unit/modules/win_lgpo/test_point_print_enabled.py @@ -1,6 +1,7 @@ """ :codeauthor: Shane Lee """ + import pytest import salt.modules.cmdmod as cmdmod diff --git a/tests/pytests/unit/modules/win_lgpo/test_point_print_nc.py b/tests/pytests/unit/modules/win_lgpo/test_point_print_nc.py index 174ca38fb50..2196c7624c3 100644 --- a/tests/pytests/unit/modules/win_lgpo/test_point_print_nc.py +++ b/tests/pytests/unit/modules/win_lgpo/test_point_print_nc.py @@ -1,6 +1,7 @@ """ :codeauthor: Shane Lee """ + import pytest import salt.config diff --git a/tests/pytests/unit/modules/win_lgpo/test_policy_info.py b/tests/pytests/unit/modules/win_lgpo/test_policy_info.py index d0ed3c911a3..a11bf800dc0 100644 --- a/tests/pytests/unit/modules/win_lgpo/test_policy_info.py +++ b/tests/pytests/unit/modules/win_lgpo/test_policy_info.py @@ -1,6 +1,7 @@ """ :codeauthor: Shane Lee """ + import pytest import salt.modules.win_file as win_file diff --git a/tests/pytests/unit/modules/win_lgpo/test_policy_info_functions.py b/tests/pytests/unit/modules/win_lgpo/test_policy_info_functions.py index bedacc237fb..2c3bb255212 100644 --- a/tests/pytests/unit/modules/win_lgpo/test_policy_info_functions.py +++ b/tests/pytests/unit/modules/win_lgpo/test_policy_info_functions.py @@ -1,6 +1,7 @@ """ :codeauthor: Shane Lee """ + import pytest import salt.modules.win_lgpo as win_lgpo diff --git a/tests/pytests/unit/modules/win_lgpo/test_policy_resources.py b/tests/pytests/unit/modules/win_lgpo/test_policy_resources.py index b7a6618f47e..8d49468792a 100644 --- a/tests/pytests/unit/modules/win_lgpo/test_policy_resources.py +++ b/tests/pytests/unit/modules/win_lgpo/test_policy_resources.py @@ -1,6 +1,7 @@ """ :codeauthor: Shane Lee """ + import pytest import salt.modules.cmdmod as cmdmod diff --git a/tests/pytests/unit/modules/win_lgpo/test_reg_pol.py b/tests/pytests/unit/modules/win_lgpo/test_reg_pol.py index 79c8a10393c..ae7a2a55f8a 100644 --- a/tests/pytests/unit/modules/win_lgpo/test_reg_pol.py +++ b/tests/pytests/unit/modules/win_lgpo/test_reg_pol.py @@ -1,6 +1,7 @@ """ :codeauthor: Shane Lee """ + import pytest import salt.modules.win_lgpo as win_lgpo diff --git a/tests/pytests/unit/modules/win_lgpo/test_secedit_policy.py b/tests/pytests/unit/modules/win_lgpo/test_secedit_policy.py index 6a0d2c027c5..81944e20ee3 100644 --- a/tests/pytests/unit/modules/win_lgpo/test_secedit_policy.py +++ b/tests/pytests/unit/modules/win_lgpo/test_secedit_policy.py @@ -78,7 +78,7 @@ def test_secedit_policy(shell, name, setting, exp_regexes, cumulative_rights, tm ) assert result is True temp_file = tmp_path / random_string("secedit-output-") - ret = shell.run("secedit", "/export", "/cfg", "{}".format(temp_file)) + ret = shell.run("secedit", "/export", "/cfg", f"{temp_file}") assert ret.returncode == 0 with salt.utils.files.fopen(temp_file, encoding="utf-16") as reader: content = reader.read() diff --git a/tests/pytests/unit/output/test_json_out.py b/tests/pytests/unit/output/test_json_out.py index 229315b31fe..3ade8e44e7c 100644 --- a/tests/pytests/unit/output/test_json_out.py +++ b/tests/pytests/unit/output/test_json_out.py @@ -1,6 +1,7 @@ """ unittests for json outputter """ + import pytest import salt.output.json_out as json_out diff --git a/tests/pytests/unit/output/test_nested.py b/tests/pytests/unit/output/test_nested.py index c56faf89672..4e85ff623cb 100644 --- a/tests/pytests/unit/output/test_nested.py +++ b/tests/pytests/unit/output/test_nested.py @@ -1,6 +1,7 @@ """ Unit tests for the Nested outputter """ + import pytest import salt.output.nested as nested diff --git a/tests/pytests/unit/output/test_yaml_out.py b/tests/pytests/unit/output/test_yaml_out.py index 6a87fd667c2..53380cc2c9a 100644 --- a/tests/pytests/unit/output/test_yaml_out.py +++ b/tests/pytests/unit/output/test_yaml_out.py @@ -1,6 +1,7 @@ """ unittests for yaml outputter """ + import pytest import salt.output.yaml_out as yaml diff --git a/tests/pytests/unit/pillar/test_csvpillar.py b/tests/pytests/unit/pillar/test_csvpillar.py index 82d270b0d43..cbb411ca9c2 100644 --- a/tests/pytests/unit/pillar/test_csvpillar.py +++ b/tests/pytests/unit/pillar/test_csvpillar.py @@ -1,6 +1,5 @@ """test for pillar csvpillar.py""" - import salt.pillar.csvpillar as csvpillar from tests.support.mock import mock_open, patch diff --git a/tests/pytests/unit/pillar/test_http_json_pillar.py b/tests/pytests/unit/pillar/test_http_json_pillar.py index 5040c2e7a14..fb9a3b09876 100644 --- a/tests/pytests/unit/pillar/test_http_json_pillar.py +++ b/tests/pytests/unit/pillar/test_http_json_pillar.py @@ -32,10 +32,10 @@ def test_ext_pillar_can_take_http_query_kwargs(backend, httpserver): # If the headers in header_dict are not in the request, httpserver will return an empty dictionary, so we know it will fail httpserver.expect_request( - "/http_json_pillar/{}".format(backend), + f"/http_json_pillar/{backend}", headers={"custom-backend-header": backend}, ).respond_with_data(salt.utils.json.dumps(response), content_type="text/plain") - url = httpserver.url_for("/http_json_pillar/{}".format(backend)) + url = httpserver.url_for(f"/http_json_pillar/{backend}") actual = http_json.ext_pillar("test-minion-id", {}, url, header_dict=header_dict) assert actual == response @@ -55,10 +55,10 @@ def test_ext_pillar_namespace(backend, httpserver): # If the headers in header_dict are not in the request, httpserver will return an empty dictionary, so we know it will fail httpserver.expect_request( - "/http_json_pillar/{}".format(backend), + f"/http_json_pillar/{backend}", headers={"custom-backend-header": backend}, ).respond_with_data(salt.utils.json.dumps(response), content_type="text/plain") - url = httpserver.url_for("/http_json_pillar/{}".format(backend)) + url = httpserver.url_for(f"/http_json_pillar/{backend}") actual = http_json.ext_pillar( "test-minion-id", {}, url, header_dict=header_dict, namespace=namespace diff --git a/tests/pytests/unit/pillar/test_http_yaml_pillar.py b/tests/pytests/unit/pillar/test_http_yaml_pillar.py index e9e0a5eee57..c4aa3450fe6 100644 --- a/tests/pytests/unit/pillar/test_http_yaml_pillar.py +++ b/tests/pytests/unit/pillar/test_http_yaml_pillar.py @@ -32,10 +32,10 @@ def test_ext_pillar_can_take_http_query_kwargs(backend, httpserver): # If the headers in header_dict are not in the request, httpserver will return an empty dictionary, so we know it will fail httpserver.expect_request( - "/http_yaml_pillar/{}".format(backend), + f"/http_yaml_pillar/{backend}", headers={"custom-backend-header": backend}, ).respond_with_data(salt.utils.json.dumps(response), content_type="text/plain") - url = httpserver.url_for("/http_yaml_pillar/{}".format(backend)) + url = httpserver.url_for(f"/http_yaml_pillar/{backend}") actual = http_yaml.ext_pillar("test-minion-id", {}, url, header_dict=header_dict) assert actual == response diff --git a/tests/pytests/unit/pillar/test_mysql.py b/tests/pytests/unit/pillar/test_mysql.py index 70dcf71fd9b..780fbca449e 100644 --- a/tests/pytests/unit/pillar/test_mysql.py +++ b/tests/pytests/unit/pillar/test_mysql.py @@ -843,7 +843,7 @@ def test_301_process_results_with_lists(): assert list(y.keys()) == ["g"] assert y["g"] == 2 else: - raise ValueError("Unexpected value {}".format(y)) + raise ValueError(f"Unexpected value {y}") elif "h" in x: assert len(x["h"]) == 1 for y in x["h"]: @@ -854,9 +854,9 @@ def test_301_process_results_with_lists(): assert len(y.keys()) == 2 assert y["k"] == 4 else: - raise ValueError("Unexpected value {}".format(y)) + raise ValueError(f"Unexpected value {y}") else: - raise ValueError("Unexpected value {}".format(x)) + raise ValueError(f"Unexpected value {x}") def test_302_process_results_with_lists_consecutive(): @@ -901,7 +901,7 @@ def test_302_process_results_with_lists_consecutive(): assert list(y.keys()) == ["g"] assert y["g"] == 2 else: - raise ValueError("Unexpected value {}".format(y)) + raise ValueError(f"Unexpected value {y}") elif len(x[0][0]) == 2: for y in x[0]: if "j" in y: @@ -911,6 +911,6 @@ def test_302_process_results_with_lists_consecutive(): assert len(y.keys()) == 2 assert y["k"] == 4 else: - raise ValueError("Unexpected value {}".format(len(x[0][0]))) + raise ValueError(f"Unexpected value {len(x[0][0])}") else: - raise ValueError("Unexpected value {}".format(x)) + raise ValueError(f"Unexpected value {x}") diff --git a/tests/pytests/unit/pillar/test_s3.py b/tests/pytests/unit/pillar/test_s3.py index ad7ff4cffba..14c76d84160 100644 --- a/tests/pytests/unit/pillar/test_s3.py +++ b/tests/pytests/unit/pillar/test_s3.py @@ -41,7 +41,7 @@ def test_refresh_buckets_cache_file(): first_range_end = 999 second_range_end = 1200 for i in range(0, first_range_end): - key_name = "{}/init.sls".format(i) + key_name = f"{i}/init.sls" tmp = { "Key": key_name, "LastModified": "2019-12-18T15:54:39.000Z", @@ -52,7 +52,7 @@ def test_refresh_buckets_cache_file(): mock_return_first.append(tmp) for i in range(first_range_end, second_range_end): - key_name = "{}/init.sls".format(i) + key_name = f"{i}/init.sls" tmp = { "Key": key_name, "LastModified": "2019-12-18T15:54:39.000Z", @@ -64,7 +64,7 @@ def test_refresh_buckets_cache_file(): _expected = {"base": {"dummy_bucket": []}} for i in range(0, second_range_end): - key_name = "{}/init.sls".format(i) + key_name = f"{i}/init.sls" tmp = { "Key": key_name, "LastModified": "2019-12-18T15:54:39.000Z", diff --git a/tests/pytests/unit/pillar/test_saltclass.py b/tests/pytests/unit/pillar/test_saltclass.py index 79fdaea8916..b96db78bc49 100644 --- a/tests/pytests/unit/pillar/test_saltclass.py +++ b/tests/pytests/unit/pillar/test_saltclass.py @@ -53,7 +53,7 @@ def temp_saltclass_tree(tmp_path, minion_id): """ default_init.write_text(test_list) - minion_node_file = nodes_dir / "{}.yml".format(minion_id) + minion_node_file = nodes_dir / f"{minion_id}.yml" nodes_text = """ environment: base diff --git a/tests/pytests/unit/proxy/nxos/test_nxos_nxapi.py b/tests/pytests/unit/proxy/nxos/test_nxos_nxapi.py index 7b703f4f901..8e632649ac1 100644 --- a/tests/pytests/unit/proxy/nxos/test_nxos_nxapi.py +++ b/tests/pytests/unit/proxy/nxos/test_nxos_nxapi.py @@ -32,7 +32,6 @@ def configure_loader_modules(): def test_check_virtual(): - """UT: nxos module:check_virtual method - return value""" result = nxos_proxy.__virtual__() @@ -40,7 +39,6 @@ def test_check_virtual(): def test_init(): - """UT: nxos module:init method - nxapi proxy""" with patch.object(nxos_proxy, "__opts__", {"proxy": {"connection": "nxapi"}}): @@ -50,7 +48,6 @@ def test_init(): def test_init_opts_none(): - """UT: nxos module:init method - __opts__ connection is None""" with patch.object(nxos_proxy, "__opts__", {"proxy": {"connection": None}}): @@ -60,14 +57,12 @@ def test_init_opts_none(): def test_init_bad_connection_type(): - """UT: nxos module:init method - bad CONNECTION type""" with patch.object(nxos_proxy, "__opts__", {"proxy": {"connection": "unknown"}}): assert not nxos_proxy.init() def test_initialized(): - """UT: nxos module:initialized method - nxapi proxy""" with patch( @@ -78,7 +73,6 @@ def test_initialized(): def test_ping(): - """UT: nxos module:ping method - nxapi proxy""" with patch("salt.proxy.nxos._ping_nxapi", autospec=True) as ping_nxapi: @@ -87,7 +81,6 @@ def test_ping(): def test_grains(): - """UT: nxos module:grains method - nxapi grains""" with patch( @@ -98,7 +91,6 @@ def test_grains(): def test_grains_cache_set(): - """UT: nxos module:grains method - nxapi grains cache set""" with patch("salt.proxy.nxos.DEVICE_DETAILS", {"grains_cache": n9k_grains["nxos"]}): @@ -112,7 +104,6 @@ def test_grains_cache_set(): def test_grains_refresh(): - """UT: nxos module:grains_refresh method - nxapi grains""" device_details = {"grains_cache": None} @@ -125,7 +116,6 @@ def test_grains_refresh(): def test_sendline(): - """UT: nxos module:sendline method - nxapi""" command = "show version" @@ -136,7 +126,6 @@ def test_sendline(): def test_proxy_config(): - """UT: nxos module:proxy_config method - nxapi success path""" commands = ["feature bgp", "router bgp 65535"] @@ -148,7 +137,6 @@ def test_proxy_config(): def test_proxy_config_save_config(): - """UT: nxos module:proxy_config method - nxapi success path""" commands = ["feature bgp", "router bgp 65535"] @@ -160,7 +148,6 @@ def test_proxy_config_save_config(): def test__init_nxapi(): - """UT: nxos module:_init_nxapi method - successful connectinon""" opts = {"proxy": {"arg1": None}} @@ -194,7 +181,6 @@ def test_bad__init_nxapi(): def test__initialized_nxapi(): - """UT: nxos module:_initialized_nxapi method""" result = nxos_proxy._initialized_nxapi() @@ -206,7 +192,6 @@ def test__initialized_nxapi(): def test__ping_nxapi(): - """UT: nxos module:_ping_nxapi method""" result = nxos_proxy._ping_nxapi() @@ -218,7 +203,6 @@ def test__ping_nxapi(): def test__shutdown_nxapi(): - """UT: nxos module:_shutdown_nxapi method""" opts = {"id": "value"} @@ -229,7 +213,6 @@ def test__shutdown_nxapi(): def test__nxapi_request_ssh_return(): - """UT: nxos module:_nxapi_request method - CONNECTION == 'ssh'""" commands = "show version" @@ -240,7 +223,6 @@ def test__nxapi_request_ssh_return(): def test__nxapi_request_connect(): - """UT: nxos module:_nxapi_request method""" commands = "show version" diff --git a/tests/pytests/unit/proxy/nxos/test_nxos_ssh.py b/tests/pytests/unit/proxy/nxos/test_nxos_ssh.py index ef14addbdf9..b6f4f991ad4 100644 --- a/tests/pytests/unit/proxy/nxos/test_nxos_ssh.py +++ b/tests/pytests/unit/proxy/nxos/test_nxos_ssh.py @@ -42,7 +42,6 @@ def configure_loader_modules(): def test_init(): - """UT: nxos module:init method - ssh proxy""" with patch("salt.proxy.nxos._init_ssh", autospec=True) as init_ssh: @@ -51,7 +50,6 @@ def test_init(): def test_init_opts_none(): - """UT: nxos module:init method - __opts__ connection is None""" with patch("salt.proxy.nxos.__opts__", {"proxy": {"connection": None}}): @@ -61,7 +59,6 @@ def test_init_opts_none(): def test_initialized(): - """UT: nxos module:initialized method - ssh proxy""" with patch("salt.proxy.nxos._initialized_ssh", autospec=True) as initialized_ssh: @@ -70,7 +67,6 @@ def test_initialized(): def test_ping(): - """UT: nxos module:ping method - ssh proxy""" with patch("salt.proxy.nxos._ping_ssh", autospec=True) as ping_ssh: @@ -79,7 +75,6 @@ def test_ping(): def test_grains(): - """UT: nxos module:grains method - ssh grains""" with patch( @@ -90,7 +85,6 @@ def test_grains(): def test_sendline(): - """UT: nxos module:sendline method - nxapi""" command = "show version" @@ -101,7 +95,6 @@ def test_sendline(): def test_proxy_config(): - """UT: nxos module:proxy_config method - ssh success path""" commands = ["feature bgp", "router bgp 65535"] @@ -113,7 +106,6 @@ def test_proxy_config(): def test_proxy_config_save_config(): - """UT: nxos module:proxy_config method - ssh success path""" commands = ["feature bgp", "router bgp 65535"] @@ -125,7 +117,6 @@ def test_proxy_config_save_config(): def test_proxy_config_error(): - """UT: nxos module:proxy_config method - CommandExecutionError""" with patch( @@ -156,7 +147,6 @@ def test__init_ssh_device_details(): def test__init_ssh_opts(): - """UT: nxos module:_init_ssh method - successful connectinon""" with patch("salt.proxy.nxos.DEVICE_DETAILS", {}): @@ -174,7 +164,6 @@ def test__init_ssh_opts(): def test__init_ssh_prompt(): - """UT: nxos module:_init_ssh method - prompt regex""" with patch("salt.proxy.nxos.DEVICE_DETAILS", {}): @@ -198,7 +187,6 @@ def test__init_ssh_prompt(): def test__initialized_ssh(): - """UT: nxos module:_initialized_ssh method""" with patch("salt.proxy.nxos.DEVICE_DETAILS", {"initialized": True}): @@ -211,7 +199,6 @@ def test__initialized_ssh(): def test__parse_output_for_errors(): - """UT: nxos module:_parse_output_for_errors method""" data = "% Incomplete command at '^' marker." @@ -246,7 +233,6 @@ def test__parse_output_for_errors(): def test__init_ssh_raise_exception(): - """UT: nxos module:_init_ssh method - raise exception""" class SSHException(Exception): diff --git a/tests/pytests/unit/proxy/test_esxdatacenter.py b/tests/pytests/unit/proxy/test_esxdatacenter.py index bcba6514af5..1142626e675 100644 --- a/tests/pytests/unit/proxy/test_esxdatacenter.py +++ b/tests/pytests/unit/proxy/test_esxdatacenter.py @@ -3,6 +3,7 @@ Tests for esxdatacenter proxy """ + import pytest import salt.exceptions diff --git a/tests/pytests/unit/proxy/test_napalm.py b/tests/pytests/unit/proxy/test_napalm.py index f93279af900..93b849a65a8 100644 --- a/tests/pytests/unit/proxy/test_napalm.py +++ b/tests/pytests/unit/proxy/test_napalm.py @@ -1,6 +1,7 @@ """ :codeauthor: :email:`Anthony Shaw ` """ + import pytest import salt.proxy.napalm as napalm_proxy diff --git a/tests/pytests/unit/renderers/test_aws_kms.py b/tests/pytests/unit/renderers/test_aws_kms.py index 9770531633f..8562d9f3e16 100644 --- a/tests/pytests/unit/renderers/test_aws_kms.py +++ b/tests/pytests/unit/renderers/test_aws_kms.py @@ -1,6 +1,7 @@ """ Unit tests for AWS KMS Decryption Renderer. """ + import pytest import salt.exceptions diff --git a/tests/pytests/unit/returners/test_elasticsearch_return.py b/tests/pytests/unit/returners/test_elasticsearch_return.py index 9b8940bc8f3..8c711d32c97 100644 --- a/tests/pytests/unit/returners/test_elasticsearch_return.py +++ b/tests/pytests/unit/returners/test_elasticsearch_return.py @@ -1,6 +1,7 @@ """ Test the elasticsearch returner """ + import pytest import salt.returners.elasticsearch_return as elasticsearch_return diff --git a/tests/pytests/unit/returners/test_pgjsonb.py b/tests/pytests/unit/returners/test_pgjsonb.py index 92abcddd7a8..d0c2bf83a5c 100644 --- a/tests/pytests/unit/returners/test_pgjsonb.py +++ b/tests/pytests/unit/returners/test_pgjsonb.py @@ -2,7 +2,6 @@ Unit tests for the PGJsonb returner (pgjsonb). """ - import pytest import salt.returners.pgjsonb as pgjsonb diff --git a/tests/pytests/unit/returners/test_slack_webhook_return.py b/tests/pytests/unit/returners/test_slack_webhook_return.py index 0cfc7df00c0..219c3208425 100644 --- a/tests/pytests/unit/returners/test_slack_webhook_return.py +++ b/tests/pytests/unit/returners/test_slack_webhook_return.py @@ -3,6 +3,7 @@ Unit tests for the Slack Webhook Returner. """ + import pytest import salt.returners.slack_webhook_return as slack_webhook @@ -183,9 +184,9 @@ def expected_payload(minion_name, author_icon): "Function: state.apply\nFunction Args: ['config.vim']\nJID:" " 20181227105933129338\nTotal: 4\nDuration: 27.03 secs" ), - "author_link": "{}".format(minion_name), - "author_name": "{}".format(minion_name), - "fallback": "{} | Failed".format(minion_name), + "author_link": f"{minion_name}", + "author_name": f"{minion_name}", + "fallback": f"{minion_name} | Failed", "author_icon": author_icon, }, {"color": "good", "title": "Unchanged: 2"}, @@ -257,7 +258,7 @@ def test_generate_payload_for_state_apply( """ Test _generate_payload private method """ - test_title = "{} | Failed".format(minion_name) + test_title = f"{minion_name} | Failed" test_report = slack_webhook._generate_report(ret, show_tasks) custom_grains = slack_webhook.__grains__ @@ -289,7 +290,7 @@ def test_generate_payload_for_test_ping(minion_name, author_icon, show_tasks): expected_payload = { "attachments": [ { - "fallback": "{} | Succeeded".format(minion_name), + "fallback": f"{minion_name} | Succeeded", "color": "#272727", "author_name": minion_name, "author_link": minion_name, @@ -301,7 +302,7 @@ def test_generate_payload_for_test_ping(minion_name, author_icon, show_tasks): ] } - test_title = "{} | Succeeded".format(minion_name) + test_title = f"{minion_name} | Succeeded" test_report = slack_webhook._generate_report(test_ping_ret, show_tasks) custom_grains = slack_webhook.__grains__ diff --git a/tests/pytests/unit/returners/test_smtp_return.py b/tests/pytests/unit/returners/test_smtp_return.py index 67ad2c877f8..61045bb548b 100644 --- a/tests/pytests/unit/returners/test_smtp_return.py +++ b/tests/pytests/unit/returners/test_smtp_return.py @@ -3,6 +3,7 @@ Test SMTP returner """ + import pytest import salt.returners.smtp_return as smtp diff --git a/tests/pytests/unit/returners/test_syslog_return.py b/tests/pytests/unit/returners/test_syslog_return.py index 8f8de24e18e..64dfca2eef2 100644 --- a/tests/pytests/unit/returners/test_syslog_return.py +++ b/tests/pytests/unit/returners/test_syslog_return.py @@ -3,6 +3,7 @@ :codeauthor: :email:`Megan Wilhite (mwilhite@saltstack.com)` """ + import pytest import salt.returners.syslog_return as syslog @@ -41,4 +42,4 @@ def test_syslog_returner_unicode(): try: syslog.returner(ret) except Exception as e: # pylint: disable=broad-except - pytest.fail("syslog.returner() failed with exception: {}".format(e)) + pytest.fail(f"syslog.returner() failed with exception: {e}") diff --git a/tests/pytests/unit/returners/test_telegram_return.py b/tests/pytests/unit/returners/test_telegram_return.py index 0502b6975a9..23cbec36ea5 100644 --- a/tests/pytests/unit/returners/test_telegram_return.py +++ b/tests/pytests/unit/returners/test_telegram_return.py @@ -3,6 +3,7 @@ :codeauthor: :email:`Roald Nefs (info@roaldnefs.com)` """ + import pytest import salt.returners.telegram_return as telegram diff --git a/tests/pytests/unit/roster/test_dir.py b/tests/pytests/unit/roster/test_dir.py index 72279119357..c99f70f61a0 100644 --- a/tests/pytests/unit/roster/test_dir.py +++ b/tests/pytests/unit/roster/test_dir.py @@ -2,7 +2,6 @@ Test the directory roster. """ - import logging import pytest @@ -111,14 +110,14 @@ def _test_match(ret, expected): assertDictEquals is too strict with OrderedDicts. The order isn't crucial for roster entries, so we test that they contain the expected members directly. """ - assert ret != {}, "Found no matches, expected {}".format(expected) + assert ret != {}, f"Found no matches, expected {expected}" for minion, data in ret.items(): assert minion in expected, "Expected minion {} to match, but it did not".format( minion ) assert ( dict(data) == expected[minion] - ), "Data for minion {} did not match expectations".format(minion) + ), f"Data for minion {minion} did not match expectations" def test_basic_glob(expected, create_roster_files): diff --git a/tests/pytests/unit/roster/test_terraform.py b/tests/pytests/unit/roster/test_terraform.py index b79d7985461..596c5723407 100644 --- a/tests/pytests/unit/roster/test_terraform.py +++ b/tests/pytests/unit/roster/test_terraform.py @@ -1,6 +1,7 @@ """ unittests for terraform roster """ + import pathlib import pytest diff --git a/tests/pytests/unit/runners/test_bgp.py b/tests/pytests/unit/runners/test_bgp.py index 4eeb32538e9..620e162a412 100644 --- a/tests/pytests/unit/runners/test_bgp.py +++ b/tests/pytests/unit/runners/test_bgp.py @@ -1,6 +1,7 @@ """ Test the bgp runner """ + import pytest import salt.runners.bgp as bgp diff --git a/tests/pytests/unit/runners/test_fileserver.py b/tests/pytests/unit/runners/test_fileserver.py index a258ace46ca..b664a56bb44 100644 --- a/tests/pytests/unit/runners/test_fileserver.py +++ b/tests/pytests/unit/runners/test_fileserver.py @@ -2,7 +2,6 @@ unit tests for the fileserver runner """ - import pytest import salt.loader @@ -20,7 +19,7 @@ class DummyFS: self.backends = backends def keys(self): - return ["{}.envs".format(x) for x in self.backends] + return [f"{x}.envs" for x in self.backends] @pytest.fixture diff --git a/tests/pytests/unit/runners/test_git_pillar.py b/tests/pytests/unit/runners/test_git_pillar.py index 958d8372360..9edabb64648 100644 --- a/tests/pytests/unit/runners/test_git_pillar.py +++ b/tests/pytests/unit/runners/test_git_pillar.py @@ -2,7 +2,6 @@ unit tests for the git_pillar runner """ - import logging import pytest diff --git a/tests/pytests/unit/runners/test_jobs.py b/tests/pytests/unit/runners/test_jobs.py index a1146e7f7d0..8d9fe3853a7 100644 --- a/tests/pytests/unit/runners/test_jobs.py +++ b/tests/pytests/unit/runners/test_jobs.py @@ -1,6 +1,7 @@ """ unit tests for the jobs runner """ + import pytest import salt.minion diff --git a/tests/pytests/unit/runners/test_network.py b/tests/pytests/unit/runners/test_network.py index 6d16d54eb94..9531d4ff8e0 100644 --- a/tests/pytests/unit/runners/test_network.py +++ b/tests/pytests/unit/runners/test_network.py @@ -1,6 +1,7 @@ """ Unit tests for Network runner """ + import logging import pytest diff --git a/tests/pytests/unit/runners/test_reactor.py b/tests/pytests/unit/runners/test_reactor.py index 10edc5de289..2b2def3cb65 100644 --- a/tests/pytests/unit/runners/test_reactor.py +++ b/tests/pytests/unit/runners/test_reactor.py @@ -2,7 +2,6 @@ unit tests for the reactor runner """ - import logging import pytest diff --git a/tests/pytests/unit/runners/test_saltutil.py b/tests/pytests/unit/runners/test_saltutil.py index e150dcc9703..f441e36aff2 100644 --- a/tests/pytests/unit/runners/test_saltutil.py +++ b/tests/pytests/unit/runners/test_saltutil.py @@ -115,13 +115,13 @@ def test_sync(module_type, module_sync_functions): sync_out = MagicMock(return_value=[[], True]) with patch("salt.utils.extmods.sync", sync_out) as extmods_sync: ret = saltutil.sync_modules() - func = "sync_{}".format(module_sync_functions[module_type]) + func = f"sync_{module_sync_functions[module_type]}" ret = getattr(saltutil, func)() assert ret == [] extmods_sync.assert_called_with( {}, - "{}".format(module_type), + f"{module_type}", extmod_blacklist=None, extmod_whitelist=None, saltenv="base", diff --git a/tests/pytests/unit/runners/test_spacewalk.py b/tests/pytests/unit/runners/test_spacewalk.py index c6bacd4b117..410b3dc290c 100644 --- a/tests/pytests/unit/runners/test_spacewalk.py +++ b/tests/pytests/unit/runners/test_spacewalk.py @@ -1,6 +1,7 @@ """ Unit tests for Spacewalk runner """ + import salt.runners.spacewalk as spacewalk from tests.support.mock import Mock, call, patch diff --git a/tests/pytests/unit/runners/test_winrepo.py b/tests/pytests/unit/runners/test_winrepo.py index aecdaaf10a4..4245ba453ac 100644 --- a/tests/pytests/unit/runners/test_winrepo.py +++ b/tests/pytests/unit/runners/test_winrepo.py @@ -2,7 +2,6 @@ Test the winrepo runner """ - import textwrap import pytest diff --git a/tests/pytests/unit/runners/vault/test_token_auth_deprecated.py b/tests/pytests/unit/runners/vault/test_token_auth_deprecated.py index feb0af6e9ad..63932911f51 100644 --- a/tests/pytests/unit/runners/vault/test_token_auth_deprecated.py +++ b/tests/pytests/unit/runners/vault/test_token_auth_deprecated.py @@ -5,7 +5,6 @@ This module only tests a deprecated function, see tests/pytests/unit/runners/test_vault.py for the current tests. """ - import logging import pytest diff --git a/tests/pytests/unit/sdb/test_yaml.py b/tests/pytests/unit/sdb/test_yaml.py index 102bf4881b2..d6a505178af 100644 --- a/tests/pytests/unit/sdb/test_yaml.py +++ b/tests/pytests/unit/sdb/test_yaml.py @@ -2,7 +2,6 @@ Test case for the YAML SDB module """ - import salt.sdb.yaml as sdb from tests.support.mock import MagicMock, patch diff --git a/tests/pytests/unit/serializers/test_serializers.py b/tests/pytests/unit/serializers/test_serializers.py index 0f3125c89e3..9721df6c0b4 100644 --- a/tests/pytests/unit/serializers/test_serializers.py +++ b/tests/pytests/unit/serializers/test_serializers.py @@ -153,7 +153,7 @@ def test_compare_sls_vs_yaml_with_jinja(): # BLAAM! yml_src is not valid ! final_obj = OrderedDict(yaml.deserialize(yml_src)) - assert obj != final_obj, "Objects matched! {} == {}".format(obj, final_obj) + assert obj != final_obj, f"Objects matched! {obj} == {final_obj}" @pytest.mark.skipif(yamlex.available is False, reason=SKIP_MESSAGE.format("sls")) diff --git a/tests/pytests/unit/state/test_state_basic.py b/tests/pytests/unit/state/test_state_basic.py index a8a56fba82b..c76a8b950ad 100644 --- a/tests/pytests/unit/state/test_state_basic.py +++ b/tests/pytests/unit/state/test_state_basic.py @@ -1,6 +1,7 @@ """ Test functions in state.py that are not a part of a class """ + import pytest import salt.state diff --git a/tests/pytests/unit/states/apache/test_conf.py b/tests/pytests/unit/states/apache/test_conf.py index 6d5fd04eb19..0a847bfd1c1 100644 --- a/tests/pytests/unit/states/apache/test_conf.py +++ b/tests/pytests/unit/states/apache/test_conf.py @@ -23,18 +23,18 @@ def test_enabled(): apache_conf.__salt__, {"apache.check_conf_enabled": mock, "apache.a2enconf": mock_str}, ): - comt = "{} already enabled.".format(name) + comt = f"{name} already enabled." ret.update({"comment": comt}) assert apache_conf.enabled(name) == ret - comt = "Apache conf {} is set to be enabled.".format(name) + comt = f"Apache conf {name} is set to be enabled." ret.update( {"comment": comt, "result": None, "changes": {"new": name, "old": None}} ) with patch.dict(apache_conf.__opts__, {"test": True}): assert apache_conf.enabled(name) == ret - comt = "Failed to enable {} Apache conf".format(name) + comt = f"Failed to enable {name} Apache conf" ret.update({"comment": comt, "result": False, "changes": {}}) with patch.dict(apache_conf.__opts__, {"test": False}): assert apache_conf.enabled(name) == ret @@ -54,16 +54,16 @@ def test_disabled(): apache_conf.__salt__, {"apache.check_conf_enabled": mock, "apache.a2disconf": mock_str}, ): - comt = "Apache conf {} is set to be disabled.".format(name) + comt = f"Apache conf {name} is set to be disabled." ret.update({"comment": comt, "changes": {"new": None, "old": name}}) with patch.dict(apache_conf.__opts__, {"test": True}): assert apache_conf.disabled(name) == ret - comt = "Failed to disable {} Apache conf".format(name) + comt = f"Failed to disable {name} Apache conf" ret.update({"comment": comt, "result": False, "changes": {}}) with patch.dict(apache_conf.__opts__, {"test": False}): assert apache_conf.disabled(name) == ret - comt = "{} already disabled.".format(name) + comt = f"{name} already disabled." ret.update({"comment": comt, "result": True}) assert apache_conf.disabled(name) == ret diff --git a/tests/pytests/unit/states/apache/test_module.py b/tests/pytests/unit/states/apache/test_module.py index 6edf200a4bc..8a647885fdd 100644 --- a/tests/pytests/unit/states/apache/test_module.py +++ b/tests/pytests/unit/states/apache/test_module.py @@ -27,18 +27,18 @@ def test_enabled(): apache_module.__salt__, {"apache.check_mod_enabled": mock, "apache.a2enmod": mock_str}, ): - comt = "{} already enabled.".format(name) + comt = f"{name} already enabled." ret.update({"comment": comt}) assert apache_module.enabled(name) == ret - comt = "Apache module {} is set to be enabled.".format(name) + comt = f"Apache module {name} is set to be enabled." ret.update( {"comment": comt, "result": None, "changes": {"new": "cgi", "old": None}} ) with patch.dict(apache_module.__opts__, {"test": True}): assert apache_module.enabled(name) == ret - comt = "Failed to enable {} Apache module".format(name) + comt = f"Failed to enable {name} Apache module" ret.update({"comment": comt, "result": False, "changes": {}}) with patch.dict(apache_module.__opts__, {"test": False}): assert apache_module.enabled(name) == ret @@ -58,16 +58,16 @@ def test_disabled(): apache_module.__salt__, {"apache.check_mod_enabled": mock, "apache.a2dismod": mock_str}, ): - comt = "Apache module {} is set to be disabled.".format(name) + comt = f"Apache module {name} is set to be disabled." ret.update({"comment": comt, "changes": {"new": None, "old": "cgi"}}) with patch.dict(apache_module.__opts__, {"test": True}): assert apache_module.disabled(name) == ret - comt = "Failed to disable {} Apache module".format(name) + comt = f"Failed to disable {name} Apache module" ret.update({"comment": comt, "result": False, "changes": {}}) with patch.dict(apache_module.__opts__, {"test": False}): assert apache_module.disabled(name) == ret - comt = "{} already disabled.".format(name) + comt = f"{name} already disabled." ret.update({"comment": comt, "result": True}) assert apache_module.disabled(name) == ret diff --git a/tests/pytests/unit/states/apache/test_site.py b/tests/pytests/unit/states/apache/test_site.py index 881148de493..ed53c53331f 100644 --- a/tests/pytests/unit/states/apache/test_site.py +++ b/tests/pytests/unit/states/apache/test_site.py @@ -23,18 +23,18 @@ def test_enabled(): apache_site.__salt__, {"apache.check_site_enabled": mock, "apache.a2ensite": mock_str}, ): - comt = "{} already enabled.".format(name) + comt = f"{name} already enabled." ret.update({"comment": comt}) assert apache_site.enabled(name) == ret - comt = "Apache site {} is set to be enabled.".format(name) + comt = f"Apache site {name} is set to be enabled." ret.update( {"comment": comt, "result": None, "changes": {"new": name, "old": None}} ) with patch.dict(apache_site.__opts__, {"test": True}): assert apache_site.enabled(name) == ret - comt = "Failed to enable {} Apache site".format(name) + comt = f"Failed to enable {name} Apache site" ret.update({"comment": comt, "result": False, "changes": {}}) with patch.dict(apache_site.__opts__, {"test": False}): assert apache_site.enabled(name) == ret @@ -54,16 +54,16 @@ def test_disabled(): apache_site.__salt__, {"apache.check_site_enabled": mock, "apache.a2dissite": mock_str}, ): - comt = "Apache site {} is set to be disabled.".format(name) + comt = f"Apache site {name} is set to be disabled." ret.update({"comment": comt, "changes": {"new": None, "old": name}}) with patch.dict(apache_site.__opts__, {"test": True}): assert apache_site.disabled(name) == ret - comt = "Failed to disable {} Apache site".format(name) + comt = f"Failed to disable {name} Apache site" ret.update({"comment": comt, "result": False, "changes": {}}) with patch.dict(apache_site.__opts__, {"test": False}): assert apache_site.disabled(name) == ret - comt = "{} already disabled.".format(name) + comt = f"{name} already disabled." ret.update({"comment": comt, "result": True}) assert apache_site.disabled(name) == ret diff --git a/tests/pytests/unit/states/file/test__clean_dir.py b/tests/pytests/unit/states/file/test__clean_dir.py index 43504105a31..7602ba6f93d 100644 --- a/tests/pytests/unit/states/file/test__clean_dir.py +++ b/tests/pytests/unit/states/file/test__clean_dir.py @@ -1,6 +1,7 @@ """ Tests for _clean_dir function """ + import pytest import salt.states.file as file diff --git a/tests/pytests/unit/states/file/test_absent.py b/tests/pytests/unit/states/file/test_absent.py index 62fc16eb6e0..3e0f7dce8ed 100644 --- a/tests/pytests/unit/states/file/test_absent.py +++ b/tests/pytests/unit/states/file/test_absent.py @@ -58,7 +58,7 @@ def test_absent(): assert filestate.absent("") == ret with patch.object(os.path, "isabs", mock_f): - comt = "Specified file {} is not an absolute path".format(name) + comt = f"Specified file {name} is not an absolute path" ret.update({"comment": comt, "name": name}) assert filestate.absent(name) == ret @@ -69,7 +69,7 @@ def test_absent(): with patch.object(os.path, "isfile", mock_t): with patch.dict(filestate.__opts__, {"test": True}): - comt = "File {} is set for removal".format(name) + comt = f"File {name} is set for removal" ret.update( { "comment": comt, @@ -82,20 +82,20 @@ def test_absent(): with patch.dict(filestate.__opts__, {"test": False}): with patch.dict(filestate.__salt__, {"file.remove": mock_file}): - comt = "Removed file {}".format(name) + comt = f"Removed file {name}" ret.update( {"comment": comt, "result": True, "changes": {"removed": name}} ) assert filestate.absent(name) == ret - comt = "Removed file {}".format(name) + comt = f"Removed file {name}" ret.update({"comment": "", "result": False, "changes": {}}) assert filestate.absent(name) == ret with patch.object(os.path, "isfile", mock_f): with patch.object(os.path, "isdir", mock_t): with patch.dict(filestate.__opts__, {"test": True}): - comt = "Directory {} is set for removal".format(name) + comt = f"Directory {name} is set for removal" ret.update( {"comment": comt, "changes": {"removed": name}, "result": None} ) @@ -103,7 +103,7 @@ def test_absent(): with patch.dict(filestate.__opts__, {"test": False}): with patch.dict(filestate.__salt__, {"file.remove": mock_tree}): - comt = "Removed directory {}".format(name) + comt = f"Removed directory {name}" ret.update( { "comment": comt, @@ -113,12 +113,12 @@ def test_absent(): ) assert filestate.absent(name) == ret - comt = "Failed to remove directory {}".format(name) + comt = f"Failed to remove directory {name}" ret.update({"comment": comt, "result": False, "changes": {}}) assert filestate.absent(name) == ret with patch.object(os.path, "isdir", mock_f): with patch.dict(filestate.__opts__, {"test": True}): - comt = "File {} is not present".format(name) + comt = f"File {name} is not present" ret.update({"comment": comt, "result": True}) assert filestate.absent(name) == ret diff --git a/tests/pytests/unit/states/file/test_comment.py b/tests/pytests/unit/states/file/test_comment.py index 0eefd36d041..6ef8b72de28 100644 --- a/tests/pytests/unit/states/file/test_comment.py +++ b/tests/pytests/unit/states/file/test_comment.py @@ -59,7 +59,7 @@ def test_comment(): mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) with patch.object(os.path, "isabs", mock_f): - comt = "Specified file {} is not an absolute path".format(name) + comt = f"Specified file {name} is not an absolute path" ret.update({"comment": comt, "name": name}) assert filestate.comment(name, regex) == ret @@ -80,7 +80,7 @@ def test_comment(): ret.update({"comment": comt, "result": True}) assert filestate.comment(name, regex, ignore_missing=True) == ret - comt = "{}: Pattern not found".format(regex) + comt = f"{regex}: Pattern not found" ret.update({"comment": comt, "result": False}) assert filestate.comment(name, regex) == ret @@ -95,7 +95,7 @@ def test_comment(): }, ): with patch.dict(filestate.__opts__, {"test": True}): - comt = "File {} is set to be updated".format(name) + comt = f"File {name} is set to be updated" ret.update( {"comment": comt, "result": None, "changes": {name: "updated"}} ) @@ -134,7 +134,7 @@ def test_uncomment(): mock_f = MagicMock(return_value=False) mock = MagicMock(side_effect=[False, True, False, False, True, True, True]) with patch.object(os.path, "isabs", mock_f): - comt = "Specified file {} is not an absolute path".format(name) + comt = f"Specified file {name} is not an absolute path" ret.update({"comment": comt, "name": name}) assert filestate.uncomment(name, regex) == ret @@ -151,12 +151,12 @@ def test_uncomment(): ret.update({"comment": comt, "result": True}) assert filestate.uncomment(name, regex) == ret - comt = "{}: Pattern not found".format(regex) + comt = f"{regex}: Pattern not found" ret.update({"comment": comt, "result": False}) assert filestate.uncomment(name, regex) == ret with patch.dict(filestate.__opts__, {"test": True}): - comt = "File {} is set to be updated".format(name) + comt = f"File {name} is set to be updated" ret.update( {"comment": comt, "result": None, "changes": {name: "updated"}} ) diff --git a/tests/pytests/unit/states/file/test_copy.py b/tests/pytests/unit/states/file/test_copy.py index d7becf580c8..291d28b4716 100644 --- a/tests/pytests/unit/states/file/test_copy.py +++ b/tests/pytests/unit/states/file/test_copy.py @@ -66,13 +66,13 @@ def test_copy(tmp_path): mock_grp = MagicMock(return_value=group) mock_io = MagicMock(side_effect=IOError) with patch.object(os.path, "isabs", mock_f): - comt = "Specified file {} is not an absolute path".format(name) + comt = f"Specified file {name} is not an absolute path" ret.update({"comment": comt, "name": name}) assert filestate.copy_(name, source) == ret with patch.object(os.path, "isabs", mock_t): with patch.object(os.path, "exists", mock_f): - comt = 'Source file "{}" is not present'.format(source) + comt = f'Source file "{source}" is not present' ret.update({"comment": comt, "result": False}) assert filestate.copy_(name, source) == ret @@ -106,7 +106,7 @@ def test_copy(tmp_path): 'The target file "{}" exists and will not be ' "overwritten".format(name) ) - comt3 = 'File "{}" is set to be copied to "{}"'.format(source, name) + comt3 = f'File "{source}" is set to be copied to "{name}"' with patch.object(os.path, "isdir", mock_f): with patch.object(os.path, "lexists", mock_t): with patch.dict(filestate.__opts__, {"test": False}): @@ -165,7 +165,7 @@ def test_copy(tmp_path): }, ): - comt = 'Copied "{}" to "{}"'.format(source, name) + comt = f'Copied "{source}" to "{name}"' with patch.dict(filestate.__opts__, {"user": "salt"}), patch.object( os.path, "isdir", mock_t ), patch.object(os.path, "lexists", mock_f), patch.dict( @@ -186,7 +186,7 @@ def test_copy(tmp_path): res = filestate.copy_(name, source, group=group, preserve=False) assert res == ret - comt = 'Copied "{}" to "{}"'.format(source, name) + comt = f'Copied "{source}" to "{name}"' with patch.dict(filestate.__opts__, {"user": "salt"}), patch.object( os.path, "isdir", MagicMock(side_effect=[False, True, False]) ), patch.object(os.path, "lexists", mock_f), patch.dict( diff --git a/tests/pytests/unit/states/file/test_directory.py b/tests/pytests/unit/states/file/test_directory.py index 042ecc9e61f..1474e4eee1a 100644 --- a/tests/pytests/unit/states/file/test_directory.py +++ b/tests/pytests/unit/states/file/test_directory.py @@ -104,7 +104,7 @@ def test_directory(): mock_check = MagicMock( return_value=( None, - 'The directory "{}" will be changed'.format(name), + f'The directory "{name}" will be changed', {name: {"directory": "new"}}, ) ) @@ -132,7 +132,7 @@ def test_directory(): assert filestate.directory(name, user=user, group=group) == ret with patch.object(os.path, "isabs", mock_f): - comt = "Specified file {} is not an absolute path".format(name) + comt = f"Specified file {name} is not an absolute path" ret.update({"comment": comt}) assert filestate.directory(name, user=user, group=group) == ret @@ -153,12 +153,12 @@ def test_directory(): ) with patch.object(os.path, "isfile", mock_t): - comt = "Specified location {} exists and is a file".format(name) + comt = f"Specified location {name} exists and is a file" ret.update({"comment": comt}) assert filestate.directory(name, user=user, group=group) == ret with patch.object(os.path, "islink", mock_t): - comt = "Specified location {} exists and is a symlink".format(name) + comt = f"Specified location {name} exists and is a symlink" ret.update({"comment": comt}) assert filestate.directory(name, user=user, group=group) == ret @@ -182,7 +182,7 @@ def test_directory(): with patch.dict(filestate.__opts__, {"test": False}): with patch.object(os.path, "isdir", mock_f): - comt = "No directory to create {} in".format(name) + comt = f"No directory to create {name} in" ret.update({"comment": comt, "result": False}) assert filestate.directory(name, user=user, group=group) == ret @@ -193,7 +193,7 @@ def test_directory(): with patch.object( os.path, "isdir", MagicMock(side_effect=isdir_side_effect) ): - comt = "Failed to create directory {}".format(name) + comt = f"Failed to create directory {name}" ret.update( { "comment": comt, @@ -266,7 +266,7 @@ def test_directory(): == ret ) - comt = "Directory {} updated".format(name) + comt = f"Directory {name} updated" ret = { "name": name, "result": True, diff --git a/tests/pytests/unit/states/file/test_filestate.py b/tests/pytests/unit/states/file/test_filestate.py index f7daf51b5a6..0d0f95f8985 100644 --- a/tests/pytests/unit/states/file/test_filestate.py +++ b/tests/pytests/unit/states/file/test_filestate.py @@ -131,7 +131,7 @@ def test_contents_and_contents_pillar(): def test_contents_pillar_doesnt_add_more_newlines(): # make sure the newline - pillar_value = "i am the pillar value{}".format(os.linesep) + pillar_value = f"i am the pillar value{os.linesep}" returner = MagicMock(return_value=None) path = "/tmp/foo" @@ -182,12 +182,12 @@ def test_exists(): assert filestate.exists("") == ret with patch.object(os.path, "exists", mock_f): - comt = "Specified path {} does not exist".format(name) + comt = f"Specified path {name} does not exist" ret.update({"comment": comt, "name": name}) assert filestate.exists(name) == ret with patch.object(os.path, "exists", mock_t): - comt = "Path {} exists".format(name) + comt = f"Path {name} exists" ret.update({"comment": comt, "result": True}) assert filestate.exists(name) == ret @@ -209,12 +209,12 @@ def test_missing(): assert filestate.missing("") == ret with patch.object(os.path, "exists", mock_t): - comt = "Specified path {} exists".format(name) + comt = f"Specified path {name} exists" ret.update({"comment": comt, "name": name}) assert filestate.missing(name) == ret with patch.object(os.path, "exists", mock_f): - comt = "Path {} is missing".format(name) + comt = f"Path {name} is missing" ret.update({"comment": comt, "result": True}) assert filestate.missing(name) == ret @@ -271,7 +271,7 @@ def test_recurse(): assert filestate.recurse(name, source, user=user, group=group) == ret with patch.object(os.path, "isabs", mock_f): - comt = "Specified file {} is not an absolute path".format(name) + comt = f"Specified file {name} is not an absolute path" ret.update({"comment": comt}) assert filestate.recurse(name, source) == ret @@ -297,12 +297,12 @@ def test_recurse(): with patch.object(os.path, "isdir", mock_f): with patch.object(os.path, "exists", mock_t): - comt = "The path {} exists and is not a directory".format(name) + comt = f"The path {name} exists and is not a directory" ret.update({"comment": comt}) assert filestate.recurse(name, source) == ret with patch.object(os.path, "isdir", mock_t): - comt = "The directory {} is in the correct state".format(name) + comt = f"The directory {name} is in the correct state" ret.update({"comment": comt, "result": True}) assert filestate.recurse(name, source) == ret @@ -325,7 +325,7 @@ def test_replace(): mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) with patch.object(os.path, "isabs", mock_f): - comt = "Specified file {} is not an absolute path".format(name) + comt = f"Specified file {name} is not an absolute path" ret.update({"comment": comt, "name": name}) assert filestate.replace(name, pattern, repl) == ret @@ -356,7 +356,7 @@ def test_blockreplace(): mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) with patch.object(os.path, "isabs", mock_f): - comt = "Specified file {} is not an absolute path".format(name) + comt = f"Specified file {name} is not an absolute path" ret.update({"comment": comt, "name": name}) assert filestate.blockreplace(name) == ret @@ -389,26 +389,26 @@ def test_touch(): mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) with patch.object(os.path, "isabs", mock_f): - comt = "Specified file {} is not an absolute path".format(name) + comt = f"Specified file {name} is not an absolute path" ret.update({"comment": comt, "name": name}) assert filestate.touch(name) == ret with patch.object(os.path, "isabs", mock_t): with patch.object(os.path, "exists", mock_f): with patch.dict(filestate.__opts__, {"test": True}): - comt = "File {} is set to be created".format(name) + comt = f"File {name} is set to be created" ret.update({"comment": comt, "result": None, "changes": {"new": name}}) assert filestate.touch(name) == ret with patch.dict(filestate.__opts__, {"test": False}): with patch.object(os.path, "isdir", mock_f): - comt = "Directory not present to touch file {}".format(name) + comt = f"Directory not present to touch file {name}" ret.update({"comment": comt, "result": False, "changes": {}}) assert filestate.touch(name) == ret with patch.object(os.path, "isdir", mock_t): with patch.dict(filestate.__salt__, {"file.touch": mock_t}): - comt = "Created empty file {}".format(name) + comt = f"Created empty file {name}" ret.update( {"comment": comt, "result": True, "changes": {"new": name}} ) @@ -482,7 +482,7 @@ def test_serialize_into_managed_file(): mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) with patch.object(os.path, "isfile", mock_f): - comt = "File {} is not present and is not set for creation".format(name) + comt = f"File {name} is not present and is not set for creation" ret.update({"comment": comt, "name": name, "result": True}) assert filestate.serialize(name, create=False) == ret @@ -516,7 +516,7 @@ def test_serialize_into_managed_file(): # __opts__['test']=True with changes with patch.dict(filestate.__salt__, {"file.check_managed_changes": mock_changes}): with patch.dict(filestate.__opts__, {"test": True}): - comt = "Dataset will be serialized and stored into {}".format(name) + comt = f"Dataset will be serialized and stored into {name}" ret.update({"comment": comt, "result": None, "changes": True}) assert filestate.serialize(name, dataset=True, formatter="python") == ret @@ -525,14 +525,14 @@ def test_serialize_into_managed_file(): filestate.__salt__, {"file.check_managed_changes": mock_no_changes} ): with patch.dict(filestate.__opts__, {"test": True}): - comt = "The file {} is in the correct state".format(name) + comt = f"The file {name} is in the correct state" ret.update({"comment": comt, "result": True, "changes": False}) assert filestate.serialize(name, dataset=True, formatter="python") == ret mock = MagicMock(return_value=ret) with patch.dict(filestate.__opts__, {"test": False}): with patch.dict(filestate.__salt__, {"file.manage_file": mock}): - comt = "Dataset will be serialized and stored into {}".format(name) + comt = f"Dataset will be serialized and stored into {name}" ret.update({"comment": comt, "result": None}) assert filestate.serialize(name, dataset=True, formatter="python") == ret diff --git a/tests/pytests/unit/states/file/test_hardlink.py b/tests/pytests/unit/states/file/test_hardlink.py index 901cae3a4b0..ea0f9a131c0 100644 --- a/tests/pytests/unit/states/file/test_hardlink.py +++ b/tests/pytests/unit/states/file/test_hardlink.py @@ -94,7 +94,7 @@ def test_hardlink(tmp_path): ), patch.dict(filestate.__salt__, {"file.group_to_gid": mock_gid}), patch.object( os.path, "isabs", mock_t ): - expected = "User {} does not exist".format(user) + expected = f"User {user} does not exist" ret = return_val(comment=expected, name=name) assert filestate.hardlink(name, target, user=user, group=group) == ret @@ -104,7 +104,7 @@ def test_hardlink(tmp_path): ), patch.dict(filestate.__salt__, {"file.group_to_gid": mock_empty}), patch.object( os.path, "isabs", mock_t ): - expected = "Group {} does not exist".format(group) + expected = f"Group {group} does not exist" ret = return_val(comment=expected, name=name) assert filestate.hardlink(name, target, user=user, group=group) == ret @@ -113,7 +113,7 @@ def test_hardlink(tmp_path): with patch.dict(filestate.__salt__, patches), patch.dict( filestate.__salt__, {"file.user_to_uid": mock_uid} ), patch.dict(filestate.__salt__, {"file.group_to_gid": mock_gid}): - expected = "Specified file {} is not an absolute path".format(nonabs) + expected = f"Specified file {nonabs} is not an absolute path" ret = return_val(comment=expected, name=nonabs) assert filestate.hardlink(nonabs, target, user=user, group=group) == ret @@ -121,7 +121,7 @@ def test_hardlink(tmp_path): with patch.dict(filestate.__salt__, patches), patch.dict( filestate.__salt__, {"file.user_to_uid": mock_uid} ), patch.dict(filestate.__salt__, {"file.group_to_gid": mock_gid}): - expected = "Specified target {} is not an absolute path".format(nonabs) + expected = f"Specified target {nonabs} is not an absolute path" ret = return_val(comment=expected, name=name) assert filestate.hardlink(name, nonabs, user=user, group=group) == ret # Test option -- nonexistent target @@ -132,7 +132,7 @@ def test_hardlink(tmp_path): ), patch.dict( filestate.__opts__, {"test": True} ): - expected = "Target {} for hard link does not exist".format(target) + expected = f"Target {target} for hard link does not exist" ret = return_val(comment=expected, name=name) assert filestate.hardlink(name, target, user=user, group=group) == ret @@ -144,7 +144,7 @@ def test_hardlink(tmp_path): ), patch.dict( filestate.__opts__, {"test": True} ): - expected = "Unable to hard link from directory {}".format(test_dir) + expected = f"Unable to hard link from directory {test_dir}" ret = return_val(comment=expected, name=name) assert filestate.hardlink(name, test_dir, user=user, group=group) == ret @@ -154,7 +154,7 @@ def test_hardlink(tmp_path): ), patch.dict(filestate.__salt__, {"file.group_to_gid": mock_gid}), patch.dict( filestate.__opts__, {"test": True} ): - expected = "Unable to hard link to directory {}".format(test_dir) + expected = f"Unable to hard link to directory {test_dir}" ret = return_val(comment=expected, name=test_dir) assert filestate.hardlink(test_dir, target, user=user, group=group) == ret @@ -164,7 +164,7 @@ def test_hardlink(tmp_path): ), patch.dict(filestate.__salt__, {"file.group_to_gid": mock_gid}), patch.dict( filestate.__opts__, {"test": True} ): - expected = "Hard link {} to {} is set for creation".format(name, target) + expected = f"Hard link {name} to {target} is set for creation" changes = dict(new=name) ret = return_val(result=None, comment=expected, name=name, changes=changes) assert filestate.hardlink(name, target, user=user, group=group) == ret @@ -181,7 +181,7 @@ def test_hardlink(tmp_path): ), patch.dict( filestate.__opts__, {"test": True} ): - expected = "The hard link {} is presently targetting {}".format(name, target) + expected = f"The hard link {name} is presently targetting {target}" ret = return_val(result=True, comment=expected, name=name) assert filestate.hardlink(name, target, user=user, group=group) == ret @@ -197,7 +197,7 @@ def test_hardlink(tmp_path): ), patch.dict( filestate.__opts__, {"test": True} ): - expected = "Link {} target is set to be changed to {}".format(name, target) + expected = f"Link {name} target is set to be changed to {target}" changes = dict(change=name) ret = return_val(result=None, comment=expected, name=name, changes=changes) assert filestate.hardlink(name, target, user=user, group=group) == ret @@ -244,7 +244,7 @@ def test_hardlink(tmp_path): with patch.dict(filestate.__salt__, patches), patch.dict( filestate.__salt__, {"file.user_to_uid": mock_uid} ), patch.dict(filestate.__salt__, {"file.group_to_gid": mock_gid}): - expected = "Unable to hard link from directory {}".format(test_dir) + expected = f"Unable to hard link from directory {test_dir}" ret = return_val(comment=expected, name=name) assert filestate.hardlink(name, test_dir, user=user, group=group) == ret @@ -252,7 +252,7 @@ def test_hardlink(tmp_path): with patch.dict(filestate.__salt__, patches), patch.dict( filestate.__salt__, {"file.user_to_uid": mock_uid} ), patch.dict(filestate.__salt__, {"file.group_to_gid": mock_gid}): - expected = "Unable to hard link to directory {}".format(test_dir) + expected = f"Unable to hard link to directory {test_dir}" ret = return_val(comment=expected, name=test_dir) assert filestate.hardlink(test_dir, target, user=user, group=group) == ret @@ -265,7 +265,7 @@ def test_hardlink(tmp_path): os.path, "isfile", mock_t ): - expected = "File exists where the hard link {} should be".format(name) + expected = f"File exists where the hard link {name} should be" ret = return_val(comment=expected, name=name) assert filestate.hardlink(name, target, user=user, group=group) == ret @@ -301,7 +301,7 @@ def test_hardlink(tmp_path): os.path, "isfile", mock_f ): - expected = "Set target of hard link {} -> {}".format(name, target) + expected = f"Set target of hard link {name} -> {target}" changes = dict(new=name) ret = return_val(result=True, comment=expected, name=name, changes=changes) assert filestate.hardlink(name, target, user=user, group=group) == ret @@ -342,7 +342,7 @@ def test_hardlink(tmp_path): os.path, "isfile", mock_f ): - expected = "Created new hard link {} -> {}".format(name, target) + expected = f"Created new hard link {name} -> {target}" changes = dict(new=name) ret = return_val(result=True, comment=expected, name=name, changes=changes) assert filestate.hardlink(name, target, user=user, group=group) == ret @@ -383,7 +383,7 @@ def test_hardlink(tmp_path): os.path, "isfile", mock_t ): - expected = "Created new hard link {} -> {}".format(name, target) + expected = f"Created new hard link {name} -> {target}" changes = dict(new=name) changes["forced"] = "File for hard link was forcibly replaced" ret = return_val(result=True, comment=expected, name=name, changes=changes) @@ -437,7 +437,7 @@ def test_hardlink(tmp_path): ): group = None - expected = "Created new hard link {} -> {}".format(name, target) + expected = f"Created new hard link {name} -> {target}" changes = dict(new=name) ret = return_val(result=True, comment=expected, name=name, changes=changes) assert filestate.hardlink(name, target, user=user, group=group) == ret diff --git a/tests/pytests/unit/states/file/test_managed.py b/tests/pytests/unit/states/file/test_managed.py index 4a826c26869..fc303d34139 100644 --- a/tests/pytests/unit/states/file/test_managed.py +++ b/tests/pytests/unit/states/file/test_managed.py @@ -179,7 +179,7 @@ def test_managed(): assert filestate.managed("") == ret with patch.object(os.path, "isfile", mock_f): - comt = "File {} is not present and is not set for creation".format(name) + comt = f"File {name} is not present and is not set for creation" ret.update({"comment": comt, "name": name, "result": True}) assert filestate.managed(name, create=False) == ret @@ -193,13 +193,13 @@ def test_managed(): assert filestate.managed(name, user=user, group=group) == ret with patch.object(os.path, "isabs", mock_f): - comt = "Specified file {} is not an absolute path".format(name) + comt = f"Specified file {name} is not an absolute path" ret.update({"comment": comt, "result": False}) assert filestate.managed(name, user=user, group=group) == ret with patch.object(os.path, "isabs", mock_t): with patch.object(os.path, "isdir", mock_t): - comt = "Specified target {} is a directory".format(name) + comt = f"Specified target {name} is a directory" ret.update({"comment": comt}) assert filestate.managed(name, user=user, group=group) == ret @@ -237,7 +237,7 @@ def test_managed(): with patch.object(os.path, "exists", mock_t): with patch.dict(filestate.__opts__, {"test": True}): - comt = "File {} not updated".format(name) + comt = f"File {name} not updated" ret.update({"comment": comt}) assert ( filestate.managed( @@ -246,7 +246,7 @@ def test_managed(): == ret ) - comt = "The file {} is in the correct state".format(name) + comt = f"The file {name} is in the correct state" ret.update({"comment": comt, "result": True}) assert ( filestate.managed( @@ -324,7 +324,7 @@ def test_managed(): if salt.utils.platform.is_windows(): mock_ret = MagicMock(return_value=ret) - comt = "File {} not updated".format(name) + comt = f"File {name} not updated" else: perms = {"luser": user, "lmode": "0644", "lgroup": group} mock_ret = MagicMock(return_value=(ret, perms)) @@ -359,7 +359,7 @@ def test_managed(): else: perms = {"luser": user, "lmode": "0644", "lgroup": group} mock_ret = MagicMock(return_value=(ret, perms)) - comt = "File {} not updated".format(name) + comt = f"File {name} not updated" with patch.dict(filestate.__salt__, {"file.check_perms": mock_ret}): with patch.object(os.path, "exists", mock_t): with patch.dict(filestate.__opts__, {"test": True}): diff --git a/tests/pytests/unit/states/file/test_prepend.py b/tests/pytests/unit/states/file/test_prepend.py index e0b4edb8d99..db528519ec0 100644 --- a/tests/pytests/unit/states/file/test_prepend.py +++ b/tests/pytests/unit/states/file/test_prepend.py @@ -86,13 +86,13 @@ def test_prepend(): assert filestate.prepend(name, makedirs=True) == ret with patch.object(os.path, "isabs", mock_f): - comt = "Specified file {} is not an absolute path".format(name) + comt = f"Specified file {name} is not an absolute path" ret.update({"comment": comt, "changes": {}}) assert filestate.prepend(name) == ret with patch.object(os.path, "isabs", mock_t): with patch.object(os.path, "exists", mock_t): - comt = "Failed to load template file {}".format(source) + comt = f"Failed to load template file {source}" ret.update({"comment": comt, "name": source, "data": []}) assert filestate.prepend(name, source=source) == ret @@ -104,7 +104,7 @@ def test_prepend(): with patch.dict(filestate.__utils__, {"files.is_text": mock_f}): with patch.dict(filestate.__opts__, {"test": True}): change = {"diff": "Replace binary file"} - comt = "File {} is set to be updated".format(name) + comt = f"File {name} is set to be updated" ret.update( {"comment": comt, "result": None, "changes": change} ) diff --git a/tests/pytests/unit/states/file/test_private_functions.py b/tests/pytests/unit/states/file/test_private_functions.py index b3fc7cbbe65..b2fa9059afb 100644 --- a/tests/pytests/unit/states/file/test_private_functions.py +++ b/tests/pytests/unit/states/file/test_private_functions.py @@ -37,7 +37,7 @@ def test__check_directory(tmp_path): def create_files(tmp_dir): for f in range(depth): - path = os.path.join(tmp_dir, "file_{:03}.txt".format(f)) + path = os.path.join(tmp_dir, f"file_{f:03}.txt") with salt.utils.files.fopen(path, "w+"): os.chmod(path, expected_mode) @@ -47,12 +47,12 @@ def test__check_directory(tmp_path): create_files(root_tmp_dir) for d in range(depth): - dir_name = os.path.join(root_tmp_dir, "dir{:03}".format(d)) + dir_name = os.path.join(root_tmp_dir, f"dir{d:03}") os.mkdir(dir_name) os.chmod(dir_name, expected_mode) create_files(dir_name) for s in range(depth): - sub_dir_name = os.path.join(dir_name, "dir{:03}".format(s)) + sub_dir_name = os.path.join(dir_name, f"dir{s:03}") os.mkdir(sub_dir_name) os.chmod(sub_dir_name, expected_mode) create_files(sub_dir_name) diff --git a/tests/pytests/unit/states/file/test_pruned.py b/tests/pytests/unit/states/file/test_pruned.py index 7afc8eadeb9..c57789ffe5b 100644 --- a/tests/pytests/unit/states/file/test_pruned.py +++ b/tests/pytests/unit/states/file/test_pruned.py @@ -28,7 +28,7 @@ def test_pruned_clean(directory_name): ret = filestate.pruned(name=directory_name) assert ret == { "changes": {}, - "comment": "Directory {} is not present".format(directory_name), + "comment": f"Directory {directory_name} is not present", "name": directory_name, "result": True, } @@ -41,7 +41,7 @@ def test_pruned_test(directory_name): ret = filestate.pruned(name=directory_name) assert ret == { "changes": {"deleted": directory_name}, - "comment": "Directory {} is set for removal".format(directory_name), + "comment": f"Directory {directory_name} is set for removal", "name": directory_name, "result": None, } @@ -55,7 +55,7 @@ def test_pruned_success(directory_name): ret = filestate.pruned(name=directory_name) assert ret == { "changes": {"deleted": directory_name}, - "comment": "Removed directory {}".format(directory_name), + "comment": f"Removed directory {directory_name}", "name": directory_name, "result": True, } diff --git a/tests/pytests/unit/states/file/test_retention_schedule.py b/tests/pytests/unit/states/file/test_retention_schedule.py index 3e9179afcbf..7fd57195a25 100644 --- a/tests/pytests/unit/states/file/test_retention_schedule.py +++ b/tests/pytests/unit/states/file/test_retention_schedule.py @@ -209,16 +209,14 @@ def test_retention_schedule(): } 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/pytests/unit/states/file/test_selinux.py b/tests/pytests/unit/states/file/test_selinux.py index 707f69f4d7f..54a781d4636 100644 --- a/tests/pytests/unit/states/file/test_selinux.py +++ b/tests/pytests/unit/states/file/test_selinux.py @@ -32,7 +32,7 @@ def test_selinux_change(): file_name = "/tmp/some-test-file" check_perms_result = [ { - "comment": "The file {} is set to be changed".format(file_name), + "comment": f"The file {file_name} is set to be changed", "changes": { "selinux": { "New": "User: unconfined_u Type: lost_found_t", diff --git a/tests/pytests/unit/states/file/test_symlink.py b/tests/pytests/unit/states/file/test_symlink.py index da2e0b7adc3..4b05b1521bb 100644 --- a/tests/pytests/unit/states/file/test_symlink.py +++ b/tests/pytests/unit/states/file/test_symlink.py @@ -91,7 +91,7 @@ def test_symlink(): }, ): if salt.utils.platform.is_windows(): - comt = "User {} does not exist".format(user) + comt = f"User {user} does not exist" ret = return_val({"comment": comt, "name": name}) else: comt = "User {} does not exist. Group {} does not exist.".format( @@ -114,12 +114,12 @@ def test_symlink(): os.path, "exists", mock_f ): if salt.utils.platform.is_windows(): - comt = "User {} does not exist".format(user) + comt = f"User {user} does not exist" ret = return_val( {"comment": comt, "result": False, "name": name, "changes": {}} ) else: - comt = "Symlink {} to {} is set for creation".format(name, target) + comt = f"Symlink {name} to {target} is set for creation" ret = return_val( {"comment": comt, "result": None, "changes": {"new": name}} ) @@ -141,12 +141,12 @@ def test_symlink(): os.path, "exists", mock_f ): if salt.utils.platform.is_windows(): - comt = "User {} does not exist".format(user) + comt = f"User {user} does not exist" ret = return_val( {"comment": comt, "result": False, "name": name, "changes": {}} ) else: - comt = "Directory {} for symlink is not present".format(test_dir) + comt = f"Directory {test_dir} for symlink is not present" ret = return_val({"comment": comt, "result": False, "changes": {}}) assert filestate.symlink(name, target, user=user, group=group) == ret @@ -169,9 +169,9 @@ def test_symlink(): "salt.utils.win_functions.get_sid_from_name", return_value="test-sid" ): if salt.utils.platform.is_windows(): - comt = "Symlink {} is present and owned by {}".format(name, user) + comt = f"Symlink {name} is present and owned by {user}" else: - comt = "Symlink {} is present and owned by {}:{}".format(name, user, group) + comt = f"Symlink {name} is present and owned by {user}:{group}" ret = return_val({"comment": comt, "result": True, "changes": {}}) assert filestate.symlink(name, target, user=user, group=group) == ret @@ -256,7 +256,7 @@ def test_symlink(): ), patch( "salt.utils.win_functions.get_sid_from_name", return_value="test-sid" ): - comt = "File exists where the symlink {} should be".format(name) + comt = f"File exists where the symlink {name} should be" ret = return_val({"comment": comt, "changes": {}, "result": False}) assert filestate.symlink(name, target, user=user, group=group) == ret @@ -281,7 +281,7 @@ def test_symlink(): ), patch( "salt.utils.win_functions.get_sid_from_name", return_value="test-sid" ): - comt = "Directory exists where the symlink {} should be".format(name) + comt = f"Directory exists where the symlink {name} should be" ret = return_val({"comment": comt, "result": False, "changes": {}}) assert filestate.symlink(name, target, user=user, group=group) == ret @@ -304,7 +304,7 @@ def test_symlink(): ), patch( "salt.utils.win_functions.get_sid_from_name", return_value="test-sid" ): - comt = "Unable to create new symlink {} -> {}: ".format(name, target) + comt = f"Unable to create new symlink {name} -> {target}: " ret = return_val({"comment": comt, "result": False, "changes": {}}) assert filestate.symlink(name, target, user=user, group=group) == ret @@ -331,7 +331,7 @@ def test_symlink(): ), patch( "salt.utils.win_functions.get_sid_from_name", return_value="test-sid" ): - comt = "Created new symlink {} -> {}".format(name, target) + comt = f"Created new symlink {name} -> {target}" ret = return_val({"comment": comt, "result": True, "changes": {"new": name}}) assert filestate.symlink(name, target, user=user, group=group) == ret @@ -392,7 +392,7 @@ def test_symlink(): ), patch( "salt.states.file._check_symlink_ownership", return_value=True ): - comt = "Created new symlink {} -> {}".format(name, target) + comt = f"Created new symlink {name} -> {target}" ret = return_val({"comment": comt, "result": True, "changes": {"new": name}}) res = filestate.symlink(name, target, user=user, group=user) assert res == ret @@ -423,9 +423,9 @@ def test_symlink(): "salt.states.file._get_symlink_ownership", return_value=(user, group) ): if salt.utils.platform.is_windows(): - comt = "Symlink {} is present and owned by {}".format(name, user) + comt = f"Symlink {name} is present and owned by {user}" else: - comt = "Symlink {} is present and owned by {}:{}".format(name, user, group) + comt = f"Symlink {name} is present and owned by {user}:{group}" ret = return_val({"comment": comt, "result": True, "changes": {}}) res = filestate.symlink(name, target, inherit_user_and_group=True) assert res == ret diff --git a/tests/pytests/unit/states/file/test_tidied.py b/tests/pytests/unit/states/file/test_tidied.py index e31e33293e6..0139cd3ac76 100644 --- a/tests/pytests/unit/states/file/test_tidied.py +++ b/tests/pytests/unit/states/file/test_tidied.py @@ -76,7 +76,7 @@ def test__tidied(): ] }, "result": True, - "comment": "Removed 3 files or directories from directory {}".format(name), + "comment": f"Removed 3 files or directories from directory {name}", } assert ret == exp assert remove.call_count == 3 @@ -107,7 +107,7 @@ def test__tidied(): ] }, "result": True, - "comment": "Removed 6 files or directories from directory {}".format(name), + "comment": f"Removed 6 files or directories from directory {name}", } assert ret == exp assert remove.call_count == 6 @@ -192,7 +192,7 @@ def test_tidied_with_exclude(): ] }, "result": True, - "comment": "Removed 2 files or directories from directory {}".format(name), + "comment": f"Removed 2 files or directories from directory {name}", } assert ret == exp assert remove.call_count == 2 @@ -220,7 +220,7 @@ def test_tidied_with_exclude(): ] }, "result": True, - "comment": "Removed 5 files or directories from directory {}".format(name), + "comment": f"Removed 5 files or directories from directory {name}", } assert ret == exp assert remove.call_count == 5 @@ -256,7 +256,7 @@ def test_tidied_with_exclude(): ] }, "result": True, - "comment": "Removed 6 files or directories from directory {}".format(name), + "comment": f"Removed 6 files or directories from directory {name}", } assert ret == exp assert remove.call_count == 6 @@ -328,7 +328,7 @@ def test_tidied_with_full_path_exclude(): ] }, "result": True, - "comment": "Removed 2 files or directories from directory {}".format(name), + "comment": f"Removed 2 files or directories from directory {name}", } assert ret == exp assert remove.call_count == 2 @@ -361,7 +361,7 @@ def test_tidied_with_full_path_exclude(): ] }, "result": True, - "comment": "Removed 5 files or directories from directory {}".format(name), + "comment": f"Removed 5 files or directories from directory {name}", } assert ret == exp assert remove.call_count == 5 @@ -395,7 +395,7 @@ def test_tidied_with_full_path_exclude(): ] }, "result": True, - "comment": "Removed 6 files or directories from directory {}".format(name), + "comment": f"Removed 6 files or directories from directory {name}", } assert ret == exp assert remove.call_count == 6 @@ -436,7 +436,7 @@ def test_tidied_age_size_args_AND_operator_age_not_size(): "name": name, "changes": {}, "result": True, - "comment": "Nothing to remove from directory {}".format(name), + "comment": f"Nothing to remove from directory {name}", } assert ret == exp assert remove.call_count == 0 @@ -500,7 +500,7 @@ def test_tidied_age_size_args_AND_operator_age_not_size_age_only(): ] }, "result": True, - "comment": "Removed 3 files or directories from directory {}".format(name), + "comment": f"Removed 3 files or directories from directory {name}", } assert ret == exp assert remove.call_count == 3 @@ -541,7 +541,7 @@ def test_tidied_age_size_args_AND_operator_size_not_age(): "name": name, "changes": {}, "result": True, - "comment": "Nothing to remove from directory {}".format(name), + "comment": f"Nothing to remove from directory {name}", } assert ret == exp assert remove.call_count == 0 @@ -605,7 +605,7 @@ def test_tidied_age_size_args_AND_operator_size_not_age_size_only(): ] }, "result": True, - "comment": "Removed 3 files or directories from directory {}".format(name), + "comment": f"Removed 3 files or directories from directory {name}", } assert ret == exp assert remove.call_count == 3 @@ -669,7 +669,7 @@ def test_tidied_age_size_args_AND_operator_size_and_age(): ] }, "result": True, - "comment": "Removed 3 files or directories from directory {}".format(name), + "comment": f"Removed 3 files or directories from directory {name}", } assert ret == exp assert remove.call_count == 3 @@ -698,7 +698,7 @@ def test_tidied_filenotfound(tmp_path): "name": name, "changes": {}, "result": True, - "comment": "Nothing to remove from directory {}".format(name), + "comment": f"Nothing to remove from directory {name}", } assert ret == exp @@ -764,7 +764,7 @@ def test_tidied_rmlinks(): ] }, "result": True, - "comment": "Removed 2 files or directories from directory {}".format(name), + "comment": f"Removed 2 files or directories from directory {name}", } assert ret == exp assert remove.call_count == 2 diff --git a/tests/pytests/unit/states/mysql/test_database.py b/tests/pytests/unit/states/mysql/test_database.py index 4176d85fb88..d9a76f6d281 100644 --- a/tests/pytests/unit/states/mysql/test_database.py +++ b/tests/pytests/unit/states/mysql/test_database.py @@ -1,6 +1,7 @@ """ This test checks mysql_database salt state """ + import pytest import salt.states.mysql_database as mysql_database @@ -48,7 +49,7 @@ def test_present(): "Database character set {} != {} needs to be updated".format( mod_charset, charset ), - "Database {} is going to be updated".format(dbname), + f"Database {dbname} is going to be updated", ] ret.update({"comment": "\n".join(comt)}) ret.update({"result": None}) @@ -56,7 +57,7 @@ def test_present(): with patch.dict(mysql_database.__opts__, {"test": True}): comt = [ - "Database {} is already present".format(dbname), + f"Database {dbname} is already present", "Database collate {} != {} needs to be updated".format( mod_collate, collate ), @@ -89,7 +90,7 @@ def test_present(): ) with patch.dict(mysql_database.__opts__, {"test": False}): - comt = "Database {} is already present".format(dbname) + comt = f"Database {dbname} is already present" ret.update({"comment": comt}) ret.update({"result": True}) assert ( @@ -104,7 +105,7 @@ def test_present(): assert mysql_database.present(dbname) == ret with patch.object(mysql_database, "_get_mysql_error", mock_no_err): - comt = "The database {} has been created".format(dbname) + comt = f"The database {dbname} has been created" ret.update({"comment": comt, "result": True}) ret.update({"changes": {dbname: "Present"}}) @@ -116,7 +117,7 @@ def test_present(): ret["comment"] = "" with patch.object(mysql_database, "_get_mysql_error", mock_no_err): ret.update({"changes": {}}) - comt = "Failed to create database {}".format(dbname) + comt = f"Failed to create database {dbname}" ret.update({"comment": comt, "result": False}) assert mysql_database.present(dbname) == ret @@ -139,12 +140,12 @@ def test_absent(): {"mysql.db_exists": mock_db_exists, "mysql.db_remove": mock_remove}, ): with patch.dict(mysql_database.__opts__, {"test": True}): - comt = "Database {} is present and needs to be removed".format(dbname) + comt = f"Database {dbname} is present and needs to be removed" ret.update({"comment": comt, "result": None}) assert mysql_database.absent(dbname) == ret with patch.dict(mysql_database.__opts__, {}): - comt = "Database {} has been removed".format(dbname) + comt = f"Database {dbname} has been removed" ret.update({"comment": comt, "result": True}) ret.update({"changes": {dbname: "Absent"}}) assert mysql_database.absent(dbname) == ret diff --git a/tests/pytests/unit/states/mysql/test_query.py b/tests/pytests/unit/states/mysql/test_query.py index 1859afa3b2d..345774923b7 100644 --- a/tests/pytests/unit/states/mysql/test_query.py +++ b/tests/pytests/unit/states/mysql/test_query.py @@ -58,7 +58,7 @@ def test_run(): assert mysql_query.run(name, database, query) == ret with patch.object(mysql_query, "_get_mysql_error", mock_none): - comt = "Database {} is not present".format(name) + comt = f"Database {name} is not present" ret.update({"comment": comt, "result": None}) assert mysql_query.run(name, database, query) == ret diff --git a/tests/pytests/unit/states/postgresql/test_cluster.py b/tests/pytests/unit/states/postgresql/test_cluster.py index 52e9f087131..b816d0861d7 100644 --- a/tests/pytests/unit/states/postgresql/test_cluster.py +++ b/tests/pytests/unit/states/postgresql/test_cluster.py @@ -25,7 +25,7 @@ def test_present(): mock_t = MagicMock(return_value=True) mock_f = MagicMock(return_value=False) - infos = {"{}/{}".format(version, name): {}} + infos = {f"{version}/{name}": {}} mock = MagicMock(return_value=infos) with patch.dict( postgres_cluster.__salt__, @@ -35,17 +35,17 @@ def test_present(): "postgres.cluster_create": mock_t, }, ): - comt = "Cluster {}/{} is already present".format(version, name) + comt = f"Cluster {version}/{name} is already present" ret.update({"comment": comt, "result": True}) assert postgres_cluster.present(version, name) == ret - infos["{}/{}".format(version, name)]["port"] = 5433 + infos[f"{version}/{name}"]["port"] = 5433 comt = ( "Cluster {}/{} has wrong parameters " "which couldn't be changed on fly.".format(version, name) ) ret.update({"comment": comt, "result": False}) assert postgres_cluster.present(version, name, port=5434) == ret - infos["{}/{}".format(version, name)]["datadir"] = "/tmp/" + infos[f"{version}/{name}"]["datadir"] = "/tmp/" comt = ( "Cluster {}/{} has wrong parameters " "which couldn't be changed on fly.".format(version, name) @@ -61,17 +61,17 @@ def test_present(): "postgres.cluster_create": mock_t, }, ): - comt = "The cluster {}/{} has been created".format(version, name) + comt = f"The cluster {version}/{name} has been created" ret.update( { "comment": comt, "result": True, - "changes": {"{}/{}".format(version, name): "Present"}, + "changes": {f"{version}/{name}": "Present"}, } ) assert postgres_cluster.present(version, name) == ret with patch.dict(postgres_cluster.__opts__, {"test": True}): - comt = "Cluster {}/{} is set to be created".format(version, name) + comt = f"Cluster {version}/{name} is set to be created" ret.update({"comment": comt, "result": None, "changes": {}}) assert postgres_cluster.present(version, name) == ret @@ -83,7 +83,7 @@ def test_present(): "postgres.cluster_create": mock_f, }, ): - comt = "Failed to create cluster {}/{}".format(version, name) + comt = f"Failed to create cluster {version}/{name}" ret.update({"comment": comt, "result": False}) assert postgres_cluster.present(version, name) == ret @@ -104,12 +104,12 @@ def test_absent(): {"postgres.cluster_exists": mock, "postgres.cluster_remove": mock_t}, ): with patch.dict(postgres_cluster.__opts__, {"test": True}): - comt = "Cluster {}/{} is set to be removed".format(version, name) + comt = f"Cluster {version}/{name} is set to be removed" ret.update({"comment": comt, "result": None}) assert postgres_cluster.absent(version, name) == ret with patch.dict(postgres_cluster.__opts__, {"test": False}): - comt = "Cluster {}/{} has been removed".format(version, name) + comt = f"Cluster {version}/{name} has been removed" ret.update({"comment": comt, "result": True, "changes": {name: "Absent"}}) assert postgres_cluster.absent(version, name) == ret diff --git a/tests/pytests/unit/states/postgresql/test_database.py b/tests/pytests/unit/states/postgresql/test_database.py index 1e50574cad2..cb8b4c009c9 100644 --- a/tests/pytests/unit/states/postgresql/test_database.py +++ b/tests/pytests/unit/states/postgresql/test_database.py @@ -28,7 +28,7 @@ def test_present(): postgres_database.__salt__, {"postgres.db_list": mock, "postgres.db_alter": mock_t}, ): - comt = "Database {} is already present".format(name) + comt = f"Database {name} is already present" ret.update({"comment": comt, "result": True}) assert postgres_database.present(name) == ret @@ -68,15 +68,15 @@ def test_absent(): {"postgres.db_exists": mock, "postgres.db_remove": mock_t}, ): with patch.dict(postgres_database.__opts__, {"test": True}): - comt = "Database {} is set to be removed".format(name) + comt = f"Database {name} is set to be removed" ret.update({"comment": comt, "result": None}) assert postgres_database.absent(name) == ret with patch.dict(postgres_database.__opts__, {"test": False}): - comt = "Database {} has been removed".format(name) + comt = f"Database {name} has been removed" ret.update({"comment": comt, "result": True, "changes": {name: "Absent"}}) assert postgres_database.absent(name) == ret - comt = "Database {} is not present, so it cannot be removed".format(name) + comt = f"Database {name} is not present, so it cannot be removed" ret.update({"comment": comt, "result": True, "changes": {}}) assert postgres_database.absent(name) == ret diff --git a/tests/pytests/unit/states/postgresql/test_initdb.py b/tests/pytests/unit/states/postgresql/test_initdb.py index aee445743f3..f9f9d1e8f0e 100644 --- a/tests/pytests/unit/states/postgresql/test_initdb.py +++ b/tests/pytests/unit/states/postgresql/test_initdb.py @@ -21,7 +21,7 @@ def test_present_existing(): ret = {"name": name, "changes": {}, "result": False, "comment": ""} mock_true = MagicMock(return_value=True) with patch.dict(postgres_initdb.__salt__, {"postgres.datadir_exists": mock_true}): - _comt = "Postgres data directory {} is already present".format(name) + _comt = f"Postgres data directory {name} is already present" ret.update({"comment": _comt, "result": True}) assert postgres_initdb.present(name) == ret @@ -39,12 +39,12 @@ def test_present_non_existing_pass(): {"postgres.datadir_exists": mock_false, "postgres.datadir_init": mock_true}, ): with patch.dict(postgres_initdb.__opts__, {"test": True}): - _comt = "Postgres data directory {} is set to be initialized".format(name) + _comt = f"Postgres data directory {name} is set to be initialized" ret.update({"comment": _comt, "result": None}) assert postgres_initdb.present(name) == ret with patch.dict(postgres_initdb.__opts__, {"test": False}): - _comt = "Postgres data directory {} has been initialized".format(name) + _comt = f"Postgres data directory {name} has been initialized" _changes = {name: "Present"} ret.update({"comment": _comt, "result": True, "changes": _changes}) assert postgres_initdb.present(name) == ret @@ -62,6 +62,6 @@ def test_present_non_existing_fail(): {"postgres.datadir_exists": mock_false, "postgres.datadir_init": mock_false}, ): with patch.dict(postgres_initdb.__opts__, {"test": False}): - _comt = "Postgres data directory {} initialization failed".format(name) + _comt = f"Postgres data directory {name} initialization failed" ret.update({"comment": _comt, "result": False}) assert postgres_initdb.present(name) == ret diff --git a/tests/pytests/unit/states/postgresql/test_language.py b/tests/pytests/unit/states/postgresql/test_language.py index f8a1fa0dbd3..cdc88bd01b8 100644 --- a/tests/pytests/unit/states/postgresql/test_language.py +++ b/tests/pytests/unit/states/postgresql/test_language.py @@ -24,7 +24,7 @@ def test_present_existing(): postgres_language.__salt__, {"postgres.language_list": mock_language_list}, ): - comt = "Language {} is already installed".format(name) + comt = f"Language {name} is already installed" ret.update({"comment": comt, "result": True}) assert postgres_language.present(name, "testdb") == ret @@ -45,12 +45,12 @@ def test_present_non_existing_pass(): }, ): with patch.dict(postgres_language.__opts__, {"test": True}): - comt = "Language {} is set to be installed".format(name) + comt = f"Language {name} is set to be installed" ret.update({"comment": comt, "result": None}) assert postgres_language.present(name, "testdb") == ret with patch.dict(postgres_language.__opts__, {"test": False}): - comt = "Language {} has been installed".format(name) + comt = f"Language {name} has been installed" ret.update( {"comment": comt, "result": True, "changes": {"plpgsql": "Present"}} ) @@ -73,12 +73,12 @@ def test_present_non_existing_fail(): }, ): with patch.dict(postgres_language.__opts__, {"test": True}): - comt = "Language {} is set to be installed".format(name) + comt = f"Language {name} is set to be installed" ret.update({"comment": comt, "result": None}) assert postgres_language.present(name, "testdb") == ret with patch.dict(postgres_language.__opts__, {"test": False}): - comt = "Failed to install language {}".format(name) + comt = f"Failed to install language {name}" ret.update({"comment": comt, "result": False}) assert postgres_language.present(name, "testdb") == ret @@ -95,12 +95,12 @@ def test_absent_existing(): {"postgres.language_exists": mock_true, "postgres.language_remove": mock_true}, ): with patch.dict(postgres_language.__opts__, {"test": True}): - comt = "Language {} is set to be removed".format(name) + comt = f"Language {name} is set to be removed" ret.update({"comment": comt, "result": None}) assert postgres_language.absent(name, "testdb") == ret with patch.dict(postgres_language.__opts__, {"test": False}): - comt = "Language {} has been removed".format(name) + comt = f"Language {name} has been removed" ret.update( {"comment": comt, "result": True, "changes": {"plpgsql": "Absent"}} ) @@ -118,6 +118,6 @@ def test_absent_non_existing(): postgres_language.__salt__, {"postgres.language_exists": mock_false} ): with patch.dict(postgres_language.__opts__, {"test": True}): - comt = "Language {} is not present so it cannot be removed".format(name) + comt = f"Language {name} is not present so it cannot be removed" ret.update({"comment": comt, "result": True}) assert postgres_language.absent(name, "testdb") == ret diff --git a/tests/pytests/unit/states/rabbitmq/test_vhost.py b/tests/pytests/unit/states/rabbitmq/test_vhost.py index d6fc3e624f5..e61d1c8a766 100644 --- a/tests/pytests/unit/states/rabbitmq/test_vhost.py +++ b/tests/pytests/unit/states/rabbitmq/test_vhost.py @@ -48,7 +48,7 @@ def test_absent(): "name": name, "changes": {}, "result": True, - "comment": "Virtual Host '{}' is not present.".format(name), + "comment": f"Virtual Host '{name}' is not present.", } mock = MagicMock(return_value=False) diff --git a/tests/pytests/unit/states/test_alias.py b/tests/pytests/unit/states/test_alias.py index db2afb9e0c4..c9e4473b230 100644 --- a/tests/pytests/unit/states/test_alias.py +++ b/tests/pytests/unit/states/test_alias.py @@ -20,7 +20,7 @@ def test_present_has_target(): name = "saltdude" target = "dude@saltstack.com" ret = { - "comment": "Alias {} already present".format(name), + "comment": f"Alias {name} already present", "changes": {}, "name": name, "result": True, @@ -38,7 +38,7 @@ def test_present_has_not_target_test(): name = "saltdude" target = "dude@saltstack.com" ret = { - "comment": "Alias {} -> {} is set to be added".format(name, target), + "comment": f"Alias {name} -> {target} is set to be added", "changes": {}, "name": name, "result": None, @@ -57,7 +57,7 @@ def test_present_set_target(): name = "saltdude" target = "dude@saltstack.com" ret = { - "comment": "Set email alias {} -> {}".format(name, target), + "comment": f"Set email alias {name} -> {target}", "changes": {"alias": name}, "name": name, "result": True, @@ -78,7 +78,7 @@ def test_present_set_target_failed(): name = "saltdude" target = "dude@saltstack.com" ret = { - "comment": "Failed to set alias {} -> {}".format(name, target), + "comment": f"Failed to set alias {name} -> {target}", "changes": {}, "name": name, "result": False, @@ -98,7 +98,7 @@ def test_absent_already_gone(): """ name = "saltdude" ret = { - "comment": "Alias {} already absent".format(name), + "comment": f"Alias {name} already absent", "changes": {}, "name": name, "result": True, @@ -115,7 +115,7 @@ def test_absent_not_gone_test(): """ name = "saltdude" ret = { - "comment": "Alias {} is set to be removed".format(name), + "comment": f"Alias {name} is set to be removed", "changes": {}, "name": name, "result": None, @@ -133,7 +133,7 @@ def test_absent_rm_alias(): """ name = "saltdude" ret = { - "comment": "Removed alias {}".format(name), + "comment": f"Removed alias {name}", "changes": {"alias": name}, "name": name, "result": True, @@ -153,7 +153,7 @@ def test_absent_rm_alias_failed(): """ name = "saltdude" ret = { - "comment": "Failed to remove alias {}".format(name), + "comment": f"Failed to remove alias {name}", "changes": {}, "name": name, "result": False, diff --git a/tests/pytests/unit/states/test_alternatives.py b/tests/pytests/unit/states/test_alternatives.py index 9dbdd8b04f5..958e923af6c 100644 --- a/tests/pytests/unit/states/test_alternatives.py +++ b/tests/pytests/unit/states/test_alternatives.py @@ -36,7 +36,7 @@ def test_install(): } bad_link = "/bin/pager" - err = "the primary link for {} must be {}".format(name, link) + err = f"the primary link for {name} must be {link}" mock_cinst = MagicMock(side_effect=[True, False]) mock_cexist = MagicMock( @@ -55,7 +55,7 @@ def test_install(): "alternatives.show_link": mock_link, }, ): - comt = "Alternative {} for {} is already registered".format(path, name) + comt = f"Alternative {path} for {name} is already registered" ret.update({"comment": comt, "result": True}) assert alternatives.install(name, link, path, priority) == ret @@ -84,7 +84,7 @@ def test_install(): with patch.dict(alternatives.__opts__, {"test": False}): assert alternatives.install(name, link, path, priority) == ret - comt = "Alternative for {} not installed: {}".format(name, err) + comt = f"Alternative for {name} not installed: {err}" ret.update({"comment": comt, "result": False, "changes": {}, "link": bad_link}) with patch.dict(alternatives.__opts__, {"test": False}): assert alternatives.install(name, bad_link, path, priority) == ret @@ -133,12 +133,12 @@ def test_remove(): "alternatives.remove": mock_bool, }, ): - comt = "Alternative for {} will be removed".format(name) + comt = f"Alternative for {name} will be removed" ret.update({"comment": comt}) with patch.dict(alternatives.__opts__, {"test": True}): assert alternatives.remove(name, path) == ret - comt = "Alternative for {} removed".format(name) + comt = f"Alternative for {name} removed" ret.update({"comment": comt, "result": True}) with patch.dict(alternatives.__opts__, {"test": False}): assert alternatives.remove(name, path) == ret @@ -148,11 +148,11 @@ def test_remove(): with patch.dict(alternatives.__opts__, {"test": False}): assert alternatives.remove(name, path) == ret - comt = "Alternative for {} is set to it's default path True".format(name) + comt = f"Alternative for {name} is set to it's default path True" ret.update({"comment": comt, "result": True, "changes": {}}) assert alternatives.remove(name, path) == ret - comt = "Alternative for {} doesn't exist".format(name) + comt = f"Alternative for {name} doesn't exist" ret.update({"comment": comt, "result": False}) assert alternatives.remove(name, path) == ret @@ -175,11 +175,11 @@ def test_auto(): alternatives.__salt__, {"alternatives.display": mock, "alternatives.auto": mock_auto}, ): - comt = "{} already in auto mode".format(name) + comt = f"{name} already in auto mode" ret.update({"comment": comt}) assert alternatives.auto(name) == ret - comt = "{} will be put in auto mode".format(name) + comt = f"{name} will be put in auto mode" ret.update({"comment": comt, "result": None}) with patch.dict(alternatives.__opts__, {"test": True}): assert alternatives.auto(name) == ret @@ -213,20 +213,20 @@ def test_set(): "alternatives.set": mock_bool, }, ): - comt = "Alternative for {} already set to {}".format(name, path) + comt = f"Alternative for {name} already set to {path}" ret.update({"comment": comt}) assert alternatives.set_(name, path) == ret - comt = "Alternative for {} will be set to path /usr/bin/less".format(name) + comt = f"Alternative for {name} will be set to path /usr/bin/less" ret.update({"comment": comt, "result": None}) with patch.dict(alternatives.__opts__, {"test": True}): assert alternatives.set_(name, path) == ret - comt = "Alternative for {} not updated".format(name) + comt = f"Alternative for {name} not updated" ret.update({"comment": comt, "result": True}) with patch.dict(alternatives.__opts__, {"test": False}): assert alternatives.set_(name, path) == ret - comt = "Alternative {} for {} doesn't exist".format(path, name) + comt = f"Alternative {path} for {name} doesn't exist" ret.update({"comment": comt, "result": False}) assert alternatives.set_(name, path) == ret diff --git a/tests/pytests/unit/states/test_aptpkg.py b/tests/pytests/unit/states/test_aptpkg.py index fb36e377800..799a0c4ff92 100644 --- a/tests/pytests/unit/states/test_aptpkg.py +++ b/tests/pytests/unit/states/test_aptpkg.py @@ -2,7 +2,6 @@ :codeauthor: Jayesh Kariya """ - import pytest import salt.states.aptpkg as aptpkg @@ -24,7 +23,7 @@ def test_held(): "name": name, "result": False, "changes": {}, - "comment": "Package {} does not have a state".format(name), + "comment": f"Package {name} does not have a state", } mock = MagicMock(return_value=False) diff --git a/tests/pytests/unit/states/test_archive.py b/tests/pytests/unit/states/test_archive.py index 178f00b83a1..b5350bc2dba 100644 --- a/tests/pytests/unit/states/test_archive.py +++ b/tests/pytests/unit/states/test_archive.py @@ -2,7 +2,6 @@ :codeauthor: Alexander Schwartz """ - import os import pytest @@ -305,7 +304,7 @@ def test_extracted_when_if_missing_path_exists(): with patch.object(os.path, "exists", MagicMock(return_value=True)): ret = archive.extracted(name, source=source, if_missing=if_missing) assert ret["result"], ret - assert ret["comment"] == "Path {} exists".format(if_missing) + assert ret["comment"] == f"Path {if_missing} exists" def test_clean_parent_conflict(): @@ -453,7 +452,7 @@ def test_skip_files_list_verify_success(): } mock_true = MagicMock(return_value=True) mock_false = MagicMock(return_value=False) - mock_cached = MagicMock(return_value="{}/{}".format(tmp_dir, source)) + mock_cached = MagicMock(return_value=f"{tmp_dir}/{source}") source_sum = {"hsum": "testhash", "hash_type": "sha256"} mock_hash = MagicMock(return_value=source_sum) mock_source_list = MagicMock(return_value=(source, None)) diff --git a/tests/pytests/unit/states/test_at.py b/tests/pytests/unit/states/test_at.py index 21f91bd5345..bf632e46601 100644 --- a/tests/pytests/unit/states/test_at.py +++ b/tests/pytests/unit/states/test_at.py @@ -60,7 +60,7 @@ def test_present(): { "result": False, "changes": {}, - "comment": "user {} does not exists".format(user), + "comment": f"user {user} does not exists", } ) @@ -134,7 +134,7 @@ def test_absent(): { "result": False, "changes": {}, - "comment": "limit parameter not supported {}".format(name), + "comment": f"limit parameter not supported {name}", } ) assert at.absent(name, limit="all") == ret_limit diff --git a/tests/pytests/unit/states/test_aws_sqs.py b/tests/pytests/unit/states/test_aws_sqs.py index dd132c88420..4a1dde198f0 100644 --- a/tests/pytests/unit/states/test_aws_sqs.py +++ b/tests/pytests/unit/states/test_aws_sqs.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import pytest import salt.states.aws_sqs as aws_sqs @@ -23,12 +24,12 @@ def test_exists(): mock = MagicMock(side_effect=[False, True]) with patch.dict(aws_sqs.__salt__, {"aws_sqs.queue_exists": mock}): - comt = "AWS SQS queue {} is set to be created".format(name) + comt = f"AWS SQS queue {name} is set to be created" ret.update({"comment": comt}) with patch.dict(aws_sqs.__opts__, {"test": True}): assert aws_sqs.exists(name, region) == ret - comt = "{} exists in {}".format(name, region) + comt = f"{name} exists in {region}" ret.update({"comment": comt, "result": True}) assert aws_sqs.exists(name, region) == ret @@ -44,11 +45,11 @@ def test_absent(): mock = MagicMock(side_effect=[True, False]) with patch.dict(aws_sqs.__salt__, {"aws_sqs.queue_exists": mock}): - comt = "AWS SQS queue {} is set to be removed".format(name) + comt = f"AWS SQS queue {name} is set to be removed" ret.update({"comment": comt}) with patch.dict(aws_sqs.__opts__, {"test": True}): assert aws_sqs.absent(name, region) == ret - comt = "{} does not exist in {}".format(name, region) + comt = f"{name} does not exist in {region}" ret.update({"comment": comt, "result": True}) assert aws_sqs.absent(name, region) == ret diff --git a/tests/pytests/unit/states/test_blockdev.py b/tests/pytests/unit/states/test_blockdev.py index a1eacf2e53b..4fe322cc9f5 100644 --- a/tests/pytests/unit/states/test_blockdev.py +++ b/tests/pytests/unit/states/test_blockdev.py @@ -29,7 +29,7 @@ def test_tuned(): ret.update({"comment": comt}) assert blockdev.tuned(name) == ret - comt = "Changes to {} will be applied ".format(name) + comt = f"Changes to {name} will be applied " with patch.dict(blockdev.__salt__, {"file.is_blkdev": True}): ret.update({"comment": comt, "result": None}) with patch.dict(blockdev.__opts__, {"test": True}): @@ -47,7 +47,7 @@ def test_formatted(): with patch.object( os.path, "exists", MagicMock(side_effect=[False, True, True, True, True]) ): - comt = "{} does not exist".format(name) + comt = f"{name} does not exist" ret.update({"comment": comt}) assert blockdev.formatted(name) == ret @@ -55,7 +55,7 @@ def test_formatted(): # Test state return when block device is already in the correct state with patch.dict(blockdev.__salt__, {"cmd.run": mock_ext4}): - comt = "{} already formatted with ext4".format(name) + comt = f"{name} already formatted with ext4" ret.update({"comment": comt, "result": True}) assert blockdev.formatted(name) == ret @@ -69,7 +69,7 @@ def test_formatted(): with patch.dict( blockdev.__salt__, {"cmd.run": MagicMock(return_value="new-thing")} ): - comt = "Changes to {} will be applied ".format(name) + comt = f"Changes to {name} will be applied " ret.update({"comment": comt, "result": None}) with patch.object(salt.utils.path, "which", MagicMock(return_value=True)): with patch.dict(blockdev.__opts__, {"test": True}): @@ -83,7 +83,7 @@ def test_formatted(): "disk.format": MagicMock(return_value=True), }, ): - comt = "Failed to format {}".format(name) + comt = f"Failed to format {name}" ret.update({"comment": comt, "result": False}) with patch.object(salt.utils.path, "which", MagicMock(return_value=True)): with patch.dict(blockdev.__opts__, {"test": False}): diff --git a/tests/pytests/unit/states/test_boto_cloudfront.py b/tests/pytests/unit/states/test_boto_cloudfront.py index fef82fcda2c..6c3a7405d3f 100644 --- a/tests/pytests/unit/states/test_boto_cloudfront.py +++ b/tests/pytests/unit/states/test_boto_cloudfront.py @@ -1,6 +1,7 @@ """ Unit tests for the boto_cloudfront state module. """ + import copy import textwrap @@ -70,7 +71,7 @@ def test_present_from_scratch(): __salt__={"boto_cloudfront.get_distribution": mock_get}, __opts__={"test": True}, ): - comment = "Distribution {} set for creation.".format(name) + comment = f"Distribution {name} set for creation." assert boto_cloudfront.present(name, config, tags) == base_ret_with( {"result": None, "comment": comment, "changes": {"old": None, "new": name}} ) @@ -184,7 +185,7 @@ def test_present_update_config_and_tags(): __salt__={"boto_cloudfront.get_distribution": mock_get}, __opts__={"test": True}, ): - header = "Distribution {} set for new config:".format(name) + header = f"Distribution {name} set for new config:" assert boto_cloudfront.present(name, config, tags) == base_ret_with( { "result": None, @@ -219,7 +220,7 @@ def test_present_update_config_and_tags(): assert boto_cloudfront.present(name, config, tags) == base_ret_with( { "result": True, - "comment": "Updated distribution {}.".format(name), + "comment": f"Updated distribution {name}.", "changes": {"diff": diff}, } ) diff --git a/tests/pytests/unit/states/test_boto_cloudwatch_alarm.py b/tests/pytests/unit/states/test_boto_cloudwatch_alarm.py index 16c655a1cdf..2102f09a2ed 100644 --- a/tests/pytests/unit/states/test_boto_cloudwatch_alarm.py +++ b/tests/pytests/unit/states/test_boto_cloudwatch_alarm.py @@ -68,7 +68,7 @@ def test_absent(): boto_cloudwatch_alarm.__salt__, {"boto_cloudwatch.get_alarm": mock} ): with patch.dict(boto_cloudwatch_alarm.__opts__, {"test": True}): - comt = "alarm {} is set to be removed.".format(name) + comt = f"alarm {name} is set to be removed." ret.update({"comment": comt}) assert boto_cloudwatch_alarm.absent(name) == ret diff --git a/tests/pytests/unit/states/test_boto_dynamodb.py b/tests/pytests/unit/states/test_boto_dynamodb.py index 2375077b805..94df32d2381 100644 --- a/tests/pytests/unit/states/test_boto_dynamodb.py +++ b/tests/pytests/unit/states/test_boto_dynamodb.py @@ -44,7 +44,7 @@ def test_present(): assert boto_dynamodb.present(name) == ret with patch.dict(boto_dynamodb.__opts__, {"test": True}): - comt = "DynamoDB table {} would be created.".format(name) + comt = f"DynamoDB table {name} would be created." ret.update({"comment": comt, "result": None}) assert boto_dynamodb.present(name) == ret @@ -85,12 +85,12 @@ def test_absent(): boto_dynamodb.__salt__, {"boto_dynamodb.exists": mock, "boto_dynamodb.delete": mock_bool}, ): - comt = "DynamoDB table {} does not exist".format(name) + comt = f"DynamoDB table {name} does not exist" ret.update({"comment": comt}) assert boto_dynamodb.absent(name) == ret with patch.dict(boto_dynamodb.__opts__, {"test": True}): - comt = "DynamoDB table {} is set to be deleted".format(name) + comt = f"DynamoDB table {name} is set to be deleted" ret.update({"comment": comt, "result": None}) assert boto_dynamodb.absent(name) == ret @@ -100,6 +100,6 @@ def test_absent(): } with patch.dict(boto_dynamodb.__opts__, {"test": False}): - comt = "Deleted DynamoDB table {}".format(name) + comt = f"Deleted DynamoDB table {name}" ret.update({"comment": comt, "result": True, "changes": changes}) assert boto_dynamodb.absent(name) == ret diff --git a/tests/pytests/unit/states/test_boto_ec2.py b/tests/pytests/unit/states/test_boto_ec2.py index 6a41900c8d7..9ba763dec85 100644 --- a/tests/pytests/unit/states/test_boto_ec2.py +++ b/tests/pytests/unit/states/test_boto_ec2.py @@ -27,16 +27,16 @@ def test_key_present(): with patch.dict( boto_ec2.__salt__, {"boto_ec2.get_key": mock, "cp.get_file_str": mock_bool} ): - comt = "The key name {} already exists".format(name) + comt = f"The key name {name} already exists" ret.update({"comment": comt}) assert boto_ec2.key_present(name) == ret - comt = "File {} not found.".format(upublic) + comt = f"File {upublic} not found." ret.update({"comment": comt, "result": False}) assert boto_ec2.key_present(name, upload_public=upublic) == ret with patch.dict(boto_ec2.__opts__, {"test": True}): - comt = "The key {} is set to be created.".format(name) + comt = f"The key {name} is set to be created." ret.update({"comment": comt, "result": None}) assert boto_ec2.key_present(name, upload_public=upublic) == ret @@ -51,11 +51,11 @@ def test_key_absent(): mock = MagicMock(side_effect=[False, True]) with patch.dict(boto_ec2.__salt__, {"boto_ec2.get_key": mock}): - comt = "The key name {} does not exist".format(name) + comt = f"The key name {name} does not exist" ret.update({"comment": comt}) assert boto_ec2.key_absent(name) == ret with patch.dict(boto_ec2.__opts__, {"test": True}): - comt = "The key {} is set to be deleted.".format(name) + comt = f"The key {name} is set to be deleted." ret.update({"comment": comt, "result": None}) assert boto_ec2.key_absent(name) == ret diff --git a/tests/pytests/unit/states/test_boto_elasticache.py b/tests/pytests/unit/states/test_boto_elasticache.py index 3692577834c..3b2584cc23c 100644 --- a/tests/pytests/unit/states/test_boto_elasticache.py +++ b/tests/pytests/unit/states/test_boto_elasticache.py @@ -38,16 +38,16 @@ def test_present(): assert boto_elasticache.present(name, engine, cache_node_type) == ret with patch.dict(boto_elasticache.__opts__, {"test": True}): - comt = "Cache cluster {} is set to be created.".format(name) + comt = f"Cache cluster {name} is set to be created." ret.update({"comment": comt}) assert boto_elasticache.present(name, engine, cache_node_type) == ret with patch.dict(boto_elasticache.__opts__, {"test": False}): - comt = "Failed to create {} cache cluster.".format(name) + comt = f"Failed to create {name} cache cluster." ret.update({"comment": comt, "result": False}) assert boto_elasticache.present(name, engine, cache_node_type) == ret - comt = "Cache cluster {} is present.".format(name) + comt = f"Cache cluster {name} is present." ret.update({"comment": comt, "result": True}) assert boto_elasticache.present(name, engine, cache_node_type) == ret @@ -62,12 +62,12 @@ def test_absent(): mock = MagicMock(side_effect=[False, True]) with patch.dict(boto_elasticache.__salt__, {"boto_elasticache.exists": mock}): - comt = "{} does not exist in None.".format(name) + comt = f"{name} does not exist in None." ret.update({"comment": comt}) assert boto_elasticache.absent(name) == ret with patch.dict(boto_elasticache.__opts__, {"test": True}): - comt = "Cache cluster {} is set to be removed.".format(name) + comt = f"Cache cluster {name} is set to be removed." ret.update({"comment": comt, "result": None}) assert boto_elasticache.absent(name) == ret @@ -84,7 +84,7 @@ def test_creategroup(): mock = MagicMock(return_value=True) with patch.dict(boto_elasticache.__salt__, {"boto_elasticache.group_exists": mock}): - comt = "{} replication group exists .".format(name) + comt = f"{name} replication group exists ." ret.update({"comment": comt}) assert ( boto_elasticache.creategroup( diff --git a/tests/pytests/unit/states/test_boto_elb.py b/tests/pytests/unit/states/test_boto_elb.py index 08699d796fe..216352bb8ec 100644 --- a/tests/pytests/unit/states/test_boto_elb.py +++ b/tests/pytests/unit/states/test_boto_elb.py @@ -151,7 +151,7 @@ def test_register_instances(): mock_bool = MagicMock(return_value=False) with patch.dict(boto_elb.__salt__, {"boto_elb.exists": mock_bool}): - comt = "Could not find lb {}".format(name) + comt = f"Could not find lb {name}" ret.update({"comment": comt}) assert boto_elb.register_instances(name, instances) == ret @@ -166,11 +166,11 @@ def test_absent(): mock = MagicMock(side_effect=[False, True]) with patch.dict(boto_elb.__salt__, {"boto_elb.exists": mock}): - comt = "{} ELB does not exist.".format(name) + comt = f"{name} ELB does not exist." ret.update({"comment": comt}) assert boto_elb.absent(name) == ret with patch.dict(boto_elb.__opts__, {"test": True}): - comt = "ELB {} is set to be removed.".format(name) + comt = f"ELB {name} is set to be removed." ret.update({"comment": comt, "result": None}) assert boto_elb.absent(name) == ret diff --git a/tests/pytests/unit/states/test_boto_iam_role.py b/tests/pytests/unit/states/test_boto_iam_role.py index 0a577e56978..3d342f80df3 100644 --- a/tests/pytests/unit/states/test_boto_iam_role.py +++ b/tests/pytests/unit/states/test_boto_iam_role.py @@ -91,7 +91,7 @@ def test_present(): }, ): with patch.dict(boto_iam_role.__opts__, {"test": False}): - comt = " Failed to create {} IAM role.".format(name) + comt = f" Failed to create {name} IAM role." ret.update({"comment": comt}) assert boto_iam_role.present(name) == ret diff --git a/tests/pytests/unit/states/test_boto_kinesis.py b/tests/pytests/unit/states/test_boto_kinesis.py index 2c3c9491ad8..af2b345830a 100644 --- a/tests/pytests/unit/states/test_boto_kinesis.py +++ b/tests/pytests/unit/states/test_boto_kinesis.py @@ -79,7 +79,7 @@ def test_stream_present(): with patch.dict(boto_kinesis.__opts__, {"test": True}): # not present, test environment (dry run) - comt = "Kinesis stream {} would be created".format(name) + comt = f"Kinesis stream {name} would be created" ret.update({"comment": comt, "result": None}) assert ( boto_kinesis.present( @@ -149,21 +149,21 @@ def test_absent(): boto_kinesis.__salt__, {"boto_kinesis.exists": mock, "boto_kinesis.delete_stream": mock_bool}, ): - comt = "Kinesis stream {} does not exist".format(name) + comt = f"Kinesis stream {name} does not exist" ret.update({"comment": comt}) assert boto_kinesis.absent(name) == ret with patch.dict(boto_kinesis.__opts__, {"test": True}): - comt = "Kinesis stream {} would be deleted".format(name) + comt = f"Kinesis stream {name} would be deleted" ret.update({"comment": comt, "result": None}) assert boto_kinesis.absent(name) == ret changes = { - "new": "Stream {} deleted".format(name), - "old": "Stream {} exists".format(name), + "new": f"Stream {name} deleted", + "old": f"Stream {name} exists", } with patch.dict(boto_kinesis.__opts__, {"test": False}): - comt = "Deleted stream {}".format(name) + comt = f"Deleted stream {name}" ret.update({"comment": comt, "result": True, "changes": changes}) assert boto_kinesis.absent(name) == ret diff --git a/tests/pytests/unit/states/test_boto_lc.py b/tests/pytests/unit/states/test_boto_lc.py index ab44a58f586..604af3bd6a7 100644 --- a/tests/pytests/unit/states/test_boto_lc.py +++ b/tests/pytests/unit/states/test_boto_lc.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import pytest import salt.states.boto_lc as boto_lc diff --git a/tests/pytests/unit/states/test_boto_route53.py b/tests/pytests/unit/states/test_boto_route53.py index 7d0f125223b..d46b94a29ca 100644 --- a/tests/pytests/unit/states/test_boto_route53.py +++ b/tests/pytests/unit/states/test_boto_route53.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import pytest import salt.modules.boto_route53 as boto53mod @@ -71,16 +72,16 @@ def test_present(): {"boto_route53.get_record": mock, "boto_route53.add_record": mock_bool}, ): with patch.dict(boto_route53.__opts__, {"test": False}): - comt = "Failed to add {} Route53 record.".format(name) + comt = f"Failed to add {name} Route53 record." ret.update({"comment": comt}) assert boto_route53.present(name, value, zone, record_type) == ret with patch.dict(boto_route53.__opts__, {"test": True}): - comt = "Route53 record {} set to be added.".format(name) + comt = f"Route53 record {name} set to be added." ret.update({"comment": comt, "result": None}) assert boto_route53.present(name, value, zone, record_type) == ret - comt = "Route53 record {} set to be updated.".format(name) + comt = f"Route53 record {name} set to be updated." ret.update({"comment": comt}) assert boto_route53.present(name, value, zone, record_type) == ret @@ -100,12 +101,12 @@ def test_absent(): mock = MagicMock(side_effect=[False, True]) with patch.dict(boto_route53.__salt__, {"boto_route53.get_record": mock}): - comt = "{} does not exist.".format(name) + comt = f"{name} does not exist." ret.update({"comment": comt}) assert boto_route53.absent(name, zone, record_type) == ret with patch.dict(boto_route53.__opts__, {"test": True}): - comt = "Route53 record {} set to be deleted.".format(name) + comt = f"Route53 record {name} set to be deleted." ret.update({"comment": comt, "result": None}) assert boto_route53.absent(name, zone, record_type) == ret diff --git a/tests/pytests/unit/states/test_boto_sns.py b/tests/pytests/unit/states/test_boto_sns.py index d6fbdcee059..22c994188be 100644 --- a/tests/pytests/unit/states/test_boto_sns.py +++ b/tests/pytests/unit/states/test_boto_sns.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import pytest import salt.states.boto_sns as boto_sns @@ -25,17 +26,17 @@ def test_present(): with patch.dict( boto_sns.__salt__, {"boto_sns.exists": mock, "boto_sns.create": mock_bool} ): - comt = "AWS SNS topic {} present.".format(name) + comt = f"AWS SNS topic {name} present." ret.update({"comment": comt}) assert boto_sns.present(name) == ret with patch.dict(boto_sns.__opts__, {"test": True}): - comt = "AWS SNS topic {} is set to be created.".format(name) + comt = f"AWS SNS topic {name} is set to be created." ret.update({"comment": comt, "result": None}) assert boto_sns.present(name) == ret with patch.dict(boto_sns.__opts__, {"test": False}): - comt = "Failed to create {} AWS SNS topic".format(name) + comt = f"Failed to create {name} AWS SNS topic" ret.update({"comment": comt, "result": False}) assert boto_sns.present(name) == ret @@ -51,7 +52,7 @@ def test_absent(): exists_mock = MagicMock(side_effect=[False, True, True, True, True, True, True]) with patch.dict(boto_sns.__salt__, {"boto_sns.exists": exists_mock}): # tests topic already absent - comt = "AWS SNS topic {} does not exist.".format(name) + comt = f"AWS SNS topic {name} does not exist." ret.update({"comment": comt}) assert boto_sns.absent(name) == ret @@ -98,7 +99,7 @@ def test_absent(): with patch.dict(boto_sns.__salt__, {"boto_sns.delete": delete_mock}): # tests topic present, unsubscribe flag True, unsubscribe succeeded, # delete succeeded - comt = "AWS SNS topic {} deleted.".format(name) + comt = f"AWS SNS topic {name} deleted." ret.update( { "changes": { @@ -136,6 +137,6 @@ def test_absent(): assert boto_sns.absent(name) == ret # tests topic present, unsubscribe flag False, delete failed - comt = "Failed to delete {} AWS SNS topic.".format(name) + comt = f"Failed to delete {name} AWS SNS topic." ret.update({"changes": {}, "result": False, "comment": comt}) assert boto_sns.absent(name) == ret diff --git a/tests/pytests/unit/states/test_boto_sqs.py b/tests/pytests/unit/states/test_boto_sqs.py index 25175463eda..a656c47bee6 100644 --- a/tests/pytests/unit/states/test_boto_sqs.py +++ b/tests/pytests/unit/states/test_boto_sqs.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import textwrap import pytest @@ -53,7 +54,7 @@ def test_present(): assert boto_sqs.present(name) == ret with patch.dict(boto_sqs.__opts__, {"test": True}): - comt = ["SQS queue {} is set to be created.".format(name)] + comt = [f"SQS queue {name} is set to be created."] ret = base_ret.copy() ret.update( { @@ -101,13 +102,13 @@ def test_absent(): mock = MagicMock(side_effect=[{"result": False}, {"result": True}]) with patch.dict(boto_sqs.__salt__, {"boto_sqs.exists": mock}): - comt = "SQS queue {} does not exist in None.".format(name) + comt = f"SQS queue {name} does not exist in None." ret = base_ret.copy() ret.update({"result": True, "comment": comt}) assert boto_sqs.absent(name) == ret with patch.dict(boto_sqs.__opts__, {"test": True}): - comt = "SQS queue {} is set to be removed.".format(name) + comt = f"SQS queue {name} is set to be removed." ret = base_ret.copy() ret.update( { diff --git a/tests/pytests/unit/states/test_bower.py b/tests/pytests/unit/states/test_bower.py index f375f6ab58c..7a019d787b4 100644 --- a/tests/pytests/unit/states/test_bower.py +++ b/tests/pytests/unit/states/test_bower.py @@ -1,6 +1,7 @@ """ :codeauthor: Alexander Pyatkin """ + import pytest import salt.states.bower as bower diff --git a/tests/pytests/unit/states/test_chocolatey.py b/tests/pytests/unit/states/test_chocolatey.py index 5f24d3cb9ae..660ba4b61b2 100644 --- a/tests/pytests/unit/states/test_chocolatey.py +++ b/tests/pytests/unit/states/test_chocolatey.py @@ -1,6 +1,7 @@ """ Unit tests for chocolatey state """ + import logging import pytest diff --git a/tests/pytests/unit/states/test_cloud.py b/tests/pytests/unit/states/test_cloud.py index ef257ee1f60..556a4ddef9e 100644 --- a/tests/pytests/unit/states/test_cloud.py +++ b/tests/pytests/unit/states/test_cloud.py @@ -46,12 +46,12 @@ def test_present(): assert cloud.present(name, cloud_provider, unless="") == ret - comt = "Already present instance {}".format(name) + comt = f"Already present instance {name}" ret.update({"comment": comt}) assert cloud.present(name, cloud_provider) == ret with patch.dict(cloud.__opts__, {"test": True}): - comt = "Instance {} needs to be created".format(name) + comt = f"Instance {name} needs to be created" ret.update({"comment": comt, "result": None}) assert cloud.present(name, cloud_provider) == ret @@ -97,12 +97,12 @@ def test_absent(): assert cloud.absent(name, unless="") == ret - comt = "Already absent instance {}".format(name) + comt = f"Already absent instance {name}" ret.update({"comment": comt}) assert cloud.absent(name) == ret with patch.dict(cloud.__opts__, {"test": True}): - comt = "Instance {} needs to be destroyed".format(name) + comt = f"Instance {name} needs to be destroyed" ret.update({"comment": comt, "result": None}) assert cloud.absent(name) == ret @@ -150,22 +150,22 @@ def test_profile(): assert cloud.profile(name, profile, unless="") == ret - comt = "Already present instance {}".format(name) + comt = f"Already present instance {name}" ret.update({"comment": comt}) assert cloud.profile(name, profile) == ret with patch.dict(cloud.__opts__, {"test": True}): - comt = "Instance {} needs to be created".format(name) + comt = f"Instance {name} needs to be created" ret.update({"comment": comt, "result": None}) assert cloud.profile(name, profile) == ret with patch.dict(cloud.__opts__, {"test": False}): - comt = "Failed to create instance {} using profile {}".format(name, profile) + comt = f"Failed to create instance {name} using profile {profile}" ret.update({"comment": comt, "result": False}) assert cloud.profile(name, profile) == ret with patch.dict(cloud.__opts__, {"test": False}): - comt = "Failed to create instance {} using profile {}".format(name, profile) + comt = f"Failed to create instance {name} using profile {profile}" ret.update({"comment": comt, "result": False}) assert cloud.profile(name, profile) == ret @@ -188,17 +188,17 @@ def test_volume_present(): ret.update({"comment": comt}) assert cloud.volume_present(name) == ret - comt = "Volume exists: {}".format(name) + comt = f"Volume exists: {name}" ret.update({"comment": comt, "result": True}) assert cloud.volume_present(name) == ret with patch.dict(cloud.__opts__, {"test": True}): - comt = "Volume {} will be created.".format(name) + comt = f"Volume {name} will be created." ret.update({"comment": comt, "result": None}) assert cloud.volume_present(name) == ret with patch.dict(cloud.__opts__, {"test": False}): - comt = "Volume {} was created".format(name) + comt = f"Volume {name} was created" ret.update( { "comment": comt, @@ -232,12 +232,12 @@ def test_volume_absent(): assert cloud.volume_absent(name) == ret with patch.dict(cloud.__opts__, {"test": True}): - comt = "Volume {} will be deleted.".format(name) + comt = f"Volume {name} will be deleted." ret.update({"comment": comt, "result": None}) assert cloud.volume_absent(name) == ret with patch.dict(cloud.__opts__, {"test": False}): - comt = "Volume {} failed to delete.".format(name) + comt = f"Volume {name} failed to delete." ret.update({"comment": comt, "result": False}) assert cloud.volume_absent(name) == ret @@ -277,15 +277,15 @@ def test_volume_attached(): ret.update({"name": server_name}) assert cloud.volume_attached(name, server_name) == ret - comt = "Volume {} is already attached: True".format(disk_name) + comt = f"Volume {disk_name} is already attached: True" ret.update({"comment": comt, "result": True}) assert cloud.volume_attached(name, server_name) == ret - comt = "Volume {} does not exist".format(name) + comt = f"Volume {name} does not exist" ret.update({"comment": comt, "result": False}) assert cloud.volume_attached(name, server_name) == ret - comt = "Server {} does not exist".format(server_name) + comt = f"Server {server_name} does not exist" ret.update({"comment": comt, "result": False}) assert cloud.volume_attached(name, server_name) == ret @@ -294,12 +294,12 @@ def test_volume_attached(): cloud.__salt__, {"cloud.action": mock, "cloud.volume_attach": mock} ): with patch.dict(cloud.__opts__, {"test": True}): - comt = "Volume {} will be will be attached.".format(name) + comt = f"Volume {name} will be will be attached." ret.update({"comment": comt, "result": None}) assert cloud.volume_attached(name, server_name) == ret with patch.dict(cloud.__opts__, {"test": False}): - comt = "Volume {} was created".format(name) + comt = f"Volume {name} was created" ret.update( { "comment": comt, @@ -348,15 +348,15 @@ def test_volume_detached(): ret.update({"name": server_name}) assert cloud.volume_detached(name, server_name) == ret - comt = "Volume {} is not currently attached to anything.".format(disk_name) + comt = f"Volume {disk_name} is not currently attached to anything." ret.update({"comment": comt, "result": True}) assert cloud.volume_detached(name, server_name) == ret - comt = "Volume {} does not exist".format(name) + comt = f"Volume {name} does not exist" ret.update({"comment": comt}) assert cloud.volume_detached(name, server_name) == ret - comt = "Server {} does not exist".format(server_name) + comt = f"Server {server_name} does not exist" ret.update({"comment": comt}) assert cloud.volume_detached(name, server_name) == ret @@ -365,12 +365,12 @@ def test_volume_detached(): cloud.__salt__, {"cloud.action": mock, "cloud.volume_detach": mock} ): with patch.dict(cloud.__opts__, {"test": True}): - comt = "Volume {} will be will be detached.".format(name) + comt = f"Volume {name} will be will be detached." ret.update({"comment": comt, "result": None}) assert cloud.volume_detached(name, server_name) == ret with patch.dict(cloud.__opts__, {"test": False}): - comt = "Volume {} was created".format(name) + comt = f"Volume {name} was created" ret.update( { "comment": comt, diff --git a/tests/pytests/unit/states/test_consul.py b/tests/pytests/unit/states/test_consul.py index 02367458356..816278fa385 100644 --- a/tests/pytests/unit/states/test_consul.py +++ b/tests/pytests/unit/states/test_consul.py @@ -2,7 +2,6 @@ Test case for the consul state module """ - import logging import pytest diff --git a/tests/pytests/unit/states/test_ddns.py b/tests/pytests/unit/states/test_ddns.py index e14ec13f0b2..1a82b67dfd7 100644 --- a/tests/pytests/unit/states/test_ddns.py +++ b/tests/pytests/unit/states/test_ddns.py @@ -25,14 +25,14 @@ def test_present(): ret = {"name": name, "result": None, "comment": "", "changes": {}} with patch.dict(ddns.__opts__, {"test": True}): - comt = 'A record "{}" will be updated'.format(name) + comt = f'A record "{name}" will be updated' ret.update({"comment": comt}) assert ddns.present(name, zone, ttl, data) == ret with patch.dict(ddns.__opts__, {"test": False}): mock = MagicMock(return_value=None) with patch.dict(ddns.__salt__, {"ddns.update": mock}): - comt = 'A record "{}" already present with ttl of {}'.format(name, ttl) + comt = f'A record "{name}" already present with ttl of {ttl}' ret.update({"comment": comt, "result": True}) assert ddns.present(name, zone, ttl, data) == ret @@ -48,7 +48,7 @@ def test_absent(): ret = {"name": name, "result": None, "comment": "", "changes": {}} with patch.dict(ddns.__opts__, {"test": True}): - comt = 'None record "{}" will be deleted'.format(name) + comt = f'None record "{name}" will be deleted' ret.update({"comment": comt}) assert ddns.absent(name, zone, data) == ret diff --git a/tests/pytests/unit/states/test_debconfmod.py b/tests/pytests/unit/states/test_debconfmod.py index eae21c97535..3151e84275f 100644 --- a/tests/pytests/unit/states/test_debconfmod.py +++ b/tests/pytests/unit/states/test_debconfmod.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import pytest import salt.states.debconfmod as debconfmod diff --git a/tests/pytests/unit/states/test_drac.py b/tests/pytests/unit/states/test_drac.py index 71f95396e25..3fba523410b 100644 --- a/tests/pytests/unit/states/test_drac.py +++ b/tests/pytests/unit/states/test_drac.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import pytest import salt.states.drac as drac @@ -25,12 +26,12 @@ def test_present(): mock = MagicMock(return_value=[name]) with patch.dict(drac.__salt__, {"drac.list_users": mock}): with patch.dict(drac.__opts__, {"test": True}): - comt = "`{}` already exists".format(name) + comt = f"`{name}` already exists" ret.update({"comment": comt}) assert drac.present(name, password, permission) == ret with patch.dict(drac.__opts__, {"test": False}): - comt = "`{}` already exists".format(name) + comt = f"`{name}` already exists" ret.update({"comment": comt}) assert drac.present(name, password, permission) == ret @@ -46,12 +47,12 @@ def test_absent(): mock = MagicMock(return_value=[]) with patch.dict(drac.__salt__, {"drac.list_users": mock}): with patch.dict(drac.__opts__, {"test": True}): - comt = "`{}` does not exist".format(name) + comt = f"`{name}` does not exist" ret.update({"comment": comt}) assert drac.absent(name) == ret with patch.dict(drac.__opts__, {"test": False}): - comt = "`{}` does not exist".format(name) + comt = f"`{name}` does not exist" ret.update({"comment": comt}) assert drac.absent(name) == ret diff --git a/tests/pytests/unit/states/test_elasticsearch.py b/tests/pytests/unit/states/test_elasticsearch.py index b3d55e1df41..89e84b1bb9f 100644 --- a/tests/pytests/unit/states/test_elasticsearch.py +++ b/tests/pytests/unit/states/test_elasticsearch.py @@ -1,6 +1,7 @@ """ :codeauthor: Lukas Raska """ + import pytest import salt.utils.dictdiffer as dictdiffer diff --git a/tests/pytests/unit/states/test_eselect.py b/tests/pytests/unit/states/test_eselect.py index 02eed1a319d..c8e3e3caa09 100644 --- a/tests/pytests/unit/states/test_eselect.py +++ b/tests/pytests/unit/states/test_eselect.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import pytest import salt.states.eselect as eselect @@ -23,6 +24,6 @@ def test_set_(): mock = MagicMock(return_value=target) with patch.dict(eselect.__salt__, {"eselect.get_current_target": mock}): - comt = "Target '{}' is already set on '{}' module.".format(target, name) + comt = f"Target '{target}' is already set on '{name}' module." ret.update({"comment": comt}) assert eselect.set_(name, target) == ret diff --git a/tests/pytests/unit/states/test_etcd_mod.py b/tests/pytests/unit/states/test_etcd_mod.py index e8fde7c48f1..17df492a1c0 100644 --- a/tests/pytests/unit/states/test_etcd_mod.py +++ b/tests/pytests/unit/states/test_etcd_mod.py @@ -9,7 +9,6 @@ :codeauthor: Caleb Beard """ - import pytest import salt.states.etcd_mod as etcd_state diff --git a/tests/pytests/unit/states/test_ethtool.py b/tests/pytests/unit/states/test_ethtool.py index c0f5267f811..dcf119fb417 100644 --- a/tests/pytests/unit/states/test_ethtool.py +++ b/tests/pytests/unit/states/test_ethtool.py @@ -51,9 +51,9 @@ def test_ethtool_pause(): with patch.dict(ethtool.__opts__, {"test": True}): expected["result"] = None expected["changes"] = {} - expected[ - "comment" - ] = "Device eth0 pause parameters are set to be updated:\nautoneg: off\nrx: off\ntx: off" + expected["comment"] = ( + "Device eth0 pause parameters are set to be updated:\nautoneg: off\nrx: off\ntx: off" + ) ret = ethtool.pause("eth0", autoneg=False, rx=False, tx=False) assert ret == expected mock_set.assert_not_called() diff --git a/tests/pytests/unit/states/test_firewalld.py b/tests/pytests/unit/states/test_firewalld.py index 867beadaa81..2f01ef6c6e0 100644 --- a/tests/pytests/unit/states/test_firewalld.py +++ b/tests/pytests/unit/states/test_firewalld.py @@ -1,6 +1,7 @@ """ :codeauthor: Hristo Voyvodov """ + import pytest import salt.states.firewalld as firewalld diff --git a/tests/pytests/unit/states/test_gem.py b/tests/pytests/unit/states/test_gem.py index 6d3a7ac001d..ab054904593 100644 --- a/tests/pytests/unit/states/test_gem.py +++ b/tests/pytests/unit/states/test_gem.py @@ -2,7 +2,6 @@ Tests of salt.states.gem """ - import pytest import salt.states.gem as gem diff --git a/tests/pytests/unit/states/test_git.py b/tests/pytests/unit/states/test_git.py index 7410239bac1..b9e9f7b6460 100644 --- a/tests/pytests/unit/states/test_git.py +++ b/tests/pytests/unit/states/test_git.py @@ -4,7 +4,6 @@ :codeauthor: Erik Johnson """ - import logging import pytest diff --git a/tests/pytests/unit/states/test_gnomedesktop.py b/tests/pytests/unit/states/test_gnomedesktop.py index 0229e734592..fd089bdc5a5 100644 --- a/tests/pytests/unit/states/test_gnomedesktop.py +++ b/tests/pytests/unit/states/test_gnomedesktop.py @@ -4,7 +4,6 @@ Test cases for salt.states.gnomedesktop """ - import pytest import salt.states.gnomedesktop as gnomedesktop diff --git a/tests/pytests/unit/states/test_grafana.py b/tests/pytests/unit/states/test_grafana.py index 3a6b73f947e..de36fa3389f 100644 --- a/tests/pytests/unit/states/test_grafana.py +++ b/tests/pytests/unit/states/test_grafana.py @@ -64,7 +64,7 @@ def test_dashboard_present(): with patch.dict(grafana.__opts__, {"test": True}): pytest.raises(SaltInvocationError, grafana.dashboard_present, name) - comt = "Dashboard {} is set to be created.".format(name) + comt = f"Dashboard {name} is set to be created." ret.update({"comment": comt}) assert grafana.dashboard_present(name, True) == ret diff --git a/tests/pytests/unit/states/test_grains.py b/tests/pytests/unit/states/test_grains.py index 8015eaf9340..a2df4028244 100644 --- a/tests/pytests/unit/states/test_grains.py +++ b/tests/pytests/unit/states/test_grains.py @@ -1,6 +1,7 @@ """ unit tests for the grains state """ + import contextlib import os diff --git a/tests/pytests/unit/states/test_group.py b/tests/pytests/unit/states/test_group.py index 72ec6ce3aa6..c401c884316 100644 --- a/tests/pytests/unit/states/test_group.py +++ b/tests/pytests/unit/states/test_group.py @@ -4,16 +4,12 @@ import salt.states.group as group import salt.utils.platform from tests.support.mock import MagicMock, call, patch -__context__ = {} - - -def ping(): - ... - @pytest.fixture def configure_loader_modules(): - return {group: {"__salt__": {"test.ping": ping}, "__opts__": {"test": False}}} + return { + group: {"__salt__": {"test.ping": MagicMock()}, "__opts__": {"test": False}} + } def test_present_with_non_unique_gid(): diff --git a/tests/pytests/unit/states/test_helm.py b/tests/pytests/unit/states/test_helm.py index d7d78432e17..9c91ab74f6c 100644 --- a/tests/pytests/unit/states/test_helm.py +++ b/tests/pytests/unit/states/test_helm.py @@ -2,7 +2,6 @@ Test cases for salt.modules.helm """ - import pytest import salt.states.helm as helm diff --git a/tests/pytests/unit/states/test_host.py b/tests/pytests/unit/states/test_host.py index 3a3ab022a02..5830747b115 100644 --- a/tests/pytests/unit/states/test_host.py +++ b/tests/pytests/unit/states/test_host.py @@ -50,9 +50,7 @@ def test_present(): ): ret = host.present(hostname, ip_str) assert ret["result"] is True - assert ret["comment"] == "Added host {} ({})".format(hostname, ip_str), ret[ - "comment" - ] + assert ret["comment"] == f"Added host {hostname} ({ip_str})", ret["comment"] assert ret["changes"] == {"added": {ip_str: [hostname]}}, ret["changes"] expected = [call(ip_str, hostname)] assert add_host.mock_calls == expected, add_host.mock_calls @@ -73,8 +71,8 @@ def test_present(): ): ret = host.present(hostname, ip_list) assert ret["result"] is True - assert "Added host {} ({})".format(hostname, ip_list[0]) in ret["comment"] - assert "Added host {} ({})".format(hostname, ip_list[1]) in ret["comment"] + assert f"Added host {hostname} ({ip_list[0]})" in ret["comment"] + assert f"Added host {hostname} ({ip_list[1]})" in ret["comment"] assert ret["changes"] == { "added": {ip_list[0]: [hostname], ip_list[1]: [hostname]} }, ret["changes"] @@ -102,10 +100,9 @@ def test_present(): ): ret = host.present(hostname, ip_str) assert ret["result"] is True - assert "Added host {} ({})".format(hostname, ip_str) in ret["comment"] + assert f"Added host {hostname} ({ip_str})" in ret["comment"] assert ( - "Host {} present for IP address {}".format(hostname, ip_list[0]) - in ret["warnings"][0] + f"Host {hostname} present for IP address {ip_list[0]}" in ret["warnings"][0] ) assert ret["changes"] == {"added": {ip_str: [hostname]}}, ret["changes"] expected = [call(ip_str, hostname)] @@ -125,8 +122,8 @@ def test_present(): ): ret = host.present(hostname, ip_str, clean=True) assert ret["result"] is True - assert "Added host {} ({})".format(hostname, ip_str) in ret["comment"] - assert "Removed host {} ({})".format(hostname, ip_list[0]) in ret["comment"] + assert f"Added host {hostname} ({ip_str})" in ret["comment"] + assert f"Removed host {hostname} ({ip_list[0]})" in ret["comment"] assert ret["changes"] == { "added": {ip_str: [hostname]}, "removed": {ip_list[0]: [hostname]}, @@ -157,8 +154,8 @@ def test_present(): ): ret = host.present(hostname, ip_list) assert ret["result"] is True - assert "Added host {} ({})".format(hostname, ip_list[0]) in ret["comment"] - assert "Added host {} ({})".format(hostname, ip_list[1]) in ret["comment"] + assert f"Added host {hostname} ({ip_list[0]})" in ret["comment"] + assert f"Added host {hostname} ({ip_list[1]})" in ret["comment"] assert ret["changes"] == { "added": {ip_list[0]: [hostname], ip_list[1]: [hostname]}, }, ret["changes"] @@ -179,9 +176,9 @@ def test_present(): ): ret = host.present(hostname, ip_list, clean=True) assert ret["result"] is True - assert "Added host {} ({})".format(hostname, ip_list[0]) in ret["comment"] - assert "Added host {} ({})".format(hostname, ip_list[1]) in ret["comment"] - assert "Removed host {} ({})".format(hostname, cur_ip) in ret["comment"] + assert f"Added host {hostname} ({ip_list[0]})" in ret["comment"] + assert f"Added host {hostname} ({ip_list[1]})" in ret["comment"] + assert f"Removed host {hostname} ({cur_ip})" in ret["comment"] assert ret["changes"] == { "added": {ip_list[0]: [hostname], ip_list[1]: [hostname]}, "removed": {cur_ip: [hostname]}, @@ -214,7 +211,7 @@ def test_present(): ): ret = host.present(hostname, ip_list) assert ret["result"] is True - assert "Added host {} ({})".format(hostname, ip_list[1]) in ret["comment"] + assert f"Added host {hostname} ({ip_list[1]})" in ret["comment"] assert ret["changes"] == {"added": {ip_list[1]: [hostname]}}, ret["changes"] expected = [call(ip_list[1], hostname)] assert add_host.mock_calls == expected, add_host.mock_calls @@ -233,8 +230,8 @@ def test_present(): ): ret = host.present(hostname, ip_list, clean=True) assert ret["result"] is True - assert "Added host {} ({})".format(hostname, ip_list[1]) in ret["comment"] - assert "Removed host {} ({})".format(hostname, cur_ip) in ret["comment"] + assert f"Added host {hostname} ({ip_list[1]})" in ret["comment"] + assert f"Removed host {hostname} ({cur_ip})" in ret["comment"] assert ret["changes"] == { "added": {ip_list[1]: [hostname]}, "removed": {cur_ip: [hostname]}, @@ -261,7 +258,7 @@ def test_present(): assert ret["result"] is True assert ( ret["comment"] - == "Host {} ({}) already present".format(hostname, ip_str) + == f"Host {hostname} ({ip_str}) already present" in ret["comment"] ) assert ret["changes"] == {}, ret["changes"] @@ -289,14 +286,8 @@ def test_present(): ): ret = host.present(hostname, ip_list) assert ret["result"] is True - assert ( - "Host {} ({}) already present".format(hostname, ip_list[0]) - in ret["comment"] - ) - assert ( - "Host {} ({}) already present".format(hostname, ip_list[1]) - in ret["comment"] - ) + assert f"Host {hostname} ({ip_list[0]}) already present" in ret["comment"] + assert f"Host {hostname} ({ip_list[1]}) already present" in ret["comment"] assert ret["changes"] == {}, ret["changes"] assert add_host.mock_calls == [], add_host.mock_calls assert rm_host.mock_calls == [], rm_host.mock_calls @@ -320,14 +311,10 @@ def test_present(): ): ret = host.present(hostname, ip_list, comment="A comment") assert ret["result"] is True - assert "Added host {} ({})".format(hostname, ip_list[0]) in ret["comment"] - assert "Added host {} ({})".format(hostname, ip_list[1]) in ret["comment"] - assert ( - "Set comment for host {} (A comment)".format(ip_list[0]) in ret["comment"] - ) - assert ( - "Set comment for host {} (A comment)".format(ip_list[1]) in ret["comment"] - ) + assert f"Added host {hostname} ({ip_list[0]})" in ret["comment"] + assert f"Added host {hostname} ({ip_list[1]})" in ret["comment"] + assert f"Set comment for host {ip_list[0]} (A comment)" in ret["comment"] + assert f"Set comment for host {ip_list[1]} (A comment)" in ret["comment"] assert ret["changes"] == { "added": {ip_list[0]: [hostname], ip_list[1]: [hostname]}, "comment_added": {ip_list[0]: ["A comment"], ip_list[1]: ["A comment"]}, diff --git a/tests/pytests/unit/states/test_incron.py b/tests/pytests/unit/states/test_incron.py index 54415c01dcd..0b57680bac9 100644 --- a/tests/pytests/unit/states/test_incron.py +++ b/tests/pytests/unit/states/test_incron.py @@ -27,7 +27,7 @@ def test_present(): ret = {"name": name, "result": None, "comment": "", "changes": {}} - comt4 = "Incron {} for user root failed to commit with error \nabsent".format(name) + comt4 = f"Incron {name} for user root failed to commit with error \nabsent" mock_dict = MagicMock( return_value={"crons": [{"path": path, "cmd": cmd, "mask": mask}]} ) @@ -36,20 +36,20 @@ def test_present(): incron.__salt__, {"incron.list_tab": mock_dict, "incron.set_job": mock} ): with patch.dict(incron.__opts__, {"test": True}): - comt = "Incron {} is set to be added".format(name) + comt = f"Incron {name} is set to be added" ret.update({"comment": comt}) assert incron.present(name, path, mask, cmd) == ret with patch.dict(incron.__opts__, {"test": False}): - comt = "Incron {} already present".format(name) + comt = f"Incron {name} already present" ret.update({"comment": comt, "result": True}) assert incron.present(name, path, mask, cmd) == ret - comt = "Incron {} added to root's incrontab".format(name) + comt = f"Incron {name} added to root's incrontab" ret.update({"comment": comt, "changes": {"root": "salt"}}) assert incron.present(name, path, mask, cmd) == ret - comt = "Incron {} updated".format(name) + comt = f"Incron {name} updated" ret.update({"comment": comt}) assert incron.present(name, path, mask, cmd) == ret @@ -69,7 +69,7 @@ def test_absent(): ret = {"name": name, "result": True, "comment": "", "changes": {}} - comt4 = "Incron {} for user root failed to commit with error new".format(name) + comt4 = f"Incron {name} for user root failed to commit with error new" mock_dict = MagicMock( return_value={"crons": [{"path": path, "cmd": cmd, "mask": mask}]} ) @@ -78,16 +78,16 @@ def test_absent(): incron.__salt__, {"incron.list_tab": mock_dict, "incron.rm_job": mock} ): with patch.dict(incron.__opts__, {"test": True}): - comt = "Incron {} is absent".format(name) + comt = f"Incron {name} is absent" ret.update({"comment": comt}) assert incron.absent(name, path, mask, cmd) == ret with patch.dict(incron.__opts__, {"test": False}): - comt = "Incron {} already absent".format(name) + comt = f"Incron {name} already absent" ret.update({"comment": comt, "result": True}) assert incron.absent(name, path, mask, cmd) == ret - comt = "Incron {} removed from root's crontab".format(name) + comt = f"Incron {name} removed from root's crontab" ret.update({"comment": comt, "changes": {"root": "salt"}}) assert incron.absent(name, path, mask, cmd) == ret diff --git a/tests/pytests/unit/states/test_influxdb08_database.py b/tests/pytests/unit/states/test_influxdb08_database.py index d5685de2131..6b93b946586 100644 --- a/tests/pytests/unit/states/test_influxdb08_database.py +++ b/tests/pytests/unit/states/test_influxdb08_database.py @@ -28,22 +28,22 @@ def test_present(): {"influxdb08.db_exists": mock, "influxdb08.db_create": mock_t}, ): with patch.dict(influxdb08_database.__opts__, {"test": True}): - comt = "Database {} is absent and needs to be created".format(name) + comt = f"Database {name} is absent and needs to be created" ret.update({"comment": comt}) assert influxdb08_database.present(name) == ret with patch.dict(influxdb08_database.__opts__, {"test": False}): - comt = "Database {} has been created".format(name) + comt = f"Database {name} has been created" ret.update( {"comment": comt, "result": True, "changes": {"salt": "Present"}} ) assert influxdb08_database.present(name) == ret - comt = "Failed to create database {}".format(name) + comt = f"Failed to create database {name}" ret.update({"comment": comt, "result": False, "changes": {}}) assert influxdb08_database.present(name) == ret - comt = "Database {} is already present, so cannot be created".format(name) + comt = f"Database {name} is already present, so cannot be created" ret.update({"comment": comt, "result": True}) assert influxdb08_database.present(name) == ret @@ -63,19 +63,19 @@ def test_absent(): {"influxdb08.db_exists": mock, "influxdb08.db_remove": mock_t}, ): with patch.dict(influxdb08_database.__opts__, {"test": True}): - comt = "Database {} is present and needs to be removed".format(name) + comt = f"Database {name} is present and needs to be removed" ret.update({"comment": comt}) assert influxdb08_database.absent(name) == ret with patch.dict(influxdb08_database.__opts__, {"test": False}): - comt = "Database {} has been removed".format(name) + comt = f"Database {name} has been removed" ret.update({"comment": comt, "result": True, "changes": {"salt": "Absent"}}) assert influxdb08_database.absent(name) == ret - comt = "Failed to remove database {}".format(name) + comt = f"Failed to remove database {name}" ret.update({"comment": comt, "result": False, "changes": {}}) assert influxdb08_database.absent(name) == ret - comt = "Database {} is not present, so it cannot be removed".format(name) + comt = f"Database {name} is not present, so it cannot be removed" ret.update({"comment": comt, "result": True}) assert influxdb08_database.absent(name) == ret diff --git a/tests/pytests/unit/states/test_influxdb08_user.py b/tests/pytests/unit/states/test_influxdb08_user.py index d5f4f29131b..32d5565478b 100644 --- a/tests/pytests/unit/states/test_influxdb08_user.py +++ b/tests/pytests/unit/states/test_influxdb08_user.py @@ -38,22 +38,22 @@ def test_present(): assert influxdb08_user.present(name, passwd, database="mydb") == ret with patch.dict(influxdb08_user.__opts__, {"test": True}): - comt = "User {} is not present and needs to be created".format(name) + comt = f"User {name} is not present and needs to be created" ret.update({"comment": comt, "result": None}) assert influxdb08_user.present(name, passwd) == ret with patch.dict(influxdb08_user.__opts__, {"test": False}): - comt = "User {} has been created".format(name) + comt = f"User {name} has been created" ret.update( {"comment": comt, "result": True, "changes": {"salt": "Present"}} ) assert influxdb08_user.present(name, passwd) == ret - comt = "Failed to create user {}".format(name) + comt = f"Failed to create user {name}" ret.update({"comment": comt, "result": False, "changes": {}}) assert influxdb08_user.present(name, passwd) == ret - comt = "User {} is already present".format(name) + comt = f"User {name} is already present" ret.update({"comment": comt, "result": True}) assert influxdb08_user.present(name, passwd) == ret @@ -73,19 +73,19 @@ def test_absent(): {"influxdb08.user_exists": mock, "influxdb08.user_remove": mock_t}, ): with patch.dict(influxdb08_user.__opts__, {"test": True}): - comt = "User {} is present and needs to be removed".format(name) + comt = f"User {name} is present and needs to be removed" ret.update({"comment": comt}) assert influxdb08_user.absent(name) == ret with patch.dict(influxdb08_user.__opts__, {"test": False}): - comt = "User {} has been removed".format(name) + comt = f"User {name} has been removed" ret.update({"comment": comt, "result": True, "changes": {"salt": "Absent"}}) assert influxdb08_user.absent(name) == ret - comt = "Failed to remove user {}".format(name) + comt = f"Failed to remove user {name}" ret.update({"comment": comt, "result": False, "changes": {}}) assert influxdb08_user.absent(name) == ret - comt = "User {} is not present, so it cannot be removed".format(name) + comt = f"User {name} is not present, so it cannot be removed" ret.update({"comment": comt, "result": True}) assert influxdb08_user.absent(name) == ret diff --git a/tests/pytests/unit/states/test_ini_manage.py b/tests/pytests/unit/states/test_ini_manage.py index 9f0217b5b40..0401b5761f3 100644 --- a/tests/pytests/unit/states/test_ini_manage.py +++ b/tests/pytests/unit/states/test_ini_manage.py @@ -2,7 +2,6 @@ Test cases for salt.states.ini_manage """ - import copy import os diff --git a/tests/pytests/unit/states/test_iptables.py b/tests/pytests/unit/states/test_iptables.py index cb372f99a64..19e8d6d4150 100644 --- a/tests/pytests/unit/states/test_iptables.py +++ b/tests/pytests/unit/states/test_iptables.py @@ -2,7 +2,6 @@ :codeauthor: Rahul Handay """ - import pytest import salt.states.iptables as iptables diff --git a/tests/pytests/unit/states/test_kapacitor.py b/tests/pytests/unit/states/test_kapacitor.py index df748455541..172852f2744 100644 --- a/tests/pytests/unit/states/test_kapacitor.py +++ b/tests/pytests/unit/states/test_kapacitor.py @@ -2,7 +2,6 @@ Test cases for salt.states.kapacitor """ - import pytest import salt.states.kapacitor as kapacitor diff --git a/tests/pytests/unit/states/test_kernelpkg.py b/tests/pytests/unit/states/test_kernelpkg.py index 22b3cbf2db0..7aa35f6a556 100644 --- a/tests/pytests/unit/states/test_kernelpkg.py +++ b/tests/pytests/unit/states/test_kernelpkg.py @@ -2,7 +2,6 @@ Test cases for salt.states.kernelpkg """ - import pytest import salt.states.kernelpkg as kernelpkg diff --git a/tests/pytests/unit/states/test_keyboard.py b/tests/pytests/unit/states/test_keyboard.py index 5c00bc21e07..a642ae35308 100644 --- a/tests/pytests/unit/states/test_keyboard.py +++ b/tests/pytests/unit/states/test_keyboard.py @@ -29,17 +29,17 @@ def test_system(): with patch.dict( keyboard.__salt__, {"keyboard.get_sys": mock, "keyboard.set_sys": mock_t} ): - comt = "System layout {} already set".format(name) + comt = f"System layout {name} already set" ret.update({"comment": comt}) assert keyboard.system(name) == ret with patch.dict(keyboard.__opts__, {"test": True}): - comt = "System layout {} needs to be set".format(name) + comt = f"System layout {name} needs to be set" ret.update({"comment": comt, "result": None}) assert keyboard.system(name) == ret with patch.dict(keyboard.__opts__, {"test": False}): - comt = "Set system keyboard layout {}".format(name) + comt = f"Set system keyboard layout {name}" ret.update({"comment": comt, "result": True, "changes": {"layout": name}}) assert keyboard.system(name) == ret @@ -64,17 +64,17 @@ def test_xorg(): with patch.dict( keyboard.__salt__, {"keyboard.get_x": mock, "keyboard.set_x": mock_t} ): - comt = "XOrg layout {} already set".format(name) + comt = f"XOrg layout {name} already set" ret.update({"comment": comt}) assert keyboard.xorg(name) == ret with patch.dict(keyboard.__opts__, {"test": True}): - comt = "XOrg layout {} needs to be set".format(name) + comt = f"XOrg layout {name} needs to be set" ret.update({"comment": comt, "result": None}) assert keyboard.xorg(name) == ret with patch.dict(keyboard.__opts__, {"test": False}): - comt = "Set XOrg keyboard layout {}".format(name) + comt = f"Set XOrg keyboard layout {name}" ret.update({"comment": comt, "result": True, "changes": {"layout": name}}) assert keyboard.xorg(name) == ret diff --git a/tests/pytests/unit/states/test_keystone.py b/tests/pytests/unit/states/test_keystone.py index d0461180433..46b8c37141f 100644 --- a/tests/pytests/unit/states/test_keystone.py +++ b/tests/pytests/unit/states/test_keystone.py @@ -30,7 +30,7 @@ def test_user_present(): mock_f = MagicMock(return_value=False) mock_lst = MagicMock(return_value=["Error"]) with patch.dict(keystone.__salt__, {"keystone.tenant_get": mock_lst}): - comt = 'Tenant / project "{}" does not exist'.format(tenant) + comt = f'Tenant / project "{tenant}" does not exist' ret.update({"comment": comt}) assert keystone.user_present(name, password, email, tenant) == ret @@ -55,7 +55,7 @@ def test_user_present(): }, ): with patch.dict(keystone.__opts__, {"test": True}): - comt = 'User "{}" will be updated'.format(name) + comt = f'User "{name}" will be updated' ret.update( { "comment": comt, @@ -113,7 +113,7 @@ def test_user_present(): assert keystone.user_present(name, password, email) == ret with patch.dict(keystone.__opts__, {"test": False}): - comt = "Keystone user {} has been added".format(name) + comt = f"Keystone user {name} has been added" ret.update( {"comment": comt, "result": True, "changes": {"User": "Created"}} ) @@ -130,7 +130,7 @@ def test_user_absent(): "name": name, "changes": {}, "result": True, - "comment": 'User "{}" is already absent'.format(name), + "comment": f'User "{name}" is already absent', } mock_lst = MagicMock(side_effect=[["Error"], []]) @@ -138,7 +138,7 @@ def test_user_absent(): assert keystone.user_absent(name) == ret with patch.dict(keystone.__opts__, {"test": True}): - comt = 'User "{}" will be deleted'.format(name) + comt = f'User "{name}" will be deleted' ret.update({"comment": comt, "result": None}) assert keystone.user_absent(name) == ret @@ -154,7 +154,7 @@ def test_tenant_present(): "name": name, "changes": {}, "result": True, - "comment": 'Tenant / project "{}" already exists'.format(name), + "comment": f'Tenant / project "{name}" already exists', } mock_dict = MagicMock( @@ -171,7 +171,7 @@ def test_tenant_present(): {"keystone.tenant_get": mock_dict, "keystone.tenant_create": mock_t}, ): with patch.dict(keystone.__opts__, {"test": True}): - comt = 'Tenant / project "{}" will be updated'.format(name) + comt = f'Tenant / project "{name}" will be updated' ret.update( { "comment": comt, @@ -181,7 +181,7 @@ def test_tenant_present(): ) assert keystone.tenant_present(name) == ret - comt = 'Tenant / project "{}" will be updated'.format(name) + comt = f'Tenant / project "{name}" will be updated' ret.update( { "comment": comt, @@ -191,7 +191,7 @@ def test_tenant_present(): ) assert keystone.tenant_present(name, description) == ret - comt = 'Tenant / project "{}" will be added'.format(name) + comt = f'Tenant / project "{name}" will be added' ret.update( { "comment": comt, @@ -202,7 +202,7 @@ def test_tenant_present(): assert keystone.tenant_present(name) == ret with patch.dict(keystone.__opts__, {"test": False}): - comt = 'Tenant / project "{}" has been added'.format(name) + comt = f'Tenant / project "{name}" has been added' ret.update( {"comment": comt, "result": True, "changes": {"Tenant": "Created"}} ) @@ -219,7 +219,7 @@ def test_tenant_absent(): "name": name, "changes": {}, "result": True, - "comment": 'Tenant / project "{}" is already absent'.format(name), + "comment": f'Tenant / project "{name}" is already absent', } mock_lst = MagicMock(side_effect=[["Error"], []]) @@ -227,7 +227,7 @@ def test_tenant_absent(): assert keystone.tenant_absent(name) == ret with patch.dict(keystone.__opts__, {"test": True}): - comt = 'Tenant / project "{}" will be deleted'.format(name) + comt = f'Tenant / project "{name}" will be deleted' ret.update({"comment": comt, "result": None}) assert keystone.tenant_absent(name) == ret @@ -242,7 +242,7 @@ def test_role_present(): "name": name, "changes": {}, "result": True, - "comment": 'Role "{}" already exists'.format(name), + "comment": f'Role "{name}" already exists', } mock_lst = MagicMock(side_effect=[[], ["Error"]]) @@ -250,7 +250,7 @@ def test_role_present(): assert keystone.role_present(name) == ret with patch.dict(keystone.__opts__, {"test": True}): - comt = 'Role "{}" will be added'.format(name) + comt = f'Role "{name}" will be added' ret.update({"comment": comt, "result": None}) assert keystone.role_present(name) == ret @@ -265,7 +265,7 @@ def test_role_absent(): "name": name, "changes": {}, "result": True, - "comment": 'Role "{}" is already absent'.format(name), + "comment": f'Role "{name}" is already absent', } mock_lst = MagicMock(side_effect=[["Error"], []]) @@ -273,7 +273,7 @@ def test_role_absent(): assert keystone.role_absent(name) == ret with patch.dict(keystone.__opts__, {"test": True}): - comt = 'Role "{}" will be deleted'.format(name) + comt = f'Role "{name}" will be deleted' ret.update({"comment": comt, "result": None}) assert keystone.role_absent(name) == ret @@ -289,7 +289,7 @@ def test_service_present(): "name": name, "changes": {}, "result": True, - "comment": 'Service "{}" already exists'.format(name), + "comment": f'Service "{name}" already exists', } mock_lst = MagicMock(side_effect=[[], ["Error"]]) @@ -297,7 +297,7 @@ def test_service_present(): assert keystone.service_present(name, service_type) == ret with patch.dict(keystone.__opts__, {"test": True}): - comt = 'Service "{}" will be added'.format(name) + comt = f'Service "{name}" will be added' ret.update({"comment": comt, "result": None}) assert keystone.service_present(name, service_type) == ret @@ -312,7 +312,7 @@ def test_service_absent(): "name": name, "changes": {}, "result": True, - "comment": 'Service "{}" is already absent'.format(name), + "comment": f'Service "{name}" is already absent', } mock_lst = MagicMock(side_effect=[["Error"], []]) @@ -320,7 +320,7 @@ def test_service_absent(): assert keystone.service_absent(name) == ret with patch.dict(keystone.__opts__, {"test": True}): - comt = 'Service "{}" will be deleted'.format(name) + comt = f'Service "{name}" will be deleted' ret.update({"comment": comt, "result": None}) assert keystone.service_absent(name) == ret @@ -352,12 +352,12 @@ def test_endpoint_present(): {"keystone.endpoint_get": mock_lst, "keystone.endpoint_create": mock}, ): - comt = 'Endpoint for service "{}" already exists'.format(name) + comt = f'Endpoint for service "{name}" already exists' ret.update({"comment": comt, "result": True, "changes": {}}) assert keystone.endpoint_present(name) == ret with patch.dict(keystone.__opts__, {"test": True}): - comt = 'Endpoint for service "{}" will be added'.format(name) + comt = f'Endpoint for service "{name}" will be added' ret.update( { "comment": comt, @@ -367,12 +367,12 @@ def test_endpoint_present(): ) assert keystone.endpoint_present(name) == ret - comt = 'Endpoint for service "{}" already exists'.format(name) + comt = f'Endpoint for service "{name}" already exists' ret.update({"comment": comt, "result": True, "changes": {}}) assert keystone.endpoint_present(name) == ret with patch.dict(keystone.__opts__, {"test": False}): - comt = 'Endpoint for service "{}" has been added'.format(name) + comt = f'Endpoint for service "{name}" has been added' ret.update({"comment": comt, "result": True, "changes": True}) assert keystone.endpoint_present(name) == ret @@ -384,7 +384,7 @@ def test_endpoint_absent(): """ name = "nova" region = "RegionOne" - comment = 'Endpoint for service "{}" is already absent'.format(name) + comment = f'Endpoint for service "{name}" is already absent' ret = {"name": name, "changes": {}, "result": True, "comment": comment} mock_lst = MagicMock(side_effect=[[], ["Error"]]) @@ -392,6 +392,6 @@ def test_endpoint_absent(): assert keystone.endpoint_absent(name, region) == ret with patch.dict(keystone.__opts__, {"test": True}): - comt = 'Endpoint for service "{}" will be deleted'.format(name) + comt = f'Endpoint for service "{name}" will be deleted' ret.update({"comment": comt, "result": None}) assert keystone.endpoint_absent(name, region) == ret diff --git a/tests/pytests/unit/states/test_kmod.py b/tests/pytests/unit/states/test_kmod.py index a4ec3dbc17c..a4375d5ad2c 100644 --- a/tests/pytests/unit/states/test_kmod.py +++ b/tests/pytests/unit/states/test_kmod.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import pytest import salt.states.kmod as kmod @@ -21,14 +22,14 @@ def test_present(): mock_mod_list = MagicMock(return_value=[name]) with patch.dict(kmod.__salt__, {"kmod.mod_list": mock_mod_list}): - comment = "Kernel module {} is already present".format(name) + comment = f"Kernel module {name} is already present" ret.update({"comment": comment}) assert kmod.present(name) == ret mock_mod_list = MagicMock(return_value=[]) with patch.dict(kmod.__salt__, {"kmod.mod_list": mock_mod_list}): with patch.dict(kmod.__opts__, {"test": True}): - comment = "Kernel module {} is set to be loaded".format(name) + comment = f"Kernel module {name} is set to be loaded" ret.update({"comment": comment, "result": None}) assert kmod.present(name) == ret @@ -44,7 +45,7 @@ def test_present(): }, ): with patch.dict(kmod.__opts__, {"test": False}): - comment = "Loaded kernel module {}".format(name) + comment = f"Loaded kernel module {name}" ret.update( {"comment": comment, "result": True, "changes": {name: "loaded"}} ) @@ -124,7 +125,7 @@ def test_absent(): mock_mod_list = MagicMock(return_value=[name]) with patch.dict(kmod.__salt__, {"kmod.mod_list": mock_mod_list}): with patch.dict(kmod.__opts__, {"test": True}): - comment = "Kernel module {} is set to be removed".format(name) + comment = f"Kernel module {name} is set to be removed" ret.update({"comment": comment, "result": None}) assert kmod.absent(name) == ret @@ -134,7 +135,7 @@ def test_absent(): kmod.__salt__, {"kmod.mod_list": mock_mod_list, "kmod.remove": mock_remove} ): with patch.dict(kmod.__opts__, {"test": False}): - comment = "Removed kernel module {}".format(name) + comment = f"Removed kernel module {name}" ret.update( {"comment": comment, "result": True, "changes": {name: "removed"}} ) @@ -143,7 +144,7 @@ def test_absent(): mock_mod_list = MagicMock(return_value=[]) with patch.dict(kmod.__salt__, {"kmod.mod_list": mock_mod_list}): with patch.dict(kmod.__opts__, {"test": True}): - comment = "Kernel module {} is already removed".format(name) + comment = f"Kernel module {name} is already removed" ret.update({"comment": comment, "result": True, "changes": {}}) assert kmod.absent(name) == ret diff --git a/tests/pytests/unit/states/test_layman.py b/tests/pytests/unit/states/test_layman.py index ad3dec64b74..7979f665782 100644 --- a/tests/pytests/unit/states/test_layman.py +++ b/tests/pytests/unit/states/test_layman.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import pytest import salt.states.layman as layman @@ -22,12 +23,12 @@ def test_present(): mock = MagicMock(side_effect=[[name], []]) with patch.dict(layman.__salt__, {"layman.list_local": mock}): - comt = "Overlay {} already present".format(name) + comt = f"Overlay {name} already present" ret.update({"comment": comt}) assert layman.present(name) == ret with patch.dict(layman.__opts__, {"test": True}): - comt = "Overlay {} is set to be added".format(name) + comt = f"Overlay {name} is set to be added" ret.update({"comment": comt, "result": None}) assert layman.present(name) == ret @@ -42,11 +43,11 @@ def test_absent(): mock = MagicMock(side_effect=[[], [name]]) with patch.dict(layman.__salt__, {"layman.list_local": mock}): - comt = "Overlay {} already absent".format(name) + comt = f"Overlay {name} already absent" ret.update({"comment": comt}) assert layman.absent(name) == ret with patch.dict(layman.__opts__, {"test": True}): - comt = "Overlay {} is set to be deleted".format(name) + comt = f"Overlay {name} is set to be deleted" ret.update({"comment": comt, "result": None}) assert layman.absent(name) == ret diff --git a/tests/pytests/unit/states/test_ldap.py b/tests/pytests/unit/states/test_ldap.py index bf57549fd9c..99d0e36a36e 100644 --- a/tests/pytests/unit/states/test_ldap.py +++ b/tests/pytests/unit/states/test_ldap.py @@ -7,6 +7,7 @@ was an ugly second implementation. I'm leaving it for now, but this should really be gutted and replaced with something sensible. """ + import copy import logging @@ -239,20 +240,24 @@ def _test_helper(init_db, expected_ret, replace, delete_others=False): "changes", { dn: { - "old": { - attr: vals - for attr, vals in old[dn].items() - if vals != new.get(dn, {}).get(attr, ()) - } - if dn in old - else None, - "new": { - attr: vals - for attr, vals in new[dn].items() - if vals != old.get(dn, {}).get(attr, ()) - } - if dn in new - else None, + "old": ( + { + attr: vals + for attr, vals in old[dn].items() + if vals != new.get(dn, {}).get(attr, ()) + } + if dn in old + else None + ), + "new": ( + { + attr: vals + for attr, vals in new[dn].items() + if vals != old.get(dn, {}).get(attr, ()) + } + if dn in new + else None + ), } for dn in replace if old.get(dn, {}) != new.get(dn, {}) @@ -323,20 +328,24 @@ def _test_helper_add(db, expected_ret, add_items, delete_others=False): "changes", { dn: { - "old": { - attr: vals - for attr, vals in old[dn].items() - if vals != new.get(dn, {}).get(attr, ()) - } - if dn in old - else None, - "new": { - attr: vals - for attr, vals in new[dn].items() - if vals != old.get(dn, {}).get(attr, ()) - } - if dn in new - else None, + "old": ( + { + attr: vals + for attr, vals in old[dn].items() + if vals != new.get(dn, {}).get(attr, ()) + } + if dn in old + else None + ), + "new": ( + { + attr: vals + for attr, vals in new[dn].items() + if vals != old.get(dn, {}).get(attr, ()) + } + if dn in new + else None + ), } for dn in add_items if old.get(dn, {}) != new.get(dn, {}) diff --git a/tests/pytests/unit/states/test_libcloud_dns.py b/tests/pytests/unit/states/test_libcloud_dns.py index 230ecb940d1..92e87531213 100644 --- a/tests/pytests/unit/states/test_libcloud_dns.py +++ b/tests/pytests/unit/states/test_libcloud_dns.py @@ -2,7 +2,6 @@ :codeauthor: Anthony Shaw """ - import pytest import salt.states.libcloud_dns as libcloud_dns diff --git a/tests/pytests/unit/states/test_linux_acl.py b/tests/pytests/unit/states/test_linux_acl.py index 60bbe55f51c..5a3d070a3d2 100644 --- a/tests/pytests/unit/states/test_linux_acl.py +++ b/tests/pytests/unit/states/test_linux_acl.py @@ -93,7 +93,7 @@ def test_present(): # Update - test=False with patch.dict(linux_acl.__salt__, {"acl.modfacl": mock_modfacl}): with patch.dict(linux_acl.__opts__, {"test": False}): - comt = "Updated permissions for {}".format(acl_name) + comt = f"Updated permissions for {acl_name}" ret = { "name": name, "comment": comt, @@ -118,7 +118,7 @@ def test_present(): {"acl.modfacl": MagicMock(side_effect=CommandExecutionError("Custom err"))}, ): with patch.dict(linux_acl.__opts__, {"test": False}): - comt = "Error updating permissions for {}: Custom err".format(acl_name) + comt = f"Error updating permissions for {acl_name}: Custom err" ret = { "name": name, "comment": comt, @@ -148,7 +148,7 @@ def test_present(): # New - test=False with patch.dict(linux_acl.__salt__, {"acl.modfacl": mock_modfacl}): with patch.dict(linux_acl.__opts__, {"test": False}): - comt = "Applied new permissions for {}".format(acl_name) + comt = f"Applied new permissions for {acl_name}" ret = { "name": name, "comment": comt, @@ -168,7 +168,7 @@ def test_present(): {"acl.modfacl": MagicMock(side_effect=CommandExecutionError("Custom err"))}, ): with patch.dict(linux_acl.__opts__, {"test": False}): - comt = "Error updating permissions for {}: Custom err".format(acl_name) + comt = f"Error updating permissions for {acl_name}: Custom err" ret = { "name": name, "comment": comt, @@ -395,7 +395,7 @@ def test_list_present(): {"acl.modfacl": MagicMock(side_effect=CommandExecutionError("Custom err"))}, ): with patch.dict(linux_acl.__opts__, {"test": False}): - comt = "Error updating permissions for {}: Custom err".format(acl_names) + comt = f"Error updating permissions for {acl_names}: Custom err" expected = { "name": name, "comment": comt, @@ -453,7 +453,7 @@ def test_list_present(): {"acl.modfacl": MagicMock(side_effect=CommandExecutionError("Custom err"))}, ): with patch.dict(linux_acl.__opts__, {"test": False}): - comt = "Error updating permissions for {}: Custom err".format(acl_names) + comt = f"Error updating permissions for {acl_names}: Custom err" expected = { "name": name, "comment": comt, diff --git a/tests/pytests/unit/states/test_lvm.py b/tests/pytests/unit/states/test_lvm.py index 10975dcdbd7..c2590c3277c 100644 --- a/tests/pytests/unit/states/test_lvm.py +++ b/tests/pytests/unit/states/test_lvm.py @@ -62,7 +62,7 @@ def test_pv_present(): """ name = "/dev/sda5" - comt = "Physical Volume {} already present".format(name) + comt = f"Physical Volume {name} already present" ret = {"name": name, "changes": {}, "result": True, "comment": comt} @@ -70,7 +70,7 @@ def test_pv_present(): with patch.dict(lvm.__salt__, {"lvm.pvdisplay": mock}): assert lvm.pv_present(name) == ret - comt = "Physical Volume {} is set to be created".format(name) + comt = f"Physical Volume {name} is set to be created" ret.update({"comment": comt, "result": None}) with patch.dict(lvm.__opts__, {"test": True}): assert lvm.pv_present(name) == ret @@ -82,7 +82,7 @@ def test_pv_absent(): """ name = "/dev/sda5" - comt = "Physical Volume {} does not exist".format(name) + comt = f"Physical Volume {name} does not exist" ret = {"name": name, "changes": {}, "result": True, "comment": comt} @@ -90,7 +90,7 @@ def test_pv_absent(): with patch.dict(lvm.__salt__, {"lvm.pvdisplay": mock}): assert lvm.pv_absent(name) == ret - comt = "Physical Volume {} is set to be removed".format(name) + comt = f"Physical Volume {name} is set to be removed" ret.update({"comment": comt, "result": None}) with patch.dict(lvm.__opts__, {"test": True}): assert lvm.pv_absent(name) == ret @@ -102,7 +102,7 @@ def test_vg_present(): """ name = "testvg00" - comt = "Failed to create Volume Group {}".format(name) + comt = f"Failed to create Volume Group {name}" ret = {"name": name, "changes": {}, "result": False, "comment": comt} @@ -111,7 +111,7 @@ def test_vg_present(): with patch.dict(lvm.__opts__, {"test": False}): assert lvm.vg_present(name) == ret - comt = "Volume Group {} is set to be created".format(name) + comt = f"Volume Group {name} is set to be created" ret.update({"comment": comt, "result": None}) with patch.dict(lvm.__opts__, {"test": True}): assert lvm.vg_present(name) == ret @@ -123,7 +123,7 @@ def test_vg_absent(): """ name = "testvg00" - comt = "Volume Group {} already absent".format(name) + comt = f"Volume Group {name} already absent" ret = {"name": name, "changes": {}, "result": True, "comment": comt} @@ -131,7 +131,7 @@ def test_vg_absent(): with patch.dict(lvm.__salt__, {"lvm.vgdisplay": mock}): assert lvm.vg_absent(name) == ret - comt = "Volume Group {} is set to be removed".format(name) + comt = f"Volume Group {name} is set to be removed" ret.update({"comment": comt, "result": None}) with patch.dict(lvm.__opts__, {"test": True}): assert lvm.vg_absent(name) == ret @@ -143,7 +143,7 @@ def test_lv_present(lv01, lv02): """ name = "testlv01" vgname = "testvg01" - comt = "Logical Volume {} already present".format(name) + comt = f"Logical Volume {name} already present" ret = {"name": name, "changes": {}, "result": True, "comment": comt} mock = MagicMock(return_value=lv01) @@ -152,7 +152,7 @@ def test_lv_present(lv01, lv02): mock = MagicMock(return_value=lv02) with patch.dict(lvm.__salt__, {"lvm.lvdisplay": mock}): - comt = "Logical Volume {} is set to be created".format(name) + comt = f"Logical Volume {name} is set to be created" ret.update({"comment": comt, "result": None}) with patch.dict(lvm.__opts__, {"test": True}): assert lvm.lv_present(name, vgname=vgname) == ret @@ -177,7 +177,7 @@ def test_lv_present_with_valid_suffixes(lv01, lv02): "4194304s", "4194304S", ] - comt = "Logical Volume {} already present".format(name) + comt = f"Logical Volume {name} already present" ret = {"name": name, "changes": {}, "result": True, "comment": comt} mock = MagicMock(return_value=lv01) @@ -207,7 +207,7 @@ def test_lv_present_with_valid_suffixes(lv01, lv02): ] mock = MagicMock(return_value=lv02) with patch.dict(lvm.__salt__, {"lvm.lvdisplay": mock}): - comt = "Logical Volume {} is set to be created".format(name) + comt = f"Logical Volume {name} is set to be created" ret.update({"comment": comt, "result": None}) with patch.dict(lvm.__opts__, {"test": True}): for size in sizes_list: @@ -221,12 +221,12 @@ def test_lv_present_with_invalid_suffixes(lv02): name = "testlv01" vgname = "testvg01" sizes_list = ["1B", "1b", "2K", "2k", "2KB", "2kb", "3BB", "3Bb", "4JKL", "YJK"] - comt = "Logical Volume {} already present".format(name) + comt = f"Logical Volume {name} already present" ret = {"name": name, "changes": {}, "result": True, "comment": comt} mock = MagicMock(return_value=lv02) with patch.dict(lvm.__salt__, {"lvm.lvdisplay": mock}): - comt = "Logical Volume {} is set to be created".format(name) + comt = f"Logical Volume {name} is set to be created" ret.update({"comment": comt, "result": None}) with patch.dict(lvm.__opts__, {"test": True}): for size in sizes_list: @@ -258,7 +258,7 @@ def test_lv_present_with_percentage_extents(lv01, lv02): extents = "42%VG" mock = MagicMock(return_value=lv02) with patch.dict(lvm.__salt__, {"lvm.lvdisplay": mock}): - comt = "Logical Volume {} is set to be created".format(name) + comt = f"Logical Volume {name} is set to be created" ret.update({"comment": comt, "result": None}) with patch.dict(lvm.__opts__, {"test": True}): assert lvm.lv_present(name, vgname=vgname, extents=extents) == ret @@ -270,7 +270,7 @@ def test_lv_present_with_force(lv01, lv02): """ name = "testlv01" vgname = "testvg01" - comt = "Logical Volume {} already present".format(name) + comt = f"Logical Volume {name} already present" ret = {"name": name, "changes": {}, "result": True, "comment": comt} mock = MagicMock(return_value=lv01) @@ -279,7 +279,7 @@ def test_lv_present_with_force(lv01, lv02): mock = MagicMock(return_value=lv02) with patch.dict(lvm.__salt__, {"lvm.lvdisplay": mock}): - comt = "Logical Volume {} is set to be created".format(name) + comt = f"Logical Volume {name} is set to be created" ret.update({"comment": comt, "result": None}) with patch.dict(lvm.__opts__, {"test": True}): assert lvm.lv_present(name, vgname=vgname, force=True) == ret @@ -291,7 +291,7 @@ def test_lv_present_with_same_size(lv01): """ name = "testlv01" vgname = "testvg01" - comt = "Logical Volume {} already present".format(name) + comt = f"Logical Volume {name} already present" ret = {"name": name, "changes": {}, "result": True, "comment": comt} mock = MagicMock(return_value=lv01) @@ -305,7 +305,7 @@ def test_lv_present_with_increase(lv01): """ name = "testlv01" vgname = "testvg01" - comt = "Logical Volume {} is set to be resized".format(name) + comt = f"Logical Volume {name} is set to be resized" ret = {"name": name, "changes": {}, "result": None, "comment": comt} mock = MagicMock(return_value=lv01) @@ -334,7 +334,7 @@ def test_lv_present_with_reduce_with_force(lv01): """ name = "testlv01" vgname = "testvg01" - comt = "Logical Volume {} is set to be resized".format(name) + comt = f"Logical Volume {name} is set to be resized" ret = {"name": name, "changes": {}, "result": None, "comment": comt} mock = MagicMock(return_value=lv01) @@ -349,7 +349,7 @@ def test_lv_absent(): """ name = "testlv00" - comt = "Logical Volume {} already absent".format(name) + comt = f"Logical Volume {name} already absent" ret = {"name": name, "changes": {}, "result": True, "comment": comt} @@ -357,7 +357,7 @@ def test_lv_absent(): with patch.dict(lvm.__salt__, {"lvm.lvdisplay": mock}): assert lvm.lv_absent(name) == ret - comt = "Logical Volume {} is set to be removed".format(name) + comt = f"Logical Volume {name} is set to be removed" ret.update({"comment": comt, "result": None}) with patch.dict(lvm.__opts__, {"test": True}): assert lvm.lv_absent(name) == ret diff --git a/tests/pytests/unit/states/test_lxc.py b/tests/pytests/unit/states/test_lxc.py index 3ee57f1b3e7..398a0456f2f 100644 --- a/tests/pytests/unit/states/test_lxc.py +++ b/tests/pytests/unit/states/test_lxc.py @@ -44,7 +44,7 @@ def test_present(): ret.update({"comment": comt, "result": None}) assert lxc.present(name, running=True, clone_from=True) == ret - comt = "Container '{}' would be stopped".format(name) + comt = f"Container '{name}' would be stopped" ret.update({"comment": comt, "result": None}) assert lxc.present(name, running=False, clone_from=True) == ret @@ -69,17 +69,17 @@ def test_absent(): mock = MagicMock(side_effect=[False, True, True]) mock_des = MagicMock(return_value={"state": True}) with patch.dict(lxc.__salt__, {"lxc.exists": mock, "lxc.destroy": mock_des}): - comt = "Container '{}' does not exist".format(name) + comt = f"Container '{name}' does not exist" ret.update({"comment": comt}) assert lxc.absent(name) == ret with patch.dict(lxc.__opts__, {"test": True}): - comt = "Container '{}' would be destroyed".format(name) + comt = f"Container '{name}' would be destroyed" ret.update({"comment": comt, "result": None}) assert lxc.absent(name) == ret with patch.dict(lxc.__opts__, {"test": False}): - comt = "Container '{}' was destroyed".format(name) + comt = f"Container '{name}' was destroyed" ret.update({"comment": comt, "result": True, "changes": {"state": True}}) assert lxc.absent(name) == ret @@ -97,7 +97,7 @@ def test_running(): with patch.dict( lxc.__salt__, {"lxc.exists": mock, "lxc.state": mock_t, "lxc.start": mock} ): - comt = "Container '{}' does not exist".format(name) + comt = f"Container '{name}' does not exist" ret.update({"comment": comt}) assert lxc.running(name) == ret @@ -133,7 +133,7 @@ def test_frozen(): mock = MagicMock(return_value={"state": {"new": "stop"}}) mock_t = MagicMock(side_effect=["frozen", "stopped", "stopped"]) with patch.dict(lxc.__salt__, {"lxc.freeze": mock, "lxc.state": mock_t}): - comt = "Container '{}' is already frozen".format(name) + comt = f"Container '{name}' is already frozen" ret.update({"comment": comt}) assert lxc.frozen(name) == ret @@ -165,11 +165,11 @@ def test_stopped(): mock = MagicMock(return_value={"state": {"new": "stop"}}) mock_t = MagicMock(side_effect=[None, "stopped", "frozen", "frozen"]) with patch.dict(lxc.__salt__, {"lxc.stop": mock, "lxc.state": mock_t}): - comt = "Container '{}' does not exist".format(name) + comt = f"Container '{name}' does not exist" ret.update({"comment": comt}) assert lxc.stopped(name) == ret - comt = "Container '{}' is already stopped".format(name) + comt = f"Container '{name}' is already stopped" ret.update({"comment": comt, "result": True}) assert lxc.stopped(name) == ret @@ -209,7 +209,7 @@ def test_edited_conf(): """ name = "web01" - comment = "{} lxc.conf will be edited".format(name) + comment = f"{name} lxc.conf will be edited" ret = {"name": name, "result": True, "comment": comment, "changes": {}} diff --git a/tests/pytests/unit/states/test_makeconf.py b/tests/pytests/unit/states/test_makeconf.py index 7f7b3a4fb86..6a46675cbb1 100644 --- a/tests/pytests/unit/states/test_makeconf.py +++ b/tests/pytests/unit/states/test_makeconf.py @@ -24,7 +24,7 @@ def test_present(): mock_t = MagicMock(return_value=True) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock_t}): - comt = "Variable {} is already present in make.conf".format(name) + comt = f"Variable {name} is already present in make.conf" ret.update({"comment": comt}) assert makeconf.present(name) == ret @@ -39,6 +39,6 @@ def test_absent(): mock = MagicMock(return_value=None) with patch.dict(makeconf.__salt__, {"makeconf.get_var": mock}): - comt = "Variable {} is already absent from make.conf".format(name) + comt = f"Variable {name} is already absent from make.conf" ret.update({"comment": comt}) assert makeconf.absent(name) == ret diff --git a/tests/pytests/unit/states/test_mongodb_database.py b/tests/pytests/unit/states/test_mongodb_database.py index e82bb159d53..9e8ecf3b1a1 100644 --- a/tests/pytests/unit/states/test_mongodb_database.py +++ b/tests/pytests/unit/states/test_mongodb_database.py @@ -28,15 +28,15 @@ def test_absent(): {"mongodb.db_exists": mock, "mongodb.db_remove": mock_t}, ): with patch.dict(mongodb_database.__opts__, {"test": True}): - comt = "Database {} is present and needs to be removed".format(name) + comt = f"Database {name} is present and needs to be removed" ret.update({"comment": comt}) assert mongodb_database.absent(name) == ret with patch.dict(mongodb_database.__opts__, {"test": False}): - comt = "Database {} has been removed".format(name) + comt = f"Database {name} has been removed" ret.update({"comment": comt, "result": True, "changes": {"mydb": "Absent"}}) assert mongodb_database.absent(name) == ret - comt = "Database {} is not present".format(name) + comt = f"Database {name} is not present" ret.update({"comment": comt, "changes": {}}) assert mongodb_database.absent(name) == ret diff --git a/tests/pytests/unit/states/test_mongodb_user.py b/tests/pytests/unit/states/test_mongodb_user.py index cc1524c85c5..5ba8b11e23b 100644 --- a/tests/pytests/unit/states/test_mongodb_user.py +++ b/tests/pytests/unit/states/test_mongodb_user.py @@ -37,12 +37,12 @@ def test_present(): assert mongodb_user.present(name, passwd) == ret with patch.dict(mongodb_user.__opts__, {"test": True}): - comt = "User {} is not present and needs to be created".format(name) + comt = f"User {name} is not present and needs to be created" ret.update({"comment": comt, "result": None}) assert mongodb_user.present(name, passwd) == ret with patch.dict(mongodb_user.__opts__, {"test": False}): - comt = "User {} has been created".format(name) + comt = f"User {name} has been created" ret.update({"comment": comt, "result": True, "changes": {name: "Present"}}) assert mongodb_user.present(name, passwd) == ret @@ -62,15 +62,15 @@ def test_absent(): {"mongodb.user_exists": mock, "mongodb.user_remove": mock_t}, ): with patch.dict(mongodb_user.__opts__, {"test": True}): - comt = "User {} is present and needs to be removed".format(name) + comt = f"User {name} is present and needs to be removed" ret.update({"comment": comt, "result": None}) assert mongodb_user.absent(name) == ret with patch.dict(mongodb_user.__opts__, {"test": False}): - comt = "User {} has been removed".format(name) + comt = f"User {name} has been removed" ret.update({"comment": comt, "result": True, "changes": {name: "Absent"}}) assert mongodb_user.absent(name) == ret - comt = "User {} is not present".format(name) + comt = f"User {name} is not present" ret.update({"comment": comt, "result": True, "changes": {}}) assert mongodb_user.absent(name) == ret diff --git a/tests/pytests/unit/states/test_mount.py b/tests/pytests/unit/states/test_mount.py index 235cabc405e..14e716f24e6 100644 --- a/tests/pytests/unit/states/test_mount.py +++ b/tests/pytests/unit/states/test_mount.py @@ -1359,9 +1359,9 @@ def test_bind_mount_copy_active_opts(mount_name): ), ): with patch.dict(mount.__opts__, {"test": True}): - ret[ - "comment" - ] = "Remount would be forced because options (nodev,noexec,nosuid) changed" + ret["comment"] = ( + "Remount would be forced because options (nodev,noexec,nosuid) changed" + ) result = mount.mounted( name=name, device=device, diff --git a/tests/pytests/unit/states/test_npm.py b/tests/pytests/unit/states/test_npm.py index 093f7065f4f..6e8e1abe7e4 100644 --- a/tests/pytests/unit/states/test_npm.py +++ b/tests/pytests/unit/states/test_npm.py @@ -140,7 +140,7 @@ def test_cache_cleaned(): pkg_ret = {"name": name, "result": False, "comment": "", "changes": {}} ret = {"name": None, "result": False, "comment": "", "changes": {}} - mock_list = MagicMock(return_value=["~/.npm", "~/.npm/{}/".format(name)]) + mock_list = MagicMock(return_value=["~/.npm", f"~/.npm/{name}/"]) mock_cache_clean_success = MagicMock(return_value=True) mock_cache_clean_failure = MagicMock(return_value=False) mock_err = MagicMock(side_effect=CommandExecutionError) @@ -151,14 +151,14 @@ def test_cache_cleaned(): assert npm.cache_cleaned() == ret with patch.dict(npm.__salt__, {"npm.cache_list": mock_err}): - comt = "Error looking up cached {}: ".format(name) + comt = f"Error looking up cached {name}: " pkg_ret.update({"comment": comt}) assert npm.cache_cleaned(name) == pkg_ret mock_data = {"npm.cache_list": mock_list, "npm.cache_clean": MagicMock()} with patch.dict(npm.__salt__, mock_data): non_cached_pkg = "salt" - comt = "Package {} is not in the cache".format(non_cached_pkg) + comt = f"Package {non_cached_pkg} is not in the cache" pkg_ret.update({"name": non_cached_pkg, "result": True, "comment": comt}) assert npm.cache_cleaned(non_cached_pkg) == pkg_ret pkg_ret.update({"name": name}) @@ -169,7 +169,7 @@ def test_cache_cleaned(): assert npm.cache_cleaned() == ret with patch.dict(npm.__opts__, {"test": True}): - comt = "Cached {} set to be removed".format(name) + comt = f"Cached {name} set to be removed" pkg_ret.update({"result": None, "comment": comt}) assert npm.cache_cleaned(name) == pkg_ret @@ -181,7 +181,7 @@ def test_cache_cleaned(): assert npm.cache_cleaned() == ret with patch.dict(npm.__opts__, {"test": False}): - comt = "Cached {} successfully removed".format(name) + comt = f"Cached {name} successfully removed" pkg_ret.update( {"result": True, "comment": comt, "changes": {name: "Removed"}} ) @@ -199,7 +199,7 @@ def test_cache_cleaned(): assert npm.cache_cleaned() == ret with patch.dict(npm.__opts__, {"test": False}): - comt = "Error cleaning cached {}".format(name) + comt = f"Error cleaning cached {name}" pkg_ret.update({"result": False, "comment": comt}) pkg_ret["changes"] = {} assert npm.cache_cleaned(name) == pkg_ret diff --git a/tests/pytests/unit/states/test_pagerduty.py b/tests/pytests/unit/states/test_pagerduty.py index 799d266b9a1..549292c2c1f 100644 --- a/tests/pytests/unit/states/test_pagerduty.py +++ b/tests/pytests/unit/states/test_pagerduty.py @@ -25,13 +25,13 @@ def test_create_event(): ret = {"name": name, "result": None, "comment": "", "changes": {}} with patch.dict(pagerduty.__opts__, {"test": True}): - comt = "Need to create event: {}".format(name) + comt = f"Need to create event: {name}" ret.update({"comment": comt}) assert pagerduty.create_event(name, details, service_key, profile) == ret with patch.dict(pagerduty.__opts__, {"test": False}): mock_t = MagicMock(return_value=True) with patch.dict(pagerduty.__salt__, {"pagerduty.create_event": mock_t}): - comt = "Created event: {}".format(name) + comt = f"Created event: {name}" ret.update({"comment": comt, "result": True}) assert pagerduty.create_event(name, details, service_key, profile) == ret diff --git a/tests/pytests/unit/states/test_pdbedit.py b/tests/pytests/unit/states/test_pdbedit.py index 900553ca4cf..35d21efe5dd 100644 --- a/tests/pytests/unit/states/test_pdbedit.py +++ b/tests/pytests/unit/states/test_pdbedit.py @@ -22,4 +22,4 @@ def test_generate_absent(): pdbedit_mod.__salt__, {"cmd.run_all": MagicMock(return_value=cmd_ret)} ): ret = pdbedit.absent(name) - assert ret["comment"] == "account {} is absent".format(name) + assert ret["comment"] == f"account {name} is absent" diff --git a/tests/pytests/unit/states/test_pecl.py b/tests/pytests/unit/states/test_pecl.py index 132a8f8de7d..32a39d9504f 100644 --- a/tests/pytests/unit/states/test_pecl.py +++ b/tests/pytests/unit/states/test_pecl.py @@ -25,7 +25,7 @@ def test_installed(): mock_lst = MagicMock(return_value={name: "stable"}) mock_t = MagicMock(return_value=True) with patch.dict(pecl.__salt__, {"pecl.list": mock_lst, "pecl.install": mock_t}): - comt = "Pecl extension {} is already installed.".format(name) + comt = f"Pecl extension {name} is already installed." ret.update({"comment": comt, "result": True}) assert pecl.installed(name) == ret @@ -57,7 +57,7 @@ def test_removed(): mock_lst = MagicMock(side_effect=[{}, {name: "stable"}, {name: "stable"}]) mock_t = MagicMock(return_value=True) with patch.dict(pecl.__salt__, {"pecl.list": mock_lst, "pecl.uninstall": mock_t}): - comt = "Pecl extension {} is not installed.".format(name) + comt = f"Pecl extension {name} is not installed." ret.update({"comment": comt, "result": True}) assert pecl.removed(name) == ret diff --git a/tests/pytests/unit/states/test_pip.py b/tests/pytests/unit/states/test_pip.py index 1a71be86ac1..1c5cda4fe14 100644 --- a/tests/pytests/unit/states/test_pip.py +++ b/tests/pytests/unit/states/test_pip.py @@ -1,6 +1,7 @@ """ :codeauthor: Eric Graham """ + import logging import pytest diff --git a/tests/pytests/unit/states/test_ports.py b/tests/pytests/unit/states/test_ports.py index 3c1bded928a..6739437e0a4 100644 --- a/tests/pytests/unit/states/test_ports.py +++ b/tests/pytests/unit/states/test_ports.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import os import pytest @@ -66,7 +67,7 @@ def test_installed(): mock_dict = MagicMock(return_value={"origin": {"origin": "salt"}}) with patch.dict(ports.__salt__, {"pkg.list_pkgs": mock_dict}): with patch.dict(ports.__opts__, {"test": True}): - comt = "{} will be installed".format(name) + comt = f"{name} will be installed" ret.update({"comment": comt, "result": None}) assert ports.installed(name) == ret diff --git a/tests/pytests/unit/states/test_powerpath.py b/tests/pytests/unit/states/test_powerpath.py index 1f808581a45..4624df76d06 100644 --- a/tests/pytests/unit/states/test_powerpath.py +++ b/tests/pytests/unit/states/test_powerpath.py @@ -42,7 +42,7 @@ def test_license_present(): ret.update({"comment": comt, "result": False}) assert powerpath.license_present(name) == ret - comt = "License key {} already present".format(name) + comt = f"License key {name} already present" ret.update({"comment": comt, "result": True}) assert powerpath.license_present(name) == ret @@ -88,7 +88,7 @@ def test_license_absent(): ret.update({"comment": comt, "result": False}) assert powerpath.license_absent(name) == ret - comt = "License key {} not present".format(name) + comt = f"License key {name} not present" ret.update({"comment": comt, "result": True}) assert powerpath.license_absent(name) == ret diff --git a/tests/pytests/unit/states/test_pyrax_queues.py b/tests/pytests/unit/states/test_pyrax_queues.py index d5315163111..0f16e00fe4f 100644 --- a/tests/pytests/unit/states/test_pyrax_queues.py +++ b/tests/pytests/unit/states/test_pyrax_queues.py @@ -31,7 +31,7 @@ def test_present(): ] ) with patch.dict(pyrax_queues.__salt__, {"cloud.action": mock_dct}): - comt = "{} present.".format(name) + comt = f"{name} present." ret.update({"comment": comt}) assert pyrax_queues.present(name, provider) == ret diff --git a/tests/pytests/unit/states/test_rbenv.py b/tests/pytests/unit/states/test_rbenv.py index b9cf9917d49..2b62a828102 100644 --- a/tests/pytests/unit/states/test_rbenv.py +++ b/tests/pytests/unit/states/test_rbenv.py @@ -42,12 +42,12 @@ def test_installed(): ): with patch.dict(rbenv.__opts__, {"test": True}): name = "1.9.3-p551" - comt = "Ruby {} is set to be installed".format(name) + comt = f"Ruby {name} is set to be installed" ret = {"name": name, "changes": {}, "comment": comt, "result": None} assert rbenv.installed(name) == ret name = "2.4.1" - comt = "Ruby {} is already installed".format(name) + comt = f"Ruby {name} is already installed" ret = { "name": name, "changes": {}, @@ -58,7 +58,7 @@ def test_installed(): assert rbenv.installed(name) == ret name = "2.3.4" - comt = "Ruby {} is already installed".format(name) + comt = f"Ruby {name} is already installed" ret = { "name": name, "changes": {}, @@ -136,16 +136,16 @@ def test_absent(): with patch.dict(rbenv.__opts__, {"test": True}): name = "1.9.3-p551" - comt = "Rbenv not installed, {} not either".format(name) + comt = f"Rbenv not installed, {name} not either" ret = {"name": name, "changes": {}, "comment": comt, "result": True} assert rbenv.absent(name) == ret - comt = "Ruby {} is already uninstalled".format(name) + comt = f"Ruby {name} is already uninstalled" ret = {"name": name, "changes": {}, "comment": comt, "result": True} assert rbenv.absent(name) == ret name = "2.3.4" - comt = "Ruby {} is set to be uninstalled".format(name) + comt = f"Ruby {name} is set to be uninstalled" ret = { "name": name, "changes": {}, @@ -156,7 +156,7 @@ def test_absent(): assert rbenv.absent("2.3.4") == ret name = "2.4.1" - comt = "Ruby {} is set to be uninstalled".format(name) + comt = f"Ruby {name} is set to be uninstalled" ret = { "name": name, "changes": {}, @@ -168,11 +168,11 @@ def test_absent(): with patch.dict(rbenv.__opts__, {"test": False}): name = "1.9.3-p551" - comt = "Rbenv not installed, {} not either".format(name) + comt = f"Rbenv not installed, {name} not either" ret = {"name": name, "changes": {}, "comment": comt, "result": True} assert rbenv.absent(name) == ret - comt = "Ruby {} is already absent".format(name) + comt = f"Ruby {name} is already absent" ret = {"name": name, "changes": {}, "comment": comt, "result": True} assert rbenv.absent(name) == ret diff --git a/tests/pytests/unit/states/test_slack.py b/tests/pytests/unit/states/test_slack.py index 5f4dfaca645..a9b59f49592 100644 --- a/tests/pytests/unit/states/test_slack.py +++ b/tests/pytests/unit/states/test_slack.py @@ -29,7 +29,7 @@ def test_post_message_apikey(): with patch.dict(slack.__opts__, {"test": True}): mock = MagicMock(return_value=True) with patch.dict(slack.__salt__, {"config.get": mock}): - comt = "The following message is to be sent to Slack: {}".format(message) + comt = f"The following message is to be sent to Slack: {message}" ret.update({"comment": comt}) assert ( slack.post_message( @@ -129,7 +129,7 @@ def test_post_message_webhook(): with patch.dict(slack.__opts__, {"test": True}): mock = MagicMock(return_value=True) with patch.dict(slack.__salt__, {"config.get": mock}): - comt = "The following message is to be sent to Slack: {}".format(message) + comt = f"The following message is to be sent to Slack: {message}" ret.update({"comment": comt}) assert ( slack.post_message( diff --git a/tests/pytests/unit/states/test_smartos.py b/tests/pytests/unit/states/test_smartos.py index b42c7e528bc..2ef24355f2f 100644 --- a/tests/pytests/unit/states/test_smartos.py +++ b/tests/pytests/unit/states/test_smartos.py @@ -21,9 +21,10 @@ def test_config_present_does_not_exist(): with patch("salt.utils.atomicfile.atomic_open", side_effect=IOError): ret = smartos.config_present(name=name, value=value) assert not ret["result"] - assert ret[ - "comment" - ] == 'Could not add property {} with value "{}" to config'.format(name, value) + assert ( + ret["comment"] + == f'Could not add property {name} with value "{value}" to config' + ) def test_parse_vmconfig_vrrp(): diff --git a/tests/pytests/unit/states/test_splunk_search.py b/tests/pytests/unit/states/test_splunk_search.py index 0f51ffe7ad9..caa12d8486a 100644 --- a/tests/pytests/unit/states/test_splunk_search.py +++ b/tests/pytests/unit/states/test_splunk_search.py @@ -27,11 +27,11 @@ def test_present(): {"splunk_search.get": mock, "splunk_search.create": mock}, ): with patch.dict(splunk_search.__opts__, {"test": True}): - comt = "Would update {}".format(name) + comt = f"Would update {name}" ret.update({"comment": comt}) assert splunk_search.present(name) == ret - comt = "Would create {}".format(name) + comt = f"Would create {name}" ret.update({"comment": comt}) assert splunk_search.present(name) == ret @@ -53,10 +53,10 @@ def test_absent(): mock = MagicMock(side_effect=[True, False]) with patch.dict(splunk_search.__salt__, {"splunk_search.get": mock}): with patch.dict(splunk_search.__opts__, {"test": True}): - comt = "Would delete {}".format(name) + comt = f"Would delete {name}" ret.update({"comment": comt}) assert splunk_search.absent(name) == ret - comt = "{} is absent.".format(name) + comt = f"{name} is absent." ret.update({"comment": comt, "result": True, "changes": {}}) assert splunk_search.absent(name) == ret diff --git a/tests/pytests/unit/states/test_ssh_auth.py b/tests/pytests/unit/states/test_ssh_auth.py index 8f487da07cd..c192b65eade 100644 --- a/tests/pytests/unit/states/test_ssh_auth.py +++ b/tests/pytests/unit/states/test_ssh_auth.py @@ -144,7 +144,7 @@ def test_manage(): with patch("salt.states.ssh_auth.present") as call_mocked_present: mock_present = { "comment": ( - "The authorized host key newkey for user {} was added".format(user) + f"The authorized host key newkey for user {user} was added" ), "changes": {"newkey": "New"}, "result": True, diff --git a/tests/pytests/unit/states/test_ssh_known_hosts.py b/tests/pytests/unit/states/test_ssh_known_hosts.py index 67c69d270e6..524a000764c 100644 --- a/tests/pytests/unit/states/test_ssh_known_hosts.py +++ b/tests/pytests/unit/states/test_ssh_known_hosts.py @@ -76,7 +76,7 @@ def test_present(): } mock = MagicMock(return_value=result) with patch.dict(ssh_known_hosts.__salt__, {"ssh.set_known_host": mock}): - comt = "{}'s key saved to .ssh/known_hosts (key: {})".format(name, key) + comt = f"{name}'s key saved to .ssh/known_hosts (key: {key})" ret.update( { "comment": comt, diff --git a/tests/pytests/unit/states/test_supervisord.py b/tests/pytests/unit/states/test_supervisord.py index 4e5609f034c..3f8f7496f67 100644 --- a/tests/pytests/unit/states/test_supervisord.py +++ b/tests/pytests/unit/states/test_supervisord.py @@ -47,7 +47,7 @@ def test_dead(): ret = {"name": name, "changes": {}, "result": None, "comment": ""} with patch.dict(supervisord.__opts__, {"test": True}): - comt = "Service {} is set to be stopped".format(name) + comt = f"Service {name} is set to be stopped" ret.update({"comment": comt}) assert supervisord.dead(name) == ret diff --git a/tests/pytests/unit/states/test_sysctl.py b/tests/pytests/unit/states/test_sysctl.py index ec81ea9d7ab..5ffad3745d9 100644 --- a/tests/pytests/unit/states/test_sysctl.py +++ b/tests/pytests/unit/states/test_sysctl.py @@ -20,7 +20,7 @@ def test_empty_config_file_and_value_not_found(): """ name = "some.unknown.oid" value = "1" - comment = "Sysctl option {} would be changed to {}".format(name, value) + comment = f"Sysctl option {name} would be changed to {value}" ret = {"name": name, "result": None, "changes": {}, "comment": comment} @@ -59,7 +59,7 @@ def test_to_be_changed_not_configured(): """ name = "vfs.usermount" value = "1" - comment = "Sysctl option {} set to be changed to {}".format(name, value) + comment = f"Sysctl option {name} set to be changed to {value}" ret = {"name": name, "result": None, "changes": {}, "comment": comment} def mock_current(config_file=None): @@ -137,7 +137,7 @@ def test_no_change(): """ name = "vfs.usermount" value = "1" - comment = "Sysctl value {} = {} is already set".format(name, value) + comment = f"Sysctl value {name} = {value} is already set" ret = {"name": name, "result": True, "changes": {}, "comment": comment} def mock_config(config_file=None): @@ -159,7 +159,7 @@ def test_change(): name = "vfs.usermount" old_value = "2" value = "1" - comment = "Sysctl option {} would be changed to {}".format(name, value) + comment = f"Sysctl option {name} would be changed to {value}" ret = {"name": name, "result": None, "changes": {}, "comment": comment} def mock_config(config_file=None): @@ -180,7 +180,7 @@ def test_failed_to_set(): """ name = "net.isr.maxthreads" value = "8" - comment = "Failed to set {} to {}: ".format(name, value) + comment = f"Failed to set {name} to {value}: " ret = {"name": name, "result": False, "changes": {}, "comment": comment} with patch.dict(sysctl.__opts__, {"test": False}): @@ -195,7 +195,7 @@ def test_already_set(): """ name = "vfs.usermount" value = "1" - comment = "Sysctl value {} = {} is already set".format(name, value) + comment = f"Sysctl value {name} = {value} is already set" ret = {"name": name, "result": True, "changes": {}, "comment": comment} with patch.dict(sysctl.__opts__, {"test": False}): mock = MagicMock(return_value="Already set") @@ -209,7 +209,7 @@ def test_updated(): """ name = "vfs.usermount" value = "1" - comment = "Updated sysctl value {} = {}".format(name, value) + comment = f"Updated sysctl value {name} = {value}" changes = {name: value} ret = {"name": name, "result": True, "changes": changes, "comment": comment} with patch.dict(sysctl.__opts__, {"test": False}): diff --git a/tests/pytests/unit/states/test_sysfs.py b/tests/pytests/unit/states/test_sysfs.py index 030af223155..1e95400826d 100644 --- a/tests/pytests/unit/states/test_sysfs.py +++ b/tests/pytests/unit/states/test_sysfs.py @@ -1,6 +1,7 @@ """ :codeauthor: Piter Punk """ + import pytest import salt.states.sysfs as sysfs @@ -18,7 +19,7 @@ def test_if_the_sysfs_attribute_exists(): """ name = "block/sda/queue/this_does_not_exist" value = "none" - comment = "SysFS attribute {} doesn't exist.".format(name) + comment = f"SysFS attribute {name} doesn't exist." ret = {"name": name, "result": False, "changes": {}, "comment": comment} mock_read = MagicMock(return_value=False) @@ -32,7 +33,7 @@ def test_name_is_an_object_and_not_an_attribute(): """ name = "block/sda/queue" value = "none" - comment = "{} is not a SysFS attribute.".format(name) + comment = f"{name} is not a SysFS attribute." ret = {"name": name, "result": False, "changes": {}, "comment": comment} read_from_sysfs = { @@ -52,7 +53,7 @@ def test_already_set(): """ name = "block/sda/queue" value = "none" - comment = "SysFS attribute {} is already set.".format(name) + comment = f"SysFS attribute {name} is already set." ret = {"name": name, "result": True, "changes": {}, "comment": comment} read_from_sysfs = "[none] mq-deadline" @@ -68,7 +69,7 @@ def test_set_new_value_with_test_equals_true(): """ name = "devices/system/cpu/cpufreq/policy0" value = "powersave" - comment = "SysFS attribute {} set to be changed.".format(name) + comment = f"SysFS attribute {name} set to be changed." ret = {"name": name, "result": None, "changes": {}, "comment": comment} read_from_sysfs = "performance" @@ -85,7 +86,7 @@ def test_set_new_value_with_success(): """ name = "block/sda/queue/scheduler" value = "mq-deadline" - comment = "Updated SysFS attribute {} to {}".format(name, value) + comment = f"Updated SysFS attribute {name} to {value}" ret = {"name": name, "result": True, "changes": {name: value}, "comment": comment} read_from_sysfs = "[none] mq-deadline" @@ -104,7 +105,7 @@ def test_set_new_value_with_failure(): """ name = "block/sda/queue/scheduler" value = "imaginary_scheduler" - comment = "Failed to set {} to {}".format(name, value) + comment = f"Failed to set {name} to {value}" ret = {"name": name, "result": False, "changes": {}, "comment": comment} read_from_sysfs = "[none] mq-deadline" diff --git a/tests/pytests/unit/states/test_virtualenv_mod.py b/tests/pytests/unit/states/test_virtualenv_mod.py index 5c2e33b85d0..d614050202e 100644 --- a/tests/pytests/unit/states/test_virtualenv_mod.py +++ b/tests/pytests/unit/states/test_virtualenv_mod.py @@ -4,7 +4,6 @@ Test cases for salt.states.virtualenv_mod """ - import os import pytest diff --git a/tests/pytests/unit/states/test_webutil.py b/tests/pytests/unit/states/test_webutil.py index d8a10f2d7a0..de8041e9770 100644 --- a/tests/pytests/unit/states/test_webutil.py +++ b/tests/pytests/unit/states/test_webutil.py @@ -2,7 +2,6 @@ :codeauthor: Alexander Pyatkin """ - import pytest import salt.states.webutil as htpasswd diff --git a/tests/pytests/unit/states/test_win_lgpo.py b/tests/pytests/unit/states/test_win_lgpo.py index 438b5c38689..cd898843986 100644 --- a/tests/pytests/unit/states/test_win_lgpo.py +++ b/tests/pytests/unit/states/test_win_lgpo.py @@ -1,6 +1,7 @@ """ :codeauthor: Shane Lee """ + import copy import pytest diff --git a/tests/pytests/unit/states/test_win_path.py b/tests/pytests/unit/states/test_win_path.py index 4f685f6fb78..17507ef1ffa 100644 --- a/tests/pytests/unit/states/test_win_path.py +++ b/tests/pytests/unit/states/test_win_path.py @@ -39,7 +39,7 @@ def test_absent(name): # Test already absent with patch.dict(win_path.__salt__, {"win_path.exists": _mock([False])}): ret = copy.deepcopy(ret_base) - ret["comment"] = "{} is not in the PATH".format(name) + ret["comment"] = f"{name} is not in the PATH" ret["result"] = True assert win_path.absent(name) == ret @@ -48,7 +48,7 @@ def test_absent(name): win_path.__salt__, {"win_path.exists": _mock([True, False])} ): ret = copy.deepcopy(ret_base) - ret["comment"] = "Removed {} from the PATH".format(name) + ret["comment"] = f"Removed {name} from the PATH" ret["changes"]["removed"] = name ret["result"] = True assert win_path.absent(name) == ret @@ -58,7 +58,7 @@ def test_absent(name): win_path.__salt__, {"win_path.exists": _mock([True, True])} ): ret = copy.deepcopy(ret_base) - ret["comment"] = "Failed to remove {} from the PATH".format(name) + ret["comment"] = f"Failed to remove {name} from the PATH" ret["result"] = False assert win_path.absent(name) == ret @@ -68,14 +68,14 @@ def test_absent(name): # Test already absent with patch.dict(win_path.__salt__, {"win_path.exists": _mock([False])}): ret = copy.deepcopy(ret_base) - ret["comment"] = "{} is not in the PATH".format(name) + ret["comment"] = f"{name} is not in the PATH" ret["result"] = True assert win_path.absent(name) == ret # Test the test-mode return with patch.dict(win_path.__salt__, {"win_path.exists": _mock([True])}): ret = copy.deepcopy(ret_base) - ret["comment"] = "{} would be removed from the PATH".format(name) + ret["comment"] = f"{name} would be removed from the PATH" ret["result"] = None assert win_path.absent(name) == ret @@ -120,7 +120,7 @@ def test_exists_add_no_index_success(name): "name": name, "changes": {"index": {"old": None, "new": 3}}, "result": True, - "comment": "Added {} to the PATH.".format(name), + "comment": f"Added {name} to the PATH.", } @@ -151,7 +151,7 @@ def test_exists_add_no_index_failure(name): "name": name, "changes": {}, "result": False, - "comment": "Failed to add {} to the PATH.".format(name), + "comment": f"Failed to add {name} to the PATH.", } @@ -216,7 +216,7 @@ def test_exists_change_index_success(name): "name": name, "changes": {"index": {"old": 3, "new": 0}}, "result": True, - "comment": "Moved {} from index 3 to 0.".format(name), + "comment": f"Moved {name} from index 3 to 0.", } @@ -249,7 +249,7 @@ def test_exists_change_negative_index_success(name): "name": name, "changes": {"index": {"old": -2, "new": -1}}, "result": True, - "comment": "Moved {} from index -2 to -1.".format(name), + "comment": f"Moved {name} from index -2 to -1.", } @@ -350,7 +350,7 @@ def test_exists_change_index_failure(name): "name": name, "changes": {}, "result": False, - "comment": "Failed to move {} from index 3 to 0.".format(name), + "comment": f"Failed to move {name} from index 3 to 0.", } @@ -383,7 +383,7 @@ def test_exists_change_negative_index_failure(name): "name": name, "changes": {}, "result": False, - "comment": "Failed to move {} from index -2 to -1.".format(name), + "comment": f"Failed to move {name} from index -2 to -1.", } @@ -412,7 +412,7 @@ def test_exists_change_index_test_mode(name): "name": name, "changes": {"index": {"old": 3, "new": 0}}, "result": None, - "comment": "{} would be moved from index 3 to 0.".format(name), + "comment": f"{name} would be moved from index 3 to 0.", } @@ -441,7 +441,7 @@ def test_exists_change_negative_index_test_mode(name): "name": name, "changes": {"index": {"old": -2, "new": -1}}, "result": None, - "comment": "{} would be moved from index -2 to -1.".format(name), + "comment": f"{name} would be moved from index -2 to -1.", } @@ -479,7 +479,7 @@ def _test_exists_add_already_present(index, test_mode, name): "changes": {}, "result": True, "comment": "{} already exists in the PATH{}.".format( - name, " at index {}".format(index) if index is not None else "" + name, f" at index {index}" if index is not None else "" ), } diff --git a/tests/pytests/unit/states/test_win_wua.py b/tests/pytests/unit/states/test_win_wua.py index 51e1d9ef987..cc6e169b0f4 100644 --- a/tests/pytests/unit/states/test_win_wua.py +++ b/tests/pytests/unit/states/test_win_wua.py @@ -1,6 +1,7 @@ """ Test the win_wua state module """ + from collections import namedtuple import pytest @@ -337,7 +338,9 @@ def test_installed(update_records, update_records_identity): ) patch_opts = patch.dict(win_wua.__opts__, {"test": False}) - with patch_winapi_com, patch_dispatch, patch_wua, patch_update_collection, patch_opts: + with ( + patch_winapi_com + ), patch_dispatch, patch_wua, patch_update_collection, patch_opts: expected = { "changes": { "installed": { @@ -433,7 +436,9 @@ def test_installed_test_mode(update_records, update_records_identity): ) patch_opts = patch.dict(win_wua.__opts__, {"test": True}) - with patch_winapi_com, patch_dispatch, patch_wua, patch_update_collection, patch_opts: + with ( + patch_winapi_com + ), patch_dispatch, patch_wua, patch_update_collection, patch_opts: expected = { "changes": {}, "comment": "Updates will be installed:", @@ -493,7 +498,9 @@ def test_installed_already_installed(update_records, update_records_identity): ) patch_opts = patch.dict(win_wua.__opts__, {"test": True}) - with patch_winapi_com, patch_dispatch, patch_wua, patch_update_collection, patch_opts: + with ( + patch_winapi_com + ), patch_dispatch, patch_wua, patch_update_collection, patch_opts: expected = { "changes": {}, "comment": "Updates already installed: KB4052623", @@ -593,7 +600,9 @@ def test_removed(update_records, update_records_identity): ) patch_opts = patch.dict(win_wua.__opts__, {"test": False}) - with patch_winapi_com, patch_dispatch, patch_wua, patch_update_collection, patch_opts: + with ( + patch_winapi_com + ), patch_dispatch, patch_wua, patch_update_collection, patch_opts: expected = { "changes": { "removed": { @@ -658,7 +667,9 @@ def test_removed_test_mode(update_records, update_records_identity): ) patch_opts = patch.dict(win_wua.__opts__, {"test": True}) - with patch_winapi_com, patch_dispatch, patch_wua, patch_update_collection, patch_opts: + with ( + patch_winapi_com + ), patch_dispatch, patch_wua, patch_update_collection, patch_opts: expected = { "changes": {}, "comment": "Updates will be removed:", diff --git a/tests/pytests/unit/states/test_win_wusa.py b/tests/pytests/unit/states/test_win_wusa.py index 9b3b29d66b9..51a303179fa 100644 --- a/tests/pytests/unit/states/test_win_wusa.py +++ b/tests/pytests/unit/states/test_win_wusa.py @@ -30,10 +30,10 @@ def test_installed_existing(kb): """ mock_installed = MagicMock(return_value=True) with patch.dict(wusa.__salt__, {"wusa.is_installed": mock_installed}): - returned = wusa.installed(name=kb, source="salt://{}.msu".format(kb)) + returned = wusa.installed(name=kb, source=f"salt://{kb}.msu") expected = { "changes": {}, - "comment": "{} already installed".format(kb), + "comment": f"{kb} already installed", "name": kb, "result": True, } @@ -48,10 +48,10 @@ def test_installed_test_true(kb): with patch.dict(wusa.__salt__, {"wusa.is_installed": mock_installed}), patch.dict( wusa.__opts__, {"test": True} ): - returned = wusa.installed(name=kb, source="salt://{}.msu".format(kb)) + returned = wusa.installed(name=kb, source=f"salt://{kb}.msu") expected = { "changes": {}, - "comment": "{} would be installed".format(kb), + "comment": f"{kb} would be installed", "name": kb, "result": None, } @@ -68,10 +68,10 @@ def test_installed_cache_fail(kb): wusa.__salt__, {"wusa.is_installed": mock_installed, "cp.cache_file": mock_cache}, ): - returned = wusa.installed(name=kb, source="salt://{}.msu".format(kb)) + returned = wusa.installed(name=kb, source=f"salt://{kb}.msu") expected = { "changes": {}, - "comment": 'Unable to cache salt://{}.msu from saltenv "base"'.format(kb), + "comment": f'Unable to cache salt://{kb}.msu from saltenv "base"', "name": kb, "result": False, } @@ -83,7 +83,7 @@ def test_installed(kb): test wusa.installed assuming success """ mock_installed = MagicMock(side_effect=[False, True]) - mock_cache = MagicMock(return_value="C:\\{}.msu".format(kb)) + mock_cache = MagicMock(return_value=f"C:\\{kb}.msu") with patch.dict( wusa.__salt__, { @@ -92,10 +92,10 @@ def test_installed(kb): "wusa.install": MagicMock(), }, ): - returned = wusa.installed(name=kb, source="salt://{}.msu".format(kb)) + returned = wusa.installed(name=kb, source=f"salt://{kb}.msu") expected = { "changes": {"new": True, "old": False}, - "comment": "{} was installed. ".format(kb), + "comment": f"{kb} was installed. ", "name": kb, "result": True, } @@ -107,7 +107,7 @@ def test_installed_failed(kb): test wusa.installed with a failure """ mock_installed = MagicMock(side_effect=[False, False]) - mock_cache = MagicMock(return_value="C:\\{}.msu".format(kb)) + mock_cache = MagicMock(return_value=f"C:\\{kb}.msu") with patch.dict( wusa.__salt__, { @@ -116,10 +116,10 @@ def test_installed_failed(kb): "wusa.install": MagicMock(), }, ): - returned = wusa.installed(name=kb, source="salt://{}.msu".format(kb)) + returned = wusa.installed(name=kb, source=f"salt://{kb}.msu") expected = { "changes": {}, - "comment": "{} failed to install. ".format(kb), + "comment": f"{kb} failed to install. ", "name": kb, "result": False, } @@ -135,7 +135,7 @@ def test_uninstalled_non_existing(kb): returned = wusa.uninstalled(name=kb) expected = { "changes": {}, - "comment": "{} already uninstalled".format(kb), + "comment": f"{kb} already uninstalled", "name": kb, "result": True, } @@ -153,7 +153,7 @@ def test_uninstalled_test_true(kb): returned = wusa.uninstalled(name=kb) expected = { "changes": {}, - "comment": "{} would be uninstalled".format(kb), + "comment": f"{kb} would be uninstalled", "name": kb, "result": None, } @@ -172,7 +172,7 @@ def test_uninstalled(kb): returned = wusa.uninstalled(name=kb) expected = { "changes": {"new": False, "old": True}, - "comment": "{} was uninstalled".format(kb), + "comment": f"{kb} was uninstalled", "name": kb, "result": True, } @@ -191,7 +191,7 @@ def test_uninstalled_failed(kb): returned = wusa.uninstalled(name=kb) expected = { "changes": {}, - "comment": "{} failed to uninstall".format(kb), + "comment": f"{kb} failed to uninstall", "name": kb, "result": False, } diff --git a/tests/pytests/unit/states/test_xml.py b/tests/pytests/unit/states/test_xml.py index 81cada32504..22a0e292cec 100644 --- a/tests/pytests/unit/states/test_xml.py +++ b/tests/pytests/unit/states/test_xml.py @@ -26,7 +26,7 @@ def test_value_already_present(): "name": name, "changes": {}, "result": True, - "comment": "{} is already present".format(value), + "comment": f"{value} is already present", } with patch.dict(xml.__salt__, {"xml.get_value": MagicMock(return_value=value)}): @@ -48,7 +48,7 @@ def test_value_update(): "name": name, "changes": {name: {"new": value, "old": old_value}}, "result": True, - "comment": "{} updated".format(name), + "comment": f"{name} updated", } with patch.dict(xml.__salt__, {"xml.get_value": MagicMock(return_value=old_value)}): @@ -71,7 +71,7 @@ def test_value_update_test(): "name": name, "changes": {name: {"old": old_value, "new": value}}, "result": None, - "comment": "{} will be updated".format(name), + "comment": f"{name} will be updated", } with patch.dict(xml.__salt__, {"xml.get_value": MagicMock(return_value=old_value)}): @@ -91,7 +91,7 @@ def test_value_update_invalid_xpath(): "name": name, "changes": {}, "result": False, - "comment": "xpath query {} not found in {}".format(xpath, name), + "comment": f"xpath query {xpath} not found in {name}", } with patch.dict(xml.__salt__, {"xml.get_value": MagicMock(return_value=False)}): diff --git a/tests/pytests/unit/states/test_xmpp.py b/tests/pytests/unit/states/test_xmpp.py index bec7224cdf1..fe672be884a 100644 --- a/tests/pytests/unit/states/test_xmpp.py +++ b/tests/pytests/unit/states/test_xmpp.py @@ -2,7 +2,6 @@ :codeauthor: Rahul Handay """ - import pytest import salt.states.xmpp as xmpp diff --git a/tests/pytests/unit/states/virt/test_domain.py b/tests/pytests/unit/states/virt/test_domain.py index 091dc5ccce2..c2ddebc7374 100644 --- a/tests/pytests/unit/states/virt/test_domain.py +++ b/tests/pytests/unit/states/virt/test_domain.py @@ -165,7 +165,11 @@ def test_defined_update(test): "initrd": "/root/f8-i386-initrd", "cmdline": "console=ttyS0 ks=http://example.com/f8-i386/os/", } - assert virt.defined("myvm", cpu=2, boot=boot,) == { + assert virt.defined( + "myvm", + cpu=2, + boot=boot, + ) == { "name": "myvm", "changes": {"myvm": {"definition": True, "cpu": True}}, "result": True if not test else None, @@ -262,9 +266,11 @@ def test_running_no_change(test, running): "name": "myvm", "result": True, "changes": {"myvm": {"started": True}} if running == "shutdown" else {}, - "comment": "Domain myvm started" - if running == "shutdown" - else "Domain myvm exists and is running", + "comment": ( + "Domain myvm started" + if running == "shutdown" + else "Domain myvm exists and is running" + ), } if running == "shutdown" and not test: start_mock.assert_called() @@ -426,9 +432,11 @@ def test_running_update(test, running): "name": "myvm", "changes": {"myvm": changes}, "result": True if not test else None, - "comment": "Domain myvm updated" - if running == "running" - else "Domain myvm updated and started", + "comment": ( + "Domain myvm updated" + if running == "running" + else "Domain myvm updated and started" + ), } if running == "shutdown" and not test: start_mock.assert_called() diff --git a/tests/pytests/unit/states/zabbix/test_action.py b/tests/pytests/unit/states/zabbix/test_action.py index 57da6be2684..7a7db80f094 100644 --- a/tests/pytests/unit/states/zabbix/test_action.py +++ b/tests/pytests/unit/states/zabbix/test_action.py @@ -159,10 +159,10 @@ def test_present_create(input_params): }, ): ret["result"] = True - ret["comment"] = 'Zabbix Action "{}" created.'.format(name) + ret["comment"] = f'Zabbix Action "{name}" created.' ret["changes"] = { name: { - "old": 'Zabbix Action "{}" did not exist.'.format(name), + "old": f'Zabbix Action "{name}" did not exist.', "new": 'Zabbix Action "{}" created according definition.'.format( name ), @@ -193,10 +193,10 @@ def test_present_exists(input_params, existing_obj): }, ): ret["result"] = True - ret[ - "comment" - ] = 'Zabbix Action "{}" already exists and corresponds to a definition.'.format( - name + ret["comment"] = ( + 'Zabbix Action "{}" already exists and corresponds to a definition.'.format( + name + ) ) assert zabbix_action.present(name, {}) == ret @@ -232,14 +232,14 @@ def test_present_update(input_params, existing_obj_diff, diff_params): }, ): ret["result"] = True - ret["comment"] = 'Zabbix Action "{}" updated.'.format(name) + ret["comment"] = f'Zabbix Action "{name}" updated.' ret["changes"] = { name: { "old": ( 'Zabbix Action "{}" differed ' "in following parameters: {}".format(name, diff_params) ), - "new": 'Zabbix Action "{}" fixed.'.format(name), + "new": f'Zabbix Action "{name}" fixed.', } } assert zabbix_action.present(name, {}) == ret @@ -257,11 +257,11 @@ def test_absent_test_mode(): {"zabbix.get_object_id_by_params": MagicMock(return_value=11)}, ): ret["result"] = True - ret["comment"] = 'Zabbix Action "{}" would be deleted.'.format(name) + ret["comment"] = f'Zabbix Action "{name}" would be deleted.' ret["changes"] = { name: { - "old": 'Zabbix Action "{}" exists.'.format(name), - "new": 'Zabbix Action "{}" would be deleted.'.format(name), + "old": f'Zabbix Action "{name}" exists.', + "new": f'Zabbix Action "{name}" would be deleted.', } } assert zabbix_action.absent(name) == ret @@ -279,7 +279,7 @@ def test_absent(): {"zabbix.get_object_id_by_params": MagicMock(return_value=False)}, ): ret["result"] = True - ret["comment"] = 'Zabbix Action "{}" does not exist.'.format(name) + ret["comment"] = f'Zabbix Action "{name}" does not exist.' assert zabbix_action.absent(name) == ret with patch.dict( @@ -291,11 +291,11 @@ def test_absent(): {"zabbix.run_query": MagicMock(return_value=True)}, ): ret["result"] = True - ret["comment"] = 'Zabbix Action "{}" deleted.'.format(name) + ret["comment"] = f'Zabbix Action "{name}" deleted.' ret["changes"] = { name: { - "old": 'Zabbix Action "{}" existed.'.format(name), - "new": 'Zabbix Action "{}" deleted.'.format(name), + "old": f'Zabbix Action "{name}" existed.', + "new": f'Zabbix Action "{name}" deleted.', } } assert zabbix_action.absent(name) == ret diff --git a/tests/pytests/unit/states/zabbix/test_template.py b/tests/pytests/unit/states/zabbix/test_template.py index 203a80a50ae..0f42560b7ec 100644 --- a/tests/pytests/unit/states/zabbix/test_template.py +++ b/tests/pytests/unit/states/zabbix/test_template.py @@ -174,10 +174,10 @@ def test_present_create(substitute_params_create): }, ): ret["result"] = True - ret["comment"] = 'Zabbix Template "{}" created.'.format(name) + ret["comment"] = f'Zabbix Template "{name}" created.' ret["changes"] = { name: { - "old": 'Zabbix Template "{}" did not exist.'.format(name), + "old": f'Zabbix Template "{name}" did not exist.', "new": ( 'Zabbix Template "{}" created according definition.'.format( name @@ -261,10 +261,10 @@ def test_present_update(diff_params, substitute_params_update): }, ): ret["result"] = True - ret["comment"] = 'Zabbix Template "{}" updated.'.format(name) + ret["comment"] = f'Zabbix Template "{name}" updated.' ret["changes"] = { name: { - "old": 'Zabbix Template "{}" differed.'.format(name), + "old": f'Zabbix Template "{name}" differed.', "new": ( 'Zabbix Template "{}" updated according definition.'.format( name @@ -287,11 +287,11 @@ def test_absent_test_mode(): {"zabbix.get_object_id_by_params": MagicMock(return_value=11)}, ): ret["result"] = True - ret["comment"] = 'Zabbix Template "{}" would be deleted.'.format(name) + ret["comment"] = f'Zabbix Template "{name}" would be deleted.' ret["changes"] = { name: { - "old": 'Zabbix Template "{}" exists.'.format(name), - "new": 'Zabbix Template "{}" would be deleted.'.format(name), + "old": f'Zabbix Template "{name}" exists.', + "new": f'Zabbix Template "{name}" would be deleted.', } } assert zabbix_template.absent(name) == ret @@ -309,7 +309,7 @@ def test_absent(): {"zabbix.get_object_id_by_params": MagicMock(return_value=False)}, ): ret["result"] = True - ret["comment"] = 'Zabbix Template "{}" does not exist.'.format(name) + ret["comment"] = f'Zabbix Template "{name}" does not exist.' assert zabbix_template.absent(name) == ret with patch.dict( @@ -321,11 +321,11 @@ def test_absent(): {"zabbix.run_query": MagicMock(return_value=True)}, ): ret["result"] = True - ret["comment"] = 'Zabbix Template "{}" deleted.'.format(name) + ret["comment"] = f'Zabbix Template "{name}" deleted.' ret["changes"] = { name: { - "old": 'Zabbix Template "{}" existed.'.format(name), - "new": 'Zabbix Template "{}" deleted.'.format(name), + "old": f'Zabbix Template "{name}" existed.', + "new": f'Zabbix Template "{name}" deleted.', } } assert zabbix_template.absent(name) == ret diff --git a/tests/pytests/unit/states/zabbix/test_valuemap.py b/tests/pytests/unit/states/zabbix/test_valuemap.py index bc589d7bc92..f1686661ff6 100644 --- a/tests/pytests/unit/states/zabbix/test_valuemap.py +++ b/tests/pytests/unit/states/zabbix/test_valuemap.py @@ -93,10 +93,10 @@ def test_present_create(input_params): }, ): ret["result"] = True - ret["comment"] = 'Zabbix Value map "{}" created.'.format(name) + ret["comment"] = f'Zabbix Value map "{name}" created.' ret["changes"] = { name: { - "old": 'Zabbix Value map "{}" did not exist.'.format(name), + "old": f'Zabbix Value map "{name}" did not exist.', "new": 'Zabbix Value map "{}" created according definition.'.format( name ), @@ -127,10 +127,10 @@ def test_present_exists(input_params, existing_obj): }, ): ret["result"] = True - ret[ - "comment" - ] = 'Zabbix Value map "{}" already exists and corresponds to a definition.'.format( - name + ret["comment"] = ( + 'Zabbix Value map "{}" already exists and corresponds to a definition.'.format( + name + ) ) assert zabbix_valuemap.present(name, {}) == ret @@ -166,14 +166,14 @@ def test_present_update(input_params, existing_obj_diff, diff_params): }, ): ret["result"] = True - ret["comment"] = 'Zabbix Value map "{}" updated.'.format(name) + ret["comment"] = f'Zabbix Value map "{name}" updated.' ret["changes"] = { name: { "old": ( 'Zabbix Value map "{}" differed ' "in following parameters: {}".format(name, diff_params) ), - "new": 'Zabbix Value map "{}" fixed.'.format(name), + "new": f'Zabbix Value map "{name}" fixed.', } } assert zabbix_valuemap.present(name, {}) == ret @@ -191,11 +191,11 @@ def test_absent_test_mode(): {"zabbix.get_object_id_by_params": MagicMock(return_value=11)}, ): ret["result"] = True - ret["comment"] = 'Zabbix Value map "{}" would be deleted.'.format(name) + ret["comment"] = f'Zabbix Value map "{name}" would be deleted.' ret["changes"] = { name: { - "old": 'Zabbix Value map "{}" exists.'.format(name), - "new": 'Zabbix Value map "{}" would be deleted.'.format(name), + "old": f'Zabbix Value map "{name}" exists.', + "new": f'Zabbix Value map "{name}" would be deleted.', } } assert zabbix_valuemap.absent(name) == ret @@ -213,7 +213,7 @@ def test_absent(): {"zabbix.get_object_id_by_params": MagicMock(return_value=False)}, ): ret["result"] = True - ret["comment"] = 'Zabbix Value map "{}" does not exist.'.format(name) + ret["comment"] = f'Zabbix Value map "{name}" does not exist.' assert zabbix_valuemap.absent(name) == ret with patch.dict( @@ -225,11 +225,11 @@ def test_absent(): {"zabbix.run_query": MagicMock(return_value=True)}, ): ret["result"] = True - ret["comment"] = 'Zabbix Value map "{}" deleted.'.format(name) + ret["comment"] = f'Zabbix Value map "{name}" deleted.' ret["changes"] = { name: { - "old": 'Zabbix Value map "{}" existed.'.format(name), - "new": 'Zabbix Value map "{}" deleted.'.format(name), + "old": f'Zabbix Value map "{name}" existed.', + "new": f'Zabbix Value map "{name}" deleted.', } } assert zabbix_valuemap.absent(name) == ret diff --git a/tests/pytests/unit/test_acl.py b/tests/pytests/unit/test_acl.py index e5788fb846d..6c75b8902d1 100644 --- a/tests/pytests/unit/test_acl.py +++ b/tests/pytests/unit/test_acl.py @@ -2,7 +2,6 @@ Unit tests for salt.acl.ClientACL """ - import pytest from salt import acl diff --git a/tests/pytests/unit/test_config.py b/tests/pytests/unit/test_config.py index cb343cb75eb..7437c8214ed 100644 --- a/tests/pytests/unit/test_config.py +++ b/tests/pytests/unit/test_config.py @@ -4,6 +4,7 @@ tests.pytests.unit.test_config Unit tests for salt's config modulet """ + import salt.config diff --git a/tests/pytests/unit/test_fileclient.py b/tests/pytests/unit/test_fileclient.py index d11f5ac2521..dee9d7901bd 100644 --- a/tests/pytests/unit/test_fileclient.py +++ b/tests/pytests/unit/test_fileclient.py @@ -1,6 +1,7 @@ """ Unit tests for salt.fileclient """ + import salt.config import salt.fileclient as fileclient from tests.support.mock import MagicMock, patch diff --git a/tests/pytests/unit/test_log.py b/tests/pytests/unit/test_log.py index 83d2e9e2cda..8e3a45b27ae 100644 --- a/tests/pytests/unit/test_log.py +++ b/tests/pytests/unit/test_log.py @@ -8,7 +8,6 @@ Test salt's "hacked" logging """ - import io import logging @@ -32,9 +31,9 @@ def test_issue_2853_regex_TypeError(): # Let's create another log instance to trigger salt's logging class # calculations. try: - SaltLoggingClass("{}.with_digits".format(__name__)) + SaltLoggingClass(f"{__name__}.with_digits") except Exception as err: # pylint: disable=broad-except - raise AssertionError("No exception should have been raised: {}".format(err)) + raise AssertionError(f"No exception should have been raised: {err}") # Remove the testing handler log.removeHandler(handler) @@ -49,9 +48,9 @@ def test_issue_2853_regex_TypeError(): # Let's create another log instance to trigger salt's logging class # calculations. try: - SaltLoggingClass("{}.without_digits".format(__name__)) + SaltLoggingClass(f"{__name__}.without_digits") except Exception as err: # pylint: disable=broad-except - raise AssertionError("No exception should have been raised: {}".format(err)) + raise AssertionError(f"No exception should have been raised: {err}") # Remove the testing handler log.removeHandler(handler) diff --git a/tests/pytests/unit/test_pillar.py b/tests/pytests/unit/test_pillar.py index d4a1a4e1c73..d44a337981f 100644 --- a/tests/pytests/unit/test_pillar.py +++ b/tests/pytests/unit/test_pillar.py @@ -6,7 +6,6 @@ ~~~~~~~~~~~~~~~~~~~~~~ """ - import logging import os import shutil diff --git a/tests/pytests/unit/test_request_channel.py b/tests/pytests/unit/test_request_channel.py index b8957f35e30..dda663057d9 100644 --- a/tests/pytests/unit/test_request_channel.py +++ b/tests/pytests/unit/test_request_channel.py @@ -1,6 +1,7 @@ """ :codeauthor: Thomas Jackson """ + import asyncio import ctypes import logging diff --git a/tests/pytests/unit/test_syspaths.py b/tests/pytests/unit/test_syspaths.py index 0ecb4789a61..66a0bc07596 100644 --- a/tests/pytests/unit/test_syspaths.py +++ b/tests/pytests/unit/test_syspaths.py @@ -4,6 +4,7 @@ tests.pytests.unit.test_syspaths Unit tests for salt's syspaths module """ + import pytest import salt.syspaths diff --git a/tests/pytests/unit/test_version.py b/tests/pytests/unit/test_version.py index ec1abed9f77..fbcfe33222b 100644 --- a/tests/pytests/unit/test_version.py +++ b/tests/pytests/unit/test_version.py @@ -4,6 +4,7 @@ tests.pytests.unit.test_version Test salt's regex git describe version parsing """ + import re import pytest diff --git a/tests/pytests/unit/tokens/test_localfs.py b/tests/pytests/unit/tokens/test_localfs.py index b1d6395abc5..230871acc78 100644 --- a/tests/pytests/unit/tokens/test_localfs.py +++ b/tests/pytests/unit/tokens/test_localfs.py @@ -42,7 +42,7 @@ def test_write_token(tmp_path): tdata = salt.tokens.localfs.mk_token(opts, {}) assert "token" in tdata t_path = os.path.join(str(tmp_path), tdata["token"]) - temp_t_path = "{}.tmp".format(t_path) + temp_t_path = f"{t_path}.tmp" assert len(fopen.called_with) == 1, len(fopen.called_with) assert fopen.called_with == [((temp_t_path, "w+b"), {})], fopen.called_with assert len(rename.called_with) == 1, len(rename.called_with) diff --git a/tests/pytests/unit/transport/test_base.py b/tests/pytests/unit/transport/test_base.py index 96e4c06f038..5d541073d67 100644 --- a/tests/pytests/unit/transport/test_base.py +++ b/tests/pytests/unit/transport/test_base.py @@ -1,6 +1,7 @@ """ Unit tests for salt.transport.base. """ + import ssl import pytest diff --git a/tests/pytests/unit/utils/jinja/conftest.py b/tests/pytests/unit/utils/jinja/conftest.py index 0b77a4fb2f7..4007bfd6ea1 100644 --- a/tests/pytests/unit/utils/jinja/conftest.py +++ b/tests/pytests/unit/utils/jinja/conftest.py @@ -1,6 +1,7 @@ """ Tests for salt.utils.jinja """ + import pytest diff --git a/tests/pytests/unit/utils/jinja/test_jinja.py b/tests/pytests/unit/utils/jinja/test_jinja.py index de8df6067f5..9e1b33c2ff0 100644 --- a/tests/pytests/unit/utils/jinja/test_jinja.py +++ b/tests/pytests/unit/utils/jinja/test_jinja.py @@ -1,6 +1,7 @@ """ Tests for salt.utils.jinja """ + import salt.utils.dateutils # pylint: disable=unused-import from salt.utils.jinja import Markup, indent, tojson diff --git a/tests/pytests/unit/utils/scheduler/conftest.py b/tests/pytests/unit/utils/scheduler/conftest.py index e74b67091bf..a1c997b1234 100644 --- a/tests/pytests/unit/utils/scheduler/conftest.py +++ b/tests/pytests/unit/utils/scheduler/conftest.py @@ -3,7 +3,6 @@ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ - import copy import logging diff --git a/tests/pytests/unit/utils/templates/test_jinja.py b/tests/pytests/unit/utils/templates/test_jinja.py index 6d47e6b80d3..99856f65054 100644 --- a/tests/pytests/unit/utils/templates/test_jinja.py +++ b/tests/pytests/unit/utils/templates/test_jinja.py @@ -1,6 +1,7 @@ """ Tests for salt.utils.templates """ + import re from collections import OrderedDict diff --git a/tests/pytests/unit/utils/templates/test_wrap_tmpl_func.py b/tests/pytests/unit/utils/templates/test_wrap_tmpl_func.py index 3bad376f272..bd1d5fa2e1d 100644 --- a/tests/pytests/unit/utils/templates/test_wrap_tmpl_func.py +++ b/tests/pytests/unit/utils/templates/test_wrap_tmpl_func.py @@ -1,6 +1,7 @@ """ Unit tests for salt.utils.templates.py """ + import logging from pathlib import PurePath, PurePosixPath diff --git a/tests/pytests/unit/utils/test_aws.py b/tests/pytests/unit/utils/test_aws.py index c4e32e369a9..22597ffcd8b 100644 --- a/tests/pytests/unit/utils/test_aws.py +++ b/tests/pytests/unit/utils/test_aws.py @@ -4,6 +4,7 @@ Test the salt aws functions """ + import io import os import time diff --git a/tests/pytests/unit/utils/test_cache.py b/tests/pytests/unit/utils/test_cache.py index 34736530d5c..efe2f417c4d 100644 --- a/tests/pytests/unit/utils/test_cache.py +++ b/tests/pytests/unit/utils/test_cache.py @@ -139,7 +139,7 @@ def test_set_cache(minion_opts, cache_mods_path, cache_mod_name, cache_dir): assert cache_test_func()["called"] == 1 assert cache_test_func()["called"] == 2 - cache_file_name = "salt.loaded.ext.rawmodule.{}.p".format(cache_mod_name) + cache_file_name = f"salt.loaded.ext.rawmodule.{cache_mod_name}.p" cached_file = cache_dir / "context" / cache_file_name assert cached_file.exists() @@ -151,9 +151,7 @@ def test_set_cache(minion_opts, cache_mods_path, cache_mod_name, cache_dir): assert target_cache_data == dict(context, called=1) # Test cache de-serialize - cc = cache.ContextCache( - minion_opts, "salt.loaded.ext.rawmodule.{}".format(cache_mod_name) - ) + cc = cache.ContextCache(minion_opts, f"salt.loaded.ext.rawmodule.{cache_mod_name}") retrieved_cache = cc.get_cache_context() assert retrieved_cache == dict(context, called=1) diff --git a/tests/pytests/unit/utils/test_cloud.py b/tests/pytests/unit/utils/test_cloud.py index 00c4798812e..340f226aedf 100644 --- a/tests/pytests/unit/utils/test_cloud.py +++ b/tests/pytests/unit/utils/test_cloud.py @@ -6,7 +6,6 @@ """ - import os import string import tempfile diff --git a/tests/pytests/unit/utils/test_compat.py b/tests/pytests/unit/utils/test_compat.py index b86dea94296..0dacd615eb9 100644 --- a/tests/pytests/unit/utils/test_compat.py +++ b/tests/pytests/unit/utils/test_compat.py @@ -1,6 +1,7 @@ """ Unit tests for salt.utils.compat.py """ + import pytest import salt.utils.compat diff --git a/tests/pytests/unit/utils/test_crypt.py b/tests/pytests/unit/utils/test_crypt.py index 9a7b35f3d2b..ccf2cfbf46e 100644 --- a/tests/pytests/unit/utils/test_crypt.py +++ b/tests/pytests/unit/utils/test_crypt.py @@ -1,6 +1,7 @@ """ Unit tests for salt.utils.crypt.py """ + import pytest import salt.utils.crypt diff --git a/tests/pytests/unit/utils/test_data.py b/tests/pytests/unit/utils/test_data.py index d8ec03fc11c..bac2acb9dab 100644 --- a/tests/pytests/unit/utils/test_data.py +++ b/tests/pytests/unit/utils/test_data.py @@ -1,6 +1,7 @@ """ Tests for salt.utils.data """ + import builtins import logging diff --git a/tests/pytests/unit/utils/test_files.py b/tests/pytests/unit/utils/test_files.py index ded95093cd2..3a0fef843d8 100644 --- a/tests/pytests/unit/utils/test_files.py +++ b/tests/pytests/unit/utils/test_files.py @@ -2,7 +2,6 @@ Unit Tests for functions located in salt/utils/files.py """ - import copy import io import os @@ -28,7 +27,7 @@ def test_safe_rm_exceptions(tmp_path): def test_safe_walk_symlink_recursion(tmp_path): if tmp_path.stat().st_ino == 0: - pytest.xfail(reason="inodes not supported in {}".format(tmp_path)) + pytest.xfail(reason=f"inodes not supported in {tmp_path}") tmp_path = str(tmp_path) os.mkdir(os.path.join(tmp_path, "fax")) diff --git a/tests/pytests/unit/utils/test_nacl.py b/tests/pytests/unit/utils/test_nacl.py index e5de4b8e645..5c60d880b2f 100644 --- a/tests/pytests/unit/utils/test_nacl.py +++ b/tests/pytests/unit/utils/test_nacl.py @@ -1,6 +1,7 @@ """ Unit tests for the salt.utils.nacl module """ + import os import pytest diff --git a/tests/pytests/unit/utils/test_pycrypto.py b/tests/pytests/unit/utils/test_pycrypto.py index 693ad10e240..1dfcf9621c4 100644 --- a/tests/pytests/unit/utils/test_pycrypto.py +++ b/tests/pytests/unit/utils/test_pycrypto.py @@ -203,7 +203,7 @@ def test_secure_password(): ) ) ) - check_whitespace = re.compile(r"[{}]".format(string.whitespace)) + check_whitespace = re.compile(rf"[{string.whitespace}]") assert check_printable.search(ret) is None assert check_whitespace.search(ret) is None assert ret @@ -224,7 +224,7 @@ def test_secure_password_all_chars(): whitespace=True, printable=True, ) - check = re.compile(r"[^{}]".format(re.escape(string.printable))) + check = re.compile(rf"[^{re.escape(string.printable)}]") assert check.search(ret) is None assert ret @@ -245,7 +245,7 @@ def test_secure_password_no_has_random(): ) ) ) - check_whitespace = re.compile(r"[{}]".format(string.whitespace)) + check_whitespace = re.compile(rf"[{string.whitespace}]") assert check_printable.search(ret) is None assert check_whitespace.search(ret) is None assert ret @@ -259,6 +259,6 @@ def test_secure_password_all_chars_no_has_random(): """ with patch("salt.utils.pycrypto.HAS_RANDOM", False): ret = salt.utils.pycrypto.secure_password(printable=True) - check = re.compile("[^{}]".format(re.escape(string.printable))) + check = re.compile(f"[^{re.escape(string.printable)}]") assert check.search(ret) is None assert ret diff --git a/tests/pytests/unit/utils/test_rsax931.py b/tests/pytests/unit/utils/test_rsax931.py index 28585f04415..0c151fc3b27 100644 --- a/tests/pytests/unit/utils/test_rsax931.py +++ b/tests/pytests/unit/utils/test_rsax931.py @@ -1,6 +1,7 @@ """ Test the RSA ANSI X9.31 signer and verifier """ + import ctypes import ctypes.util import fnmatch diff --git a/tests/pytests/unit/utils/test_versions.py b/tests/pytests/unit/utils/test_versions.py index 417bb9e3632..a1197778296 100644 --- a/tests/pytests/unit/utils/test_versions.py +++ b/tests/pytests/unit/utils/test_versions.py @@ -58,9 +58,7 @@ def test_cmp_strict(v1, v2, wanted): ) except InvalidVersion: if wanted is not InvalidVersion: - raise AssertionError( - "cmp({}, {}) shouldn't raise InvalidVersion".format(v1, v2) - ) + raise AssertionError(f"cmp({v1}, {v2}) shouldn't raise InvalidVersion") @pytest.mark.parametrize( @@ -83,7 +81,7 @@ def test_cmp_strict(v1, v2, wanted): ) def test_cmp(v1, v2, wanted): res = LooseVersion(v1)._cmp(LooseVersion(v2)) - assert res == wanted, "cmp({}, {}) should be {}, got {}".format(v1, v2, wanted, res) + assert res == wanted, f"cmp({v1}, {v2}) should be {wanted}, got {res}" def test_compare(): @@ -249,7 +247,7 @@ def test_warn_until_warning_raised(subtests): "Deprecation Message until {version}!", _version_info_=(vrs.major - 1, 0), ) - assert "Deprecation Message until {}!".format(vrs.formatted_version) == str( + assert f"Deprecation Message until {vrs.formatted_version}!" == str( recorded_warnings[0].message ) diff --git a/tests/pytests/unit/utils/test_win_reg.py b/tests/pytests/unit/utils/test_win_reg.py index 206c40b3089..3954318c013 100644 --- a/tests/pytests/unit/utils/test_win_reg.py +++ b/tests/pytests/unit/utils/test_win_reg.py @@ -200,7 +200,7 @@ def test_list_keys_non_existing(fake_key): """ Test the list_keys function using a non existing registry key """ - expected = (False, "Cannot find key: HKLM\\{}".format(fake_key)) + expected = (False, f"Cannot find key: HKLM\\{fake_key}") assert win_reg.list_keys(hive="HKLM", key=fake_key) == expected @@ -208,7 +208,7 @@ def test_list_keys_access_denied(fake_key): """ Test the list_keys function using a registry key when access is denied """ - expected = (False, "Access is denied: HKLM\\{}".format(fake_key)) + expected = (False, f"Access is denied: HKLM\\{fake_key}") mock_error = MagicMock( side_effect=win32api.error(5, "RegOpenKeyEx", "Access is denied") ) @@ -261,7 +261,7 @@ def test_list_values_non_existing(fake_key): """ Test the list_values function using a non existing registry key """ - expected = (False, "Cannot find key: HKLM\\{}".format(fake_key)) + expected = (False, f"Cannot find key: HKLM\\{fake_key}") assert win_reg.list_values(hive="HKLM", key=fake_key) == expected @@ -269,7 +269,7 @@ def test_list_values_access_denied(fake_key): """ Test the list_values function using a registry key when access is denied """ - expected = (False, "Access is denied: HKLM\\{}".format(fake_key)) + expected = (False, f"Access is denied: HKLM\\{fake_key}") mock_error = MagicMock( side_effect=win32api.error(5, "RegOpenKeyEx", "Access is denied") ) @@ -359,7 +359,7 @@ def test_read_value_non_existing_key(fake_key): Test the read_value function using a non existing registry key """ expected = { - "comment": "Cannot find key: HKLM\\{}".format(fake_key), + "comment": f"Cannot find key: HKLM\\{fake_key}", "vdata": None, "vtype": None, "vname": "fake_name", @@ -375,7 +375,7 @@ def test_read_value_access_denied(fake_key): Test the read_value function using a registry key when access is denied """ expected = { - "comment": "Access is denied: HKLM\\{}".format(fake_key), + "comment": f"Access is denied: HKLM\\{fake_key}", "vdata": None, "vtype": None, "vname": "fake_name", diff --git a/tests/pytests/unit/utils/test_x509.py b/tests/pytests/unit/utils/test_x509.py index f13ac97fb33..ab7384ffde2 100644 --- a/tests/pytests/unit/utils/test_x509.py +++ b/tests/pytests/unit/utils/test_x509.py @@ -1472,9 +1472,11 @@ def test_parse_general_names_rejects_invalid(inpt): ) def test_get_dn(inpt, expected): expected_parsed = [ - cx509.RelativeDistinguishedName({x}) - if not isinstance(x, cx509.RelativeDistinguishedName) - else x + ( + cx509.RelativeDistinguishedName({x}) + if not isinstance(x, cx509.RelativeDistinguishedName) + else x + ) for x in expected ] res = x509._get_dn(inpt) diff --git a/tests/pytests/unit/utils/vault/conftest.py b/tests/pytests/unit/utils/vault/conftest.py index 1ab4e39a16e..58ab67da745 100644 --- a/tests/pytests/unit/utils/vault/conftest.py +++ b/tests/pytests/unit/utils/vault/conftest.py @@ -462,10 +462,8 @@ def req_any(req, request): @pytest.fixture def req_unwrapping(wrapped_role_id_lookup_response, role_id_response, req): - req.side_effect = ( - lambda method, url, **kwargs: _mock_json_response( - wrapped_role_id_lookup_response - ) + req.side_effect = lambda method, url, **kwargs: ( + _mock_json_response(wrapped_role_id_lookup_response) if url.endswith("sys/wrapping/lookup") else _mock_json_response(role_id_response) ) @@ -550,7 +548,7 @@ def salt_runtype(request): ] ) def opts_runtype(request): - return { + rtype = { "master": { "__role": "master", "vault": {}, @@ -585,4 +583,5 @@ def opts_runtype(request): "minion_remote": { "grains": {"id": "test-minion"}, }, - }[request.param] + } + return rtype[request.param] diff --git a/tests/pytests/unit/utils/vault/test_factory.py b/tests/pytests/unit/utils/vault/test_factory.py index e9d62165b93..e82b0251a15 100644 --- a/tests/pytests/unit/utils/vault/test_factory.py +++ b/tests/pytests/unit/utils/vault/test_factory.py @@ -633,11 +633,12 @@ class TestFetchSecretId: @pytest.fixture(params=["plain", "wrapped", "dict"]) def secret_id(self, secret_id_response, wrapped_secret_id_response, request): - return { + ret = { "plain": "test-secret-id", "wrapped": {"wrap_info": wrapped_secret_id_response["wrap_info"]}, "dict": secret_id_response["data"], - }[request.param] + } + return ret[request.param] @pytest.mark.parametrize("test_remote_config", ["approle"], indirect=True) @pytest.mark.parametrize( @@ -817,11 +818,12 @@ class TestFetchToken: @pytest.fixture(params=["plain", "wrapped", "dict"]) def token(self, token_auth, wrapped_token_auth_response, request): - return { + ret = { "plain": token_auth["auth"]["client_token"], "wrapped": {"wrap_info": wrapped_token_auth_response["wrap_info"]}, "dict": token_auth["auth"], - }[request.param] + } + return ret[request.param] @pytest.mark.parametrize( "test_remote_config", ["token", "wrapped_token"], indirect=True diff --git a/tests/pytests/unit/utils/verify/test_clean_path_link.py b/tests/pytests/unit/utils/verify/test_clean_path_link.py index ff83d1f54b3..8effa56a59c 100644 --- a/tests/pytests/unit/utils/verify/test_clean_path_link.py +++ b/tests/pytests/unit/utils/verify/test_clean_path_link.py @@ -1,6 +1,7 @@ """ Ensure salt.utils.clean_path works with symlinked directories and files """ + import ctypes import pytest diff --git a/tests/pytests/unit/utils/verify/test_verify.py b/tests/pytests/unit/utils/verify/test_verify.py index 5dcb90b0857..60171523cb4 100644 --- a/tests/pytests/unit/utils/verify/test_verify.py +++ b/tests/pytests/unit/utils/verify/test_verify.py @@ -257,9 +257,11 @@ def test_max_open_files(caplog): logmsg_chk.format( newmax, mof_test, - mof_test - newmax - if sys.platform.startswith("win") - else mof_h - newmax, + ( + mof_test - newmax + if sys.platform.startswith("win") + else mof_h - newmax + ), ) in caplog.messages ) @@ -279,9 +281,11 @@ def test_max_open_files(caplog): logmsg_crash.format( newmax, mof_test, - mof_test - newmax - if sys.platform.startswith("win") - else mof_h - newmax, + ( + mof_test - newmax + if sys.platform.startswith("win") + else mof_h - newmax + ), ) in caplog.messages ) diff --git a/tests/pytests/unit/utils/win_lgpo/test_auditpol.py b/tests/pytests/unit/utils/win_lgpo/test_auditpol.py index 1d67eb7640e..85e53780efe 100644 --- a/tests/pytests/unit/utils/win_lgpo/test_auditpol.py +++ b/tests/pytests/unit/utils/win_lgpo/test_auditpol.py @@ -64,7 +64,7 @@ def test_set_setting(settings): value = random.choice(settings) win_lgpo_auditpol.set_setting(name=name, value=value) switches = win_lgpo_auditpol.settings[value] - cmd = 'auditpol /set /subcategory:"{}" {}'.format(name, switches) + cmd = f'auditpol /set /subcategory:"{name}" {switches}' mock_set.assert_called_once_with(cmd=cmd, python_shell=True) mock_set.reset_mock() diff --git a/tests/support/case.py b/tests/support/case.py index 55b537f6ffd..a59da1742b7 100644 --- a/tests/support/case.py +++ b/tests/support/case.py @@ -77,7 +77,7 @@ class ShellCase(TestCase, AdaptedConfigurationTestCaseMixin, ScriptPathMixin): if timeout is None: timeout = self.RUN_TIMEOUT - arg_str = "-t {} {}".format(timeout, arg_str) + arg_str = f"-t {timeout} {arg_str}" return self.run_script( "salt", arg_str, @@ -99,7 +99,7 @@ class ShellCase(TestCase, AdaptedConfigurationTestCaseMixin, ScriptPathMixin): ssh_opts="", log_level="error", config_dir=None, - **kwargs + **kwargs, ): """ Execute salt-ssh @@ -128,7 +128,7 @@ class ShellCase(TestCase, AdaptedConfigurationTestCaseMixin, ScriptPathMixin): raw=True, timeout=timeout, config_dir=config_dir, - **kwargs + **kwargs, ) log.debug("Result of run_ssh for command '%s %s': %s", arg_str, kwargs, ret) return ret @@ -141,7 +141,7 @@ class ShellCase(TestCase, AdaptedConfigurationTestCaseMixin, ScriptPathMixin): asynchronous=False, timeout=None, config_dir=None, - **kwargs + **kwargs, ): """ Execute salt-run @@ -284,7 +284,7 @@ class ShellCase(TestCase, AdaptedConfigurationTestCaseMixin, ScriptPathMixin): catch_stderr=False, local=False, timeout=RUN_TIMEOUT, - **kwargs + **kwargs, ): """ Execute function with salt-call. @@ -349,7 +349,7 @@ class ShellCase(TestCase, AdaptedConfigurationTestCaseMixin, ScriptPathMixin): popen_kwargs=None, log_output=None, config_dir=None, - **kwargs + **kwargs, ): """ Execute a script with the given argument string @@ -398,13 +398,13 @@ class ShellCase(TestCase, AdaptedConfigurationTestCaseMixin, ScriptPathMixin): import salt.utils.json for key, value in kwargs.items(): - cmd += "'{}={} '".format(key, salt.utils.json.dumps(value)) + cmd += f"'{key}={salt.utils.json.dumps(value)} '" tmp_file = tempfile.SpooledTemporaryFile() popen_kwargs = dict( {"shell": True, "stdout": tmp_file, "universal_newlines": True}, - **popen_kwargs + **popen_kwargs, ) if catch_stderr is True: @@ -639,7 +639,7 @@ class SPMCase(TestCase, AdaptedConfigurationTestCaseMixin): "cachedir": os.path.join(self._tmp_spm, "cache"), "spm_repo_dups": "ignore", "spm_share_dir": os.path.join(self._tmp_spm, "share"), - } + }, ) import salt.utils.yaml @@ -723,7 +723,7 @@ class ModuleCase(TestCase, SaltClientTestCaseMixin): minion_tgt="minion", timeout=300, master_tgt=None, - **kwargs + **kwargs, ): """ Run a single salt function and condition the return down to match the @@ -809,7 +809,7 @@ class ModuleCase(TestCase, SaltClientTestCaseMixin): job_data, job_kill ) ) - ret.append("[TEST SUITE ENFORCED]{}[/TEST SUITE ENFORCED]".format(msg)) + ret.append(f"[TEST SUITE ENFORCED]{msg}[/TEST SUITE ENFORCED]") return ret diff --git a/tests/support/cli_scripts.py b/tests/support/cli_scripts.py index ee18d6856a0..58e54c6ec56 100644 --- a/tests/support/cli_scripts.py +++ b/tests/support/cli_scripts.py @@ -5,7 +5,6 @@ Code to generate Salt CLI scripts for test runs """ - import logging import os diff --git a/tests/support/helpers.py b/tests/support/helpers.py index 32bdf043d75..ab435d248ff 100644 --- a/tests/support/helpers.py +++ b/tests/support/helpers.py @@ -8,6 +8,7 @@ Test support helpers """ + import asyncio import base64 import builtins diff --git a/tests/support/kernelpkg.py b/tests/support/kernelpkg.py index eada8d931d1..49c1efa5d3a 100644 --- a/tests/support/kernelpkg.py +++ b/tests/support/kernelpkg.py @@ -4,6 +4,7 @@ :maturity: develop .. versionadded:: 2018.3.0 """ + # pylint: disable=invalid-name,no-member diff --git a/tests/support/mixins.py b/tests/support/mixins.py index 53f7e75108b..6c3bdf2f0bb 100644 --- a/tests/support/mixins.py +++ b/tests/support/mixins.py @@ -91,7 +91,7 @@ class AdaptedConfigurationTestCaseMixin: if key not in config_overrides: config_overrides[key] = key if "log_file" not in config_overrides: - config_overrides["log_file"] = "logs/{}.log".format(config_for) + config_overrides["log_file"] = f"logs/{config_for}.log" if "user" not in config_overrides: config_overrides["user"] = RUNTIME_VARS.RUNNING_TESTS_USER config_overrides["root_dir"] = rootdir @@ -287,9 +287,9 @@ class SaltClientTestCaseMixin(AdaptedConfigurationTestCaseMixin): mopts = self.get_config( self._salt_client_config_file_name_, from_scratch=True ) - RUNTIME_VARS.RUNTIME_CONFIGS[ - "runtime_client" - ] = salt.client.get_local_client(mopts=mopts) + RUNTIME_VARS.RUNTIME_CONFIGS["runtime_client"] = ( + salt.client.get_local_client(mopts=mopts) + ) return RUNTIME_VARS.RUNTIME_CONFIGS["runtime_client"] @@ -443,7 +443,7 @@ class SaltReturnAssertsMixin: self.assertTrue(isinstance(ret, dict)) except AssertionError: raise AssertionError( - "{} is not dict. Salt returned: {}".format(type(ret).__name__, ret) + f"{type(ret).__name__} is not dict. Salt returned: {ret}" ) def assertReturnNonEmptySaltType(self, ret): @@ -478,7 +478,7 @@ class SaltReturnAssertsMixin: except (KeyError, TypeError): raise AssertionError( "Could not get ret{} from salt's return: {}".format( - "".join(["['{}']".format(k) for k in keys]), part + "".join([f"['{k}']" for k in keys]), part ) ) while okeys: @@ -487,7 +487,7 @@ class SaltReturnAssertsMixin: except (KeyError, TypeError): raise AssertionError( "Could not get ret{} from salt's return: {}".format( - "".join(["['{}']".format(k) for k in keys]), part + "".join([f"['{k}']" for k in keys]), part ) ) ret_data.append(ret_item) @@ -525,9 +525,7 @@ class SaltReturnAssertsMixin: ) ) except (AttributeError, IndexError): - raise AssertionError( - "Failed to get result. Salt Returned: {}".format(ret) - ) + raise AssertionError(f"Failed to get result. Salt Returned: {ret}") def assertSaltNoneReturn(self, ret): try: @@ -542,9 +540,7 @@ class SaltReturnAssertsMixin: ) ) except (AttributeError, IndexError): - raise AssertionError( - "Failed to get result. Salt Returned: {}".format(ret) - ) + raise AssertionError(f"Failed to get result. Salt Returned: {ret}") def assertInSaltComment(self, in_comment, ret): for saltret in self.__getWithinSaltReturn(ret, "comment"): @@ -633,7 +629,7 @@ class SaltMinionEventAssertsMixin: cls.fetch_proc = salt.utils.process.SignalHandlingProcess( target=_fetch_events, args=(cls.q, opts), - name="Process-{}-Queue".format(cls.__name__), + name=f"Process-{cls.__name__}-Queue", ) cls.fetch_proc.start() # Wait for the event bus to be connected @@ -670,6 +666,4 @@ class SaltMinionEventAssertsMixin: if time.time() - start >= timeout: break self.fetch_proc.terminate() - raise AssertionError( - "Event {} was not received by minion".format(desired_event) - ) + raise AssertionError(f"Event {desired_event} was not received by minion") diff --git a/tests/support/mock.py b/tests/support/mock.py index 2f9970d4b04..63e794f9764 100644 --- a/tests/support/mock.py +++ b/tests/support/mock.py @@ -11,6 +11,7 @@ Note: mock >= 2.0.0 required since unittest.mock does not have MagicMock.assert_called in Python < 3.6. """ + # pylint: disable=unused-import,function-redefined,blacklisted-module,blacklisted-external-module diff --git a/tests/support/napalm.py b/tests/support/napalm.py index 58bc45bfb18..bb096189403 100644 --- a/tests/support/napalm.py +++ b/tests/support/napalm.py @@ -4,7 +4,6 @@ Base classes for napalm unit tests :codeauthor: :email:`Anthony Shaw ` """ - from functools import wraps from salt.utils.immutabletypes import freeze diff --git a/tests/support/netapi.py b/tests/support/netapi.py index f61650173b9..e6a8339778d 100644 --- a/tests/support/netapi.py +++ b/tests/support/netapi.py @@ -30,9 +30,7 @@ class TestsHttpClient: if "headers" not in kwargs and self.headers: kwargs["headers"] = self.headers.copy() try: - response = await self.client.fetch( - "{}{}".format(self.address, path), **kwargs - ) + response = await self.client.fetch(f"{self.address}{path}", **kwargs) return self._decode_body(response) except HTTPError as exc: exc.response = self._decode_body(exc.response) @@ -75,7 +73,7 @@ class TestsTornadoHttpServer: @address.default def _address_default(self): - return "{}://127.0.0.1:{}".format(self.protocol, self.port) + return f"{self.protocol}://127.0.0.1:{self.port}" @server.default def _server_default(self): diff --git a/tests/support/pytest/etcd.py b/tests/support/pytest/etcd.py index 6606e9436b8..ac7609444ed 100644 --- a/tests/support/pytest/etcd.py +++ b/tests/support/pytest/etcd.py @@ -59,7 +59,7 @@ def confirm_container_started(timeout_at, container): sleeptime = 1 while time.time() <= timeout_at: try: - response = requests.get("http://localhost:{}/version".format(etcd_port)) + response = requests.get(f"http://localhost:{etcd_port}/version") try: version = response.json() if "etcdserver" in version: diff --git a/tests/support/pytest/helpers.py b/tests/support/pytest/helpers.py index 77d46e1dcf2..4ddb0f2548a 100644 --- a/tests/support/pytest/helpers.py +++ b/tests/support/pytest/helpers.py @@ -4,6 +4,7 @@ PyTest helpers functions """ + import logging import os import pathlib diff --git a/tests/support/pytest/loader.py b/tests/support/pytest/loader.py index 2ac99459c2a..62203a56016 100644 --- a/tests/support/pytest/loader.py +++ b/tests/support/pytest/loader.py @@ -4,6 +4,7 @@ Salt's Loader PyTest Mock Support """ + import logging import sys import types @@ -127,13 +128,11 @@ class LoaderModuleMock: self._finalizers.append((func, args, kwargs)) def _format_callback(self, callback, args, kwargs): - callback_str = "{}(".format(callback.__qualname__) + callback_str = f"{callback.__qualname__}(" if args: callback_str += ", ".join([repr(arg) for arg in args]) if kwargs: - callback_str += ", ".join( - ["{}={!r}".format(k, v) for (k, v) in kwargs.items()] - ) + callback_str += ", ".join([f"{k}={v!r}" for (k, v) in kwargs.items()]) callback_str += ")" return callback_str @@ -143,7 +142,7 @@ class LoaderModuleMock: sys_modules = mocks["sys.modules"] if not isinstance(sys_modules, dict): raise RuntimeError( - "'sys.modules' must be a dictionary not: {}".format(type(sys_modules)) + f"'sys.modules' must be a dictionary not: {type(sys_modules)}" ) patcher = patch.dict(sys.modules, values=sys_modules) patcher.start() diff --git a/tests/support/runtests.py b/tests/support/runtests.py index ce5c9644cd3..046c20bd01f 100644 --- a/tests/support/runtests.py +++ b/tests/support/runtests.py @@ -192,12 +192,16 @@ RUNTIME_VARS = RuntimeVars( TMP_BASEENV_PILLAR_TREE=paths.TMP_PILLAR_TREE, TMP_PRODENV_STATE_TREE=paths.TMP_PRODENV_STATE_TREE, TMP_PRODENV_PILLAR_TREE=paths.TMP_PRODENV_PILLAR_TREE, - SHELL_TRUE_PATH=salt.utils.path.which("true") - if not salt.utils.platform.is_windows() - else "cmd /c exit 0 > nul", - SHELL_FALSE_PATH=salt.utils.path.which("false") - if not salt.utils.platform.is_windows() - else "cmd /c exit 1 > nul", + SHELL_TRUE_PATH=( + salt.utils.path.which("true") + if not salt.utils.platform.is_windows() + else "cmd /c exit 0 > nul" + ), + SHELL_FALSE_PATH=( + salt.utils.path.which("false") + if not salt.utils.platform.is_windows() + else "cmd /c exit 1 > nul" + ), RUNNING_TESTS_USER=this_user(), RUNTIME_CONFIGS={}, CODE_DIR=paths.CODE_DIR, diff --git a/tests/support/sminion.py b/tests/support/sminion.py index abf45fd7bde..1fbe69dbd03 100644 --- a/tests/support/sminion.py +++ b/tests/support/sminion.py @@ -234,7 +234,7 @@ def check_required_sminion_attributes(sminion_attr, required_items): available_items = list(getattr(sminion, sminion_attr)) not_available_items = set() - name = "__not_available_{items}s__".format(items=sminion_attr) + name = f"__not_available_{sminion_attr}s__" if not hasattr(sminion, name): setattr(sminion, name, set()) diff --git a/tests/support/unit.py b/tests/support/unit.py index dc1051ea773..88dd7808a22 100644 --- a/tests/support/unit.py +++ b/tests/support/unit.py @@ -18,6 +18,7 @@ .. _`unittest2`: https://pypi.python.org/pypi/unittest2 """ + # pylint: disable=unused-import,blacklisted-module,deprecated-method @@ -225,7 +226,7 @@ class TestCase(_TestCase): found_zombies += 1 except Exception: # pylint: disable=broad-except pass - proc_info += "|Z:{}".format(found_zombies) + proc_info += f"|Z:{found_zombies}" proc_info += "] {short_desc}".format(short_desc=desc if desc else "") return proc_info else: diff --git a/tests/support/win_installer.py b/tests/support/win_installer.py index 6a2f387dc84..a316fc8dfa7 100644 --- a/tests/support/win_installer.py +++ b/tests/support/win_installer.py @@ -21,15 +21,15 @@ def latest_installer_name(arch="AMD64", **kwargs): """ Create an installer file name """ - return "Salt-Minion-Latest-Py3-{}-Setup.exe".format(arch) + return f"Salt-Minion-Latest-Py3-{arch}-Setup.exe" def download_and_verify(fp, name, repo=REPO): """ Download an installer and verify its contents. """ - md5 = "{}.md5".format(name) - url = lambda x: "{}/{}".format(repo, x) + md5 = f"{name}.md5" + url = lambda x: f"{repo}/{x}" resp = requests.get(url(md5)) if resp.status_code != 200: raise Exception("Unable to fetch installer md5") diff --git a/tests/support/xmlunit.py b/tests/support/xmlunit.py index 940bbfe66ae..5b959799cc0 100644 --- a/tests/support/xmlunit.py +++ b/tests/support/xmlunit.py @@ -9,6 +9,7 @@ XML Unit Tests """ + # pylint: disable=wrong-import-order,wrong-import-position diff --git a/tests/support/zfs.py b/tests/support/zfs.py index 31fabe3d059..b9631ac1b6c 100644 --- a/tests/support/zfs.py +++ b/tests/support/zfs.py @@ -5,7 +5,6 @@ ZFS related unit test data structures """ - import salt.utils.zfs from tests.support.mock import MagicMock, patch diff --git a/tests/unit/ext/test_ipaddress.py b/tests/unit/ext/test_ipaddress.py index e4b2f98c357..95b3692ddce 100644 --- a/tests/unit/ext/test_ipaddress.py +++ b/tests/unit/ext/test_ipaddress.py @@ -265,7 +265,7 @@ class AddressTestCase_v4(BaseTestCase, CommonTestMixin_v4): ("s", "1.2.3.42"), ("", "1.2.3.42"), ] - for (fmt, txt) in v4_pairs: + for fmt, txt in v4_pairs: self.assertEqual(txt, format(v4, fmt)) def test_network_passed_as_address(self): @@ -312,7 +312,7 @@ class AddressTestCase_v4(BaseTestCase, CommonTestMixin_v4): def test_invalid_characters(self): def assertBadOctet(addr, octet): - msg = "Only decimal digits permitted in {!r} in {!r}".format(octet, addr) + msg = f"Only decimal digits permitted in {octet!r} in {addr!r}" with self.assertAddressError(re.escape(msg)): ipaddress.IPv4Address(addr) @@ -402,7 +402,7 @@ class AddressTestCase_v6(BaseTestCase, CommonTestMixin_v6): ("", "::102:32a"), ] - for (fmt, txt) in v6_pairs: + for fmt, txt in v6_pairs: self.assertEqual(txt, format(v6, fmt)) def test_network_passed_as_address(self): @@ -657,7 +657,7 @@ class NetmaskTestMixin_v4(CommonTestMixin_v4): def assertBadNetmask(addr, netmask): msg = "%r is not a valid netmask" % netmask with self.assertNetmaskError(re.escape(msg)): - self.factory("{}/{}".format(addr, netmask)) + self.factory(f"{addr}/{netmask}") assertBadNetmask("1.2.3.4", "") assertBadNetmask("1.2.3.4", "-1") @@ -827,7 +827,7 @@ class NetmaskTestMixin_v6(CommonTestMixin_v6): def assertBadNetmask(addr, netmask): msg = "%r is not a valid netmask" % netmask with self.assertNetmaskError(re.escape(msg)): - self.factory("{}/{}".format(addr, netmask)) + self.factory(f"{addr}/{netmask}") assertBadNetmask("::1", "") assertBadNetmask("::1", "::1") diff --git a/tests/unit/modules/nxos/nxos_n36k.py b/tests/unit/modules/nxos/nxos_n36k.py index c6e0879665f..3721337158b 100644 --- a/tests/unit/modules/nxos/nxos_n36k.py +++ b/tests/unit/modules/nxos/nxos_n36k.py @@ -19,7 +19,6 @@ from tests.unit.modules.nxos.nxos_platform import NXOSPlatform class N36KPlatform(NXOSPlatform): - """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 9436978273f..0210f26caee 100644 --- a/tests/unit/modules/nxos/nxos_n3k.py +++ b/tests/unit/modules/nxos/nxos_n3k.py @@ -19,7 +19,6 @@ from tests.unit.modules.nxos.nxos_platform import NXOSPlatform class N3KPlatform(NXOSPlatform): - """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 b5f21f2e691..ccaf838658a 100644 --- a/tests/unit/modules/nxos/nxos_n5k.py +++ b/tests/unit/modules/nxos/nxos_n5k.py @@ -19,7 +19,6 @@ from tests.unit.modules.nxos.nxos_platform import NXOSPlatform class N5KPlatform(NXOSPlatform): - """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 18018748c66..ec7b84768c3 100644 --- a/tests/unit/modules/nxos/nxos_n7k.py +++ b/tests/unit/modules/nxos/nxos_n7k.py @@ -19,7 +19,6 @@ from tests.unit.modules.nxos.nxos_platform import NXOSPlatform class N7KPlatform(NXOSPlatform): - """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 a495da3da05..15517fa524e 100644 --- a/tests/unit/modules/nxos/nxos_n93k.py +++ b/tests/unit/modules/nxos/nxos_n93k.py @@ -19,7 +19,6 @@ from tests.unit.modules.nxos.nxos_platform import NXOSPlatform class N93KPlatform(NXOSPlatform): - """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 4f45e3650a9..6cb91a819da 100644 --- a/tests/unit/modules/nxos/nxos_n93klxc.py +++ b/tests/unit/modules/nxos/nxos_n93klxc.py @@ -19,7 +19,6 @@ from tests.unit.modules.nxos.nxos_platform import NXOSPlatform class N93KLXCPlatform(NXOSPlatform): - """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 c249f5e0bb7..1e3146affa6 100644 --- a/tests/unit/modules/nxos/nxos_n95k.py +++ b/tests/unit/modules/nxos/nxos_n95k.py @@ -21,7 +21,6 @@ from tests.unit.modules.nxos.nxos_platform import NXOSPlatform class N95KPlatform(NXOSPlatform): - """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 02cc2736523..22d8c8dc036 100644 --- a/tests/unit/modules/nxos/nxos_platform.py +++ b/tests/unit/modules/nxos/nxos_platform.py @@ -25,7 +25,6 @@ from string import Template class NXOSPlatform: - """Cisco Systems Base Platform Unit Test Object""" chassis = "Unknown NXOS Chassis" @@ -106,7 +105,6 @@ Module Image Running-Version(pri:alt) New-Versi install_all_non_disruptive_success = None def __init__(self, *args, **kwargs): - """ ckimage - current kickstart image cimage - current system image @@ -163,14 +161,12 @@ Module Image Running-Version(pri:alt) New-Versi @staticmethod def templatize(template, 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""" ver = None diff --git a/tests/unit/modules/test_boto3_elasticsearch.py b/tests/unit/modules/test_boto3_elasticsearch.py index 0e60a9e0746..4c3156042bf 100644 --- a/tests/unit/modules/test_boto3_elasticsearch.py +++ b/tests/unit/modules/test_boto3_elasticsearch.py @@ -1,6 +1,7 @@ """ Tests for salt.modules.boto3_elasticsearch """ + import datetime import random import string diff --git a/tests/unit/modules/test_boto3_route53.py b/tests/unit/modules/test_boto3_route53.py index 5e7332fbb35..eb19cd5e6c9 100644 --- a/tests/unit/modules/test_boto3_route53.py +++ b/tests/unit/modules/test_boto3_route53.py @@ -1,6 +1,7 @@ """ Tests for salt.modules.boto3_route53 """ + import random import string diff --git a/tests/unit/modules/test_boto_route53.py b/tests/unit/modules/test_boto_route53.py index 5c257c09c33..4f884dacad6 100644 --- a/tests/unit/modules/test_boto_route53.py +++ b/tests/unit/modules/test_boto_route53.py @@ -70,7 +70,7 @@ def _has_required_moto(): @pytest.mark.skipif(HAS_MOTO is False, reason="The moto module must be installed.") @pytest.mark.skipif( _has_required_moto() is False, - reason="The moto module must be >= to {}".format(required_moto), + reason=f"The moto module must be >= to {required_moto}", ) class BotoRoute53TestCase(TestCase, LoaderModuleMockMixin): """ diff --git a/tests/unit/modules/test_boto_secgroup.py b/tests/unit/modules/test_boto_secgroup.py index 05167ffe774..1832dac4323 100644 --- a/tests/unit/modules/test_boto_secgroup.py +++ b/tests/unit/modules/test_boto_secgroup.py @@ -70,7 +70,7 @@ boto_conn_parameters = { def _random_group_id(): - group_id = "sg-{:x}".format(random.randrange(2**32)) + group_id = f"sg-{random.randrange(2**32):x}" return group_id diff --git a/tests/unit/modules/test_boto_vpc.py b/tests/unit/modules/test_boto_vpc.py index a670cd3628f..0841dd7ac0d 100644 --- a/tests/unit/modules/test_boto_vpc.py +++ b/tests/unit/modules/test_boto_vpc.py @@ -708,7 +708,7 @@ class BotoVpcTestCase(BotoVpcTestCaseBase, BotoVpcTestCaseMixin): ) @pytest.mark.skipif( _has_required_moto() is False, - reason="The moto version must be >= to version {}".format(required_moto_version), + reason=f"The moto version must be >= to version {required_moto_version}", ) class BotoVpcSubnetsTestCase(BotoVpcTestCaseBase, BotoVpcTestCaseMixin): @mock_ec2_deprecated @@ -1262,7 +1262,7 @@ class BotoVpcCustomerGatewayTestCase(BotoVpcTestCaseBase, BotoVpcTestCaseMixin): ) @pytest.mark.skipif( _has_required_moto() is False, - reason="The moto version must be >= to version {}".format(required_moto_version), + reason=f"The moto version must be >= to version {required_moto_version}", ) class BotoVpcDHCPOptionsTestCase(BotoVpcTestCaseBase, BotoVpcTestCaseMixin): @mock_ec2_deprecated @@ -2223,7 +2223,7 @@ class BotoVpcRouteTablesTestCase(BotoVpcTestCaseBase, BotoVpcTestCaseMixin): ) @pytest.mark.skipif( _has_required_moto() is False, - reason="The moto version must be >= to version {}".format(required_moto_version), + reason=f"The moto version must be >= to version {required_moto_version}", ) class BotoVpcPeeringConnectionsTest(BotoVpcTestCaseBase, BotoVpcTestCaseMixin): @mock_ec2_deprecated @@ -2239,7 +2239,7 @@ class BotoVpcPeeringConnectionsTest(BotoVpcTestCaseBase, BotoVpcTestCaseMixin): name="my_peering", requester_vpc_id=my_vpc.id, peer_vpc_id=other_vpc.id, - **conn_parameters + **conn_parameters, ) ) @@ -2256,7 +2256,7 @@ class BotoVpcPeeringConnectionsTest(BotoVpcTestCaseBase, BotoVpcTestCaseMixin): requester_vpc_id=my_vpc.id, peer_vpc_id=other_vpc.id, peer_region="test_region", - **conn_parameters + **conn_parameters, ) @mock_ec2_deprecated @@ -2272,14 +2272,14 @@ class BotoVpcPeeringConnectionsTest(BotoVpcTestCaseBase, BotoVpcTestCaseMixin): requester_vpc_id=my_vpc.id, requester_vpc_name="foobar", peer_vpc_id=other_vpc.id, - **conn_parameters + **conn_parameters, ) boto_vpc.request_vpc_peering_connection( name="my_peering", requester_vpc_name="my_peering", peer_vpc_id=other_vpc.id, - **conn_parameters + **conn_parameters, ) diff --git a/tests/unit/modules/test_bsd_shadow.py b/tests/unit/modules/test_bsd_shadow.py index 11e20c6e7f6..e60acb5172f 100644 --- a/tests/unit/modules/test_bsd_shadow.py +++ b/tests/unit/modules/test_bsd_shadow.py @@ -1,6 +1,7 @@ """ :codeauthor: Alan Somers """ + import re import pytest diff --git a/tests/unit/modules/test_cron.py b/tests/unit/modules/test_cron.py index 0a35436b332..ba031d4fb4d 100644 --- a/tests/unit/modules/test_cron.py +++ b/tests/unit/modules/test_cron.py @@ -849,7 +849,7 @@ class CronTestCase(TestCase, LoaderModuleMockMixin): (L + "# foo\n* * * * * ls\n"), ( L - + "# foo {}:blah\n".format(cron.SALT_CRON_IDENTIFIER) + + f"# foo {cron.SALT_CRON_IDENTIFIER}:blah\n" + "* * * * * ls\n" ), ] @@ -1428,7 +1428,7 @@ class PsTestCase(TestCase, LoaderModuleMockMixin): Expected to run without runas argument. """ temp_path = "some_temp_path" - crontab_cmd = "crontab {}".format(temp_path) + crontab_cmd = f"crontab {temp_path}" with patch.dict(cron.__grains__, {"os_family": "RedHat"}), patch.dict( cron.__salt__, {"cmd.run_all": MagicMock()} @@ -1480,7 +1480,7 @@ class PsTestCase(TestCase, LoaderModuleMockMixin): Expected to run with runas argument. """ temp_path = "some_temp_path" - crontab_cmd = "crontab {}".format(temp_path) + crontab_cmd = f"crontab {temp_path}" with patch.dict(cron.__grains__, {"os_family": "RedHat"}), patch.dict( cron.__salt__, {"cmd.run_all": MagicMock()} @@ -1508,7 +1508,7 @@ class PsTestCase(TestCase, LoaderModuleMockMixin): Expected to run with runas argument. """ temp_path = "some_temp_path" - crontab_cmd = "crontab {}".format(temp_path) + crontab_cmd = f"crontab {temp_path}" with patch.dict(cron.__grains__, {"os_family": "AIX"}), patch.dict( cron.__salt__, {"cmd.run_all": MagicMock()} @@ -1531,7 +1531,7 @@ class PsTestCase(TestCase, LoaderModuleMockMixin): Expected to run with runas argument. """ temp_path = "some_temp_path" - crontab_cmd = "crontab {}".format(temp_path) + crontab_cmd = f"crontab {temp_path}" with patch.dict(cron.__grains__, {"os_family": "Solaris"}), patch.dict( cron.__salt__, {"cmd.run_all": MagicMock()} diff --git a/tests/unit/modules/test_freezer.py b/tests/unit/modules/test_freezer.py index 436ec4b7446..aaa542d0e4a 100644 --- a/tests/unit/modules/test_freezer.py +++ b/tests/unit/modules/test_freezer.py @@ -3,7 +3,6 @@ :platform: Linux """ - import salt.modules.freezer as freezer from salt.exceptions import CommandExecutionError from tests.support.mixins import LoaderModuleMockMixin diff --git a/tests/unit/modules/test_influxdb08mod.py b/tests/unit/modules/test_influxdb08mod.py index d58d99da138..79cf8542d87 100644 --- a/tests/unit/modules/test_influxdb08mod.py +++ b/tests/unit/modules/test_influxdb08mod.py @@ -2,7 +2,6 @@ :codeauthor: Rupesh Tare """ - import salt.modules.influxdb08mod as influx08 from tests.support.mock import MagicMock, patch from tests.support.unit import TestCase diff --git a/tests/unit/modules/test_k8s.py b/tests/unit/modules/test_k8s.py index db11296bde5..bec159ffd9a 100644 --- a/tests/unit/modules/test_k8s.py +++ b/tests/unit/modules/test_k8s.py @@ -81,7 +81,7 @@ class TestK8SSecrets(TestCase): def test_get_one_secret(self): name = self.name - filename = "/tmp/{}.json".format(name) + filename = f"/tmp/{name}.json" with salt.utils.files.fopen(filename, "w") as f: salt.utils.json.dump(self.request, f) @@ -102,7 +102,7 @@ class TestK8SSecrets(TestCase): def test_get_decoded_secret(self): name = self.name - filename = "/tmp/{}.json".format(name) + filename = f"/tmp/{name}.json" with salt.utils.files.fopen(filename, "w") as f: salt.utils.json.dump(self.request, f) @@ -124,12 +124,10 @@ class TestK8SSecrets(TestCase): names = [] expected_data = {} for i in range(2): - names.append("/tmp/{}-{}".format(name, i)) - with salt.utils.files.fopen("/tmp/{}-{}".format(name, i), "w") as f: - expected_data["{}-{}".format(name, i)] = base64.b64encode( - "{}{}".format(name, i) - ) - f.write(salt.utils.stringutils.to_str("{}{}".format(name, i))) + names.append(f"/tmp/{name}-{i}") + with salt.utils.files.fopen(f"/tmp/{name}-{i}", "w") as f: + expected_data[f"{name}-{i}"] = base64.b64encode(f"{name}{i}") + f.write(salt.utils.stringutils.to_str(f"{name}{i}")) res = k8s.create_secret( "default", name, names, apiserver_url="http://127.0.0.1:8080" ) @@ -145,7 +143,7 @@ class TestK8SSecrets(TestCase): def test_update_secret(self): name = self.name - filename = "/tmp/{}.json".format(name) + filename = f"/tmp/{name}.json" with salt.utils.files.fopen(filename, "w") as f: salt.utils.json.dump(self.request, f) @@ -157,12 +155,12 @@ class TestK8SSecrets(TestCase): expected_data = {} names = [] for i in range(3): - names.append("/tmp/{}-{}-updated".format(name, i)) - with salt.utils.files.fopen("/tmp/{}-{}-updated".format(name, i), "w") as f: - expected_data["{}-{}-updated".format(name, i)] = base64.b64encode( - "{}{}-updated".format(name, i) + names.append(f"/tmp/{name}-{i}-updated") + with salt.utils.files.fopen(f"/tmp/{name}-{i}-updated", "w") as f: + expected_data[f"{name}-{i}-updated"] = base64.b64encode( + f"{name}{i}-updated" ) - f.write("{}{}-updated".format(name, i)) + f.write(f"{name}{i}-updated") res = k8s.update_secret( "default", name, names, apiserver_url="http://127.0.0.1:8080" @@ -180,7 +178,7 @@ class TestK8SSecrets(TestCase): def test_delete_secret(self): name = self.name - filename = "/tmp/{}.json".format(name) + filename = f"/tmp/{name}.json" with salt.utils.files.fopen(filename, "w") as f: salt.utils.json.dump(self.request, f) @@ -199,9 +197,7 @@ class TestK8SSecrets(TestCase): kubectl_out, err = proc.communicate() # stdout is empty, stderr is showing something like "not found" self.assertEqual("", kubectl_out) - self.assertEqual( - 'Error from server: secrets "{}" not found\n'.format(name), err - ) + self.assertEqual(f'Error from server: secrets "{name}" not found\n', err) @pytest.mark.skip_if_binaries_missing("kubectl") @@ -241,12 +237,12 @@ spec: """.format( name ) - filename = "/tmp/{}.yaml".format(name) + filename = f"/tmp/{name}.yaml" with salt.utils.files.fopen(filename, "w") as f: f.write(salt.utils.stringutils.to_str(request)) create = Popen( - ["kubectl", "--namespace={}".format(namespace), "create", "-f", filename], + ["kubectl", f"--namespace={namespace}", "create", "-f", filename], stdout=PIPE, ) # wee need to give kubernetes time save data in etcd @@ -256,7 +252,7 @@ spec: proc = Popen( [ "kubectl", - "--namespace={}".format(namespace), + f"--namespace={namespace}", "get", "quota", "-o", @@ -292,12 +288,12 @@ spec: """.format( name ) - filename = "/tmp/{}.yaml".format(name) + filename = f"/tmp/{name}.yaml" with salt.utils.files.fopen(filename, "w") as f: f.write(salt.utils.stringutils.to_str(request)) create = Popen( - ["kubectl", "--namespace={}".format(namespace), "create", "-f", filename], + ["kubectl", f"--namespace={namespace}", "create", "-f", filename], stdout=PIPE, ) # wee need to give kubernetes time save data in etcd @@ -309,7 +305,7 @@ spec: proc = Popen( [ "kubectl", - "--namespace={}".format(namespace), + f"--namespace={namespace}", "get", "quota", name, @@ -335,7 +331,7 @@ spec: proc = Popen( [ "kubectl", - "--namespace={}".format(namespace), + f"--namespace={namespace}", "get", "quota", name, @@ -371,12 +367,12 @@ spec: """.format( name ) - filename = "/tmp/{}.yaml".format(name) + filename = f"/tmp/{name}.yaml" with salt.utils.files.fopen(filename, "w") as f: f.write(salt.utils.stringutils.to_str(request)) create = Popen( - ["kubectl", "--namespace={}".format(namespace), "create", "-f", filename], + ["kubectl", f"--namespace={namespace}", "create", "-f", filename], stdout=PIPE, ) # wee need to give kubernetes time save data in etcd @@ -392,7 +388,7 @@ spec: proc = Popen( [ "kubectl", - "--namespace={}".format(namespace), + f"--namespace={namespace}", "get", "quota", name, @@ -449,7 +445,7 @@ spec: name ) limits = {"Container": {"defaultRequest": {"cpu": "100m"}}} - filename = "/tmp/{}.yaml".format(name) + filename = f"/tmp/{name}.yaml" with salt.utils.files.fopen(filename, "w") as f: f.write(salt.utils.stringutils.to_str(request)) @@ -505,7 +501,7 @@ spec: """.format( name ) - filename = "/tmp/{}.yaml".format(name) + filename = f"/tmp/{name}.yaml" with salt.utils.files.fopen(filename, "w") as f: f.write(salt.utils.stringutils.to_str(request)) diff --git a/tests/unit/modules/test_kernelpkg_linux_apt.py b/tests/unit/modules/test_kernelpkg_linux_apt.py index 92f40f89767..cf56deb4a4a 100644 --- a/tests/unit/modules/test_kernelpkg_linux_apt.py +++ b/tests/unit/modules/test_kernelpkg_linux_apt.py @@ -4,6 +4,7 @@ :maturity: develop .. versionadded:: 2018.3.0 """ + # pylint: disable=invalid-name,no-member import re @@ -39,7 +40,7 @@ class AptKernelPkgTestCase(KernelPkgTestCase, TestCase, LoaderModuleMockMixin): @classmethod def setUpClass(cls): version = re.match(r"^(\d+\.\d+\.\d+)-(\d+)", cls.KERNEL_LIST[-1]) - cls.LATEST = "{}.{}".format(version.group(1), version.group(2)) + cls.LATEST = f"{version.group(1)}.{version.group(2)}" for kernel in cls.KERNEL_LIST: pkg = "{}-{}".format( @@ -66,8 +67,7 @@ class AptKernelPkgTestCase(KernelPkgTestCase, TestCase, LoaderModuleMockMixin): Test - Return return the latest installed kernel version """ PACKAGE_LIST = [ - "{}-{}".format(kernelpkg._package_prefix(), kernel) - for kernel in self.KERNEL_LIST + f"{kernelpkg._package_prefix()}-{kernel}" for kernel in self.KERNEL_LIST ] # pylint: disable=protected-access mock = MagicMock(return_value=PACKAGE_LIST) diff --git a/tests/unit/modules/test_kernelpkg_linux_yum.py b/tests/unit/modules/test_kernelpkg_linux_yum.py index 4005a4897d7..058af383d60 100644 --- a/tests/unit/modules/test_kernelpkg_linux_yum.py +++ b/tests/unit/modules/test_kernelpkg_linux_yum.py @@ -4,6 +4,7 @@ :maturity: develop .. versionadded:: 2018.3.0 """ + # pylint: disable=invalid-name,no-member import pytest @@ -42,7 +43,7 @@ class YumKernelPkgTestCase(KernelPkgTestCase, TestCase, LoaderModuleMockMixin): "__grains__": { "os": self.OS_NAME, "osmajorrelease": self.OS_MAJORRELEASE, - "kernelrelease": "{}.{}".format(self.KERNEL_LIST[0], self.OS_ARCH), + "kernelrelease": f"{self.KERNEL_LIST[0]}.{self.OS_ARCH}", }, "__salt__": { "pkg.normalize_name": pkg.normalize_name, diff --git a/tests/unit/modules/test_kubernetesmod.py b/tests/unit/modules/test_kubernetesmod.py index 4d38d63bb51..049ed53663f 100644 --- a/tests/unit/modules/test_kubernetesmod.py +++ b/tests/unit/modules/test_kubernetesmod.py @@ -1,6 +1,7 @@ """ :codeauthor: Jochen Breuer """ + # pylint: disable=no-value-for-parameter import os from contextlib import contextmanager diff --git a/tests/unit/modules/test_libcloud_compute.py b/tests/unit/modules/test_libcloud_compute.py index a95a64c1bad..15893fefe3b 100644 --- a/tests/unit/modules/test_libcloud_compute.py +++ b/tests/unit/modules/test_libcloud_compute.py @@ -1,6 +1,7 @@ """ :codeauthor: :email:`Anthony Shaw ` """ + import logging import pytest diff --git a/tests/unit/modules/test_libcloud_dns.py b/tests/unit/modules/test_libcloud_dns.py index 87416c98199..77c64fa1ed2 100644 --- a/tests/unit/modules/test_libcloud_dns.py +++ b/tests/unit/modules/test_libcloud_dns.py @@ -1,6 +1,7 @@ """ :codeauthor: Anthony Shaw """ + import pytest import salt.modules.libcloud_dns as libcloud_dns diff --git a/tests/unit/modules/test_libcloud_loadbalancer.py b/tests/unit/modules/test_libcloud_loadbalancer.py index 02ae019759c..69b8ae26117 100644 --- a/tests/unit/modules/test_libcloud_loadbalancer.py +++ b/tests/unit/modules/test_libcloud_loadbalancer.py @@ -1,6 +1,7 @@ """ :codeauthor: :email:`Anthony Shaw ` """ + import pytest import salt.modules.libcloud_loadbalancer as libcloud_loadbalancer diff --git a/tests/unit/modules/test_libcloud_storage.py b/tests/unit/modules/test_libcloud_storage.py index 8f7fd069782..9347e2571c2 100644 --- a/tests/unit/modules/test_libcloud_storage.py +++ b/tests/unit/modules/test_libcloud_storage.py @@ -1,6 +1,7 @@ """ :codeauthor: :email:`Anthony Shaw ` """ + import pytest import salt.modules.libcloud_storage as libcloud_storage diff --git a/tests/unit/modules/test_linux_acl.py b/tests/unit/modules/test_linux_acl.py index 35dadbedacf..b8e601344f1 100644 --- a/tests/unit/modules/test_linux_acl.py +++ b/tests/unit/modules/test_linux_acl.py @@ -15,7 +15,7 @@ class LinuxAclTestCase(TestCase, LoaderModuleMockMixin): self.file = "/tmp/file" self.quoted_file = '"/tmp/file"' self.files = ["/tmp/file1", "/tmp/file2", "/tmp/file3 with whitespaces"] - self.quoted_files = ['"{}"'.format(f) for f in self.files] + self.quoted_files = [f'"{f}"' for f in self.files] self.u_acl = ["u", "myuser", "rwx"] self.user_acl = ["user", "myuser", "rwx"] self.user_acl_cmd = "u:myuser:rwx" diff --git a/tests/unit/modules/test_localemod.py b/tests/unit/modules/test_localemod.py index 83496de3dfd..cc2706b20be 100644 --- a/tests/unit/modules/test_localemod.py +++ b/tests/unit/modules/test_localemod.py @@ -1,6 +1,7 @@ """ :codeauthor: Rupesh Tare """ + import pytest import salt.modules.localemod as localemod @@ -417,9 +418,7 @@ class LocalemodTestCase(TestCase, LoaderModuleMockMixin): == "/etc/sysconfig/language" ) assert localemod.__salt__["file.replace"].call_args[0][1] == "^RC_LANG=.*" - assert localemod.__salt__["file.replace"].call_args[0][ - 2 - ] == 'RC_LANG="{}"'.format(loc) + assert localemod.__salt__["file.replace"].call_args[0][2] == f'RC_LANG="{loc}"' @patch("salt.utils.path.which", MagicMock(return_value=None)) @patch( diff --git a/tests/unit/modules/test_memcached.py b/tests/unit/modules/test_memcached.py index b62986f2317..f51c9fb8e8d 100644 --- a/tests/unit/modules/test_memcached.py +++ b/tests/unit/modules/test_memcached.py @@ -2,7 +2,6 @@ :codeauthor: Jayesh Kariya """ - import salt.modules.memcached as memcached from salt.exceptions import CommandExecutionError, SaltInvocationError from tests.support.mock import MagicMock, patch diff --git a/tests/unit/modules/test_napalm_probes.py b/tests/unit/modules/test_napalm_probes.py index 2ebda0dc84a..6eaa80b8310 100644 --- a/tests/unit/modules/test_napalm_probes.py +++ b/tests/unit/modules/test_napalm_probes.py @@ -2,7 +2,6 @@ :codeauthor: :email:`Anthony Shaw ` """ - import salt.modules.napalm_probes as napalm_probes import tests.support.napalm as napalm_test_support from tests.support.mixins import LoaderModuleMockMixin @@ -53,7 +52,7 @@ class NapalmProbesModuleTestCase(TestCase, LoaderModuleMockMixin): if template == "schedule_probes": assert kwargs["probes"] == self._test_schedule_probes.copy() return napalm_test_support.TEST_TERM_CONFIG.copy() - raise ValueError("incorrect template {}".format(template)) + raise ValueError(f"incorrect template {template}") module_globals = { "__salt__": { diff --git a/tests/unit/modules/test_napalm_yang_mod.py b/tests/unit/modules/test_napalm_yang_mod.py index 9d711b04ca3..6e5f848fb10 100644 --- a/tests/unit/modules/test_napalm_yang_mod.py +++ b/tests/unit/modules/test_napalm_yang_mod.py @@ -2,7 +2,6 @@ :codeauthor: :email:`Anthony Shaw ` """ - import salt.modules.napalm_network as napalm_network import salt.modules.napalm_yang_mod as napalm_yang_mod import tests.support.napalm as napalm_test_support diff --git a/tests/unit/modules/test_netbox.py b/tests/unit/modules/test_netbox.py index a2257068b75..45958e677fb 100644 --- a/tests/unit/modules/test_netbox.py +++ b/tests/unit/modules/test_netbox.py @@ -1,6 +1,7 @@ """ :codeauthor: :email:`Zach Moody ` """ + import pytest import salt.modules.netbox as netbox diff --git a/tests/unit/modules/test_netscaler.py b/tests/unit/modules/test_netscaler.py index 46b195ec297..d320f0fbe5a 100644 --- a/tests/unit/modules/test_netscaler.py +++ b/tests/unit/modules/test_netscaler.py @@ -2,7 +2,6 @@ :codeauthor: Jayesh Kariya """ - import salt.modules.netscaler as netscaler from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch diff --git a/tests/unit/modules/test_neutron.py b/tests/unit/modules/test_neutron.py index 7fed7bcc121..c6fb5b38445 100644 --- a/tests/unit/modules/test_neutron.py +++ b/tests/unit/modules/test_neutron.py @@ -2,7 +2,6 @@ :codeauthor: Jayesh Kariya """ - import salt.modules.neutron as neutron from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock diff --git a/tests/unit/modules/test_nova.py b/tests/unit/modules/test_nova.py index f9cb3db9490..47fa1d3742d 100644 --- a/tests/unit/modules/test_nova.py +++ b/tests/unit/modules/test_nova.py @@ -2,7 +2,6 @@ :codeauthor: Rahul Handay """ - import salt.modules.nova as nova from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import MagicMock, patch diff --git a/tests/unit/modules/test_nxos.py b/tests/unit/modules/test_nxos.py index 7610abadab0..cedf1e707ff 100644 --- a/tests/unit/modules/test_nxos.py +++ b/tests/unit/modules/test_nxos.py @@ -45,7 +45,6 @@ from tests.unit.modules.nxos.nxos_show_run import ( class NxosTestCase(TestCase, LoaderModuleMockMixin): - """Test cases for salt.modules.nxos""" COPY_RS = "copy running-config startup-config" @@ -58,14 +57,12 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): @staticmethod def test_check_virtual(): - """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""" with patch("salt.utils.platform.is_proxy", return_value=True, autospec=True): with patch.dict( @@ -75,7 +72,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertTrue(result) def test_ping_native_minion(self): - """UT: nxos module:ping method - proxy""" with patch("salt.utils.platform.is_proxy", return_value=False, autospec=True): @@ -86,7 +82,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertTrue(result) def test_check_password_return_none(self): - """UT: nxos module:check_password method - return None""" username = "admin" @@ -97,7 +92,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertIsNone(result) def test_check_password_password_nxos_comment(self): - """UT: nxos module:check_password method - password_line has '!'""" username = "admin" @@ -112,7 +106,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): reason="compatible crypt method for fake data not available", ) def test_check_password_password_encrypted_false(self): - """UT: nxos module:check_password method - password is not encrypted""" username = "salt_test" @@ -127,7 +120,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertTrue(result) def test_check_password_password_encrypted_true(self): - """UT: nxos module:check_password method - password is encrypted""" username = "salt_test" @@ -142,7 +134,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertTrue(result) def test_check_password_password_encrypted_true_negative(self): - """UT: nxos module:check_password method - password is not encrypted""" username = "salt_test" @@ -155,7 +146,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertFalse(result) def test_check_role_true(self): - """UT: nxos module:check_role method - Role configured""" username = "salt_test" @@ -166,7 +156,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertTrue(result) def test_check_role_false(self): - """UT: nxos module:check_role method - Role not configured""" username = "salt_test" @@ -177,7 +166,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertFalse(result) def test_cmd_any_function(self): - """UT: nxos module:cmd method - check_role function""" with patch.dict( @@ -198,7 +186,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertTrue(result) def test_cmd_function_absent(self): - """UT: nxos module:cmd method - non existent function""" result = nxos_module.cmd( @@ -207,7 +194,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertFalse(result) def test_find_single_match(self): - """UT: nxos module:test_find method - Find single match in running config""" find_pattern = "^vrf context testing$" @@ -220,7 +206,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertIn(find_string, result) def test_find_multiple_matches(self): - """UT: nxos module:test_find method - Find multiple matches in running config""" find_pattern = "^no logging.*$" @@ -234,7 +219,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(len(result), 7) def test_get_roles_user_not_configured(self): - """UT: nxos module:get_roles method - User not configured""" username = "salt_does_not_exist" @@ -245,7 +229,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, []) def test_get_roles_user_configured(self): - """UT: nxos module:get_roles method - User configured""" username = "salt_test" @@ -260,7 +243,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result.sort(), expected_result.sort()) def test_get_roles_user_configured_no_role(self): - """UT: nxos module:get_roles method - User configured no roles""" username = "salt_test" @@ -271,7 +253,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, []) def test_get_user_configured(self): - """UT: nxos module:get_user method - User configured""" username = "salt_test" @@ -286,7 +267,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, expected_output) def test_grains(self): - """UT: nxos module:grains method""" nxos_module.DEVICE_DETAILS["grains_cache"] = {} @@ -316,7 +296,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, expected_grains) def test_grains_get_cache(self): - """UT: nxos module:grains method""" expected_grains = { @@ -346,7 +325,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, expected_grains) def test_grains_refresh(self): - """UT: nxos module:grains_refresh method""" expected_grains = { @@ -368,7 +346,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, expected_grains) def test_system_info(self): - """UT: nxos module:system_info method""" expected_grains = { @@ -397,7 +374,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, expected_grains) def test_sendline_invalid_method(self): - """UT: nxos module:sendline method - invalid method""" command = "show version" @@ -409,7 +385,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertIn("INPUT ERROR", result) def test_sendline_valid_method_proxy(self): - """UT: nxos module:sendline method - valid method over proxy""" command = "show version" @@ -424,7 +399,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertIn(n9k_show_ver, result) def test_sendline_valid_method_nxapi_uds(self): - """UT: nxos module:sendline method - valid method over nxapi uds""" command = "show version" @@ -440,7 +414,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertIn(n9k_show_ver, result) def test_show_raw_text_invalid(self): - """UT: nxos module:show method - invalid argument""" command = "show version" @@ -450,7 +423,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertIn("INPUT ERROR", result) def test_show_raw_text_true(self): - """UT: nxos module:show method - raw_test true""" command = "show version" @@ -463,7 +435,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, n9k_show_ver) def test_show_raw_text_true_multiple_commands(self): - """UT: nxos module:show method - raw_test true multiple commands""" command = "show bgp sessions ; show processes" @@ -475,7 +446,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, data) def test_show_nxapi(self): - """UT: nxos module:show method - nxapi returns info as list""" command = "show version; show interface eth1/1" @@ -491,7 +461,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result[1], n9k_show_ver_int_list[1]) def test_show_nxapi_structured(self): - """UT: nxos module:show method - nxapi returns info as list""" command = "show version; show interface eth1/1" @@ -507,7 +476,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result[1], n9k_show_ver_int_list_structured[1]) def test_show_run(self): - """UT: nxos module:show_run method""" expected_output = n9k_show_running_config_list[0] @@ -518,7 +486,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, expected_output) def test_show_ver(self): - """UT: nxos module:show_ver method""" expected_output = n9k_show_ver_list[0] @@ -529,7 +496,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, expected_output) def test_add_config(self): - """UT: nxos module:add_config method""" expected_output = "COMMAND_LIST: feature bgp" @@ -541,7 +507,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, expected_output) def test_config_commands(self): - """UT: nxos module:config method - Using commands arg""" commands = ["no feature ospf", ["no feature ospf"]] @@ -573,7 +538,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, expected_output) def test_config_commands_template_none(self): - """UT: nxos module:config method - Template engine is None""" commands = ["no feature ospf", ["no feature ospf"]] @@ -605,7 +569,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, expected_output) def test_config_commands_string(self): - """UT: nxos module:config method - Using commands arg and output is string""" commands = "no feature ospf" @@ -636,7 +599,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, expected_output) def test_config_file(self): - """UT: nxos module:config method - Using config_file arg""" config_file = "salt://bgp_config.txt" @@ -676,7 +638,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, expected_output) def test_config_file_error1(self): - """UT: nxos module:config method - Error file not found""" config_file = "salt://bgp_config.txt" @@ -704,7 +665,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): nxos_module.config(config_file=config_file) def test_config_nxos_error_ssh(self): - """UT: nxos module:config method - nxos device error over ssh transport""" commands = ["feature bgp", "router bgp 57"] @@ -740,7 +700,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, expected_output) def test_commands_error(self): - """UT: nxos module:config method - Mandatory arg commands not specified""" commands = None @@ -768,7 +727,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): nxos_module.config(commands=commands) def test_config_file_error2(self): - """UT: nxos module:config method - Mandatory arg config_file not specified""" config_file = None @@ -796,7 +754,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): nxos_module.config(config_file=config_file) def test_delete_config(self): - """UT: nxos module:delete_config method""" for lines in ["feature bgp", ["feature bgp"]]: @@ -806,7 +763,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, nxos_module.config.return_value) def test_remove_user(self): - """UT: nxos module:remove_user method""" with patch("salt.modules.nxos.config", autospec=True): @@ -815,7 +771,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, nxos_module.config.return_value) def test_replace(self): - """UT: nxos module:replace method""" old_value = "feature bgp" @@ -837,7 +792,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result["new"], ["feature ospf"]) def test_replace_full_match_true(self): - """UT: nxos module:replace method - full match true""" old_value = "feature bgp" @@ -859,7 +813,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result["new"], ["feature ospf"]) def test_replace_no_match(self): - """UT: nxos module:replace method - no match""" old_value = "feature does_not_exist" @@ -881,7 +834,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result["new"], []) def test_save_running_config(self): - """UT: nxos module:save_running_config method""" with patch( @@ -891,7 +843,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, save_running_config) def test_set_password_enc_false_cs_none(self): - """UT: nxos module:set_password method - encrypted False, crypt_salt None""" username = "devops" @@ -916,7 +867,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual("password_set", result) def test_set_password_enc_false_cs_set(self): - """UT: nxos module:set_password method - encrypted False, crypt_salt set""" username = "devops" @@ -944,7 +894,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual("password_set", result) def test_set_password_enc_true(self): - """UT: nxos module:set_password method - encrypted True""" username = "devops" @@ -968,7 +917,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual("password_set", result) def test_set_password_role_none(self): - """UT: nxos module:set_password method - role none""" username = "devops" @@ -993,7 +941,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual("password_set", result) def test_set_password_blowfish_crypt(self): - """UT: nxos module:set_password method - role none""" with self.assertRaises(SaltInvocationError): @@ -1002,7 +949,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): ) def test_set_role(self): - """UT: nxos module:save_running_config method""" username = "salt_test" @@ -1013,7 +959,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, set_role) def test_unset_role(self): - """UT: nxos module:save_running_config method""" username = "salt_test" @@ -1024,7 +969,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, unset_role) def test_configure_device(self): - """UT: nxos module:_configure_device method""" with patch("salt.utils.platform.is_proxy", autospec=True, return_value=True): @@ -1043,7 +987,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, "configured") def test_nxapi_config(self): - """UT: nxos module:_nxapi_config method""" mock_cmd = MagicMock(return_value={"nxos": {"save_config": False}}) @@ -1057,7 +1000,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, [["show version"], "router_data"]) def test_nxapi_config_failure(self): - """UT: nxos module:_nxapi_config method""" side_effect = ["Failure", "saved_data"] @@ -1073,7 +1015,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, [["show bad_command"], "Failure"]) def test_nxapi_request_proxy(self): - """UT: nxos module:_nxapi_request method - proxy""" with patch("salt.utils.platform.is_proxy", autospec=True, return_value=True): @@ -1087,7 +1028,6 @@ class NxosTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(result, "router_data") def test_nxapi_request_no_proxy(self): - """UT: nxos module:_nxapi_request method - no proxy""" with patch("salt.utils.platform.is_proxy", autospec=True, return_value=False): diff --git a/tests/unit/modules/test_nxos_upgrade.py b/tests/unit/modules/test_nxos_upgrade.py index 1b6be938ef4..1c0c5013caf 100644 --- a/tests/unit/modules/test_nxos_upgrade.py +++ b/tests/unit/modules/test_nxos_upgrade.py @@ -35,14 +35,12 @@ from tests.unit.modules.nxos.nxos_n95k import N95KPlatform class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): - """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 bool(condition), "{}: Upgrade {} -> {}".format( @@ -50,7 +48,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): ) def setup_loader_modules(self): - """Define list of platforms for Unit Test""" self.platform_list = [ @@ -81,7 +78,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): @staticmethod def test_check_upgrade_impact_input_validation(): - """UT: nxos_upgrade module:check_upgrade_impact method - input validation""" result = nxos_upgrade.check_upgrade_impact("dummy-platform-image.bin", issu=1) @@ -89,14 +85,12 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): @staticmethod def test_upgrade_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""" for platform in self.platform_list: @@ -116,7 +110,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): self.assert_platform_upgrade(not result["succeeded"], platform) 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""" for platform in self.platform_list: @@ -134,7 +127,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): self.assert_platform_upgrade(not result["succeeded"], platform) 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""" for platform in self.platform_list: @@ -152,7 +144,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): self.assert_platform_upgrade(not result["succeeded"], platform) def test_check_upgrade_impact_internal_server_error_500(self): - """UT: nxos_upgrade module:check_upgrade_impact method - internal server error HTTP code 500""" for platform in self.platform_list: @@ -176,7 +167,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): self.assert_platform_upgrade(not result["succeeded"], platform) def test_check_upgrade_impact_non_disruptive_success(self): - """UT: nxos_upgrade module:check_upgrade_impact method - non-disruptive success""" for platform in self.platform_list: @@ -197,7 +187,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): self.assert_platform_upgrade(result["module_data"], platform) def test_check_upgrade_impact_disruptive_success(self): - """UT: nxos_upgrade module:check_upgrade_impact method - disruptive success""" for platform in self.platform_list: @@ -225,7 +214,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): self.assert_platform_upgrade(result["module_data"], platform) def test_upgrade_show_install_all_impact_no_module_data(self): - """UT: nxos_upgrade module: upgrade method - no module data""" for platform in self.platform_list: @@ -245,7 +233,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): ) def test_upgrade_invalid_command(self): - """UT: nxos_upgrade module:upgrade method - invalid command""" for platform in self.platform_list: @@ -259,7 +246,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): self.assert_platform_upgrade(not result["succeeded"], platform) def test_upgrade_install_in_progress(self): - """UT: nxos_upgrade module:upgrade method - in-progress""" for platform in self.platform_list: @@ -277,7 +263,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): self.assert_platform_upgrade(not result["succeeded"], platform) def test_upgrade_install_in_progress_terminal_dont_ask(self): - """UT: nxos_upgrade module:upgrade method - in-progress (terminal don't-ask)""" for platform in self.platform_list: @@ -298,7 +283,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): self.assert_platform_upgrade(not result["succeeded"], platform) def test_upgrade_install_in_progress_sans_terminal_dont_ask(self): - """UT: nxos_upgrade module:upgrade method - in-progress (sans terminal don't-ask)""" for platform in self.platform_list: @@ -316,7 +300,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): self.assert_platform_upgrade(not result["succeeded"], platform) def test_upgrade_internal_server_error_500(self): - """UT: nxos_upgrade module:upgrade method - internal server error 500""" for platform in self.platform_list: @@ -337,7 +320,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): self.assert_platform_upgrade(not result["succeeded"], platform) def test_upgrade_install_all_disruptive(self): - """UT: nxos_upgrade module:upgrade method - install all disruptive""" for platform in self.platform_list: @@ -367,7 +349,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): ) def test_upgrade_install_all_non_disruptive(self): - """UT: nxos_upgrade module:upgrade method - install all non-disruptive""" for platform in self.platform_list: @@ -390,7 +371,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): self.assert_platform_upgrade(result["succeeded"], platform) def test_upgrade_CommandExecutionError_Exception(self): - """UT: nxos_upgrade module:upgrade method - raise CommandExecutionError exception #1""" for platform in self.platform_list: @@ -418,7 +398,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): self.assert_platform_upgrade(not result["succeeded"], platform) def test_upgrade_CommandExecutionError_Exception2(self): - """UT: nxos_upgrade module:upgrade method - raise CommandExecutionError exception #2""" for platform in self.platform_list: @@ -454,7 +433,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): self.assert_platform_upgrade(result["succeeded"], platform) def test_upgrade_NxosError_Exception(self): - """UT: nxos_upgrade module:upgrade method - raise NxosError exception""" for platform in self.platform_list: @@ -485,7 +463,6 @@ class NxosUpgradeTestCase(TestCase, LoaderModuleMockMixin): self.assert_platform_upgrade(result["succeeded"], platform) def test_upgrade_NxosError_Exception2(self): - """UT: nxos_upgrade module:upgrade method - raise NxosError exception #2""" for platform in self.platform_list: diff --git a/tests/unit/modules/test_openstack_config.py b/tests/unit/modules/test_openstack_config.py index 56976992c21..d014547160d 100644 --- a/tests/unit/modules/test_openstack_config.py +++ b/tests/unit/modules/test_openstack_config.py @@ -2,7 +2,6 @@ :codeauthor: Jayesh Kariya """ - import salt.modules.openstack_config as openstack_config from salt.exceptions import CommandExecutionError from tests.support.mixins import LoaderModuleMockMixin diff --git a/tests/unit/modules/test_opkg.py b/tests/unit/modules/test_opkg.py index d1df495db4b..6242f5fa31a 100644 --- a/tests/unit/modules/test_opkg.py +++ b/tests/unit/modules/test_opkg.py @@ -51,9 +51,9 @@ class OpkgTestCase(TestCase, LoaderModuleMockMixin): @classmethod def tearDownClass(cls): - cls.opkg_vim_info = ( - cls.opkg_vim_files - ) = cls.installed = cls.removed = cls.packages = None + cls.opkg_vim_info = cls.opkg_vim_files = cls.installed = cls.removed = ( + cls.packages + ) = None def setup_loader_modules(self): # pylint: disable=no-self-use """ diff --git a/tests/unit/modules/test_parted_partition.py b/tests/unit/modules/test_parted_partition.py index b164569c0c4..72fdded4af0 100644 --- a/tests/unit/modules/test_parted_partition.py +++ b/tests/unit/modules/test_parted_partition.py @@ -6,7 +6,6 @@ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ - import salt.modules.parted_partition as parted from salt.exceptions import CommandExecutionError from tests.support.mixins import LoaderModuleMockMixin diff --git a/tests/unit/modules/test_rh_ip.py b/tests/unit/modules/test_rh_ip.py index d061978ae35..b868144fb91 100644 --- a/tests/unit/modules/test_rh_ip.py +++ b/tests/unit/modules/test_rh_ip.py @@ -509,7 +509,7 @@ class RhipTestCase(TestCase, LoaderModuleMockMixin): expected = [ "downdelay=200", "miimon=100", - "mode={}".format(mode_num), + f"mode={mode_num}", "use_carrier=0", ] assert bonding_opts == expected, bonding_opts @@ -523,7 +523,7 @@ class RhipTestCase(TestCase, LoaderModuleMockMixin): "arp_ip_target=1.2.3.4,5.6.7.8", "downdelay=200", "miimon=100", - "mode={}".format(mode_num), + f"mode={mode_num}", "use_carrier=0", ] assert bonding_opts == expected, bonding_opts @@ -535,7 +535,7 @@ class RhipTestCase(TestCase, LoaderModuleMockMixin): expected = [ "arp_interval=300", "arp_ip_target=1.2.3.4,5.6.7.8", - "mode={}".format(mode_num), + f"mode={mode_num}", ] assert bonding_opts == expected, bonding_opts @@ -718,7 +718,7 @@ class RhipTestCase(TestCase, LoaderModuleMockMixin): "miimon=100", "mode=4", "use_carrier=0", - "xmit_hash_policy={}".format(hash_alg), + f"xmit_hash_policy={hash_alg}", ] assert bonding_opts == expected, bonding_opts @@ -739,7 +739,7 @@ class RhipTestCase(TestCase, LoaderModuleMockMixin): "miimon=100", "mode=4", "use_carrier=0", - "xmit_hash_policy={}".format(hash_alg), + f"xmit_hash_policy={hash_alg}", ] assert bonding_opts == expected, bonding_opts @@ -786,14 +786,12 @@ class RhipTestCase(TestCase, LoaderModuleMockMixin): raise else: expected = [ - "ad_select={}".format(ad_select), + f"ad_select={ad_select}", "downdelay=200", "lacp_rate={}".format( "1" if lacp_rate == "fast" - else "0" - if lacp_rate == "slow" - else lacp_rate + else "0" if lacp_rate == "slow" else lacp_rate ), "miimon=100", "mode=4", diff --git a/tests/unit/modules/test_snapper.py b/tests/unit/modules/test_snapper.py index 0729ad9a1ef..2ca4250e642 100644 --- a/tests/unit/modules/test_snapper.py +++ b/tests/unit/modules/test_snapper.py @@ -4,6 +4,7 @@ Unit tests for the Snapper module :codeauthor: Duncan Mac-Vicar P. :codeauthor: Pablo Suárez Hernández """ + import pytest import salt.modules.snapper as snapper diff --git a/tests/unit/modules/test_sqlite3.py b/tests/unit/modules/test_sqlite3.py index 1b534e7d963..8b69855dcce 100644 --- a/tests/unit/modules/test_sqlite3.py +++ b/tests/unit/modules/test_sqlite3.py @@ -2,7 +2,6 @@ :codeauthor: Jayesh Kariya """ - import salt.modules.sqlite3 as sqlite3 from tests.support.mixins import LoaderModuleMockMixin from tests.support.unit import TestCase diff --git a/tests/unit/modules/test_ssh.py b/tests/unit/modules/test_ssh.py index 8ffbed434d5..10822f837f5 100644 --- a/tests/unit/modules/test_ssh.py +++ b/tests/unit/modules/test_ssh.py @@ -116,7 +116,7 @@ class SSHAuthKeyTestCase(TestCase, LoaderModuleMockMixin): _fh.write(comment_line) # Add empty line for #41335 _fh.write(empty_line) - _fh.write("{} {} {} {}".format(options, enc, key, email)) + _fh.write(f"{options} {enc} {key} {email}") with patch.dict(ssh.__salt__, {"user.info": MagicMock(return_value={})}): with patch( @@ -138,7 +138,7 @@ class SSHAuthKeyTestCase(TestCase, LoaderModuleMockMixin): key = "abcxyz" with salt.utils.files.fopen(temp_file.name, "a") as _fh: - _fh.write(salt.utils.stringutils.to_str("{} {}".format(enc, key))) + _fh.write(salt.utils.stringutils.to_str(f"{enc} {key}")) # Replace the simple key from before with the more complicated options + new email # Option example is taken from Pull Request #39855 @@ -181,7 +181,7 @@ class SSHAuthKeyTestCase(TestCase, LoaderModuleMockMixin): key = "abcxyz" with salt.utils.files.fopen(temp_file.name, "a") as _fh: - _fh.write(salt.utils.stringutils.to_str("{} {}".format(enc, key))) + _fh.write(salt.utils.stringutils.to_str(f"{enc} {key}")) # Replace the simple key from before with the more complicated options + new email # Option example is taken from Pull Request #39855 @@ -209,7 +209,7 @@ class SSHAuthKeyTestCase(TestCase, LoaderModuleMockMixin): with salt.utils.files.fopen(temp_file.name) as _fh: file_txt = salt.utils.stringutils.to_unicode(_fh.read()) # the initial key must have been replaced and no longer present - self.assertNotIn("\n{} {}\n".format(enc, key), file_txt) + self.assertNotIn(f"\n{enc} {key}\n", file_txt) # the new key must be present self.assertIn( "{} {} {} {}".format(",".join(options), enc, key, email), file_txt @@ -231,11 +231,7 @@ class SSHAuthKeyTestCase(TestCase, LoaderModuleMockMixin): email = "foo@example.com" with salt.utils.files.fopen(temp_file.name, "w") as _fh: - _fh.write( - salt.utils.stringutils.to_str( - "{} {} {} {}".format(options, enc, key, email) - ) - ) + _fh.write(salt.utils.stringutils.to_str(f"{options} {enc} {key} {email}")) with patch.dict(ssh.__salt__, {"user.info": MagicMock(return_value={})}): with patch( @@ -251,7 +247,7 @@ class SSHAuthKeyTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual( ssh.rm_auth_key( "foo", - "{}".format(key), + f"{key}", config=temp_file.name, ), "Key removed", diff --git a/tests/unit/modules/test_supervisord.py b/tests/unit/modules/test_supervisord.py index 1d4ce112f27..8bcae14288e 100644 --- a/tests/unit/modules/test_supervisord.py +++ b/tests/unit/modules/test_supervisord.py @@ -2,7 +2,6 @@ :codeauthor: Jayesh Kariya """ - import salt.modules.supervisord as supervisord from salt.exceptions import CommandExecutionError from tests.support.mixins import LoaderModuleMockMixin diff --git a/tests/unit/modules/test_sysmod.py b/tests/unit/modules/test_sysmod.py index 00185a90099..bd0d7073e8c 100644 --- a/tests/unit/modules/test_sysmod.py +++ b/tests/unit/modules/test_sysmod.py @@ -2,7 +2,6 @@ :codeauthor: Jayesh Kariya """ - import salt.modules.sysmod as sysmod from tests.support.mixins import LoaderModuleMockMixin from tests.support.mock import patch @@ -108,18 +107,18 @@ class SysmodTestCase(TestCase, LoaderModuleMockMixin): cls.salt_dunder = {} for func in cls._functions: - docstring = "docstring for {}".format(func) + docstring = f"docstring for {func}" cls.salt_dunder[func] = MockDocstringable(docstring) cls._docstrings[func] = docstring module = func.split(".")[0] cls._statedocstrings[func] = docstring - cls._statedocstrings[module] = "docstring for {}".format(module) + cls._statedocstrings[module] = f"docstring for {module}" cls._modules.add(func.split(".")[0]) - docstring = "docstring for {}".format(func) + docstring = f"docstring for {func}" mock = MockDocstringable(docstring) mock.set_module_docstring("docstring for {}".format(func.split(".")[0])) Mockstate.State.states[func] = mock diff --git a/tests/unit/modules/test_twilio_notify.py b/tests/unit/modules/test_twilio_notify.py index 682cb7f7711..4785e4a974d 100644 --- a/tests/unit/modules/test_twilio_notify.py +++ b/tests/unit/modules/test_twilio_notify.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import pytest import salt.modules.twilio_notify as twilio_notify diff --git a/tests/unit/modules/test_useradd.py b/tests/unit/modules/test_useradd.py index bc7903dd5bb..533e3644b3e 100644 --- a/tests/unit/modules/test_useradd.py +++ b/tests/unit/modules/test_useradd.py @@ -1,6 +1,7 @@ """ :codeauthor: Jayesh Kariya """ + import pytest import salt.modules.useradd as useradd diff --git a/tests/unit/modules/test_virt.py b/tests/unit/modules/test_virt.py index 0342152a72d..d595b67f6c5 100644 --- a/tests/unit/modules/test_virt.py +++ b/tests/unit/modules/test_virt.py @@ -1831,18 +1831,22 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): ret = virt._diff_disk_lists(old_disks, new_disks) self.assertEqual( [ - disk.find("source").get("file") - if disk.find("source") is not None - else None + ( + disk.find("source").get("file") + if disk.find("source") is not None + else None + ) for disk in ret["unchanged"] ], [], ) self.assertEqual( [ - disk.find("source").get("file") - if disk.find("source") is not None - else None + ( + disk.find("source").get("file") + if disk.find("source") is not None + else None + ) for disk in ret["new"] ], ["/path/to/img3.qcow2", "/path/to/img0.qcow2", "/path/to/img4.qcow2", None], @@ -1853,9 +1857,11 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): ) self.assertEqual( [ - disk.find("source").get("file") - if disk.find("source") is not None - else None + ( + disk.find("source").get("file") + if disk.find("source") is not None + else None + ) for disk in ret["sorted"] ], ["/path/to/img3.qcow2", "/path/to/img0.qcow2", "/path/to/img4.qcow2", None], @@ -1863,9 +1869,11 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): self.assertEqual(ret["new"][1].find("target").get("bus"), "virtio") self.assertEqual( [ - disk.find("source").get("file") - if disk.find("source") is not None - else None + ( + disk.find("source").get("file") + if disk.find("source") is not None + else None + ) for disk in ret["deleted"] ], [ @@ -3501,9 +3509,7 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): }, virt.update("vm_with_memtune_param", mem=memtune_new_val), ) - self.assertEqual( - domain_mock.setMemoryFlags.call_args[0][0], int(2.5 * 1024**2) - ) + self.assertEqual(domain_mock.setMemoryFlags.call_args[0][0], int(2.5 * 1024**2)) setxml = ET.fromstring(define_mock.call_args[0][0]) self.assertEqual( @@ -3569,9 +3575,7 @@ class VirtTestCase(TestCase, LoaderModuleMockMixin): }, virt.update("vm_with_memtune_param", mem=max_swap_none), ) - self.assertEqual( - domain_mock.setMemoryFlags.call_args[0][0], int(2.5 * 1024**2) - ) + self.assertEqual(domain_mock.setMemoryFlags.call_args[0][0], int(2.5 * 1024**2)) setxml = ET.fromstring(define_mock.call_args[0][0]) self.assertEqual( diff --git a/tests/unit/modules/test_virtualenv_mod.py b/tests/unit/modules/test_virtualenv_mod.py index 468ce61f235..552a93264b2 100644 --- a/tests/unit/modules/test_virtualenv_mod.py +++ b/tests/unit/modules/test_virtualenv_mod.py @@ -278,7 +278,7 @@ class VirtualenvTestCase(TestCase, LoaderModuleMockMixin): python=sys.executable, ) mock.assert_called_once_with( - ["virtualenv", "--python={}".format(sys.executable), "/tmp/foo"], + ["virtualenv", f"--python={sys.executable}", "/tmp/foo"], runas=None, python_shell=False, ) diff --git a/tests/unit/modules/test_vsphere.py b/tests/unit/modules/test_vsphere.py index 7dcb13e4d30..da64fe52239 100644 --- a/tests/unit/modules/test_vsphere.py +++ b/tests/unit/modules/test_vsphere.py @@ -4,6 +4,7 @@ Tests for functions in salt.modules.vsphere """ + import pytest import salt.modules.vsphere as vsphere @@ -809,7 +810,7 @@ class VsphereTestCase(TestCase, LoaderModuleMockMixin): config = "foo" ret = { "success": False, - "message": "'{}' is not a valid config variable.".format(config), + "message": f"'{config}' is not a valid config variable.", } self.assertEqual( ret, vsphere._set_syslog_config_helper(HOST, USER, PASSWORD, config, "bar") @@ -3509,7 +3510,7 @@ class TestCertificateVerify(TestCase, LoaderModuleMockMixin): USER, PASSWORD, certificate_verify=certificate_verify_value, - **kwargs + **kwargs, ) http_query_mock.assert_called_once_with( "https://1.2.3.4:443/host/ssh_root_authorized_keys", @@ -3519,7 +3520,7 @@ class TestCertificateVerify(TestCase, LoaderModuleMockMixin): text=True, username="root", verify_ssl=certificate_verify_value, - **expected_kwargs + **expected_kwargs, ) def test_get_ssh_key(self): diff --git a/tests/unit/modules/test_win_system.py b/tests/unit/modules/test_win_system.py index 9a217c93d0e..ea73661dc39 100644 --- a/tests/unit/modules/test_win_system.py +++ b/tests/unit/modules/test_win_system.py @@ -633,6 +633,7 @@ class WinSystemTestCase(TestCase, LoaderModuleMockMixin): the WMI Class Win32_Processor. Older versions of Windows are missing this property """ + # Create a mock processor class that does not have the # NumberOfCoresEnabled property class MockWMIProcessor: diff --git a/tests/unit/modules/test_zypperpkg.py b/tests/unit/modules/test_zypperpkg.py index c9c0685d4b9..55f8c85f71c 100644 --- a/tests/unit/modules/test_zypperpkg.py +++ b/tests/unit/modules/test_zypperpkg.py @@ -2,7 +2,6 @@ :codeauthor: Bo Maryniuk """ - import configparser import errno import io diff --git a/tests/unit/states/test_boto_vpc.py b/tests/unit/states/test_boto_vpc.py index 95febd66834..32305d1a589 100644 --- a/tests/unit/states/test_boto_vpc.py +++ b/tests/unit/states/test_boto_vpc.py @@ -267,7 +267,7 @@ class BotoVpcResourceTestCaseMixin(BotoVpcTestCaseMixin): vpc = self._create_vpc(name="test") with patch.dict(botomod.__salt__, self.funcs): resource_present_result = self.salt_states[ - "boto_vpc.{}_present".format(self.resource_type) + f"boto_vpc.{self.resource_type}_present" ](name="test", vpc_name="test", **self.extra_kwargs) self.assertTrue(resource_present_result["result"]) @@ -288,7 +288,7 @@ class BotoVpcResourceTestCaseMixin(BotoVpcTestCaseMixin): self._create_resource(vpc_id=vpc.id, name="test") with patch.dict(botomod.__salt__, self.funcs): resource_present_result = self.salt_states[ - "boto_vpc.{}_present".format(self.resource_type) + f"boto_vpc.{self.resource_type}_present" ](name="test", vpc_name="test", **self.extra_kwargs) self.assertTrue(resource_present_result["result"]) self.assertEqual(resource_present_result["changes"], {}) @@ -300,11 +300,11 @@ class BotoVpcResourceTestCaseMixin(BotoVpcTestCaseMixin): def test_present_with_failure(self): vpc = self._create_vpc(name="test") with patch( - "moto.ec2.models.{}".format(self.backend_create), + f"moto.ec2.models.{self.backend_create}", side_effect=BotoServerError(400, "Mocked error"), ): resource_present_result = self.salt_states[ - "boto_vpc.{}_present".format(self.resource_type) + f"boto_vpc.{self.resource_type}_present" ](name="test", vpc_name="test", **self.extra_kwargs) self.assertFalse(resource_present_result["result"]) @@ -322,7 +322,7 @@ class BotoVpcResourceTestCaseMixin(BotoVpcTestCaseMixin): """ with patch.dict(botomod.__salt__, self.funcs): resource_absent_result = self.salt_states[ - "boto_vpc.{}_absent".format(self.resource_type) + f"boto_vpc.{self.resource_type}_absent" ]("test") self.assertTrue(resource_absent_result["result"]) self.assertEqual(resource_absent_result["changes"], {}) @@ -339,7 +339,7 @@ class BotoVpcResourceTestCaseMixin(BotoVpcTestCaseMixin): with patch.dict(botomod.__salt__, self.funcs): resource_absent_result = self.salt_states[ - "boto_vpc.{}_absent".format(self.resource_type) + f"boto_vpc.{self.resource_type}_absent" ]("test") self.assertTrue(resource_absent_result["result"]) self.assertEqual( @@ -359,11 +359,11 @@ class BotoVpcResourceTestCaseMixin(BotoVpcTestCaseMixin): self._create_resource(vpc_id=vpc.id, name="test") with patch( - "moto.ec2.models.{}".format(self.backend_delete), + f"moto.ec2.models.{self.backend_delete}", side_effect=BotoServerError(400, "Mocked error"), ): resource_absent_result = self.salt_states[ - "boto_vpc.{}_absent".format(self.resource_type) + f"boto_vpc.{self.resource_type}_absent" ]("test") self.assertFalse(resource_absent_result["result"]) self.assertTrue("Mocked error" in resource_absent_result["comment"]) diff --git a/tests/unit/states/test_group.py b/tests/unit/states/test_group.py index b9bf3434e72..eaa1c61cf8f 100644 --- a/tests/unit/states/test_group.py +++ b/tests/unit/states/test_group.py @@ -2,7 +2,6 @@ :codeauthor: Rahul Handay """ - import salt.states.group as group from salt.utils.odict import OrderedDict from tests.support.mixins import LoaderModuleMockMixin diff --git a/tests/unit/states/test_ipset.py b/tests/unit/states/test_ipset.py index f253d52be1d..5c2993e6dfb 100644 --- a/tests/unit/states/test_ipset.py +++ b/tests/unit/states/test_ipset.py @@ -53,7 +53,7 @@ class IpsetSetPresentTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": True, - "comment": "ipset set {} already exists for ipv4".format(self.fake_name), + "comment": f"ipset set {self.fake_name} already exists for ipv4", "changes": {}, } self._runner(ret, check_set=True, new_set_assertion=False) @@ -66,7 +66,7 @@ class IpsetSetPresentTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": None, - "comment": "ipset set {} would be added for ipv4".format(self.fake_name), + "comment": f"ipset set {self.fake_name} would be added for ipv4", "changes": {}, } self._runner(ret, test=True, new_set_assertion=False) @@ -86,7 +86,7 @@ class IpsetSetPresentTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": False, - "comment": "Failed to create set {} for ipv4: ".format(self.fake_name), + "comment": f"Failed to create set {self.fake_name} for ipv4: ", "changes": {}, } self._runner(ret, new_set="") @@ -142,7 +142,7 @@ class IpsetSetAbsentTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": True, - "comment": "ipset set {} for ipv4 is already absent".format(self.fake_name), + "comment": f"ipset set {self.fake_name} for ipv4 is already absent", "changes": {}, } self._runner(ret, check_set=False, delete_set=None) @@ -151,7 +151,7 @@ class IpsetSetAbsentTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": None, - "comment": "ipset set {} for ipv4 would be removed".format(self.fake_name), + "comment": f"ipset set {self.fake_name} for ipv4 would be removed", "changes": {}, } self._runner(ret, test=True, delete_set=None) @@ -160,7 +160,7 @@ class IpsetSetAbsentTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": False, - "comment": "Failed to delete set {} for ipv4: ".format(self.fake_name), + "comment": f"Failed to delete set {self.fake_name} for ipv4: ", "changes": {}, } self._runner(ret, flush_assertion=True, delete_set_assertion=True) @@ -420,7 +420,7 @@ class IpsetFlushTestCase(TestCase, LoaderModuleMockMixin): ret = { "name": self.fake_name, "result": False, - "comment": "ipset set {} does not exist for ipv4".format(self.fake_name), + "comment": f"ipset set {self.fake_name} does not exist for ipv4", "changes": {}, } self._runner(ret, check_set=False, flush_assertion=False) diff --git a/tests/unit/states/test_module.py b/tests/unit/states/test_module.py index 4853c24ca07..4fd0dcad0bc 100644 --- a/tests/unit/states/test_module.py +++ b/tests/unit/states/test_module.py @@ -2,7 +2,6 @@ :codeauthor: Nicole Thomas (nicole@saltstack.com) """ - import logging from inspect import FullArgSpec diff --git a/tests/unit/states/test_syslog_ng.py b/tests/unit/states/test_syslog_ng.py index f367df58b17..132d95ad903 100644 --- a/tests/unit/states/test_syslog_ng.py +++ b/tests/unit/states/test_syslog_ng.py @@ -2,7 +2,6 @@ Test module for syslog_ng state """ - import os import re import tempfile diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index 5cc58c273d0..c5196372b32 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -1,6 +1,7 @@ """ Unit tests for salt.config """ + import logging import os import textwrap @@ -52,7 +53,7 @@ MOCK_ETC_HOSTS = textwrap.dedent( hostname=MOCK_HOSTNAME ) ) -MOCK_ETC_HOSTNAME = "{}\n".format(MOCK_HOSTNAME) +MOCK_ETC_HOSTNAME = f"{MOCK_HOSTNAME}\n" PATH = "path/to/some/cloud/conf/file" DEFAULT = {"default_include": PATH} @@ -86,7 +87,7 @@ class SampleConfTest(DefaultConfigsBase, TestCase): self.assertEqual( ret, {}, - "Sample config file '{}' must be commented out.".format(master_config), + f"Sample config file '{master_config}' must be commented out.", ) def test_conf_minion_sample_is_commented(self): @@ -99,7 +100,7 @@ class SampleConfTest(DefaultConfigsBase, TestCase): self.assertEqual( ret, {}, - "Sample config file '{}' must be commented out.".format(minion_config), + f"Sample config file '{minion_config}' must be commented out.", ) def test_conf_cloud_sample_is_commented(self): @@ -112,7 +113,7 @@ class SampleConfTest(DefaultConfigsBase, TestCase): self.assertEqual( ret, {}, - "Sample config file '{}' must be commented out.".format(cloud_config), + f"Sample config file '{cloud_config}' must be commented out.", ) def test_conf_cloud_profiles_sample_is_commented(self): @@ -155,7 +156,7 @@ class SampleConfTest(DefaultConfigsBase, TestCase): self.assertEqual( ret, {}, - "Sample config file '{}' must be commented out.".format(proxy_config), + f"Sample config file '{proxy_config}' must be commented out.", ) def test_conf_roster_sample_is_commented(self): @@ -168,7 +169,7 @@ class SampleConfTest(DefaultConfigsBase, TestCase): self.assertEqual( ret, {}, - "Sample config file '{}' must be commented out.".format(roster_config), + f"Sample config file '{roster_config}' must be commented out.", ) def test_conf_cloud_profiles_d_files_are_commented(self): @@ -179,9 +180,7 @@ class SampleConfTest(DefaultConfigsBase, TestCase): """ cloud_sample_dir = SAMPLE_CONF_DIR + "cloud.profiles.d/" if not os.path.exists(cloud_sample_dir): - self.skipTest( - "Sample config directory '{}' is missing.".format(cloud_sample_dir) - ) + self.skipTest(f"Sample config directory '{cloud_sample_dir}' is missing.") cloud_sample_files = os.listdir(cloud_sample_dir) for conf_file in cloud_sample_files: profile_conf = cloud_sample_dir + conf_file @@ -189,7 +188,7 @@ class SampleConfTest(DefaultConfigsBase, TestCase): self.assertEqual( ret, {}, - "Sample config file '{}' must be commented out.".format(conf_file), + f"Sample config file '{conf_file}' must be commented out.", ) def test_conf_cloud_providers_d_files_are_commented(self): @@ -200,9 +199,7 @@ class SampleConfTest(DefaultConfigsBase, TestCase): """ cloud_sample_dir = SAMPLE_CONF_DIR + "cloud.providers.d/" if not os.path.exists(cloud_sample_dir): - self.skipTest( - "Sample config directory '{}' is missing.".format(cloud_sample_dir) - ) + self.skipTest(f"Sample config directory '{cloud_sample_dir}' is missing.") cloud_sample_files = os.listdir(cloud_sample_dir) for conf_file in cloud_sample_files: provider_conf = cloud_sample_dir + conf_file @@ -210,7 +207,7 @@ class SampleConfTest(DefaultConfigsBase, TestCase): self.assertEqual( ret, {}, - "Sample config file '{}' must be commented out.".format(conf_file), + f"Sample config file '{conf_file}' must be commented out.", ) def test_conf_cloud_maps_d_files_are_commented(self): @@ -221,9 +218,7 @@ class SampleConfTest(DefaultConfigsBase, TestCase): """ cloud_sample_dir = SAMPLE_CONF_DIR + "cloud.maps.d/" if not os.path.exists(cloud_sample_dir): - self.skipTest( - "Sample config directory '{}' is missing.".format(cloud_sample_dir) - ) + self.skipTest(f"Sample config directory '{cloud_sample_dir}' is missing.") cloud_sample_files = os.listdir(cloud_sample_dir) for conf_file in cloud_sample_files: map_conf = cloud_sample_dir + conf_file @@ -231,7 +226,7 @@ class SampleConfTest(DefaultConfigsBase, TestCase): self.assertEqual( ret, {}, - "Sample config file '{}' must be commented out.".format(conf_file), + f"Sample config file '{conf_file}' must be commented out.", ) @@ -239,14 +234,14 @@ def _unhandled_mock_read(filename): """ Raise an error because we should not be calling salt.utils.files.fopen() """ - raise CommandExecutionError("Unhandled mock read for {}".format(filename)) + raise CommandExecutionError(f"Unhandled mock read for {filename}") def _salt_configuration_error(filename): """ Raise an error to indicate error in the Salt configuration file """ - raise SaltConfigurationError("Configuration error in {}".format(filename)) + raise SaltConfigurationError(f"Configuration error in {filename}") class ConfigTestCase(TestCase, AdaptedConfigurationTestCaseMixin): @@ -290,7 +285,7 @@ class ConfigTestCase(TestCase, AdaptedConfigurationTestCaseMixin): os.makedirs(root_dir) fpath = os.path.join(root_dir, "config") with salt.utils.files.fopen(fpath, "w") as fp_: - fp_.write("root_dir: {}\nlog_file: {}\n".format(root_dir, fpath)) + fp_.write(f"root_dir: {root_dir}\nlog_file: {fpath}\n") config = salt.config.master_config(fpath) self.assertEqual(config["log_file"], fpath) @@ -300,7 +295,7 @@ class ConfigTestCase(TestCase, AdaptedConfigurationTestCaseMixin): os.makedirs(root_dir) fpath = os.path.join(root_dir, "config") with salt.utils.files.fopen(fpath, "w") as fp_: - fp_.write("root_dir: {}\nlog_file: {}\n".format(root_dir, fpath)) + fp_.write(f"root_dir: {root_dir}\nlog_file: {fpath}\n") config = salt.config.master_config(fpath) self.assertEqual(config["log_file"], fpath) @@ -314,17 +309,17 @@ class ConfigTestCase(TestCase, AdaptedConfigurationTestCaseMixin): env_fpath = os.path.join(env_root_dir, "config-env") with salt.utils.files.fopen(env_fpath, "w") as fp_: - fp_.write("root_dir: {}\nlog_file: {}\n".format(env_root_dir, env_fpath)) + fp_.write(f"root_dir: {env_root_dir}\nlog_file: {env_fpath}\n") with patched_environ(SALT_MASTER_CONFIG=env_fpath): # Should load from env variable, not the default configuration file. - config = salt.config.master_config("{}/master".format(CONFIG_DIR)) + config = salt.config.master_config(f"{CONFIG_DIR}/master") self.assertEqual(config["log_file"], env_fpath) root_dir = os.path.join(tempdir, "foo", "bar") os.makedirs(root_dir) fpath = os.path.join(root_dir, "config") with salt.utils.files.fopen(fpath, "w") as fp_: - fp_.write("root_dir: {}\nlog_file: {}\n".format(root_dir, fpath)) + fp_.write(f"root_dir: {root_dir}\nlog_file: {fpath}\n") # Let's set the environment variable, yet, since the configuration # file path is not the default one, i.e., the user has passed an # alternative configuration file form the CLI parser, the @@ -343,18 +338,18 @@ class ConfigTestCase(TestCase, AdaptedConfigurationTestCaseMixin): env_fpath = os.path.join(env_root_dir, "config-env") with salt.utils.files.fopen(env_fpath, "w") as fp_: - fp_.write("root_dir: {}\nlog_file: {}\n".format(env_root_dir, env_fpath)) + fp_.write(f"root_dir: {env_root_dir}\nlog_file: {env_fpath}\n") with patched_environ(SALT_MINION_CONFIG=env_fpath): # Should load from env variable, not the default configuration file - config = salt.config.minion_config("{}/minion".format(CONFIG_DIR)) + config = salt.config.minion_config(f"{CONFIG_DIR}/minion") self.assertEqual(config["log_file"], env_fpath) root_dir = os.path.join(tempdir, "foo", "bar") os.makedirs(root_dir) fpath = os.path.join(root_dir, "config") with salt.utils.files.fopen(fpath, "w") as fp_: - fp_.write("root_dir: {}\nlog_file: {}\n".format(root_dir, fpath)) + fp_.write(f"root_dir: {root_dir}\nlog_file: {fpath}\n") # Let's set the environment variable, yet, since the configuration # file path is not the default one, i.e., the user has passed an # alternative configuration file form the CLI parser, the @@ -386,7 +381,7 @@ class ConfigTestCase(TestCase, AdaptedConfigurationTestCaseMixin): # Now the client configuration file env_fpath = os.path.join(env_root_dir, "config-env") with salt.utils.files.fopen(env_fpath, "w") as fp_: - fp_.write("root_dir: {}\nlog_file: {}\n".format(env_root_dir, env_fpath)) + fp_.write(f"root_dir: {env_root_dir}\nlog_file: {env_fpath}\n") with patched_environ( SALT_MASTER_CONFIG=master_config, SALT_CLIENT_CONFIG=env_fpath @@ -400,7 +395,7 @@ class ConfigTestCase(TestCase, AdaptedConfigurationTestCaseMixin): os.makedirs(root_dir) fpath = os.path.join(root_dir, "config") with salt.utils.files.fopen(fpath, "w") as fp_: - fp_.write("root_dir: {}\nlog_file: {}\n".format(root_dir, fpath)) + fp_.write(f"root_dir: {root_dir}\nlog_file: {fpath}\n") # Let's set the environment variable, yet, since the configuration # file path is not the default one, i.e., the user has passed an # alternative configuration file form the CLI parser, the @@ -1675,7 +1670,7 @@ class ConfigTestCase(TestCase, AdaptedConfigurationTestCaseMixin): env_fpath = os.path.join(env_root_dir, "config-env") with salt.utils.files.fopen(env_fpath, "w") as fp_: - fp_.write("root_dir: {}\nlog_file: {}\n".format(env_root_dir, env_fpath)) + fp_.write(f"root_dir: {env_root_dir}\nlog_file: {env_fpath}\n") with patched_environ(SALT_CLOUD_CONFIG=env_fpath): # Should load from env variable, not the default configuration file @@ -1686,7 +1681,7 @@ class ConfigTestCase(TestCase, AdaptedConfigurationTestCaseMixin): os.makedirs(root_dir) fpath = os.path.join(root_dir, "config") with salt.utils.files.fopen(fpath, "w") as fp_: - fp_.write("root_dir: {}\nlog_file: {}\n".format(root_dir, fpath)) + fp_.write(f"root_dir: {root_dir}\nlog_file: {fpath}\n") # Let's set the environment variable, yet, since the configuration # file path is not the default one, i.e., the user has passed an # alternative configuration file form the CLI parser, the @@ -1725,9 +1720,7 @@ class ConfigTestCase(TestCase, AdaptedConfigurationTestCaseMixin): """ config_file = self.get_config_file_path("cloud") log.debug("Cloud config file path: %s", config_file) - self.assertTrue( - os.path.exists(config_file), "{} does not exist".format(config_file) - ) + self.assertTrue(os.path.exists(config_file), f"{config_file} does not exist") config = salt.config.cloud_config(config_file) self.assertIn("providers", config) self.assertIn("ec2-config", config["providers"]) @@ -1900,7 +1893,7 @@ class ConfigTestCase(TestCase, AdaptedConfigurationTestCaseMixin): overrides = {} with salt.utils.files.fopen(fpath, "w") as wfh: - wfh.write("root_dir: /\nkey_logfile: key\ncachedir: {}".format(cachedir)) + wfh.write(f"root_dir: /\nkey_logfile: key\ncachedir: {cachedir}") config = salt.config.mminion_config(fpath, overrides) self.assertEqual(config["__role"], "master") self.assertEqual(config["cachedir"], cachedir) @@ -1944,7 +1937,7 @@ class APIConfigTestCase(DefaultConfigsBase, TestCase): RUNTIME_VARS.TMP_ROOT_DIR if RUNTIME_VARS.TMP_ROOT_DIR != "/" else "" ) if salt.utils.platform.is_windows(): - expected = "{}\\var\\log\\salt\\api".format(RUNTIME_VARS.TMP_ROOT_DIR) + expected = f"{RUNTIME_VARS.TMP_ROOT_DIR}\\var\\log\\salt\\api" ret = salt.config.api_config("/some/fake/path") self.assertEqual(ret["log_file"], expected) diff --git a/tests/unit/test_mock.py b/tests/unit/test_mock.py index a6c100dc41b..39ee7e65fc0 100644 --- a/tests/unit/test_mock.py +++ b/tests/unit/test_mock.py @@ -142,20 +142,20 @@ class MockOpenMixin: with salt.utils.files.fopen("foo.txt", mode) as self.fh: index = 0 for line in self.fh: - assert line == questions[index], "Line {}: {}".format(index, line) + assert line == questions[index], f"Line {index}: {line}" index += 1 if multifile: with salt.utils.files.fopen("bar.txt", mode) as self.fh2: index = 0 for line in self.fh2: - assert line == answers[index], "Line {}: {}".format(index, line) + assert line == answers[index], f"Line {index}: {line}" index += 1 with salt.utils.files.fopen("baz.txt", mode) as self.fh3: index = 0 for line in self.fh3: - assert line == answers[index], "Line {}: {}".format(index, line) + assert line == answers[index], f"Line {index}: {line}" index += 1 try: diff --git a/tests/unit/test_zypp_plugins.py b/tests/unit/test_zypp_plugins.py index 7bd248ffbd9..d7bc58e5a2e 100644 --- a/tests/unit/test_zypp_plugins.py +++ b/tests/unit/test_zypp_plugins.py @@ -1,6 +1,7 @@ """ :codeauthor: Bo Maryniuk """ + import imp import os @@ -32,7 +33,7 @@ class ZyppPluginsTestCase(TestCase): @pytest.mark.skipif( not os.path.exists(ZYPPNOTIFY_FILE), - reason="Required file '{}' does not exist.".format(ZYPPNOTIFY_FILE), + reason=f"Required file '{ZYPPNOTIFY_FILE}' does not exist.", ) def test_drift_detector(self): """ diff --git a/tests/unit/transport/test_ipc.py b/tests/unit/transport/test_ipc.py index 639a9f606f6..eb469d6efb4 100644 --- a/tests/unit/transport/test_ipc.py +++ b/tests/unit/transport/test_ipc.py @@ -1,6 +1,7 @@ """ :codeauthor: Mike Place """ + import errno import logging import os diff --git a/tests/unit/transport/test_tcp.py b/tests/unit/transport/test_tcp.py index 2719ab02a0c..0d53af250a6 100644 --- a/tests/unit/transport/test_tcp.py +++ b/tests/unit/transport/test_tcp.py @@ -54,7 +54,7 @@ class AsyncPubServerTest(AsyncTestCase, AdaptedConfigurationTestCaseMixin): "tcp_master_pull_port": tcp_master_pull_port, "tcp_master_publish_pull": tcp_master_publish_pull, "tcp_master_workers": tcp_master_workers, - } + }, ) cls.minion_config = cls.get_temp_config( @@ -64,8 +64,8 @@ class AsyncPubServerTest(AsyncTestCase, AdaptedConfigurationTestCaseMixin): "master_ip": "127.0.0.1", "auth_timeout": 1, "master_port": ret_port, - "master_uri": "tcp://127.0.0.1:{}".format(ret_port), - } + "master_uri": f"tcp://127.0.0.1:{ret_port}", + }, ) cls.process_manager = salt.utils.process.ProcessManager( @@ -121,7 +121,7 @@ class AsyncPubServerTest(AsyncTestCase, AdaptedConfigurationTestCaseMixin): if self._start_handlers.get(k) != v: failures.append((k, v)) if failures: - raise Exception("FDs still attached to the IOLoop: {}".format(failures)) + raise Exception(f"FDs still attached to the IOLoop: {failures}") del self.channel del self._start_handlers diff --git a/tests/unit/utils/test_color.py b/tests/unit/utils/test_color.py index b80b2e4eaf1..741db780a23 100644 --- a/tests/unit/utils/test_color.py +++ b/tests/unit/utils/test_color.py @@ -2,7 +2,6 @@ Unit tests for salt.utils.color.py """ - import salt.utils.color from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_context.py b/tests/unit/utils/test_context.py index c8b0e5f44f1..eebbb17fcaa 100644 --- a/tests/unit/utils/test_context.py +++ b/tests/unit/utils/test_context.py @@ -3,7 +3,6 @@ tests.unit.context_test ~~~~~~~~~~~~~~~~~~~~~~~ """ - import salt.utils.json from salt.utils.context import NamespacedDictWrapper from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_decorators.py b/tests/unit/utils/test_decorators.py index 21992ccacc4..e3be199a028 100644 --- a/tests/unit/utils/test_decorators.py +++ b/tests/unit/utils/test_decorators.py @@ -3,7 +3,6 @@ unit.utils.decorators_test """ - import inspect import salt.utils.decorators as decorators diff --git a/tests/unit/utils/test_dns.py b/tests/unit/utils/test_dns.py index 75ceeef1359..c8e72ade46f 100644 --- a/tests/unit/utils/test_dns.py +++ b/tests/unit/utils/test_dns.py @@ -307,7 +307,7 @@ class DNSlookupsCase(TestCase): self.assertEqual( lookup_cb("mocksrvr.example.com", rec_t, secure=True), False, - msg="Insecure {} returns should not be returned".format(rec_t), + msg=f"Insecure {rec_t} returns should not be returned", ) for rec_t, tests in secure.items(): @@ -316,7 +316,7 @@ class DNSlookupsCase(TestCase): self.assertEqual( lookup_cb("mocksrvr.example.com", rec_t, secure=True), test_res, - msg="Error parsing DNSSEC'd {} returns".format(rec_t), + msg=f"Error parsing DNSSEC'd {rec_t} returns", ) @pytest.mark.skipif( @@ -366,7 +366,7 @@ class DNSlookupsCase(TestCase): @pytest.mark.skipif(not salt.utils.dns.HAS_DIG, reason="dig is not available") def test_dig_options(self): - cmd = "dig {} -v".format(salt.utils.dns.DIG_OPTIONS) + cmd = f"dig {salt.utils.dns.DIG_OPTIONS} -v" cmd = salt.modules.cmdmod.retcode( cmd, python_shell=False, output_loglevel="quiet" ) @@ -585,7 +585,7 @@ class DNSlookupsCase(TestCase): self.assertEqual( _lookup_gai("mockq", rec_t), test_res, - msg="Error parsing {} returns".format(rec_t), + msg=f"Error parsing {rec_t} returns", ) def test_host(self): diff --git a/tests/unit/utils/test_doc.py b/tests/unit/utils/test_doc.py index 62be2d15880..31088ac0831 100644 --- a/tests/unit/utils/test_doc.py +++ b/tests/unit/utils/test_doc.py @@ -2,7 +2,6 @@ Unit Tests for functions located in salt.utils.doc.py. """ - import salt.utils.doc from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_dockermod.py b/tests/unit/utils/test_dockermod.py index f93f2a80b8b..14f6dbb9a26 100644 --- a/tests/unit/utils/test_dockermod.py +++ b/tests/unit/utils/test_dockermod.py @@ -114,19 +114,19 @@ class Assert: salt.utils.dockermod.translate_input( self.translator, validate_ip_addrs=False, - **{item: [{"foo": "bar"}, {"baz": "qux"}]} + **{item: [{"foo": "bar"}, {"baz": "qux"}]}, ), testcase.apply_defaults({name: expected}), ) if alias is not None: # Test collision - test_kwargs = {name: vals, alias: "hello{}world".format(delimiter)} + test_kwargs = {name: vals, alias: f"hello{delimiter}world"} testcase.assertEqual( salt.utils.dockermod.translate_input( self.translator, validate_ip_addrs=False, ignore_collisions=True, - **test_kwargs + **test_kwargs, ), testcase.apply_defaults({name: expected}), ) @@ -137,7 +137,7 @@ class Assert: self.translator, validate_ip_addrs=False, ignore_collisions=False, - **test_kwargs + **test_kwargs, ) @@ -505,7 +505,7 @@ class assert_device_rates(Assert): "Path '{}' is not absolute".format(path.replace("\\", "\\\\")), ): salt.utils.dockermod.translate_input( - self.translator, **{item: "{}:1048576".format(path)} + self.translator, **{item: f"{path}:1048576"} ) if name.endswith("_bps"): @@ -661,7 +661,7 @@ class assert_subnet(Assert): ): log.debug("Verifying '%s' is not a valid subnet", val) with testcase.assertRaisesRegex( - CommandExecutionError, "'{}' is not a valid subnet".format(val) + CommandExecutionError, f"'{val}' is not a valid subnet" ): salt.utils.dockermod.translate_input( self.translator, validate_ip_addrs=True, **{item: val} @@ -1945,7 +1945,7 @@ class TranslateNetworkInputTestCase(TranslateBase): for val in self.ip_addrs[False]: with self.assertRaisesRegex( - CommandExecutionError, "'{}' is not a valid IP address".format(val) + CommandExecutionError, f"'{val}' is not a valid IP address" ): salt.utils.dockermod.translate_input( self.translator, @@ -1983,7 +1983,7 @@ class TranslateNetworkInputTestCase(TranslateBase): for val in self.ip_addrs[False]: addresses = {"foo.bar.tld": val} with self.assertRaisesRegex( - CommandExecutionError, "'{}' is not a valid IP address".format(val) + CommandExecutionError, f"'{val}' is not a valid IP address" ): salt.utils.dockermod.translate_input( self.translator, validate_ip_addrs=True, **{item: addresses} diff --git a/tests/unit/utils/test_environment.py b/tests/unit/utils/test_environment.py index d36de65a33d..54972226994 100644 --- a/tests/unit/utils/test_environment.py +++ b/tests/unit/utils/test_environment.py @@ -1,6 +1,7 @@ """ Test case for utils/__init__.py """ + import salt.utils.environment from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_extend.py b/tests/unit/utils/test_extend.py index d96f588decc..94a9a92ca51 100644 --- a/tests/unit/utils/test_extend.py +++ b/tests/unit/utils/test_extend.py @@ -4,6 +4,7 @@ Test the salt extend script, leave templates/test alone to keep this working! """ + import os import shutil from datetime import date diff --git a/tests/unit/utils/test_filebuffer.py b/tests/unit/utils/test_filebuffer.py index b88a2f4fc56..5f0fc0f3fdb 100644 --- a/tests/unit/utils/test_filebuffer.py +++ b/tests/unit/utils/test_filebuffer.py @@ -6,7 +6,6 @@ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ """ - import os from salt.utils.filebuffer import BufferedReader, InvalidFileMode diff --git a/tests/unit/utils/test_immutabletypes.py b/tests/unit/utils/test_immutabletypes.py index 745f9b933ed..28afcaac698 100644 --- a/tests/unit/utils/test_immutabletypes.py +++ b/tests/unit/utils/test_immutabletypes.py @@ -8,7 +8,6 @@ Test salt.utils.immutabletypes """ - import salt.utils.immutabletypes as immutabletypes from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_jid.py b/tests/unit/utils/test_jid.py index f6749228304..347e1411328 100644 --- a/tests/unit/utils/test_jid.py +++ b/tests/unit/utils/test_jid.py @@ -2,7 +2,6 @@ Tests for salt.utils.jid """ - import datetime import os @@ -35,9 +34,9 @@ class JidTestCase(TestCase): self.assertEqual(ret, "20021225120000000000") with patch("salt.utils.jid.LAST_JID_DATETIME", None): ret = salt.utils.jid.gen_jid({"unique_jid": True}) - self.assertEqual(ret, "20021225120000000000_{}".format(os.getpid())) + self.assertEqual(ret, f"20021225120000000000_{os.getpid()}") ret = salt.utils.jid.gen_jid({"unique_jid": True}) - self.assertEqual(ret, "20021225120000000001_{}".format(os.getpid())) + self.assertEqual(ret, f"20021225120000000001_{os.getpid()}") def test_deprecation_58225(self): # check that type error will be raised diff --git a/tests/unit/utils/test_job.py b/tests/unit/utils/test_job.py index 3d25719ade3..2e824e02351 100644 --- a/tests/unit/utils/test_job.py +++ b/tests/unit/utils/test_job.py @@ -2,7 +2,6 @@ unit tests for salt.utils.job """ - import salt.minion import salt.utils.job as job from tests.support.mock import patch diff --git a/tests/unit/utils/test_json.py b/tests/unit/utils/test_json.py index b123e7e8844..9b3a6c66362 100644 --- a/tests/unit/utils/test_json.py +++ b/tests/unit/utils/test_json.py @@ -105,7 +105,7 @@ class JSONTestCase(TestCase): self.assertDictEqual(ret, expected_ret) # Now pre-pend some garbage and re-test - garbage_prepend_json = "{}{}".format(LOREM_IPSUM, test_sample_json) + garbage_prepend_json = f"{LOREM_IPSUM}{test_sample_json}" ret = salt.utils.json.find_json(garbage_prepend_json) self.assertDictEqual(ret, expected_ret) diff --git a/tests/unit/utils/test_mac_utils.py b/tests/unit/utils/test_mac_utils.py index 9de2b56a844..609c939cd8d 100644 --- a/tests/unit/utils/test_mac_utils.py +++ b/tests/unit/utils/test_mac_utils.py @@ -1,6 +1,7 @@ """ mac_utils tests """ + import os import plistlib import subprocess diff --git a/tests/unit/utils/test_msgpack.py b/tests/unit/utils/test_msgpack.py index 9bcd9609e53..2d81c922f1b 100644 --- a/tests/unit/utils/test_msgpack.py +++ b/tests/unit/utils/test_msgpack.py @@ -1,6 +1,7 @@ """ Test the MessagePack utility """ + import inspect import os import pprint diff --git a/tests/unit/utils/test_pbm.py b/tests/unit/utils/test_pbm.py index b254ba8ada3..567e27e0c08 100644 --- a/tests/unit/utils/test_pbm.py +++ b/tests/unit/utils/test_pbm.py @@ -348,7 +348,7 @@ class GetStoragePoliciesTestCase(TestCase): resourceType=pbm.profile.ResourceTypeEnum.STORAGE ) ) - mock_obj.name = "fake_policy{}".format(i) + mock_obj.name = f"fake_policy{i}" self.mock_policies.append(mock_obj) patches = ( ( diff --git a/tests/unit/utils/test_proxy.py b/tests/unit/utils/test_proxy.py index 1c9a34ede31..a2ea8a6b660 100644 --- a/tests/unit/utils/test_proxy.py +++ b/tests/unit/utils/test_proxy.py @@ -3,7 +3,6 @@ :codeauthor: :email:`Gareth J. Greenaway ` """ - import salt.utils.proxy from tests.support.mock import patch from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_roster_matcher.py b/tests/unit/utils/test_roster_matcher.py index d49bc29f1de..b3ce554c837 100644 --- a/tests/unit/utils/test_roster_matcher.py +++ b/tests/unit/utils/test_roster_matcher.py @@ -1,6 +1,7 @@ """ Test generic roster matching utility. """ + import os import pytest diff --git a/tests/unit/utils/test_schema.py b/tests/unit/utils/test_schema.py index 113c6836e07..ebe3698978f 100644 --- a/tests/unit/utils/test_schema.py +++ b/tests/unit/utils/test_schema.py @@ -509,7 +509,7 @@ class ConfigTestCase(TestCase): Requirements.serialize(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") try: jsonschema.validate( @@ -517,7 +517,7 @@ class ConfigTestCase(TestCase): Requirements.serialize(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") try: jsonschema.validate( @@ -525,7 +525,7 @@ class ConfigTestCase(TestCase): Requirements.serialize(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate( @@ -583,7 +583,7 @@ class ConfigTestCase(TestCase): try: jsonschema.validate({"item": False}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate({"item": 1}, TestConf.serialize()) @@ -692,7 +692,7 @@ class ConfigTestCase(TestCase): try: jsonschema.validate({"item": "the item"}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") class TestConf(schema.Schema): item = schema.StringItem( @@ -702,7 +702,7 @@ class ConfigTestCase(TestCase): try: jsonschema.validate({"item": "the item"}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate({"item": 3}, TestConf.serialize()) @@ -729,7 +729,7 @@ class ConfigTestCase(TestCase): try: jsonschema.validate({"item": "foo"}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") class TestConf(schema.Schema): item = schema.StringItem( @@ -752,7 +752,7 @@ class ConfigTestCase(TestCase): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate( @@ -788,7 +788,7 @@ class ConfigTestCase(TestCase): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate( @@ -825,7 +825,7 @@ class ConfigTestCase(TestCase): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate( @@ -861,7 +861,7 @@ class ConfigTestCase(TestCase): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate( @@ -897,7 +897,7 @@ class ConfigTestCase(TestCase): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate( @@ -936,7 +936,7 @@ class ConfigTestCase(TestCase): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate( @@ -985,7 +985,7 @@ class ConfigTestCase(TestCase): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate( @@ -1100,7 +1100,7 @@ class ConfigTestCase(TestCase): try: jsonschema.validate({"item": 2}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate({"item": "3"}, TestConf.serialize()) @@ -1114,7 +1114,7 @@ class ConfigTestCase(TestCase): try: jsonschema.validate({"item": 4.4}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate({"item": 4}, TestConf.serialize()) @@ -1128,7 +1128,7 @@ class ConfigTestCase(TestCase): try: jsonschema.validate({"item": 3}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate({"item": 11}, TestConf.serialize()) @@ -1173,7 +1173,7 @@ class ConfigTestCase(TestCase): try: jsonschema.validate({"item": 4}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") class TestConf(schema.Schema): item = schema.NumberItem( @@ -1289,7 +1289,7 @@ class ConfigTestCase(TestCase): try: jsonschema.validate({"item": 2}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate({"item": 3.1}, TestConf.serialize()) @@ -1303,7 +1303,7 @@ class ConfigTestCase(TestCase): try: jsonschema.validate({"item": 4}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate({"item": 3}, TestConf.serialize()) @@ -1317,7 +1317,7 @@ class ConfigTestCase(TestCase): try: jsonschema.validate({"item": 3}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate({"item": 11}, TestConf.serialize()) @@ -1362,7 +1362,7 @@ class ConfigTestCase(TestCase): try: jsonschema.validate({"item": 4}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") class TestConf(schema.Schema): item = schema.IntegerItem( @@ -1497,7 +1497,7 @@ class ConfigTestCase(TestCase): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate( @@ -1523,7 +1523,7 @@ class ConfigTestCase(TestCase): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate( @@ -1567,7 +1567,7 @@ class ConfigTestCase(TestCase): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate( @@ -1591,7 +1591,7 @@ class ConfigTestCase(TestCase): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate( @@ -1611,7 +1611,7 @@ class ConfigTestCase(TestCase): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") try: jsonschema.validate( {"item": ["Tobias"]}, @@ -1619,7 +1619,7 @@ class ConfigTestCase(TestCase): format_checker=jsonschema.FormatChecker(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate( @@ -1797,7 +1797,7 @@ class ConfigTestCase(TestCase): try: jsonschema.validate({"item": {"sides": 1}}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate({"item": {"sides": "1"}}, TestConf.serialize()) @@ -1820,7 +1820,7 @@ class ConfigTestCase(TestCase): {"item": {"sides": 1, "color": "red"}}, TestConf.serialize() ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate( @@ -1872,7 +1872,7 @@ class ConfigTestCase(TestCase): TestConf.serialize(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate( @@ -1904,7 +1904,7 @@ class ConfigTestCase(TestCase): {"item": {"color": "red", "sides": 1}}, TestConf.serialize() ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") try: jsonschema.validate( @@ -1912,7 +1912,7 @@ class ConfigTestCase(TestCase): TestConf.serialize(), ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate({"item": {"color": "blue"}}, TestConf.serialize()) @@ -1999,7 +1999,7 @@ class ConfigTestCase(TestCase): try: jsonschema.validate({"item": ["no"]}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate({"item": ["maybe"]}, TestConf.serialize()) @@ -2048,22 +2048,22 @@ class ConfigTestCase(TestCase): try: jsonschema.validate({"item": ["no"]}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") try: jsonschema.validate({"item": ["yes"]}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") try: jsonschema.validate({"item": [True]}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") try: jsonschema.validate({"item": [False]}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate({"item": ["maybe"]}, TestConf.serialize()) @@ -2108,12 +2108,12 @@ class ConfigTestCase(TestCase): try: jsonschema.validate({"item": ["no"]}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") try: jsonschema.validate({"item": ["yes"]}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate({"item": ["maybe"]}, TestConf.serialize()) @@ -2145,12 +2145,12 @@ class ConfigTestCase(TestCase): try: jsonschema.validate({"item": ["no"]}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") try: jsonschema.validate({"item": ["yes"]}, TestConf.serialize()) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") with self.assertRaises(jsonschema.exceptions.ValidationError) as excinfo: jsonschema.validate({"item": [True]}, TestConf.serialize()) @@ -2494,7 +2494,7 @@ class ComplexSchemaTestCase(TestCase): try: jsonschema.validate({"complex_item": {"thirsty": True}}, serialized) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") @pytest.mark.skipif( HAS_JSONSCHEMA is False, reason="The 'jsonschema' library is missing" @@ -2515,7 +2515,7 @@ class ComplexSchemaTestCase(TestCase): try: jsonschema.validate({"complex_complex_item": {"hungry": True}}, serialized) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") @pytest.mark.skipif( HAS_JSONSCHEMA is False, reason="The 'jsonschema' library is missing" @@ -2533,7 +2533,7 @@ class ComplexSchemaTestCase(TestCase): serialized, ) except jsonschema.exceptions.ValidationError as exc: - self.fail("ValidationError raised: {}".format(exc)) + self.fail(f"ValidationError raised: {exc}") @pytest.mark.skipif( HAS_JSONSCHEMA is False, reason="The 'jsonschema' library is missing" diff --git a/tests/unit/utils/test_sdb.py b/tests/unit/utils/test_sdb.py index 87886cbc521..614a7173481 100644 --- a/tests/unit/utils/test_sdb.py +++ b/tests/unit/utils/test_sdb.py @@ -2,7 +2,6 @@ :codeauthor: :email:`Vernon Cole ` """ - import os import salt.utils.sdb as sdb diff --git a/tests/unit/utils/test_ssdp.py b/tests/unit/utils/test_ssdp.py index 252efeb735f..4af97ea071c 100644 --- a/tests/unit/utils/test_ssdp.py +++ b/tests/unit/utils/test_ssdp.py @@ -80,7 +80,7 @@ class SSDPBaseTestCase(TestCase, Mocks): Side effect :return: """ - raise AttributeError("attribute error: {}. {}".format(args, kwargs)) + raise AttributeError(f"attribute error: {args}. {kwargs}") @patch("salt.utils.ssdp._json", None) @patch("salt.utils.ssdp.asyncio", None) @@ -235,7 +235,7 @@ class SSDPFactoryTestCase(TestCase, Mocks): :return: """ factory = self.get_ssdp_factory() - data = "{}nonsense".format(ssdp.SSDPBase.DEFAULTS[ssdp.SSDPBase.SIGNATURE]) + data = f"{ssdp.SSDPBase.DEFAULTS[ssdp.SSDPBase.SIGNATURE]}nonsense" addr = "10.10.10.10", "foo.suse.de" with patch.object(factory, "log", MagicMock()), patch.object( factory, "_sendto", MagicMock() @@ -257,7 +257,7 @@ class SSDPFactoryTestCase(TestCase, Mocks): factory = self.get_ssdp_factory() factory.disable_hidden = True signature = ssdp.SSDPBase.DEFAULTS[ssdp.SSDPBase.SIGNATURE] - data = "{}nonsense".format(signature) + data = f"{signature}nonsense" addr = "10.10.10.10", "foo.suse.de" with patch.object(factory, "log", MagicMock()), patch.object( factory, "_sendto", MagicMock() @@ -269,10 +269,7 @@ class SSDPFactoryTestCase(TestCase, Mocks): in factory.log.debug.call_args[0][0] ) assert factory._sendto.called - assert ( - "{}:E:Invalid timestamp".format(signature) - == factory._sendto.call_args[0][0] - ) + assert f"{signature}:E:Invalid timestamp" == factory._sendto.call_args[0][0] def test_datagram_signature_outdated_timestamp_quiet(self): """ @@ -331,9 +328,9 @@ class SSDPFactoryTestCase(TestCase, Mocks): assert factory.log.debug.called assert factory.disable_hidden assert factory._sendto.called - assert factory._sendto.call_args[0][ - 0 - ] == "{}:E:Timestamp is too old".format(signature) + assert ( + factory._sendto.call_args[0][0] == f"{signature}:E:Timestamp is too old" + ) assert "Received outdated package" in factory.log.debug.call_args[0][0] def test_datagram_signature_correct_timestamp_reply(self): @@ -365,7 +362,7 @@ class SSDPFactoryTestCase(TestCase, Mocks): assert factory.disable_hidden assert factory._sendto.called assert factory._sendto.call_args[0][0] == salt.utils.stringutils.to_bytes( - "{}:@:{{}}".format(signature) + f"{signature}:@:{{}}" ) assert 'Received "%s" from %s:%s' in factory.log.debug.call_args[0][0] @@ -512,7 +509,7 @@ class SSDPClientTestCase(TestCase, Mocks): assert clnt._socket.sendto.called message, target = clnt._socket.sendto.call_args[0] assert message == salt.utils.stringutils.to_bytes( - "{}{}".format(config[ssdp.SSDPBase.SIGNATURE], f_time) + f"{config[ssdp.SSDPBase.SIGNATURE]}{f_time}" ) assert target[0] == "" assert target[1] == config[ssdp.SSDPBase.PORT] @@ -580,7 +577,7 @@ class SSDPClientTestCase(TestCase, Mocks): signature = ssdp.SSDPBase.DEFAULTS[ssdp.SSDPBase.SIGNATURE] fake_resource = SSDPClientTestCase.Resource() fake_resource.pool = [ - ("{}:E:{}".format(signature, error), "10.10.10.10"), + (f"{signature}:E:{error}", "10.10.10.10"), (None, None), ] @@ -613,7 +610,7 @@ class SSDPClientTestCase(TestCase, Mocks): signature = ssdp.SSDPBase.DEFAULTS[ssdp.SSDPBase.SIGNATURE] fake_resource = SSDPClientTestCase.Resource() fake_resource.pool = [ - ("{}:E:{}".format(signature, error), "10.10.10.10"), + (f"{signature}:E:{error}", "10.10.10.10"), (None, None), ] diff --git a/tests/unit/utils/test_state.py b/tests/unit/utils/test_state.py index 1b533e494f2..ba2c31d07f5 100644 --- a/tests/unit/utils/test_state.py +++ b/tests/unit/utils/test_state.py @@ -2,7 +2,6 @@ Unit Tests for functions located in salt.utils.state.py. """ - import copy import textwrap @@ -122,9 +121,7 @@ class StateUtilTestCase(TestCase): ), } for test, data in test_valid_false_states.items(): - self.assertFalse( - salt.utils.state.check_result(data), msg="{} failed".format(test) - ) + self.assertFalse(salt.utils.state.check_result(data), msg=f"{test} failed") test_valid_true_states = { "test1": salt.utils.odict.OrderedDict( [ @@ -214,9 +211,7 @@ class StateUtilTestCase(TestCase): ), } for test, data in test_valid_true_states.items(): - self.assertTrue( - salt.utils.state.check_result(data), msg="{} failed".format(test) - ) + self.assertTrue(salt.utils.state.check_result(data), msg=f"{test} failed") test_invalid_true_ht_states = { "test_onfail_simple2": ( salt.utils.odict.OrderedDict( @@ -519,7 +514,7 @@ class StateUtilTestCase(TestCase): tdata["__id__"] = t_ self.assertFalse( salt.utils.state.check_result(data, highstate=ht), - msg="{} failed".format(test), + msg=f"{test} failed", ) test_valid_true_ht_states = { @@ -746,7 +741,7 @@ class StateUtilTestCase(TestCase): tdata["__id__"] = t_ self.assertTrue( salt.utils.state.check_result(data, highstate=ht), - msg="{} failed".format(test), + msg=f"{test} failed", ) test_valid_false_state = {"host1": {"test_state": {"result": False}}} self.assertFalse(salt.utils.state.check_result(test_valid_false_state)) diff --git a/tests/unit/utils/test_systemd.py b/tests/unit/utils/test_systemd.py index 698a2337e5e..8f7e1de3b7a 100644 --- a/tests/unit/utils/test_systemd.py +++ b/tests/unit/utils/test_systemd.py @@ -78,7 +78,7 @@ class SystemdTestCase(TestCase): """ with patch("subprocess.Popen") as popen_mock: _version = 231 - output = "systemd {}\n-SYSVINIT".format(_version) + output = f"systemd {_version}\n-SYSVINIT" popen_mock.return_value = Mock( communicate=lambda *args, **kwargs: (output, None), pid=lambda: 12345, @@ -162,7 +162,7 @@ class SystemdTestCase(TestCase): with patch("subprocess.Popen") as popen_mock: _expected = False _version = 204 - _output = "systemd {}\n-SYSVINIT".format(_version) + _output = f"systemd {_version}\n-SYSVINIT" popen_mock.return_value = Mock( communicate=lambda *args, **kwargs: (_output, None), pid=lambda: 12345, @@ -196,7 +196,7 @@ class SystemdTestCase(TestCase): with patch("subprocess.Popen") as popen_mock: _expected = True _version = 205 - _output = "systemd {}\n-SYSVINIT".format(_version) + _output = f"systemd {_version}\n-SYSVINIT" popen_mock.return_value = Mock( communicate=lambda *args, **kwargs: (_output, None), pid=lambda: 12345, @@ -230,7 +230,7 @@ class SystemdTestCase(TestCase): with patch("subprocess.Popen") as popen_mock: _expected = True _version = 206 - _output = "systemd {}\n-SYSVINIT".format(_version) + _output = f"systemd {_version}\n-SYSVINIT" popen_mock.return_value = Mock( communicate=lambda *args, **kwargs: (_output, None), pid=lambda: 12345, diff --git a/tests/unit/utils/test_thin.py b/tests/unit/utils/test_thin.py index 7fd1e7b5dc3..d67dca16890 100644 --- a/tests/unit/utils/test_thin.py +++ b/tests/unit/utils/test_thin.py @@ -919,9 +919,9 @@ class SSHThinTestCase(TestCase): files = [] for py in ("py3", "pyall"): for i in range(1, 4): - files.append(os.path.join(py, "root", "r{}".format(i))) + files.append(os.path.join(py, "root", f"r{i}")) for i in range(4, 7): - files.append(os.path.join(py, "root2", "r{}".format(i))) + files.append(os.path.join(py, "root2", f"r{i}")) for cl in thin.tarfile.open().method_calls[:-6]: arcname = cl[2].get("arcname") self.assertIn(arcname, files) @@ -997,9 +997,9 @@ class SSHThinTestCase(TestCase): files = [] for py in ("pyall", "pyall", "py3"): for i in range(1, 4): - files.append(os.path.join("namespace", py, "root", "r{}".format(i))) + files.append(os.path.join("namespace", py, "root", f"r{i}")) for i in range(4, 7): - files.append(os.path.join("namespace", py, "root2", "r{}".format(i))) + files.append(os.path.join("namespace", py, "root2", f"r{i}")) for idx, cl in enumerate(thin.tarfile.open().method_calls[:-6]): arcname = cl[2].get("arcname") @@ -1247,7 +1247,7 @@ class SSHThinTestCase(TestCase): thin._pack_alternative(ext_conf, self.digest, self.tar) calls = self.tar.mock_calls for _file in exp_files: - assert [x for x in calls if "{}".format(_file) in x[-2]] + assert [x for x in calls if f"{_file}" in x[-2]] def test_pack_alternatives(self): """ @@ -1257,7 +1257,7 @@ class SSHThinTestCase(TestCase): thin._pack_alternative(self.ext_conf, self.digest, self.tar) calls = self.tar.mock_calls for _file in self.exp_files: - assert [x for x in calls if "{}".format(_file) in x[-2]] + assert [x for x in calls if f"{_file}" in x[-2]] assert [ x for x in calls @@ -1275,7 +1275,7 @@ class SSHThinTestCase(TestCase): thin._pack_alternative(self.ext_conf, self.digest, self.tar) calls = self.tar.mock_calls for _file in self.exp_files: - assert [x for x in calls if "{}".format(_file) in x[-2]] + assert [x for x in calls if f"{_file}" in x[-2]] assert [ x for x in calls @@ -1302,7 +1302,7 @@ class SSHThinTestCase(TestCase): assert msg in log_handler.messages calls = self.tar.mock_calls for _file in self.exp_files: - arg = [x for x in calls if "{}".format(_file) in x[-2]] + arg = [x for x in calls if f"{_file}" in x[-2]] kwargs = [ x for x in calls @@ -1344,7 +1344,7 @@ class SSHThinTestCase(TestCase): thin._pack_alternative(ext_conf, self.digest, self.tar) calls = self.tar.mock_calls for _file in exp_files: - assert [x for x in calls if "{}".format(_file) in x[-2]] + assert [x for x in calls if f"{_file}" in x[-2]] def test_pack_alternatives_empty_dependencies(self): """ @@ -1376,7 +1376,7 @@ class SSHThinTestCase(TestCase): thin._pack_alternative(ext_conf, self.digest, self.tar) calls = self.tar.mock_calls for _file in exp_files: - assert [x for x in calls if "{}".format(_file) in x[-2]] + assert [x for x in calls if f"{_file}" in x[-2]] @pytest.mark.slow_test @pytest.mark.skip_on_windows(reason="salt-ssh does not deploy to/from windows") @@ -1390,11 +1390,11 @@ class SSHThinTestCase(TestCase): # This was previously an integration test and is now here, as a unit test. # Should actually be a functional test with VirtualEnv() as venv: - salt.utils.thin.gen_thin(str(venv.venv_dir)) + thin.gen_thin(str(venv.venv_dir)) thin_dir = venv.venv_dir / "thin" thin_archive = thin_dir / "thin.tgz" tar = tarfile.open(str(thin_archive)) - tar.extractall(str(thin_dir)) + tar.extractall(str(thin_dir)) # nosec tar.close() ret = venv.run( venv.venv_python, diff --git a/tests/unit/utils/test_vmware.py b/tests/unit/utils/test_vmware.py index ca8cbdc46c4..e61539a29bf 100644 --- a/tests/unit/utils/test_vmware.py +++ b/tests/unit/utils/test_vmware.py @@ -3701,9 +3701,9 @@ class GetLicenseAssignmentManagerTestCase(TestCase): def setUp(self): self.mock_si = MagicMock() self.mock_lic_assign_mgr = MagicMock() - type( - self.mock_si.content.licenseManager - ).licenseAssignmentManager = PropertyMock(return_value=self.mock_lic_assign_mgr) + type(self.mock_si.content.licenseManager).licenseAssignmentManager = ( + PropertyMock(return_value=self.mock_lic_assign_mgr) + ) def tearDown(self): for attr in ("mock_si", "mock_lic_assign_mgr"): @@ -3712,9 +3712,9 @@ class GetLicenseAssignmentManagerTestCase(TestCase): def test_raise_no_permission(self): exc = vim.fault.NoPermission() exc.privilegeId = "Fake privilege" - type( - self.mock_si.content.licenseManager - ).licenseAssignmentManager = PropertyMock(side_effect=exc) + type(self.mock_si.content.licenseManager).licenseAssignmentManager = ( + PropertyMock(side_effect=exc) + ) with self.assertRaises(VMwareApiError) as excinfo: salt.utils.vmware.get_license_assignment_manager(self.mock_si) self.assertEqual( @@ -3725,9 +3725,9 @@ class GetLicenseAssignmentManagerTestCase(TestCase): def test_raise_vim_fault(self): exc = vim.fault.VimFault() exc.msg = "VimFault msg" - type( - self.mock_si.content.licenseManager - ).licenseAssignmentManager = PropertyMock(side_effect=exc) + type(self.mock_si.content.licenseManager).licenseAssignmentManager = ( + PropertyMock(side_effect=exc) + ) with self.assertRaises(VMwareApiError) as excinfo: salt.utils.vmware.get_license_assignment_manager(self.mock_si) self.assertEqual(excinfo.exception.strerror, "VimFault msg") @@ -3735,17 +3735,17 @@ class GetLicenseAssignmentManagerTestCase(TestCase): def test_raise_runtime_fault(self): exc = vmodl.RuntimeFault() exc.msg = "RuntimeFault msg" - type( - self.mock_si.content.licenseManager - ).licenseAssignmentManager = PropertyMock(side_effect=exc) + type(self.mock_si.content.licenseManager).licenseAssignmentManager = ( + PropertyMock(side_effect=exc) + ) with self.assertRaises(VMwareRuntimeError) as excinfo: salt.utils.vmware.get_license_assignment_manager(self.mock_si) self.assertEqual(excinfo.exception.strerror, "RuntimeFault msg") def test_empty_license_assignment_manager(self): - type( - self.mock_si.content.licenseManager - ).licenseAssignmentManager = PropertyMock(return_value=None) + type(self.mock_si.content.licenseManager).licenseAssignmentManager = ( + PropertyMock(return_value=None) + ) with self.assertRaises(VMwareObjectRetrievalError) as excinfo: salt.utils.vmware.get_license_assignment_manager(self.mock_si) self.assertEqual( diff --git a/tests/unit/utils/test_vsan.py b/tests/unit/utils/test_vsan.py index 8231776d694..fe2cd6cf5c9 100644 --- a/tests/unit/utils/test_vsan.py +++ b/tests/unit/utils/test_vsan.py @@ -3,6 +3,7 @@ Tests functions in salt.utils.vsan """ + import logging import pytest diff --git a/tests/unit/utils/test_vt.py b/tests/unit/utils/test_vt.py index 876cf0e01fa..8984ace39cf 100644 --- a/tests/unit/utils/test_vt.py +++ b/tests/unit/utils/test_vt.py @@ -76,7 +76,7 @@ class VTTestCase(TestCase): buffer_o += stdout if stderr: buffer_e += stderr - assert buffer_o.strip() == "24 {}".format(cols) + assert buffer_o.strip() == f"24 {cols}" try: # Then wait for the terminal child to exit, this will raise an # exception if the process has already exited. @@ -120,7 +120,7 @@ class VTTestCase(TestCase): for idx in range(0, nr_ptys + n_executions): try: with salt.utils.vt.Terminal( - 'echo "Run {}"'.format(idx), + f'echo "Run {idx}"', shell=True, stream_stdout=False, stream_stderr=False, @@ -142,7 +142,7 @@ class VTTestCase(TestCase): for idx in range(0, nr_ptys + n_executions): try: terminal = salt.utils.vt.Terminal( - 'echo "Run {}"'.format(idx), + f'echo "Run {idx}"', shell=True, stream_stdout=False, stream_stderr=False, diff --git a/tests/unit/utils/test_win_chcp.py b/tests/unit/utils/test_win_chcp.py index 7fa0f0c35a8..b93e38f6b92 100644 --- a/tests/unit/utils/test_win_chcp.py +++ b/tests/unit/utils/test_win_chcp.py @@ -1,6 +1,7 @@ """ Test win_chcp """ + import pytest from salt.exceptions import CodePageError diff --git a/tests/unit/utils/test_win_service.py b/tests/unit/utils/test_win_service.py index a1acede897e..f6de830c2b9 100644 --- a/tests/unit/utils/test_win_service.py +++ b/tests/unit/utils/test_win_service.py @@ -14,9 +14,7 @@ class WinServiceImportTestCase(TestCase): Simply importing should not raise an error, especially on Linux """ if isinstance(win_service, Exception): - raise Exception( - "Importing win_system caused traceback: {}".format(win_service) - ) + raise Exception(f"Importing win_system caused traceback: {win_service}") @pytest.mark.skip_unless_on_windows diff --git a/tests/unit/utils/test_win_system.py b/tests/unit/utils/test_win_system.py index a30d539c53a..870b47bc4cd 100644 --- a/tests/unit/utils/test_win_system.py +++ b/tests/unit/utils/test_win_system.py @@ -18,9 +18,7 @@ class WinSystemImportTestCase(TestCase): def test_import(self): if isinstance(win_system, Exception): - raise Exception( - "Importing win_system caused traceback: {}".format(win_system) - ) + raise Exception(f"Importing win_system caused traceback: {win_system}") @pytest.mark.skip_unless_on_windows diff --git a/tests/unit/utils/test_xmlutil.py b/tests/unit/utils/test_xmlutil.py index d9a4ae5cc0c..4170cd80ffe 100644 --- a/tests/unit/utils/test_xmlutil.py +++ b/tests/unit/utils/test_xmlutil.py @@ -2,6 +2,7 @@ tests.unit.xmlutil_test ~~~~~~~~~~~~~~~~~~~~ """ + import xml.etree.ElementTree as ET import salt.utils.xmlutil as xml diff --git a/tests/unit/utils/test_yamlencoding.py b/tests/unit/utils/test_yamlencoding.py index 179b7067cd1..6e0876cbe83 100644 --- a/tests/unit/utils/test_yamlencoding.py +++ b/tests/unit/utils/test_yamlencoding.py @@ -2,7 +2,6 @@ Tests for salt.utils.yamlencoding """ - import salt.utils.yaml import salt.utils.yamlencoding from tests.support.unit import TestCase diff --git a/tests/unit/utils/test_zeromq.py b/tests/unit/utils/test_zeromq.py index 1dcd69af997..fdb4faaaeb1 100644 --- a/tests/unit/utils/test_zeromq.py +++ b/tests/unit/utils/test_zeromq.py @@ -1,6 +1,7 @@ """ Test salt.utils.zeromq """ + import pytest import zmq diff --git a/tests/unit/utils/test_zfs.py b/tests/unit/utils/test_zfs.py index 253710f94fe..cdde04336de 100644 --- a/tests/unit/utils/test_zfs.py +++ b/tests/unit/utils/test_zfs.py @@ -9,7 +9,6 @@ Tests for the zfs utils library .. versionadded:: 2018.3.1 """ - import salt.utils.zfs as zfs from salt.utils.odict import OrderedDict from tests.support.mock import MagicMock, patch diff --git a/tools/changelog.py b/tools/changelog.py index 12bbba22d3c..f39b3ed0a43 100644 --- a/tools/changelog.py +++ b/tools/changelog.py @@ -1,6 +1,7 @@ """ These commands are used manage Salt's changelog. """ + # pylint: disable=resource-leakage,broad-except,3rd-party-module-not-gated from __future__ import annotations diff --git a/tools/ci.py b/tools/ci.py index ae84227735d..85e4471b465 100644 --- a/tools/ci.py +++ b/tools/ci.py @@ -1,6 +1,7 @@ """ These commands are used in the CI pipeline. """ + # pylint: disable=resource-leakage,broad-except,3rd-party-module-not-gated from __future__ import annotations diff --git a/tools/docs.py b/tools/docs.py index 5e38583024d..38604f32f25 100644 --- a/tools/docs.py +++ b/tools/docs.py @@ -1,6 +1,7 @@ """ These commands are used to generate Salt's manpages. """ + # pylint: disable=resource-leakage,broad-except,3rd-party-module-not-gated from __future__ import annotations diff --git a/tools/pkg/__init__.py b/tools/pkg/__init__.py index 2d843893640..1ff06cae5f5 100644 --- a/tools/pkg/__init__.py +++ b/tools/pkg/__init__.py @@ -1,6 +1,7 @@ """ These commands are used to build Salt packages. """ + # pylint: disable=resource-leakage,broad-except,3rd-party-module-not-gated from __future__ import annotations @@ -61,7 +62,7 @@ class Recompress: d_targz = tempd.joinpath(targz.name) with tarfile.open(d_tar, "w|") as wfile: with tarfile.open(targz, "r:gz") as rfile: - rfile.extractall(d_src) + rfile.extractall(d_src) # nosec extracted_dir = next(pathlib.Path(d_src).iterdir()) for name in sorted(extracted_dir.rglob("*")): wfile.add( diff --git a/tools/pkg/build.py b/tools/pkg/build.py index c2c37eaa1f9..434e1060114 100644 --- a/tools/pkg/build.py +++ b/tools/pkg/build.py @@ -1,6 +1,7 @@ """ These commands are used to build the salt onedir and system packages. """ + # pylint: disable=resource-leakage,broad-except from __future__ import annotations @@ -227,7 +228,7 @@ def macos( ctx.info(f"Extracting the onedir artifact to {build_root}") with tarfile.open(str(onedir_artifact)) as tarball: with ctx.chdir(onedir_artifact.parent): - tarball.extractall(path=build_root) + tarball.extractall(path=build_root) # nosec else: ctx.info("Building package without an existing onedir") @@ -357,7 +358,7 @@ def windows( unzip_dir = checkout / "pkg" / "windows" ctx.info(f"Unzipping the onedir artifact to {unzip_dir}") with zipfile.ZipFile(onedir_artifact, mode="r") as archive: - archive.extractall(unzip_dir) + archive.extractall(unzip_dir) # nosec move_dir = unzip_dir / "salt" build_env = unzip_dir / "buildenv" diff --git a/tools/pkg/repo/__init__.py b/tools/pkg/repo/__init__.py index e48671051f2..fb028895553 100644 --- a/tools/pkg/repo/__init__.py +++ b/tools/pkg/repo/__init__.py @@ -1,6 +1,7 @@ """ These commands are used to build the package repository files. """ + # pylint: disable=resource-leakage,broad-except,3rd-party-module-not-gated from __future__ import annotations diff --git a/tools/pkg/repo/create.py b/tools/pkg/repo/create.py index 1457d84a7af..0464249ad22 100644 --- a/tools/pkg/repo/create.py +++ b/tools/pkg/repo/create.py @@ -1,6 +1,7 @@ """ These commands are used to build the package repository files. """ + # pylint: disable=resource-leakage,broad-except,3rd-party-module-not-gated from __future__ import annotations diff --git a/tools/pkg/repo/publish.py b/tools/pkg/repo/publish.py index 2a743ac046b..345705b4419 100644 --- a/tools/pkg/repo/publish.py +++ b/tools/pkg/repo/publish.py @@ -1,6 +1,7 @@ """ These commands are used to build the package repository files. """ + # pylint: disable=resource-leakage,broad-except,3rd-party-module-not-gated from __future__ import annotations diff --git a/tools/precommit/__init__.py b/tools/precommit/__init__.py index c10eadeb479..2bffffbb2ec 100644 --- a/tools/precommit/__init__.py +++ b/tools/precommit/__init__.py @@ -1,6 +1,7 @@ """ These commands, and sub-commands, are used by pre-commit. """ + from ptscripts import command_group import tools.utils diff --git a/tools/precommit/changelog.py b/tools/precommit/changelog.py index 5e108af5f11..43c1f5f3e40 100644 --- a/tools/precommit/changelog.py +++ b/tools/precommit/changelog.py @@ -1,6 +1,7 @@ """ These commands are used to validate changelog entries """ + # pylint: disable=resource-leakage,broad-except,3rd-party-module-not-gated from __future__ import annotations diff --git a/tools/precommit/docs.py b/tools/precommit/docs.py index 84b741d3106..1fcb50592a4 100644 --- a/tools/precommit/docs.py +++ b/tools/precommit/docs.py @@ -1,6 +1,7 @@ """ Check salt code base for for missing or wrong docs """ + # pylint: disable=resource-leakage,broad-except,3rd-party-module-not-gated from __future__ import annotations diff --git a/tools/precommit/docstrings.py b/tools/precommit/docstrings.py index 0fecdcfcb1e..829acac37c0 100644 --- a/tools/precommit/docstrings.py +++ b/tools/precommit/docstrings.py @@ -1,6 +1,7 @@ """ Check salt code base for for missing or wrong docstrings. """ + # Skip mypy checks since it will follow into Salt which doesn't yet have proper types defined # mypy: ignore-errors # pylint: disable=resource-leakage,broad-except,3rd-party-module-not-gated diff --git a/tools/precommit/filemap.py b/tools/precommit/filemap.py index 96a662fa7e7..7870375f299 100644 --- a/tools/precommit/filemap.py +++ b/tools/precommit/filemap.py @@ -1,6 +1,7 @@ """ `tests/filename_map.yml` validity checks """ + import pathlib import re diff --git a/tools/precommit/workflows.py b/tools/precommit/workflows.py index 9c9a9e95ee9..6ace8a3ecb2 100644 --- a/tools/precommit/workflows.py +++ b/tools/precommit/workflows.py @@ -1,6 +1,7 @@ """ These commands are used for our GitHub Actions workflows. """ + # pylint: disable=resource-leakage,broad-except,3rd-party-module-not-gated from __future__ import annotations diff --git a/tools/release.py b/tools/release.py index 78fa1747aad..5943d1ed99d 100644 --- a/tools/release.py +++ b/tools/release.py @@ -1,6 +1,7 @@ """ These commands are used to release Salt. """ + # pylint: disable=resource-leakage,broad-except,3rd-party-module-not-gated from __future__ import annotations diff --git a/tools/testsuite/__init__.py b/tools/testsuite/__init__.py index 08abf12ddcd..3c851336f5f 100644 --- a/tools/testsuite/__init__.py +++ b/tools/testsuite/__init__.py @@ -1,6 +1,7 @@ """ These commands are related to the test suite. """ + # pylint: disable=resource-leakage,broad-except,3rd-party-module-not-gated from __future__ import annotations diff --git a/tools/testsuite/download.py b/tools/testsuite/download.py index d70dfb5f384..b1403556bd3 100644 --- a/tools/testsuite/download.py +++ b/tools/testsuite/download.py @@ -1,6 +1,7 @@ """ These commands are related to downloading test suite CI artifacts. """ + # pylint: disable=resource-leakage,broad-except,3rd-party-module-not-gated from __future__ import annotations diff --git a/tools/vm.py b/tools/vm.py index 996ebc845d1..8d1f93a1b06 100644 --- a/tools/vm.py +++ b/tools/vm.py @@ -2,6 +2,7 @@ These commands are used to create/destroy VMs, sync the local checkout to the VM and to run commands on the VM. """ + # pylint: disable=resource-leakage,broad-except,3rd-party-module-not-gated from __future__ import annotations