Merge ~sylvain-pineau/plainbox-provider-checkbox:fix_flake8_errors into plainbox-provider-checkbox:master

Proposed by Sylvain Pineau
Status: Merged
Approved by: Sylvain Pineau
Approved revision: d4209d6896e6166fc9c52a62f298c37ac0c2de03
Merged at revision: 793f29ded5511784f80864af9b1d332e7ef31290
Proposed branch: ~sylvain-pineau/plainbox-provider-checkbox:fix_flake8_errors
Merge into: plainbox-provider-checkbox:master
Diff against target: 5375 lines (+824/-2129)
73 files modified
bin/accelerometer_test.py (+17/-14)
bin/alsa_tests.py (+1/-0)
bin/ansi_parser.py (+2/-1)
bin/audio_driver_info.py (+4/-3)
bin/audio_test.py (+136/-121)
bin/battery_test.py (+4/-4)
bin/bluetooth_test.py (+1/-0)
bin/bmc_info.py (+5/-5)
bin/boot_mode_test_snappy.py (+0/-1)
bin/brightness_test.py (+11/-10)
bin/bt_connect.py (+1/-0)
bin/bt_list_adapters.py (+1/-1)
bin/color_depth_info.py (+2/-1)
bin/cpu_offlining.py (+1/-0)
bin/cpu_topology.py (+3/-2)
bin/cpuid.py (+3/-3)
bin/create_connection.py (+6/-6)
bin/dmitest.py (+16/-16)
bin/edid_cycle.py (+4/-2)
bin/evdev_touch_test.py (+1/-1)
bin/fan_reaction_test.py (+6/-2)
bin/frequency_governors_test.py (+157/-98)
bin/fresh_rate_info.py (+3/-2)
bin/get_make_and_model.py (+7/-5)
bin/gpu_test.py (+12/-12)
bin/graphic_memory_info.py (+4/-3)
bin/graphics_driver.py (+11/-9)
bin/graphics_modes_info.py (+5/-5)
bin/graphics_stress_test.py (+26/-20)
bin/gst_pipeline_test.py (+18/-11)
bin/hdd_parking.py (+7/-3)
bin/hotkey_tests.py (+1/-0)
bin/key_test.py (+11/-9)
bin/keyboard_test.py (+1/-0)
bin/lock_screen_watcher.py (+3/-2)
bin/lsmod_info.py (+1/-0)
bin/mac_passthrough.py (+2/-2)
bin/manage_compiz_plugin.py (+4/-4)
bin/memory_compare.py (+2/-2)
bin/memory_test.py (+2/-2)
bin/network.py (+14/-11)
bin/network_check.py (+6/-2)
bin/network_ntp_test.py (+7/-5)
bin/network_reconnect_resume_test.py (+6/-4)
bin/network_restart.py (+15/-9)
bin/optical_read_test.py (+13/-16)
bin/pm_log_check.py (+12/-8)
bin/pm_test.py (+14/-13)
bin/process_wait.py (+6/-3)
bin/pulse-active-port-change.py (+15/-14)
bin/removable_storage_test.py (+26/-23)
bin/removable_storage_watcher.py (+75/-60)
bin/resolution_test.py (+5/-3)
bin/rotation_test.py (+3/-1)
bin/sleep_test.py (+5/-4)
bin/sleep_test_log_check.py (+8/-7)
bin/sleep_time_check.py (+10/-4)
bin/stress_ng_test.py (+1/-1)
bin/test_bt_keyboard.py (+1/-1)
bin/touchpad_driver_info.py (+2/-2)
bin/touchpad_test.py (+3/-2)
bin/virtualization.py (+5/-24)
bin/volume_test.py (+44/-34)
bin/wifi_ap_wizard.py (+1/-0)
bin/wifi_client_test_netplan.py (+4/-4)
bin/wifi_master_mode.py (+1/-1)
bin/wifi_time2reconnect.py (+5/-6)
bin/window_test.py (+4/-3)
bin/wwan_tests.py (+1/-24)
bin/xrandr_cycle.py (+8/-8)
dev/null (+0/-1450)
requirements/container-tests-provider-checkbox (+1/-0)
requirements/deb-base.txt (+1/-0)
Reviewer Review Type Date Requested Status
Sylvain Pineau (community) Needs Resubmitting
Devices Certification Bot Needs Fixing
Jonathan Cave (community) Approve
Review via email: mp+387579@code.launchpad.net

Description of the change

test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/accelerometer_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/alsa_pcm_info.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/alsa_tests.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/ansi_parser.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/audio_driver_info.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/audio_settings.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/audio_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/battery_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/bluetooth_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/bluez_list_adapters.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/bmc_info.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/boot_mode_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/boot_mode_test_snappy.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/booted_kernel_tests.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/brightness_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/bt_connect.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/bt_list_adapters.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/camera_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/camera_test_rpi.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/chameleon_edid_stress.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/chameleon_hdmi_hotplug.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/check-prerelease.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/check_static.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/color_depth_info.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/cpu_offlining.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/cpu_topology.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/cpuid.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/create_connection.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/disk_info.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/disk_smart.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/dkms_info.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/dmi_sysfs_resource.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/dmitest.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/edid_cycle.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/efi-pxeboot.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/evdev_touch_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/fan_reaction_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/fde_tests.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/frequency_governors_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/fresh_rate_info.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/fstrim_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/gatt-notify-test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/get_make_and_model.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/gpio_gpiomem_loopback.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/gpio_sysfs_loopback.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/gpu_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/gputest_benchmark.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/graphic_memory_info.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/graphics_driver.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/graphics_modes_info.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/graphics_stress_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/gst_pipeline_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/hdd_parking.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/hotkey_tests.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/i2c_driver_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/ipmi_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/kernel_taint_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/key_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/keyboard_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/lock_screen_watcher.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/lsmod_info.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/mac_passthrough.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/manage_compiz_plugin.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/memory_compare.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/memory_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/module_loaded_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/multitap_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/net_driver_info.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/net_if_watcher.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/network.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/network_check.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/network_device_info.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/network_ntp_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/network_reconnect_resume_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/network_restart.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/optical_read_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/plug_connected_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/pm_log_check.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/pm_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/process_wait.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/pulse-active-port-change.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/recovery_info.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/removable_storage_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/removable_storage_watcher.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/resolution_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/rotation_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/roundtrip_qr.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/serial_loopback.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/sleep_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/sleep_test_log_check.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/sleep_time_check.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/snap_tests.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/socketcan_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/storage_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/stress_ng_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/system_info.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/test_bt_keyboard.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/touchpad_driver_info.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/touchpad_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/tpm_sysfs_resoource.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/ubuntucore_image_checks.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/virtualization.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/volume_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/wifi_ap_wizard.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/wifi_client_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/wifi_client_test_netplan.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/wifi_master_mode.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/wifi_nmcli_backup.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/wifi_nmcli_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/wifi_time2reconnect.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/window_test.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/wwan_tests.py (plainbox.provider_manager.Flake8Tests) ... ok
test_flake8_/home/sylvain/lp/plainbox-provider-checkbox/bin/xrandr_cycle.py (plainbox.provider_manager.Flake8Tests) ... ok

----------------------------------------------------------------------
Ran 113 tests in 27.136s

OK

To post a comment you must log in.
Revision history for this message
Jonathan Cave (jocave) wrote :

Thanks for the massive clean up. +1

review: Approve
Revision history for this message
Devices Certification Bot (ce-certification-qa) wrote :

The merge was fine but running tests failed.

[xenial] [09:16:46] starting container
Device project added to xenial-testing
[focal] [09:16:57] starting container
[xenial] [09:16:58] provisioning container
Device project added to focal-testing
[xenial] [09:17:10] Starting tests...
[xenial] Found a test script: ./requirements/container-tests-provider-checkbox
[focal] [09:17:11] provisioning container
[focal] [09:17:35] Starting tests...
[focal] Found a test script: ./requirements/container-tests-provider-checkbox
[bionic] [09:18:24] starting container
Device project added to bionic-testing
[bionic] [09:18:38] provisioning container
[bionic] [09:18:51] Starting tests...
[bionic] Found a test script: ./requirements/container-tests-provider-checkbox
[focal] [09:20:59] container-tests-provider-checkbox: PASS
[focal] [09:20:59] Fixing file permissions in source directory
[focal] [09:20:59] Destroying container
[bionic] [09:21:09] container-tests-provider-checkbox: PASS
[bionic] [09:21:09] Fixing file permissions in source directory
[bionic] [09:21:10] Destroying container
[xenial] [09:21:20] container-tests-provider-checkbox: FAIL
[xenial] output: https://paste.ubuntu.com/p/NzGBpvYnDP/
[xenial] [09:21:24] Fixing file permissions in source directory
[xenial] [09:21:24] Destroying container

review: Needs Fixing
Revision history for this message
Sylvain Pineau (sylvain-pineau) wrote :

Fix W503 warnings for xenial

review: Needs Resubmitting

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1diff --git a/bin/accelerometer_test.py b/bin/accelerometer_test.py
2index 2d95ca8..130e22d 100755
3--- a/bin/accelerometer_test.py
4+++ b/bin/accelerometer_test.py
5@@ -23,6 +23,7 @@ The purpose of this script is to simply interact with an onboard
6 accelerometer, and check to be sure that the x, y, z axis respond
7 to physical movement of hardware.
8 '''
9+
10 from argparse import ArgumentParser
11 import gi
12 import logging
13@@ -34,9 +35,10 @@ import time
14 gi.require_version('Gdk', '3.0')
15 gi.require_version('GLib', '2.0')
16 gi.require_version("Gtk", "3.0")
17-from gi.repository import Gdk, GLib, Gtk
18-from subprocess import Popen, PIPE, check_output, STDOUT, CalledProcessError
19-from checkbox_support.parsers.modinfo import ModinfoParser
20+from gi.repository import Gdk, GLib, Gtk # noqa: E402
21+from subprocess import Popen, PIPE, check_output, STDOUT # noqa: E402
22+from subprocess import CalledProcessError # noqa: E402
23+from checkbox_support.parsers.modinfo import ModinfoParser # noqa: E402
24
25 handler = logging.StreamHandler()
26 logger = logging.getLogger()
27@@ -86,8 +88,8 @@ class AccelerometerUI(Gtk.Window):
28
29 def update_axis_icon(self, direction):
30 """Change desired directional icon to checkmark"""
31- exec('self.%s_icon.set_from_stock' % (direction) \
32- + '(Gtk.STOCK_YES, size=Gtk.IconSize.BUTTON)')
33+ exec('self.%s_icon.set_from_stock' % (direction) +
34+ '(Gtk.STOCK_YES, size=Gtk.IconSize.BUTTON)')
35
36 def update_debug_label(self, text):
37 """Update axis information in center of UI"""
38@@ -131,7 +133,7 @@ class AxisData(threading.Thread):
39 self.x_test_pool = ["up", "down"]
40 self.y_test_pool = ["left", "right"]
41
42- if self.ui == None:
43+ if self.ui is None:
44 self.ui.enabled = False
45
46 def grab_current_readings(self):
47@@ -223,8 +225,8 @@ class AxisData(threading.Thread):
48 def insert_supported_module(oem_module):
49 """Try and insert supported module to see if we get any init errors"""
50 try:
51- stream = check_output(['modinfo', oem_module], stderr=STDOUT,
52- universal_newlines=True)
53+ stream = check_output(
54+ ['modinfo', oem_module], stderr=STDOUT, universal_newlines=True)
55 except CalledProcessError as err:
56 print("Error accessing modinfo for %s: " % oem_module, file=sys.stderr)
57 print(err.output, file=sys.stderr)
58@@ -232,7 +234,7 @@ def insert_supported_module(oem_module):
59
60 parser = ModinfoParser(stream)
61 module = os.path.basename(parser.get_field('filename'))
62-
63+
64 insmod_output = Popen(['insmod %s' % module], stderr=PIPE,
65 shell=True, universal_newlines=True)
66
67@@ -259,10 +261,10 @@ def check_module_status():
68 if "Permission denied" in error:
69 raise PermissionException(error)
70
71- vendor_data = re.findall("Vendor:\s.*", output)
72+ vendor_data = re.findall(r"Vendor:\s.*", output)
73 try:
74 manufacturer = vendor_data[0].split(":")[1].strip()
75- except IndexError as exception:
76+ except IndexError:
77 logging.error("Failed to find Manufacturing data")
78 return
79
80@@ -275,8 +277,8 @@ def check_module_status():
81 oem_module = oem_driver_pool.get(vendor)
82 break # We've found our desired module to probe.
83
84- if oem_module != None:
85- if insert_supported_module(oem_module) != None:
86+ if oem_module is not None:
87+ if insert_supported_module(oem_module) is not None:
88 logging.error("Failed module insertion")
89 # Check dmesg status for supported module
90 driver_status = Popen(['dmesg'], stdout=PIPE, universal_newlines=True)
91@@ -347,5 +349,6 @@ def main():
92 # Reading is not instant.
93 time.sleep(5)
94
95+
96 if __name__ == '__main__':
97- main();
98+ main()
99diff --git a/bin/alsa_tests.py b/bin/alsa_tests.py
100index 16fb044..e919570 100755
101--- a/bin/alsa_tests.py
102+++ b/bin/alsa_tests.py
103@@ -168,5 +168,6 @@ def main():
104 device = None
105 return(actions[args.action](args.duration, device))
106
107+
108 if __name__ == '__main__':
109 sys.exit(main())
110diff --git a/bin/ansi_parser.py b/bin/ansi_parser.py
111index c7cf26c..b5cec30 100755
112--- a/bin/ansi_parser.py
113+++ b/bin/ansi_parser.py
114@@ -128,7 +128,8 @@ def parse_filename(filename):
115 def main(args):
116 usage = "Usage: %prog [OPTIONS] [FILE...]"
117 parser = OptionParser(usage=usage)
118- parser.add_option("-o", "--output",
119+ parser.add_option(
120+ "-o", "--output",
121 metavar="FILE",
122 help="File where to output the result.")
123 (options, args) = parser.parse_args(args)
124diff --git a/bin/audio_driver_info.py b/bin/audio_driver_info.py
125index b9bfaf8..424b125 100755
126--- a/bin/audio_driver_info.py
127+++ b/bin/audio_driver_info.py
128@@ -41,7 +41,6 @@ class PacmdAudioDevice():
129 print("Error running %s:" % cmd, file=sys.stderr)
130 print(err.output, file=sys.stderr)
131 return None
132-
133 if not stream:
134 print("Error: modinfo returned nothing", file=sys.stderr)
135 return None
136@@ -74,7 +73,8 @@ def list_device_info():
137 pacmd_entries = check_output(["pacmd", "list-%ss" % vtype],
138 universal_newlines=True)
139 except Exception as e:
140- print("Error when running pacmd list-%ss: %s" % (vtype, e),
141+ print(
142+ "Error when running pacmd list-%ss: %s" % (vtype, e),
143 file=sys.stderr)
144 return 1
145
146@@ -102,8 +102,9 @@ def list_device_info():
147
148 def main():
149 parser = ArgumentParser("List audio device and driver information")
150- args = parser.parse_args()
151+ parser.parse_args()
152 return list_device_info()
153
154+
155 if __name__ == "__main__":
156 sys.exit(main())
157diff --git a/bin/audio_test.py b/bin/audio_test.py
158index 7bd6c44..2a56df4 100755
159--- a/bin/audio_test.py
160+++ b/bin/audio_test.py
161@@ -13,7 +13,7 @@ import time
162 try:
163 import gi
164 gi.require_version('GLib', '2.0')
165- gi.require_version('Gst','1.0')
166+ gi.require_version('Gst', '1.0')
167 from gi.repository import GObject
168 from gi.repository import Gst
169 from gi.repository import GLib
170@@ -29,26 +29,27 @@ try:
171 except ImportError:
172 from collections import Callable # backward compatible
173
174-#Frequency bands for FFT
175+# Frequency bands for FFT
176 BINS = 256
177-#How often to take a sample and do FFT on it.
178+# How often to take a sample and do FFT on it.
179 FFT_INTERVAL = 100000000 # In nanoseconds, so this is every 1/10th second
180-#Sampling frequency. The effective maximum frequency we can analyze is
181-#half of this (see Nyquist's theorem)
182+# Sampling frequency. The effective maximum frequency we can analyze is
183+# half of this (see Nyquist's theorem)
184 SAMPLING_FREQUENCY = 44100
185-#The default test frequency is in the middle of the band that contains 5000Hz
186-#This frequency was determined experimentally to be high enough but more
187-#reliable than others we tried.
188+# The default test frequency is in the middle of the band that contains 5000Hz
189+# This frequency was determined experimentally to be high enough but more
190+# reliable than others we tried.
191 DEFAULT_TEST_FREQUENCY = 5035
192-#only sample a signal when peak level is in this range (in dB attenuation,
193-#0 means no attenuation (and horrible clipping).
194+# only sample a signal when peak level is in this range (in dB attenuation,
195+# 0 means no attenuation (and horrible clipping).
196 REC_LEVEL_RANGE = (-2.0, -12.0)
197-#For our test signal to be considered present, it has to be this much higher
198-#than the base level (minimum magnitude). This is in dB.
199+# For our test signal to be considered present, it has to be this much higher
200+# than the base level (minimum magnitude). This is in dB.
201 MAGNITUDE_THRESHOLD = 2.5
202-#Volume for the sample tone (in %)
203+# Volume for the sample tone (in %)
204 PLAY_VOLUME = 70
205
206+
207 class PIDController(object):
208 """ A Proportional-Integrative-Derivative controller (PID) controls a
209 process's output to try to maintain a desired output value (known as
210@@ -141,7 +142,7 @@ class PAVolumeController(object):
211 'set-%s-volume' % (self.pa_types[self.type]),
212 str(self.identifier[0]),
213 str(int(volume)) + "%"]
214- if False == self.method(command):
215+ if not self.method(command):
216 return False
217 self._volume = volume
218 return True
219@@ -159,7 +160,7 @@ class PAVolumeController(object):
220 'set-%s-mute' % (self.pa_types[self.type]),
221 str(self.identifier[0]),
222 mute]
223- if False == self.method(command):
224+ if not self.method(command):
225 return False
226 return True
227
228@@ -187,10 +188,10 @@ class PAVolumeController(object):
229 return None
230 command = ['pactl', 'list', self.pa_types[type] + "s", 'short']
231
232- #Expect lines of this form (field separator is tab):
233- #<ID>\t<NAME>\t<MODULE>\t<SAMPLE_SPEC_WITH_SPACES>\t<STATE>
234- #What we need to return is the ID for the first element on this list
235- #that does not contain auto_null or monitor.
236+ # Expect lines of this form (field separator is tab):
237+ # <ID>\t<NAME>\t<MODULE>\t<SAMPLE_SPEC_WITH_SPACES>\t<STATE>
238+ # What we need to return is the ID for the first element on this list
239+ # that does not contain auto_null or monitor.
240 pa_info = self.method(command)
241 valid_elements = None
242
243@@ -203,17 +204,17 @@ class PAVolumeController(object):
244 self.logger.error("No valid PulseAudio elements"
245 " for %s" % (self.type))
246 return None
247- #We only need the pulseaudio numeric ID and long name for each element
248+ # We only need the pulseaudio numeric ID and long name for each element
249 valid_elements = [(int(e.split()[0]), e.split()[1])
250 for e in valid_elements]
251 return valid_elements[0]
252
253 def _pactl_output(self, command):
254- #This method mainly calls pactl (hence the name). Since pactl may
255- #return a failure if the audio layer is not yet initialized, we will
256- #try running a few times in case of failure. All our invocations of
257- #pactl should be "idempotent" so repeating them should not have
258- #any bad effects.
259+ # This method mainly calls pactl (hence the name). Since pactl may
260+ # return a failure if the audio layer is not yet initialized, we will
261+ # try running a few times in case of failure. All our invocations of
262+ # pactl should be "idempotent" so repeating them should not have
263+ # any bad effects.
264 for attempt in range(0, 3):
265 try:
266 return subprocess.check_output(command,
267@@ -242,8 +243,8 @@ class SpectrumAnalyzer(object):
268 self.number_of_samples = 0
269 self.wanted_samples = wanted_samples
270 self.sampling_frequency = sampling_frequency
271- #Frequencies should contain *real* frequency which is half of
272- #the sampling frequency
273+ # Frequencies should contain *real* frequency which is half of
274+ # the sampling frequency
275 self.frequencies = [((sampling_frequency / 2.0) / points) * i
276 for i in range(points)]
277
278@@ -259,14 +260,14 @@ class SpectrumAnalyzer(object):
279 self.number_of_samples += 1
280
281 def frequencies_with_peak_magnitude(self, threshold=1.0):
282- #First establish the base level
283+ # First establish the base level
284 per_magnitude_bins = collections.defaultdict(int)
285 for magnitude in self.spectrum:
286 per_magnitude_bins[magnitude] += 1
287 base_level = max(per_magnitude_bins,
288 key=lambda x: per_magnitude_bins[x])
289- #Now return all values that are higher (more positive)
290- #than base_level + threshold
291+ # Now return all values that are higher (more positive)
292+ # than base_level + threshold
293 peaks = []
294 for i in range(1, len(self.spectrum) - 1):
295 first_index = i - 1
296@@ -282,10 +283,10 @@ class SpectrumAnalyzer(object):
297 """Convenience function to tell me which band
298 a frequency is contained in
299 """
300- #Note that actual frequencies are half of what the sampling
301- #frequency would tell us. If SF is 44100 then maximum actual
302- #frequency is 22050, and if I have 10 frequency bins each will
303- #contain only 2205 Hz, not 4410 Hz.
304+ # Note that actual frequencies are half of what the sampling
305+ # frequency would tell us. If SF is 44100 then maximum actual
306+ # frequency is 22050, and if I have 10 frequency bins each will
307+ # contain only 2205 Hz, not 4410 Hz.
308 max_frequency = self.sampling_frequency / 2
309 if frequency > max_frequency or frequency < 0:
310 return None
311@@ -339,34 +340,33 @@ class GStreamerMessageHandler(object):
312 if message.type == Gst.MessageType.ELEMENT:
313 message_name = message.get_structure().get_name()
314 if message_name == 'spectrum':
315- #TODO: Due to an upstream bug, a structure's get_value method
316- #doesn't work if the value in question is an array (as is the
317- #case with the magnitudes).
318- #https://bugzilla.gnome.org/show_bug.cgi?id=693168
319- #We have to resort to parsing the string representation of the
320- #structure. It's an ugly hack but it works.
321- #Ideally we'd be able to say this to get fft_magnitudes:
322- #message.get_structure.get_value('magnitude').
323- #If an upstream fix ever makes it into gstreamer,
324- #remember to remove this hack and the parse_spectrum
325- #method
326+ # TODO: Due to an upstream bug, a structure's get_value method
327+ # doesn't work if the value in question is an array (as is the
328+ # case with the magnitudes).
329+ # https://bugzilla.gnome.org/show_bug.cgi?id=693168
330+ # We have to resort to parsing the string representation of the
331+ # structure. It's an ugly hack but it works.
332+ # Ideally we'd be able to say this to get fft_magnitudes:
333+ # message.get_structure.get_value('magnitude').
334+ # If an upstream fix ever makes it into gstreamer,
335+ # remember to remove this hack and the parse_spectrum method
336 struct_string = message.get_structure().to_string()
337 structure = parse_spectrum_message_structure(struct_string)
338 fft_magnitudes = structure['magnitude']
339 self.spectrum_method(self.spectrum_analyzer, fft_magnitudes)
340
341 if message_name == 'level':
342- #peak_value is our process feedback
343- #It's returned as an array, so I need the first (and only)
344- #element
345+ # peak_value is our process feedback
346+ # It's returned as an array, so I need the first (and only)
347+ # element
348 peak_value = message.get_structure().get_value('peak')[0]
349 self.level_method(peak_value, self.pid_controller,
350 self.volume_controller)
351
352- #Adjust recording level
353+ # Adjust recording level
354 def level_method(self, level, pid_controller, volume_controller):
355- #If volume controller doesn't return a valid volume,
356- #we can't control it :(
357+ # If volume controller doesn't return a valid volume,
358+ # we can't control it :(
359 current_volume = volume_controller.get_volume()
360 if current_volume is None:
361 self.logger.error("Unable to control recording volume."
362@@ -375,19 +375,20 @@ class GStreamerMessageHandler(object):
363 self.current_level = level
364 change = pid_controller.input_change(level, 0.10)
365 if self.logger:
366- self.logger.debug("Peak level: %(peak_level).2f, "
367- "volume: %(volume)d%%, Volume change: %(change)f%%" %
368- {'peak_level': level,
369- 'change': change,
370- 'volume': current_volume})
371+ self.logger.debug(
372+ "Peak level: %(peak_level).2f, "
373+ "volume: %(volume)d%%, Volume change: %(change)f%%" % {
374+ 'peak_level': level,
375+ 'change': change,
376+ 'volume': current_volume})
377 volume_controller.set_volume(current_volume + change)
378
379- #Only sample if level is within the threshold
380+ # Only sample if level is within the threshold
381 def spectrum_method(self, analyzer, spectrum):
382 if self.rec_level_range[1] <= self.current_level \
383 or self.current_level <= self.rec_level_range[0]:
384- self.logger.debug("Sampling, recorded %d samples" %
385- analyzer.number_of_samples)
386+ self.logger.debug(
387+ "Sampling, recorded %d samples" % analyzer.number_of_samples)
388 analyzer.sample(spectrum)
389 if analyzer.sampling_complete() and self._quit_method:
390 self.logger.info("Sampling complete, ending process")
391@@ -414,10 +415,11 @@ class GstAudioObject(object):
392 class Player(GstAudioObject):
393 def __init__(self, frequency=DEFAULT_TEST_FREQUENCY, logger=None):
394 super(Player, self).__init__()
395- self.pipeline_description = ("audiotestsrc wave=sine freq=%s "
396- "! audioconvert "
397- "! audioresample "
398- "! autoaudiosink" % int(frequency))
399+ self.pipeline_description = (
400+ "audiotestsrc wave=sine freq=%s "
401+ "! audioconvert "
402+ "! audioresample "
403+ "! autoaudiosink" % int(frequency))
404 self.logger = logger
405 if self.logger:
406 self.logger.debug(self.pipeline_description)
407@@ -437,11 +439,11 @@ class Recorder(GstAudioObject):
408 ! audioresample
409 ! spectrum interval=%(fft_interval)s bands = %(bands)s
410 ! wavenc
411- ! filesink location=%(file)s''' %
412- {'bands': bins,
413- 'rate': sampling_frequency,
414- 'fft_interval': fft_interval,
415- 'file': output_file})
416+ ! filesink location=%(file)s''' % {
417+ 'bands': bins,
418+ 'rate': sampling_frequency,
419+ 'fft_interval': fft_interval,
420+ 'file': output_file})
421 self.logger = logger
422 if self.logger:
423 self.logger.debug(pipeline_description)
424@@ -457,25 +459,25 @@ class Recorder(GstAudioObject):
425
426
427 def parse_spectrum_message_structure(struct_string):
428- #First let's jsonize this
429- #This is the message name, which we don't need
430+ # First let's jsonize this
431+ # This is the message name, which we don't need
432 text = struct_string.replace("spectrum, ", "")
433- #name/value separator in json is : and not =
434- text = text.replace("=",": ")
435- #Mutate the {} array notation from the structure to
436- #[] notation for json.
437- text = text.replace("{","[")
438- text = text.replace("}","]")
439- #Remove a few stray semicolons that aren't needed
440- text = text.replace(";","")
441- #Remove the data type fields, as json doesn't need them
442+ # name/value separator in json is : and not =
443+ text = text.replace("=", ": ")
444+ # Mutate the {} array notation from the structure to
445+ # [] notation for json.
446+ text = text.replace("{", "[")
447+ text = text.replace("}", "]")
448+ # Remove a few stray semicolons that aren't needed
449+ text = text.replace(";", "")
450+ # Remove the data type fields, as json doesn't need them
451 text = re.sub(r"\(.+?\)", "", text)
452- #double-quote the identifiers
453+ # double-quote the identifiers
454 text = re.sub(r"([\w-]+):", r'"\1":', text)
455- #Wrap the whole thing in brackets
456+ # Wrap the whole thing in brackets
457 text = ("{"+text+"}")
458- #Try to parse and return something sensible here, even if
459- #the data was unparsable.
460+ # Try to parse and return something sensible here, even if
461+ # the data was unparsable.
462 try:
463 return json.loads(text)
464 except ValueError:
465@@ -489,32 +491,38 @@ def process_arguments():
466 presence of the played frequency, if present it exits with success.
467 """
468 parser = argparse.ArgumentParser(description=description)
469- parser.add_argument("-t", "--time",
470+ parser.add_argument(
471+ "-t", "--time",
472 dest='test_duration',
473 action='store',
474 default=30,
475 type=int,
476 help="""Maximum test duration, default %(default)s seconds.
477 It may exit sooner if it determines it has enough data.""")
478- parser.add_argument("-a", "--audio",
479+ parser.add_argument(
480+ "-a", "--audio",
481 action='store',
482 default="/dev/null",
483 type=str,
484 help="File to save recorded audio in .wav format")
485- parser.add_argument("-q", "--quiet",
486+ parser.add_argument(
487+ "-q", "--quiet",
488 action='store_true',
489 default=False,
490 help="Be quiet, no output unless there's an error.")
491- parser.add_argument("-d", "--debug",
492+ parser.add_argument(
493+ "-d", "--debug",
494 action='store_true',
495 default=False,
496 help="Debugging output")
497- parser.add_argument("-f", "--frequency",
498+ parser.add_argument(
499+ "-f", "--frequency",
500 action='store',
501 default=DEFAULT_TEST_FREQUENCY,
502 type=int,
503 help="Frequency for test signal, default %(default)s Hz")
504- parser.add_argument("-u", "--spectrum",
505+ parser.add_argument(
506+ "-u", "--spectrum",
507 action='store',
508 type=str,
509 help="""File to save spectrum information for plotting
510@@ -524,10 +532,10 @@ def process_arguments():
511
512 #
513 def main():
514- #Get arguments.
515+ # Get arguments.
516 args = process_arguments()
517
518- #Setup logging
519+ # Setup logging
520 level = logging.INFO
521 if args.debug:
522 level = logging.DEBUG
523@@ -535,56 +543,57 @@ def main():
524 level = logging.ERROR
525 logging.basicConfig(level=level)
526 try:
527- #Launches recording pipeline. I need to hook up into the gst
528- #messages.
529+ # Launches recording pipeline. I need to hook up into the gst
530+ # messages.
531 recorder = Recorder(output_file=args.audio, logger=logging)
532- #Just launches the playing pipeline
533+ # Just launches the playing pipeline
534 player = Player(frequency=args.frequency, logger=logging)
535 except GObject.GError as excp:
536 logging.critical("Unable to initialize GStreamer pipelines: %s", excp)
537 sys.exit(127)
538
539- #This just receives a process feedback and tells me how much to change to
540- #achieve the setpoint
541+ # This just receives a process feedback and tells me how much to change to
542+ # achieve the setpoint
543 pidctrl = PIDController(Kp=0.7, Ki=.01, Kd=0.01,
544 setpoint=REC_LEVEL_RANGE[0])
545 pidctrl.set_change_limit(5)
546- #This gathers spectrum data.
547+ # This gathers spectrum data.
548 analyzer = SpectrumAnalyzer(points=BINS,
549 sampling_frequency=SAMPLING_FREQUENCY)
550
551- #Volume controllers actually set volumes for their device types.
552- #we should at least issue a warning
553+ # Volume controllers actually set volumes for their device types.
554+ # we should at least issue a warning
555 recorder.volumecontroller = PAVolumeController(type='input',
556 logger=logging)
557 if not recorder.volumecontroller.get_identifier():
558- logging.warning("Unable to get input volume control identifier. "
559- "Test results will probably be invalid")
560+ logging.warning(
561+ "Unable to get input volume control identifier. "
562+ "Test results will probably be invalid")
563 recorder.volumecontroller.set_volume(0)
564 recorder.volumecontroller.mute(False)
565
566 player.volumecontroller = PAVolumeController(type='output',
567 logger=logging)
568 if not player.volumecontroller.get_identifier():
569- logging.warning("Unable to get output volume control identifier. "
570- "Test results will probably be invalid")
571+ logging.warning(
572+ "Unable to get output volume control identifier. "
573+ "Test results will probably be invalid")
574 player.volumecontroller.set_volume(PLAY_VOLUME)
575 player.volumecontroller.mute(False)
576
577- #This handles the messages from gstreamer and orchestrates
578- #the passed volume controllers, pid controller and spectrum analyzer
579- #accordingly.
580+ # This handles the messages from gstreamer and orchestrates
581+ # the passed volume controllers, pid controller and spectrum analyzer
582+ # accordingly.
583 gmh = GStreamerMessageHandler(rec_level_range=REC_LEVEL_RANGE,
584 logger=logging,
585 volumecontroller=recorder.volumecontroller,
586 pidcontroller=pidctrl,
587 spectrum_analyzer=analyzer)
588
589- #I need to tell the recorder which method will handle messages.
590+ # I need to tell the recorder which method will handle messages.
591 recorder.register_message_handler(gmh.bus_message_handler)
592
593- #Create the loop and add a few triggers
594-# GObject.threads_init() #Not needed?
595+ # Create the loop and add a few triggers
596 loop = GLib.MainLoop()
597 GLib.timeout_add_seconds(0, player.start)
598 GLib.timeout_add_seconds(0, recorder.start)
599@@ -595,29 +604,32 @@ def main():
600
601 loop.run()
602
603- #When the loop ends, set things back to reasonable states
604+ # When the loop ends, set things back to reasonable states
605 player.stop()
606 recorder.stop()
607 player.volumecontroller.set_volume(50)
608 recorder.volumecontroller.set_volume(10)
609
610- #See if data gathering was successful.
611+ # See if data gathering was successful.
612 test_band = analyzer.frequency_band_for(args.frequency)
613- candidate_bands = analyzer.frequencies_with_peak_magnitude(MAGNITUDE_THRESHOLD)
614+ candidate_bands = analyzer.frequencies_with_peak_magnitude(
615+ MAGNITUDE_THRESHOLD)
616 for band in candidate_bands:
617 logging.debug("Band (%.2f,%.2f) contains a magnitude peak" %
618 analyzer.frequencies_for_band(band))
619 if test_band in candidate_bands:
620 freqs_for_band = analyzer.frequencies_for_band(test_band)
621- logging.info("PASS: Test frequency of %s in band (%.2f, %.2f) "
622- "which contains a magnitude peak" %
623+ logging.info(
624+ "PASS: Test frequency of %s in band (%.2f, %.2f) "
625+ "which contains a magnitude peak" %
626 ((args.frequency,) + freqs_for_band))
627 return_value = 0
628 else:
629- logging.info("FAIL: Test frequency of %s is not in one of the "
630- "bands with magnitude peaks" % args.frequency)
631+ logging.info(
632+ "FAIL: Test frequency of %s is not in one of the "
633+ "bands with magnitude peaks" % args.frequency)
634 return_value = 1
635- #Is the microphone broken?
636+ # Is the microphone broken?
637 if len(set(analyzer.spectrum)) <= 1:
638 logging.info("WARNING: Microphone seems broken, didn't even "
639 "record ambient noise")
640@@ -625,14 +637,17 @@ def main():
641 if args.spectrum:
642 logging.info("Saving spectrum data for plotting as %s" %
643 args.spectrum)
644- if not FileDumper().write_to_file(args.spectrum,
645- ["%s,%s" % t for t in
646- zip(analyzer.frequencies,
647- analyzer.spectrum)]):
648+ if (
649+ not FileDumper().write_to_file(
650+ args.spectrum,
651+ ["%s,%s" % t for t in zip(
652+ analyzer.frequencies, analyzer.spectrum)])
653+ ):
654 logging.error("Couldn't save spectrum data for plotting",
655 file=sys.stderr)
656
657 return return_value
658
659+
660 if __name__ == "__main__":
661 sys.exit(main())
662diff --git a/bin/battery_test.py b/bin/battery_test.py
663index b2682c7..112ef5e 100755
664--- a/bin/battery_test.py
665+++ b/bin/battery_test.py
666@@ -1,14 +1,13 @@
667 #!/usr/bin/env python3
668
669 import gi
670-import os
671 import time
672 import re
673 import subprocess
674 import sys
675 import argparse
676 gi.require_version('Gio', '2.0')
677-from gi.repository import Gio
678+from gi.repository import Gio # noqa: E402
679
680
681 class Battery():
682@@ -89,10 +88,10 @@ def get_battery_state():
683
684 def validate_battery_info(battery):
685 if battery is None:
686- print ("Error obtaining battery info")
687+ print("Error obtaining battery info")
688 return False
689 if battery._state != "discharging":
690- print ("Error: battery is not discharging, test will not be valid")
691+ print("Error: battery is not discharging, test will not be valid")
692 return False
693 return True
694
695@@ -173,5 +172,6 @@ def main():
696
697 return(battery_life(battery_before, battery_after, test_time))
698
699+
700 if __name__ == "__main__":
701 sys.exit(main())
702diff --git a/bin/bluetooth_test.py b/bin/bluetooth_test.py
703index 8fafad6..fd3c956 100755
704--- a/bin/bluetooth_test.py
705+++ b/bin/bluetooth_test.py
706@@ -145,5 +145,6 @@ def main():
707 format='%(levelname)s: %(message)s')
708 return getattr(ObexFTPTest(args.file.name, args.btaddr), args.action)()
709
710+
711 if __name__ == "__main__":
712 sys.exit(main())
713diff --git a/bin/bmc_info.py b/bin/bmc_info.py
714index d7aec9b..674d7e8 100755
715--- a/bin/bmc_info.py
716+++ b/bin/bmc_info.py
717@@ -4,6 +4,7 @@ import sys
718 import shlex
719 from subprocess import check_output, CalledProcessError
720
721+
722 def main():
723 # First, we need to get output
724 cmd = "ipmitool mc info"
725@@ -14,7 +15,7 @@ def main():
726 file=sys.stderr)
727 return 1
728 except CalledProcessError as e:
729- print("Problem running %s. Error was %s" % (cmd,e),file=sys.stderr)
730+ print("Problem running %s. Error was %s" % (cmd, e), file=sys.stderr)
731 return 1
732 result = result.split('\n')
733
734@@ -47,12 +48,11 @@ def main():
735 if type(data[field]) is list:
736 # Sometimes the first item in the list is ''. This will remove it
737 data[field].remove('')
738- print(field.ljust(30),':',data[field].pop(0))
739+ print(field.ljust(30), ':', data[field].pop(0))
740 for item in data[field]:
741- print(' '.ljust(32),item)
742+ print(' '.ljust(32), item)
743 else:
744- print(field.ljust(30),":",data[field])
745- #print("{}:\t{}".format(field, data[field]))
746+ print(field.ljust(30), ":", data[field])
747
748 return 0
749
750diff --git a/bin/boot_mode_test_snappy.py b/bin/boot_mode_test_snappy.py
751index 864be29..23b30e4 100755
752--- a/bin/boot_mode_test_snappy.py
753+++ b/bin/boot_mode_test_snappy.py
754@@ -14,7 +14,6 @@ import tempfile
755
756 import yaml
757
758-from checkbox_support.parsers.kernel_cmdline import parse_kernel_cmdline
759 from checkbox_support.snap_utils.system import get_lk_bootimg_path
760
761
762diff --git a/bin/brightness_test.py b/bin/brightness_test.py
763index 52d478a..e3a8e90 100755
764--- a/bin/brightness_test.py
765+++ b/bin/brightness_test.py
766@@ -28,7 +28,6 @@ import sys
767 import os
768 import time
769
770-from sys import stdout, stderr
771 from glob import glob
772
773
774@@ -42,7 +41,7 @@ class Brightness(object):
775 # See if the source is a file or a file object
776 # and act accordingly
777 file = path
778- if file == None:
779+ if file is None:
780 lines_list = []
781 else:
782 # It's a file
783@@ -102,8 +101,10 @@ class Brightness(object):
784 Note: this doesn't guarantee that screen brightness
785 changed.
786 '''
787- if (abs(self.get_actual_brightness(interface) -
788- self.get_last_set_brightness(interface)) > 1):
789+ if (
790+ abs(self.get_actual_brightness(interface) -
791+ self.get_last_set_brightness(interface)) > 1
792+ ):
793 return 1
794 else:
795 return 0
796@@ -132,9 +133,9 @@ def main():
797 max_brightness = brightness.get_max_brightness(interface)
798
799 # Set the brightness to half the max value
800- brightness.write_value(max_brightness / 2,
801- os.path.join(interface,
802- 'brightness'))
803+ brightness.write_value(
804+ max_brightness / 2,
805+ os.path.join(interface, 'brightness'))
806
807 # Check that "actual_brightness" reports the same value we
808 # set "brightness" to
809@@ -144,9 +145,9 @@ def main():
810 time.sleep(2)
811
812 # Set the brightness back to its original value
813- brightness.write_value(current_brightness,
814- os.path.join(interface,
815- 'brightness'))
816+ brightness.write_value(
817+ current_brightness,
818+ os.path.join(interface, 'brightness'))
819
820 exit(exit_status)
821
822diff --git a/bin/bt_connect.py b/bin/bt_connect.py
823index 1fed30e..8d6757c 100755
824--- a/bin/bt_connect.py
825+++ b/bin/bt_connect.py
826@@ -131,5 +131,6 @@ def main():
827 # capture all other silence failures
828 return 1
829
830+
831 if __name__ == "__main__":
832 sys.exit(main())
833diff --git a/bin/bt_list_adapters.py b/bin/bt_list_adapters.py
834index e791442..c8db787 100755
835--- a/bin/bt_list_adapters.py
836+++ b/bin/bt_list_adapters.py
837@@ -38,7 +38,7 @@ def main():
838 with open(namef, 'r') as f:
839 name = f.read().strip()
840 print(rfdev, name)
841- if found_adatper == False:
842+ if found_adatper is False:
843 raise SystemExit('No bluetooth adatpers registered with rfkill')
844
845
846diff --git a/bin/color_depth_info.py b/bin/color_depth_info.py
847index 129f051..fcab953 100755
848--- a/bin/color_depth_info.py
849+++ b/bin/color_depth_info.py
850@@ -53,7 +53,7 @@ def get_color_depth(log_dir='/var/log/'):
851 return (depth, pixmap_format)
852
853 with open(current_log, 'rb') as stream:
854- for match in re.finditer('Depth (\d+) pixmap format is (\d+) bpp',
855+ for match in re.finditer(r'Depth (\d+) pixmap format is (\d+) bpp',
856 str(stream.read())):
857 depth = int(match.group(1))
858 pixmap_format = int(match.group(2))
859@@ -72,5 +72,6 @@ def main():
860 return 1
861 return 0
862
863+
864 if __name__ == '__main__':
865 sys.exit(main())
866diff --git a/bin/cpu_offlining.py b/bin/cpu_offlining.py
867index 5616e30..3d269ac 100755
868--- a/bin/cpu_offlining.py
869+++ b/bin/cpu_offlining.py
870@@ -68,5 +68,6 @@ def main():
871 print(' '.join(failed_onlines))
872 return 1
873
874+
875 if __name__ == '__main__':
876 main()
877diff --git a/bin/cpu_topology.py b/bin/cpu_topology.py
878index 0ce68c5..425e3c4 100755
879--- a/bin/cpu_topology.py
880+++ b/bin/cpu_topology.py
881@@ -21,8 +21,8 @@ class proc_cpuinfo():
882 finally:
883 cpu_fh.close()
884
885- r_s390 = re.compile("processor [0-9]")
886- r_x86 = re.compile("processor\s+:")
887+ r_s390 = re.compile(r"processor [0-9]")
888+ r_x86 = re.compile(r"processor\s+:")
889 for i in temp:
890 # Handle s390 first
891 if r_s390.match(i):
892@@ -111,5 +111,6 @@ def main():
893 else:
894 return 0
895
896+
897 if __name__ == '__main__':
898 sys.exit(main())
899diff --git a/bin/cpuid.py b/bin/cpuid.py
900index d0cdea9..6543dc4 100755
901--- a/bin/cpuid.py
902+++ b/bin/cpuid.py
903@@ -25,10 +25,9 @@
904 # Modifications: 2019 Jeffrey Lane (jeffrey.lane@canonical.com)
905
906 import ctypes
907-import os
908 import platform
909 import sys
910-from ctypes import (c_uint32, c_int, c_long, c_ulong, c_size_t, c_void_p,
911+from ctypes import (c_uint32, c_int, c_size_t, c_void_p,
912 POINTER, CFUNCTYPE)
913 from subprocess import check_output
914
915@@ -84,7 +83,8 @@ CPUIDS = {
916 "Broadwell": ['0x4067', '0x306d4', '0x5066', '0x406f'],
917 "Canon Lake": ['0x6066'],
918 "Cascade Lake": ['0x50655', '0x50656', '0x50657'],
919- "Coffee Lake": ['0x806ea', '0x906ea', '0x906eb', '0x906ec', '0x906ed'],
920+ "Coffee Lake": [
921+ '0x806ea', '0x906ea', '0x906eb', '0x906ec', '0x906ed'],
922 "Haswell": ['0x306c', '0x4065', '0x4066', '0x306f'],
923 "Ice Lake": ['0x706e'],
924 "Ivy Bridge": ['0x306a', '0x306e'],
925diff --git a/bin/create_connection.py b/bin/create_connection.py
926index 71e9572..9dc977e 100755
927--- a/bin/create_connection.py
928+++ b/bin/create_connection.py
929@@ -6,9 +6,8 @@ import time
930
931 from subprocess import check_call, check_output, CalledProcessError
932 try:
933- from subprocess import DEVNULL # >= python3.3
934+ from subprocess import DEVNULL # >= python3.3
935 except ImportError:
936- import os
937 DEVNULL = open(os.devnull, 'wb')
938
939 from uuid import uuid4
940@@ -154,7 +153,7 @@ def block_until_created(connection, retries, interval):
941 sys.exit(1)
942 else:
943 try:
944- nmcli_con_up = check_call(['nmcli', 'con', 'up', 'id', connection])
945+ check_call(['nmcli', 'con', 'up', 'id', connection])
946 print("Connection %s activated." % connection)
947 except CalledProcessError as error:
948 print("Failed to activate %s." % connection, file=sys.stderr)
949@@ -168,8 +167,8 @@ def write_connection_file(name, connection_info):
950 os.fchmod(connection_file.fileno(), 0o600)
951 connection_file.close()
952 except IOError:
953- print("Can't write to " + CONNECTIONS_PATH + name
954- + ". Is this command being run as root?", file=sys.stderr)
955+ print("Can't write to " + CONNECTIONS_PATH + name +
956+ ". Is this command being run as root?", file=sys.stderr)
957 sys.exit(1)
958
959
960@@ -216,7 +215,7 @@ def create_mobilebroadband_connection(args):
961 args.apn,
962 args.username,
963 args.password,
964- args.pin)
965+ args.pin)
966
967 if args.type == 'cdma':
968 mobilebroadband_connection += mobilebroadband_ppp_section()
969@@ -288,5 +287,6 @@ def main():
970 # Make sure we don't exit until the connection is fully created
971 block_until_created(connection_name, args.retries, args.interval)
972
973+
974 if __name__ == "__main__":
975 main()
976diff --git a/bin/dmitest.py b/bin/dmitest.py
977index 642af3a..2be50cc 100755
978--- a/bin/dmitest.py
979+++ b/bin/dmitest.py
980@@ -146,26 +146,26 @@ def standard_tests(args, stream, dmi_data):
981 if find_in_section(stream, dmi_data, 'Chassis Information',
982 'Manufacturer:',
983 ['empty', 'chassis manufacture', 'null', 'insyde',
984- 'to be filled by o\.e\.m\.', 'no enclosure',
985- '\.\.\.\.\.'], True):
986+ r'to be filled by o\.e\.m\.', 'no enclosure',
987+ r'\.\.\.\.\.'], True):
988 dmi_data['Chassis Information']['Manufacturer'] += \
989 " *** Invalid chassis manufacturer!"
990 retval += 1
991 if find_in_section(stream, dmi_data, 'System Information', 'Manufacturer:',
992 ['system manufacture', 'insyde', 'standard',
993- 'to be filled by o\.e\.m\.', 'no enclosure'], True):
994+ r'to be filled by o\.e\.m\.', 'no enclosure'], True):
995 dmi_data['System Information']['Manufacturer'] += \
996 " *** Invalid system manufacturer!"
997 retval += 1
998 if find_in_section(stream, dmi_data, 'Base Board Information',
999 'Manufacturer:',
1000- ['to be filled by o\.e\.m\.'], True):
1001+ [r'to be filled by o\.e\.m\.'], True):
1002 dmi_data['Base Board Information']['Manufacturer'] += \
1003 " *** Invalid base board manufacturer!"
1004 retval += 1
1005 if find_in_section(stream, dmi_data, 'System Information',
1006 'Product Name:',
1007- ['system product name', 'to be filled by o\.e\.m\.'],
1008+ ['system product name', r'to be filled by o\.e\.m\.'],
1009 False):
1010 dmi_data['System Information']['Product Name'] += \
1011 " *** Invalid system product name!"
1012@@ -173,7 +173,7 @@ def standard_tests(args, stream, dmi_data):
1013 if find_in_section(stream, dmi_data, 'Base Board Information',
1014 'Product Name:',
1015 ['base board product name',
1016- 'to be filled by o\.e\.m\.'], False):
1017+ r'to be filled by o\.e\.m\.'], False):
1018 dmi_data['Base Board Information']['Product Name'] += \
1019 " *** Invalid base board product name!"
1020 retval += 1
1021@@ -193,21 +193,21 @@ def version_tests(args, stream, dmi_data):
1022 """
1023 retval = 0
1024 if find_in_section(stream, dmi_data, 'Chassis Information', 'Version:',
1025- ['to be filled by o\.e\.m\.', 'empty', 'x\.x'],
1026+ [r'to be filled by o\.e\.m\.', 'empty', r'x\.x'],
1027 False):
1028 dmi_data['Chassis Information']['Version'] += \
1029 " *** Invalid chassis version!"
1030 retval += 1
1031 if find_in_section(stream, dmi_data, 'System Information', 'Version:',
1032- ['to be filled by o\.e\.m\.', '\(none\)',
1033+ [r'to be filled by o\.e\.m\.', r'\(none\)',
1034 'null', 'system version', 'not applicable',
1035- '\.\.\.\.\.'], False):
1036+ r'\.\.\.\.\.'], False):
1037 dmi_data['System Information']['Version'] += \
1038 " *** Invalid system information version!"
1039 retval += 1
1040 if find_in_section(stream, dmi_data, 'Base Board Information', 'Version:',
1041- ['base board version', 'x\.x',
1042- 'empty', 'to be filled by o\.e\.m\.'], False):
1043+ ['base board version', r'x\.x',
1044+ 'empty', r'to be filled by o\.e\.m\.'], False):
1045 dmi_data['Base Board Information']['Version'] += \
1046 " *** Invalid base board version!"
1047 retval += 1
1048@@ -228,8 +228,8 @@ def serial_tests(args, stream, dmi_data):
1049 retval = 0
1050 if find_in_section(stream, dmi_data, 'System Information',
1051 'Serial Number:',
1052- ['to be filled by o\.e\.m\.',
1053- 'system serial number', '\.\.\.\.\.'],
1054+ [r'to be filled by o\.e\.m\.',
1055+ 'system serial number', r'\.\.\.\.\.'],
1056 False):
1057 dmi_data['System Information']['Serial Number'] += \
1058 " *** Invalid system information serial number!"
1059@@ -237,8 +237,8 @@ def serial_tests(args, stream, dmi_data):
1060 if find_in_section(stream, dmi_data, 'Base Board Information',
1061 'Serial Number:',
1062 ['n/a', 'base board serial number',
1063- 'to be filled by o\.e\.m\.',
1064- 'empty', '\.\.\.'],
1065+ r'to be filled by o\.e\.m\.',
1066+ 'empty', r'\.\.\.'],
1067 False):
1068 dmi_data['Base Board Information']['Serial Number'] += \
1069 " *** Invalid base board serial number!"
1070@@ -306,7 +306,7 @@ def main():
1071 if args.test_serials:
1072 retval += serial_tests(args, stream, dmi_data)
1073 if find_in_section(stream, dmi_data, 'Processor Information', 'Version:',
1074- ['sample', 'Genuine Intel\(R\) CPU 0000'], False):
1075+ ['sample', r'Genuine Intel\(R\) CPU 0000'], False):
1076 dmi_data['Processor Information']['Version'] += \
1077 " *** Invalid processor information!"
1078 retval += 1
1079diff --git a/bin/edid_cycle.py b/bin/edid_cycle.py
1080index a6daf1c..e327cb0 100755
1081--- a/bin/edid_cycle.py
1082+++ b/bin/edid_cycle.py
1083@@ -21,7 +21,7 @@ def check_resolution():
1084 output = subprocess.check_output('xdpyinfo')
1085 for line in output.decode(sys.stdout.encoding).splitlines():
1086 if 'dimensions' in line:
1087- match = re.search('(\d+)x(\d+)\ pixels', line)
1088+ match = re.search(r'(\d+)x(\d+)\ pixels', line)
1089 if match and len(match.groups()) == 2:
1090 return '{}x{}'.format(*match.groups())
1091
1092@@ -29,7 +29,8 @@ def check_resolution():
1093 def change_edid(host, edid_file):
1094 with open(edid_file, 'rb') as f:
1095 cmd = ['ssh', host, '/snap/bin/pigbox', 'run',
1096- '\'v4l2-ctl --set-edid=file=-,format=raw --fix-edid-checksums\'']
1097+ '\'v4l2-ctl --set-edid=file=-,'
1098+ 'format=raw --fix-edid-checksums\'']
1099 subprocess.check_output(cmd, input=f.read())
1100
1101
1102@@ -52,5 +53,6 @@ def main():
1103 print('PASS')
1104 return failed
1105
1106+
1107 if __name__ == '__main__':
1108 raise SystemExit(main())
1109diff --git a/bin/evdev_touch_test.py b/bin/evdev_touch_test.py
1110index 5649701..bc52cc4 100755
1111--- a/bin/evdev_touch_test.py
1112+++ b/bin/evdev_touch_test.py
1113@@ -53,7 +53,7 @@ while True:
1114 for e in dev.read():
1115 tap = args.xfingers
1116 if tap == 1:
1117- if (e.type == 3 and e.code == 47 and e.value > 0):
1118+ if (e.type == 3 and e.code == 47 and e.value > 0):
1119 raise SystemExit(
1120 "Multitouch Event detected but Single was expected")
1121 # type 1 is evdev.ecodes.EV_KEY
1122diff --git a/bin/fan_reaction_test.py b/bin/fan_reaction_test.py
1123index a4ab744..c37054b 100755
1124--- a/bin/fan_reaction_test.py
1125+++ b/bin/fan_reaction_test.py
1126@@ -34,6 +34,7 @@ class FanMonitor:
1127 if not self._fan_paths:
1128 print('Fan monitoring interface not found in SysFS')
1129 raise SystemExit(0)
1130+
1131 def get_rpm(self):
1132 result = {}
1133 for p in self._fan_paths:
1134@@ -44,6 +45,7 @@ class FanMonitor:
1135 except OSError:
1136 print('Fan SysFS node dissappeared ({})'.format(p))
1137 return result
1138+
1139 def get_average_rpm(self, period):
1140 acc = self.get_rpm()
1141 for i in range(period):
1142@@ -83,14 +85,15 @@ class Stressor:
1143 def _stress_fun(self):
1144 """Actual stress function."""
1145 # generate some random data
1146- data = bytes(random.getrandbits(8) for _ in range(1024))
1147- hasher = hashlib.sha256()
1148+ data = bytes(random.getrandbits(8) for _ in range(1024))
1149+ hasher = hashlib.sha256()
1150 hasher.update(data)
1151 while True:
1152 new_digest = hasher.digest()
1153 # use the newly obtained digest as the new data to the hasher
1154 hasher.update(new_digest)
1155
1156+
1157 def main():
1158 """Entry point."""
1159
1160@@ -153,5 +156,6 @@ def main():
1161 if not (rpm_rose_during_stress and rpm_dropped_during_cooling):
1162 raise SystemExit("Fans did not react to stress expectedly")
1163
1164+
1165 if __name__ == '__main__':
1166 main()
1167diff --git a/bin/frequency_governors_test.py b/bin/frequency_governors_test.py
1168index 6072ded..fb652f5 100755
1169--- a/bin/frequency_governors_test.py
1170+++ b/bin/frequency_governors_test.py
1171@@ -8,7 +8,8 @@ import time
1172 import argparse
1173 import logging
1174
1175-from subprocess import check_output, check_call, CalledProcessError, PIPE
1176+from subprocess import check_output, check_call, CalledProcessError
1177+
1178
1179 class CPUScalingTest(object):
1180
1181@@ -37,11 +38,11 @@ class CPUScalingTest(object):
1182 for subdirectory in os.listdir(self.sysCPUDirectory):
1183 match = pattern.search(subdirectory)
1184 if match and match.group("cpuNumber"):
1185- cpufreqDirectory = os.path.join(self.sysCPUDirectory,
1186- subdirectory, "cpufreq")
1187+ cpufreqDirectory = os.path.join(
1188+ self.sysCPUDirectory, subdirectory, "cpufreq")
1189 if not os.path.exists(cpufreqDirectory):
1190- logging.error("CPU %s has no cpufreq directory %s"
1191- % (match.group("cpuNumber"), cpufreqDirectory))
1192+ logging.error("CPU %s has no cpufreq directory %s" % (
1193+ match.group("cpuNumber"), cpufreqDirectory))
1194 return None
1195 # otherwise
1196 self.cpufreqDirectories.append(cpufreqDirectory)
1197@@ -59,7 +60,8 @@ class CPUScalingTest(object):
1198 for cpufreqDirectory in self.cpufreqDirectories:
1199 parameters = self.getParameters(cpufreqDirectory, file)
1200 if not parameters:
1201- logging.error("Error: could not determine cpu parameters from %s"
1202+ logging.error(
1203+ "Error: could not determine cpu parameters from %s"
1204 % os.path.join(cpufreqDirectory, file))
1205 return None
1206 if not current:
1207@@ -91,7 +93,7 @@ class CPUScalingTest(object):
1208 return rf
1209 return None
1210
1211- logging.debug("Setting %s to %s" % (setFile,value))
1212+ logging.debug("Setting %s to %s" % (setFile, value))
1213 path = None
1214 if not skip:
1215 if automatch:
1216@@ -115,8 +117,9 @@ class CPUScalingTest(object):
1217 parameterFile = open(path)
1218 line = parameterFile.readline()
1219 if not line or line.strip() != str(value):
1220- logging.error("Error: could not verify that %s was set to %s"
1221- % (path, value))
1222+ logging.error(
1223+ "Error: could not verify that %s was set to %s" % (
1224+ path, value))
1225 if line:
1226 logging.error("Actual Value: %s" % line)
1227 else:
1228@@ -127,6 +130,7 @@ class CPUScalingTest(object):
1229
1230 def checkSelectorExecutable(self):
1231 logging.debug("Determining if %s is executable" % self.selectorExe)
1232+
1233 def is_exe(fpath):
1234 return os.path.exists(fpath) and os.access(fpath, os.X_OK)
1235
1236@@ -179,8 +183,9 @@ class CPUScalingTest(object):
1237 parameterFile = open(parameterFilePath)
1238 line = parameterFile.readline()
1239 if not line:
1240- logging.error("Error: failed to get %s for %s"
1241- % (parameter, self.cpufreqDirectory))
1242+ logging.error(
1243+ "Error: failed to get %s for %s" % (
1244+ parameter, self.cpufreqDirectory))
1245 return None
1246 value = line.strip()
1247 return value
1248@@ -198,8 +203,9 @@ class CPUScalingTest(object):
1249 parameterFile = open(path)
1250 line = parameterFile.readline()
1251 if not line:
1252- logging.error("Error: failed to get %s for %s"
1253- % (parameter, cpufreqDirectory))
1254+ logging.error(
1255+ "Error: failed to get %s for %s" % (
1256+ parameter, cpufreqDirectory))
1257 return None
1258 values.append(line.strip())
1259 logging.debug("Found parameters:")
1260@@ -231,15 +237,18 @@ class CPUScalingTest(object):
1261 runTime = stop_elapsed_time - start_elapsed_time
1262 else:
1263 thisTime = stop_elapsed_time - start_elapsed_time
1264- if ((abs(thisTime - runTime) / runTime) * 100
1265- < self.retryTolerance):
1266+ if (
1267+ (abs(thisTime - runTime) / runTime) * 100 <
1268+ self.retryTolerance
1269+ ):
1270 return runTime
1271 else:
1272 runTime = thisTime
1273 tries += 1
1274
1275- logging.error("Could not repeat load test times within %.1f%%"
1276- % self.retryTolerance)
1277+ logging.error(
1278+ "Could not repeat load test times within %.1f%%" %
1279+ self.retryTolerance)
1280 return None
1281
1282 def pi(self):
1283@@ -262,9 +271,11 @@ class CPUScalingTest(object):
1284 logging.info("Done.")
1285 minimumFrequency = self.getParameter("scaling_min_freq")
1286 currentFrequency = self.getParameter("scaling_cur_freq")
1287- if (not minimumFrequency
1288- or not currentFrequency
1289- or (minimumFrequency != currentFrequency)):
1290+ if (
1291+ not minimumFrequency or
1292+ not currentFrequency or
1293+ (minimumFrequency != currentFrequency)
1294+ ):
1295 return False
1296
1297 # otherwise
1298@@ -310,7 +321,8 @@ class CPUScalingTest(object):
1299 logging.info(" cpu%u: %s" % (i, g))
1300 i += 1
1301 else:
1302- logging.error("Error: could not determine current governor settings")
1303+ logging.error(
1304+ "Error: could not determine current governor settings")
1305 return False
1306
1307 self.getCPUFlags()
1308@@ -333,7 +345,7 @@ class CPUScalingTest(object):
1309 logging.debug("Found the following CPU Flags:")
1310 for line in self.cpuFlags:
1311 logging.debug(" %s" % line)
1312- except:
1313+ except OSError:
1314 logging.warning("Could not read CPU flags")
1315
1316 def runUserSpaceTests(self):
1317@@ -356,82 +368,103 @@ class CPUScalingTest(object):
1318
1319 # Set the the CPU speed to it's lowest value
1320 frequency = self.minFreq
1321- logging.info("Setting CPU frequency to %u MHz" % (int(frequency) / 1000))
1322+ logging.info(
1323+ "Setting CPU frequency to %u MHz" % (int(frequency) / 1000))
1324 if not self.setFrequency(frequency):
1325 success = False
1326
1327 # Verify the speed is set to the lowest value
1328 minimumFrequency = self.getParameter("scaling_min_freq")
1329 currentFrequency = self.getParameter("scaling_cur_freq")
1330- if (not minimumFrequency
1331- or not currentFrequency
1332- or (minimumFrequency != currentFrequency)):
1333- logging.error("Could not verify that cpu frequency is set to the minimum value of %s"
1334- % minimumFrequency)
1335+ if (
1336+ not minimumFrequency or
1337+ not currentFrequency or
1338+ (minimumFrequency != currentFrequency)
1339+ ):
1340+ logging.error(
1341+ "Could not verify that cpu frequency is set to the minimum"
1342+ " value of %s" % minimumFrequency)
1343 success = False
1344
1345 # Run Load Test
1346 self.minimumFrequencyTestTime = self.runLoadTest()
1347 if not self.minimumFrequencyTestTime:
1348- logging.error("Could not retrieve the minimum frequency test's execution time.")
1349+ logging.error(
1350+ "Could not retrieve the minimum frequency test's"
1351+ " execution time.")
1352 success = False
1353 else:
1354- logging.info("Minimum frequency load test time: %.2f"
1355- % self.minimumFrequencyTestTime)
1356+ logging.info(
1357+ "Minimum frequency load test time: %.2f"
1358+ % self.minimumFrequencyTestTime)
1359
1360 # Set the CPU speed to it's highest value as above.
1361 frequency = self.maxFreq
1362- logging.info("Setting CPU frequency to %u MHz" % (int(frequency) / 1000))
1363+ logging.info(
1364+ "Setting CPU frequency to %u MHz" % (int(frequency) / 1000))
1365 if not self.setFrequency(frequency):
1366 success = False
1367
1368 maximumFrequency = self.getParameter("scaling_max_freq")
1369 currentFrequency = self.getParameter("scaling_cur_freq")
1370- if (not maximumFrequency
1371- or not currentFrequency
1372- or (maximumFrequency != currentFrequency)):
1373- logging.error("Could not verify that cpu frequency is set to the maximum value of %s"
1374- % maximumFrequency)
1375+ if (
1376+ not maximumFrequency or
1377+ not currentFrequency or
1378+ (maximumFrequency != currentFrequency)
1379+ ):
1380+ logging.error(
1381+ "Could not verify that cpu frequency is set to the"
1382+ " maximum value of %s" % maximumFrequency)
1383 success = False
1384
1385 # Repeat workload test
1386 self.maximumFrequencyTestTime = self.runLoadTest()
1387 if not self.maximumFrequencyTestTime:
1388- logging.error("Could not retrieve the maximum frequency test's execution time.")
1389+ logging.error(
1390+ "Could not retrieve the maximum frequency test's "
1391+ "execution time.")
1392 success = False
1393 else:
1394- logging.info("Maximum frequency load test time: %.2f"
1395- % self.maximumFrequencyTestTime)
1396+ logging.info(
1397+ "Maximum frequency load test time: %.2f"
1398+ % self.maximumFrequencyTestTime)
1399
1400 # Verify MHz increase is comparable to time % decrease
1401- predictedSpeedup = (float(maximumFrequency)
1402- / float(minimumFrequency))
1403+ predictedSpeedup = (float(maximumFrequency) /
1404+ float(minimumFrequency))
1405
1406 # If "ida" turbo thing, increase the expectation by 8%
1407 if self.cpuFlags and self.idaFlag in self.cpuFlags:
1408- logging.info("Found %s flag, increasing expected speedup by %.1f%%"
1409- % (self.idaFlag, self.idaSpeedupFactor))
1410+ logging.info(
1411+ "Found %s flag, increasing expected speedup by %.1f%%"
1412+ % (self.idaFlag, self.idaSpeedupFactor))
1413 predictedSpeedup = \
1414- (predictedSpeedup
1415- * (1.0 / (1.0 - (self.idaSpeedupFactor / 100.0))))
1416+ (predictedSpeedup *
1417+ (1.0 / (1.0 - (self.idaSpeedupFactor / 100.0))))
1418
1419 if self.minimumFrequencyTestTime and self.maximumFrequencyTestTime:
1420- measuredSpeedup = (self.minimumFrequencyTestTime
1421- / self.maximumFrequencyTestTime)
1422+ measuredSpeedup = (self.minimumFrequencyTestTime /
1423+ self.maximumFrequencyTestTime)
1424 logging.info("CPU Frequency Speed Up: %.2f" % predictedSpeedup)
1425 logging.info("Measured Speed Up: %.2f" % measuredSpeedup)
1426- differenceSpeedUp = (((measuredSpeedup - predictedSpeedup) / predictedSpeedup) * 100)
1427- logging.info("Percentage Difference %.1f%%" % differenceSpeedUp)
1428+ differenceSpeedUp = (
1429+ ((measuredSpeedup - predictedSpeedup) / predictedSpeedup) *
1430+ 100)
1431+ logging.info(
1432+ "Percentage Difference %.1f%%" % differenceSpeedUp)
1433 if differenceSpeedUp > self.speedUpTolerance:
1434- logging.error("Measured speedup vs expected speedup is %.1f%% and is not within %.1f%% margin."
1435- % (differenceSpeedUp, self.speedUpTolerance))
1436+ logging.error(
1437+ "Measured speedup vs expected speedup is %.1f%% "
1438+ "and is not within %.1f%% margin."
1439+ % (differenceSpeedUp, self.speedUpTolerance))
1440 success = False
1441 elif differenceSpeedUp < 0:
1442- logging.info("""
1443- Measured speed up %.2f exceeded expected speedup %.2f
1444- """ % (measuredSpeedup, predictedSpeedup))
1445+ logging.info(
1446+ "Measured speed up %.2f exceeded expected speedup %.2f"
1447+ % (measuredSpeedup, predictedSpeedup))
1448 else:
1449- logging.error("Not enough timing data to calculate speed differences.")
1450+ logging.error(
1451+ "Not enough timing data to calculate speed differences.")
1452
1453 return success
1454
1455@@ -453,7 +486,9 @@ class CPUScalingTest(object):
1456 # Wait a fixed period of time, then verify current speed
1457 # is the slowest in as before
1458 if not self.verifyMinimumFrequency():
1459- logging.error("Could not verify that cpu frequency has settled to the minimum value")
1460+ logging.error(
1461+ "Could not verify that cpu frequency has settled to the "
1462+ "minimum value")
1463 success = False
1464
1465 # Repeat workload test
1466@@ -462,27 +497,33 @@ class CPUScalingTest(object):
1467 logging.warning("No On Demand load test time available.")
1468 success = False
1469 else:
1470- logging.info("On Demand load test time: %.2f" % onDemandTestTime)
1471+ logging.info(
1472+ "On Demand load test time: %.2f" % onDemandTestTime)
1473
1474 if onDemandTestTime and self.maximumFrequencyTestTime:
1475 # Compare the timing to the max results from earlier,
1476 # again time should be within self.speedUpTolerance
1477 differenceOnDemandVsMaximum = \
1478- (abs(onDemandTestTime - self.maximumFrequencyTestTime)
1479- / self.maximumFrequencyTestTime) * 100
1480- logging.info("Percentage Difference vs. maximum frequency: %.1f%%"
1481- % differenceOnDemandVsMaximum)
1482+ (abs(onDemandTestTime - self.maximumFrequencyTestTime) /
1483+ self.maximumFrequencyTestTime) * 100
1484+ logging.info(
1485+ "Percentage Difference vs. maximum frequency: %.1f%%"
1486+ % differenceOnDemandVsMaximum)
1487 if differenceOnDemandVsMaximum > self.speedUpTolerance:
1488- logging.error("On demand performance vs maximum of %.1f%% is not within %.1f%% margin"
1489- % (differenceOnDemandVsMaximum,
1490- self.speedUpTolerance))
1491+ logging.error(
1492+ "On demand performance vs maximum of %.1f%% is not "
1493+ "within %.1f%% margin"
1494+ % (differenceOnDemandVsMaximum, self.speedUpTolerance))
1495 success = False
1496 else:
1497- logging.error("Not enough timing data to calculate speed differences.")
1498+ logging.error(
1499+ "Not enough timing data to calculate speed differences.")
1500
1501 # Verify the current speed has returned to the lowest speed again
1502 if not self.verifyMinimumFrequency():
1503- logging.error("Could not verify that cpu frequency has settled to the minimum value")
1504+ logging.error(
1505+ "Could not verify that cpu frequency has settled to the "
1506+ "minimum value")
1507 success = False
1508
1509 return success
1510@@ -504,11 +545,14 @@ class CPUScalingTest(object):
1511 # Verify the current speed is the same as scaling_max_freq
1512 maximumFrequency = self.getParameter("scaling_max_freq")
1513 currentFrequency = self.getParameter("scaling_cur_freq")
1514- if (not maximumFrequency
1515- or not currentFrequency
1516- or (maximumFrequency != currentFrequency)):
1517- logging.error("Current cpu frequency of %s is not set to the maximum value of %s"
1518- % (currentFrequency, maximumFrequency))
1519+ if (
1520+ not maximumFrequency or
1521+ not currentFrequency or
1522+ (maximumFrequency != currentFrequency)
1523+ ):
1524+ logging.error(
1525+ "Current cpu frequency of %s is not set to the maximum "
1526+ "value of %s" % (currentFrequency, maximumFrequency))
1527 success = False
1528
1529 # Repeat work load test
1530@@ -517,22 +561,27 @@ class CPUScalingTest(object):
1531 logging.error("No Performance load test time available.")
1532 success = False
1533 else:
1534- logging.info("Performance load test time: %.2f" % performanceTestTime)
1535+ logging.info(
1536+ "Performance load test time: %.2f" % performanceTestTime)
1537
1538 if performanceTestTime and self.maximumFrequencyTestTime:
1539 # Compare the timing to the max results
1540 differencePerformanceVsMaximum = \
1541- (abs(performanceTestTime - self.maximumFrequencyTestTime)
1542- / self.maximumFrequencyTestTime) * 100
1543- logging.info("Percentage Difference vs. maximum frequency: %.1f%%"
1544- % differencePerformanceVsMaximum)
1545+ (abs(performanceTestTime - self.maximumFrequencyTestTime) /
1546+ self.maximumFrequencyTestTime) * 100
1547+ logging.info(
1548+ "Percentage Difference vs. maximum frequency: %.1f%%"
1549+ % differencePerformanceVsMaximum)
1550 if differencePerformanceVsMaximum > self.speedUpTolerance:
1551- logging.error("Performance setting vs maximum of %.1f%% is not within %.1f%% margin"
1552- % (differencePerformanceVsMaximum,
1553- self.speedUpTolerance))
1554+ logging.error(
1555+ "Performance setting vs maximum of %.1f%% is not "
1556+ "within %.1f%% margin"
1557+ % (differencePerformanceVsMaximum,
1558+ self.speedUpTolerance))
1559 success = False
1560 else:
1561- logging.error("Not enough timing data to calculate speed differences.")
1562+ logging.error(
1563+ "Not enough timing data to calculate speed differences.")
1564
1565 return success
1566
1567@@ -559,7 +608,9 @@ class CPUScalingTest(object):
1568 # Wait a fixed period of time,
1569 # then verify current speed is the slowest in as before
1570 if not self.verifyMinimumFrequency(10):
1571- logging.error("Could not verify that cpu frequency has settled to the minimum value")
1572+ logging.error(
1573+ "Could not verify that cpu frequency has settled "
1574+ "to the minimum value")
1575 success = False
1576
1577 # Set the frequency step to 0,
1578@@ -573,28 +624,35 @@ class CPUScalingTest(object):
1579 logging.error("No Conservative load test time available.")
1580 success = False
1581 else:
1582- logging.info("Conservative load test time: %.2f"
1583- % conservativeTestTime)
1584+ logging.info(
1585+ "Conservative load test time: %.2f"
1586+ % conservativeTestTime)
1587
1588 if conservativeTestTime and self.minimumFrequencyTestTime:
1589 # Compare the timing to the max results
1590 differenceConservativeVsMinimum = \
1591- (abs(conservativeTestTime - self.minimumFrequencyTestTime)
1592- / self.minimumFrequencyTestTime) * 100
1593- logging.info("Percentage Difference vs. minimum frequency: %.1f%%"
1594- % differenceConservativeVsMinimum)
1595+ (abs(conservativeTestTime -
1596+ self.minimumFrequencyTestTime) /
1597+ self.minimumFrequencyTestTime) * 100
1598+ logging.info(
1599+ "Percentage Difference vs. minimum frequency: %.1f%%"
1600+ % differenceConservativeVsMinimum)
1601 if differenceConservativeVsMinimum > self.speedUpTolerance:
1602- logging.error("Performance setting vs minimum of %.1f%% is not within %.1f%% margin"
1603- % (differenceConservativeVsMinimum,
1604- self.speedUpTolerance))
1605+ logging.error(
1606+ "Performance setting vs minimum of %.1f%% is not "
1607+ "within %.1f%% margin"
1608+ % (differenceConservativeVsMinimum,
1609+ self.speedUpTolerance))
1610 success = False
1611 else:
1612- logging.error("Not enough timing data to calculate speed differences.")
1613+ logging.error(
1614+ "Not enough timing data to calculate speed differences.")
1615
1616 return success
1617
1618 def restoreGovernors(self):
1619- logging.info("Restoring original governor to %s" % (self.originalGovernors[0]))
1620+ logging.info(
1621+ "Restoring original governor to %s" % (self.originalGovernors[0]))
1622 self.setGovernor(self.originalGovernors[0])
1623
1624
1625@@ -604,8 +662,9 @@ def main():
1626 help="Suppress output.")
1627 parser.add_argument("-c", "--capabilities", action="store_true",
1628 help="Only output CPU capabilities.")
1629- parser.add_argument("-d", "--debug", action="store_true",
1630- help="Turn on debug level output for extra info during test run.")
1631+ parser.add_argument(
1632+ "-d", "--debug", action="store_true",
1633+ help="Turn on debug level output for extra info during test run.")
1634 args = parser.parse_args()
1635
1636 # Set up the logging system (unless we don't want ANY logging)
1637@@ -614,11 +673,11 @@ def main():
1638 logger.setLevel(logging.DEBUG)
1639 format = '%(asctime)s %(levelname)-8s %(message)s'
1640 date_format = '%Y-%m-%d %H:%M:%S'
1641-
1642+
1643 # If we DO want console output
1644 if not args.quiet:
1645- console_handler = logging.StreamHandler() #logging.StreamHandler()
1646- console_handler.setFormatter(logging.Formatter(format,date_format))
1647+ console_handler = logging.StreamHandler()
1648+ console_handler.setFormatter(logging.Formatter(format, date_format))
1649 console_handler.setLevel(logging.INFO)
1650 logger.addHandler(console_handler)
1651
1652diff --git a/bin/fresh_rate_info.py b/bin/fresh_rate_info.py
1653index 43a8f2a..3089b48 100755
1654--- a/bin/fresh_rate_info.py
1655+++ b/bin/fresh_rate_info.py
1656@@ -38,13 +38,13 @@ def xrandr_paser(data=None):
1657 resolution = None
1658 xrandrs = list()
1659 for line in str(data).split('\n'):
1660- for match in re.finditer('(.+) connected (\d+x\d+)\+', line):
1661+ for match in re.finditer(r'(.+) connected (\d+x\d+)\+', line):
1662 connector = match.group(1)
1663 resolution = match.group(2)
1664 break
1665 if resolution is None:
1666 continue
1667- for match in re.finditer('{0}\s+(.+)\*'.format(resolution),
1668+ for match in re.finditer(r'{0}\s+(.+)\*'.format(resolution),
1669 line):
1670 refresh_rate = match.group(1)
1671 xrandr = {'connector': connector,
1672@@ -72,5 +72,6 @@ def main():
1673 xrandr['resolution'],
1674 xrandr['refresh_rate']))
1675
1676+
1677 if __name__ == '__main__':
1678 sys.exit(main())
1679diff --git a/bin/get_make_and_model.py b/bin/get_make_and_model.py
1680index 496a949..42fb219 100755
1681--- a/bin/get_make_and_model.py
1682+++ b/bin/get_make_and_model.py
1683@@ -1,26 +1,28 @@
1684 #!/usr/bin/env python3
1685
1686-import os.path
1687 import shlex
1688 from subprocess import check_output
1689
1690+
1691 def print_header(value):
1692 print("{}:".format(value))
1693
1694+
1695 def print_data(key, value):
1696 print(" {}: {}".format(key, value))
1697
1698+
1699 def run_cmd(option):
1700 cmd = "lshw -C " + option
1701- out = check_output(shlex.split(cmd),
1702- universal_newlines = True)
1703+ out = check_output(shlex.split(cmd), universal_newlines=True)
1704 return out.split('\n')
1705
1706+
1707 def main():
1708 keys = {'Manufacturer': 'vendor',
1709 'Model': 'product',
1710 'Version': 'version'}
1711- lshw_classes = {'system': 'System',
1712+ lshw_classes = {'system': 'System',
1713 'bus': 'Mainboard'}
1714
1715 for lshw_class in lshw_classes:
1716@@ -38,6 +40,6 @@ def main():
1717 for key in data:
1718 print_data(key, data[key])
1719
1720+
1721 if __name__ == "__main__":
1722 raise SystemExit(main())
1723-
1724diff --git a/bin/gpu_test.py b/bin/gpu_test.py
1725index 49ea31a..4f2af2e 100755
1726--- a/bin/gpu_test.py
1727+++ b/bin/gpu_test.py
1728@@ -30,9 +30,9 @@ import subprocess
1729 import sys
1730 import time
1731 gi.require_version('Gio', '2.0')
1732-from gi.repository import Gio
1733-from math import cos, sin
1734-from threading import Thread
1735+from gi.repository import Gio # noqa: E402
1736+from math import cos, sin # noqa: E402
1737+from threading import Thread # noqa: E402
1738
1739
1740 class GlxThread(Thread):
1741@@ -44,14 +44,13 @@ class GlxThread(Thread):
1742
1743 try:
1744 self.process = subprocess.Popen(
1745- ["glxgears","-geometry", "400x400"],
1746+ ["glxgears", "-geometry", "400x400"],
1747 stdout=subprocess.PIPE,
1748 stderr=subprocess.STDOUT)
1749 self.process.communicate()
1750 except (subprocess.CalledProcessError, FileNotFoundError) as er:
1751 print("WARNING: Unable to start glxgears (%s)" % er)
1752
1753-
1754 def terminate(self):
1755 if not hasattr(self, 'id'):
1756 print("WARNING: Attempted to terminate non-existing window.")
1757@@ -121,8 +120,8 @@ class Html5VideoThread(Thread):
1758 def html5_path(self):
1759 if os.getenv('PLAINBOX_PROVIDER_DATA'):
1760 return os.path.join(
1761- os.getenv('PLAINBOX_PROVIDER_DATA'),
1762- 'websites/html5_video.html')
1763+ os.getenv('PLAINBOX_PROVIDER_DATA'),
1764+ 'websites/html5_video.html')
1765
1766 def run(self):
1767 if self.html5_path and os.path.isfile(self.html5_path):
1768@@ -136,8 +135,8 @@ class Html5VideoThread(Thread):
1769 print("WARNING: test results may be invalid.")
1770
1771 def terminate(self):
1772- if self.html5_path and os.path.isfile(self.html5_path):
1773- subprocess.call("pkill firefox", shell=True)
1774+ if self.html5_path and os.path.isfile(self.html5_path):
1775+ subprocess.call("pkill firefox", shell=True)
1776
1777
1778 def check_gpu(log=None):
1779@@ -172,10 +171,10 @@ def main():
1780 print("WARNING: Got an exception %s" % er)
1781 windows = ""
1782 for app in sorted(windows.splitlines(), reverse=True):
1783- if not b'glxgears' in app:
1784+ if b'glxgears' not in app:
1785 continue
1786 GlxWindows[i].id = str(
1787- re.match(b'^(0x\w+)', app).group(0), 'utf-8')
1788+ re.match(b'^(0x\w+)', app).group(0), 'utf-8') # noqa: W605
1789 break
1790 if hasattr(GlxWindows[i], "id"):
1791 rotator = RotateGlxThread(GlxWindows[i].id, i + 1)
1792@@ -204,7 +203,7 @@ def main():
1793 'gconftool --get /apps/compiz-1/general/screen0/options/vsize',
1794 shell=True))
1795 (x_res, y_res) = re.search(
1796- b'DG:\s+(\d+)x(\d+)',
1797+ b'DG:\s+(\d+)x(\d+)', # noqa: W605
1798 subprocess.check_output('wmctrl -d', shell=True)).groups()
1799 DesktopSwitch = ChangeWorkspace(
1800 hsize, vsize, int(x_res) // hsize, int(y_res) // vsize)
1801@@ -230,5 +229,6 @@ def main():
1802 settings.set_int("vsize", vsize_ori)
1803 Gio.Settings.sync()
1804
1805+
1806 if __name__ == '__main__':
1807 sys.exit(main())
1808diff --git a/bin/graphic_memory_info.py b/bin/graphic_memory_info.py
1809index ba7eece..29040a5 100755
1810--- a/bin/graphic_memory_info.py
1811+++ b/bin/graphic_memory_info.py
1812@@ -42,13 +42,13 @@ def vgamem_paser(data=None):
1813 device = None
1814 vgamems = list()
1815 for line in data.split('\n'):
1816- for match in re.finditer('(\d\d:\d\d\.\d) VGA(.+): (.+)', line):
1817+ for match in re.finditer(r'(\d\d:\d\d\.\d) VGA(.+): (.+)', line):
1818 device = match.group(1)
1819 name = match.group(3)
1820 if device is None:
1821 continue
1822-#Memory at e0000000 (32-bit, prefetchable) [size=256M]
1823- for match in re.finditer('Memory(.+) prefetchable\) \[size=(\d+)M\]',
1824+# Memory at e0000000 (32-bit, prefetchable) [size=256M]
1825+ for match in re.finditer(r'Memory(.+) prefetchable\) \[size=(\d+)M\]',
1826 line):
1827 vgamem_size = match.group(2)
1828 vgamem = {'device': device,
1829@@ -77,5 +77,6 @@ def main():
1830 vgamem['name'],
1831 vgamem['vgamem_size']))
1832
1833+
1834 if __name__ == '__main__':
1835 sys.exit(main())
1836diff --git a/bin/graphics_driver.py b/bin/graphics_driver.py
1837index 6d28f5a..f9bdff3 100755
1838--- a/bin/graphics_driver.py
1839+++ b/bin/graphics_driver.py
1840@@ -129,7 +129,7 @@ class XorgLog(object):
1841 gathering_module = False
1842 module = None
1843 m = re.search(
1844- '\(II\) Loading.*modules\/drivers\/(.+)_drv\.so', line)
1845+ r'\(II\) Loading.*modules\/drivers\/(.+)_drv\.so', line)
1846 if m:
1847 found_ddx = True
1848 continue
1849@@ -207,7 +207,8 @@ class XorgLog(object):
1850 # For NVIDIA
1851 m = re.search(r'\(II\) (.*)\(\d+\): Setting mode "(.*?):', line)
1852 if not m:
1853- m = re.search(r'\(II\) (.*)\(\d+\): Setting mode "(NULL)"', line)
1854+ m = re.search(
1855+ r'\(II\) (.*)\(\d+\): Setting mode "(NULL)"', line)
1856 if m:
1857 self.displays[display_name] = display
1858 self.video_driver = m.group(1)
1859@@ -314,8 +315,8 @@ def is_laptop():
1860
1861 def hybrid_graphics_check(xlog):
1862 '''Check for Hybrid Graphics'''
1863- card_id1 = re.compile('.*0300: *(.+):(.+) \(.+\)')
1864- card_id2 = re.compile('.*03..: *(.+):(.+)')
1865+ card_id1 = re.compile(r'.*0300: *(.+):(.+) \(.+\)')
1866+ card_id2 = re.compile(r'.*03..: *(.+):(.+)')
1867 cards_dict = {'8086': 'Intel', '10de': 'NVIDIA', '1002': 'AMD'}
1868 cards = []
1869 drivers = []
1870@@ -350,12 +351,12 @@ def hybrid_graphics_check(xlog):
1871 drivers.append(module['name'])
1872 print('Loaded DDX Drivers: %s' % ', '.join(drivers))
1873
1874- has_hybrid_graphics = (len(cards) > 1 and is_laptop()
1875- and (cards_dict.get('8086') in formatted_cards
1876- or cards_dict.get('1002') in formatted_cards))
1877+ has_hybrid_graphics = (len(cards) > 1 and is_laptop() and
1878+ (cards_dict.get('8086') in formatted_cards or
1879+ cards_dict.get('1002') in formatted_cards))
1880
1881- print('Hybrid Graphics: %s' % (has_hybrid_graphics
1882- and 'yes' or 'no'))
1883+ print('Hybrid Graphics: %s' % (has_hybrid_graphics and
1884+ 'yes' or 'no'))
1885
1886 return 0
1887
1888@@ -372,5 +373,6 @@ def main():
1889
1890 return 1 if 1 in results else 0
1891
1892+
1893 if __name__ == "__main__":
1894 sys.exit(main())
1895diff --git a/bin/graphics_modes_info.py b/bin/graphics_modes_info.py
1896index f3c962a..f92cd76 100755
1897--- a/bin/graphics_modes_info.py
1898+++ b/bin/graphics_modes_info.py
1899@@ -32,7 +32,7 @@ from checkbox_support.contrib import xrandr
1900 def print_modes_info(screen):
1901 """Print some information about the detected screen and its outputs"""
1902 xrandr._check_required_version((1, 0))
1903- print("Screen %s: minimum %s x %s, current %s x %s, maximum %s x %s" %\
1904+ print("Screen %s: minimum %s x %s, current %s x %s, maximum %s x %s" %
1905 (screen._screen,
1906 screen._width_min, screen._height_min,
1907 screen._width, screen._height,
1908@@ -50,10 +50,9 @@ def print_modes_info(screen):
1909 for m in range(len(modes)):
1910 mode = modes[m]
1911 refresh = mode.dotClock / (mode.hTotal * mode.vTotal)
1912- print(" [%s] %s x %s @ %s Hz" % (m,
1913- mode.width,
1914- mode.height,
1915- refresh), end=' ')
1916+ print(
1917+ " [%s] %s x %s @ %s Hz" %
1918+ (m, mode.width, mode.height, refresh), end=' ')
1919 if mode.id == output._mode:
1920 print("(current)", end=' ')
1921 if m == output.get_preferred_mode():
1922@@ -70,5 +69,6 @@ def main():
1923 except(xrandr.UnsupportedRRError):
1924 print('Error: RandR version lower than 1.0', file=sys.stderr)
1925
1926+
1927 if __name__ == '__main__':
1928 main()
1929diff --git a/bin/graphics_stress_test.py b/bin/graphics_stress_test.py
1930index d467b3f..c0eeb4a 100755
1931--- a/bin/graphics_stress_test.py
1932+++ b/bin/graphics_stress_test.py
1933@@ -45,7 +45,7 @@ class VtWrapper(object):
1934 vt = 0
1935 proc = Popen(['ps', 'aux'], stdout=PIPE, universal_newlines=True)
1936 proc_output = proc.communicate()[0].split('\n')
1937- proc_line = re.compile('.*tty(\d+).+/usr/bin/X.*')
1938+ proc_line = re.compile(r'.*tty(\d+).+/usr/bin/X.*')
1939 for line in proc_output:
1940 match = proc_line.match(line)
1941 if match:
1942@@ -56,6 +56,7 @@ class VtWrapper(object):
1943 retcode = call(['chvt', '%d' % vt])
1944 return retcode
1945
1946+
1947 class SuspendWrapper(object):
1948 def __init__(self):
1949 pass
1950@@ -132,6 +133,7 @@ class SuspendWrapper(object):
1951
1952 return status
1953
1954+
1955 class RotationWrapper(object):
1956
1957 def __init__(self):
1958@@ -178,6 +180,7 @@ class RotationWrapper(object):
1959 result = 1
1960 return result
1961
1962+
1963 class RenderCheckWrapper(object):
1964 """A simple class to run the rendercheck suites"""
1965
1966@@ -234,14 +237,15 @@ class RenderCheckWrapper(object):
1967 passed = int(match_output.group(1).strip())
1968 total = int(match_output.group(2).strip())
1969 logging.info('Results:')
1970- logging.info(' %d tests passed out of %d.'
1971- % (passed, total))
1972+ logging.info(
1973+ ' %d tests passed out of %d.' % (passed, total))
1974 if show_errors and match_errors:
1975 error = match_errors.group(0).strip()
1976 if first_error:
1977- logging.debug('Rendercheck %s suite errors '
1978- 'from iteration %d:'
1979- % (suites, iteration))
1980+ logging.debug(
1981+ 'Rendercheck %s suite errors '
1982+ 'from iteration %d:'
1983+ % (suites, iteration))
1984 first_error = False
1985 logging.debug(' %s' % error)
1986
1987@@ -254,17 +258,17 @@ class RenderCheckWrapper(object):
1988 exit_status = 0
1989 for suite in suites:
1990 for it in range(iterations):
1991- logging.info('Iteration %d of Rendercheck %s suite...'
1992- % (it + 1, suite))
1993- (status, passed, total) = \
1994- self._print_test_info(suites=suite,
1995- iteration=it + 1,
1996- show_errors=show_errors)
1997+ logging.info(
1998+ 'Iteration %d of Rendercheck %s suite...'
1999+ % (it + 1, suite))
2000+ (status, passed, total) = self._print_test_info(
2001+ suites=suite, iteration=it + 1, show_errors=show_errors)
2002 if status != 0:
2003 # Make sure to catch a non-zero exit status
2004- logging.info('Iteration %d of Rendercheck %s suite '
2005- 'exited with status %d.'
2006- % (it + 1, suite, status))
2007+ logging.info(
2008+ 'Iteration %d of Rendercheck %s suite '
2009+ 'exited with status %d.'
2010+ % (it + 1, suite, status))
2011 exit_status = status
2012 it += 1
2013
2014@@ -372,7 +376,6 @@ def main():
2015
2016 logfile_handler.setFormatter(logging.Formatter(format))
2017 logger.addHandler(logfile_handler)
2018- log_path = os.path.abspath(logfile)
2019
2020 # Write only to stdout
2021 else:
2022@@ -402,16 +405,18 @@ def main():
2023 logging.info('Iteration %d...', it)
2024 retcode = vt_wrap.set_vt(target_vt)
2025 if retcode != 0:
2026- logging.error('Error: switching to tty%d failed with code %d '
2027- 'on iteration %d' % (target_vt, retcode, it))
2028+ logging.error(
2029+ 'Error: switching to tty%d failed with code %d '
2030+ 'on iteration %d' % (target_vt, retcode, it))
2031 status = 1
2032 else:
2033 logging.info('Switching to tty%d: passed' % (target_vt))
2034 time.sleep(2)
2035 retcode = vt_wrap.set_vt(vt_wrap.x_vt)
2036 if retcode != 0:
2037- logging.error('Error: switching to tty%d failed with code %d '
2038- 'on iteration %d' % (vt_wrap.x_vt, retcode, it))
2039+ logging.error(
2040+ 'Error: switching to tty%d failed with code %d '
2041+ 'on iteration %d' % (vt_wrap.x_vt, retcode, it))
2042 else:
2043 logging.info('Switching to tty%d: passed' % (vt_wrap.x_vt))
2044 status = 1
2045@@ -463,5 +468,6 @@ def main():
2046
2047 return status
2048
2049+
2050 if __name__ == '__main__':
2051 exit(main())
2052diff --git a/bin/gst_pipeline_test.py b/bin/gst_pipeline_test.py
2053index c7a9af5..f022632 100755
2054--- a/bin/gst_pipeline_test.py
2055+++ b/bin/gst_pipeline_test.py
2056@@ -9,9 +9,9 @@ import sys
2057 import time
2058 gi.require_version('Gst', '1.0')
2059 gi.require_version('GLib', '2.0')
2060-from gi.repository import Gst
2061-from gi.repository import GLib
2062-from subprocess import check_output
2063+from gi.repository import Gst # noqa: E402
2064+from gi.repository import GLib # noqa: E402
2065+from subprocess import check_output # noqa: E402
2066
2067
2068 def check_state(device):
2069@@ -22,8 +22,11 @@ def check_state(device):
2070
2071 data = sink_info.split("\n")
2072 try:
2073- device_name = re.findall(".*Name:\s.*%s.*" % device, sink_info, re.IGNORECASE)[0].lstrip()
2074- sink = re.findall(".*Name:\s(.*%s.*)" % device, sink_info, re.IGNORECASE)[0].lstrip()
2075+ device_name = re.findall(
2076+ r".*Name:\s.*%s.*" % device, sink_info, re.IGNORECASE)[0].lstrip()
2077+ sink = re.findall(
2078+ r".*Name:\s(.*%s.*)" % device, sink_info,
2079+ re.IGNORECASE)[0].lstrip()
2080 status = data[data.index("\t" + device_name) - 1]
2081 except (IndexError, ValueError):
2082 logging.error("Failed to find status for device: %s" % device)
2083@@ -32,22 +35,26 @@ def check_state(device):
2084 os.environ['PULSE_SINK'] = sink
2085 logging.info("[ Pulse sink ]".center(80, '='))
2086 logging.info("Device: %s %s" % (device_name.strip(), status.strip()))
2087- return status
2088+ return status
2089
2090
2091 def main():
2092 parser = ArgumentParser(description='Simple GStreamer pipeline player')
2093- parser.add_argument('PIPELINE',
2094+ parser.add_argument(
2095+ 'PIPELINE',
2096 help='Quoted GStreamer pipeline to launch')
2097- parser.add_argument('-t', '--timeout',
2098+ parser.add_argument(
2099+ '-t', '--timeout',
2100 type=int, required=True,
2101 help='Timeout for running the pipeline')
2102- parser.add_argument('-d', '--device',
2103+ parser.add_argument(
2104+ '-d', '--device',
2105 type=str,
2106 help="Device to check for status")
2107 args = parser.parse_args()
2108
2109- logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.INFO,
2110+ logging.basicConfig(
2111+ format='%(levelname)s:%(message)s', level=logging.INFO,
2112 stream=sys.stdout)
2113
2114 exit_code = 0
2115@@ -63,7 +70,7 @@ def main():
2116 except GLib.GError as error:
2117 print("Specified pipeline couldn't be processed.")
2118 print("Error when processing pipeline: {}".format(error))
2119- #Exit harmlessly
2120+ # Exit harmlessly
2121 return(2)
2122
2123 print("Pipeline initialized, now starting playback.")
2124diff --git a/bin/hdd_parking.py b/bin/hdd_parking.py
2125index 6d34904..01022ba 100755
2126--- a/bin/hdd_parking.py
2127+++ b/bin/hdd_parking.py
2128@@ -25,7 +25,7 @@
2129 """
2130 This script verifies that a systems HDD protection capabilities
2131 are triggered when appropriate. There are many implementations
2132-of HDD protection from different OEMs, each implemented in a
2133+of HDD protection from different OEMs, each implemented in a
2134 different way, so this script can only support implementations
2135 which are known to work and are testable. Currently the list
2136 of supported implementations is:
2137@@ -42,10 +42,12 @@ from subprocess import Popen, PIPE
2138
2139 TIMEOUT = 15.0
2140
2141+
2142 def hdaps_test(run_time):
2143 try:
2144- hdapsd = Popen(['/usr/sbin/hdapsd'], stdout=PIPE, stderr=PIPE,
2145- universal_newlines=True)
2146+ hdapsd = Popen(
2147+ ['/usr/sbin/hdapsd'], stdout=PIPE, stderr=PIPE,
2148+ universal_newlines=True)
2149 except OSError as err:
2150 print("Unable to start hdapsd: {}".format(err))
2151 return 1
2152@@ -59,6 +61,7 @@ def hdaps_test(run_time):
2153 return 0
2154 return 1
2155
2156+
2157 def main():
2158 # First establish the driver used
2159 parser = ArgumentParser("Tests a systems HDD protection capabilities. "
2160@@ -70,5 +73,6 @@ def main():
2161 'all axis. No particular force should be required.')
2162 return hdaps_test(parser.parse_args().timeout)
2163
2164+
2165 if __name__ == "__main__":
2166 sys.exit(main())
2167diff --git a/bin/hotkey_tests.py b/bin/hotkey_tests.py
2168index f1b3560..066f36c 100755
2169--- a/bin/hotkey_tests.py
2170+++ b/bin/hotkey_tests.py
2171@@ -554,5 +554,6 @@ def main():
2172 if failed:
2173 raise SystemExit('Some test failed!')
2174
2175+
2176 if __name__ == '__main__':
2177 main()
2178diff --git a/bin/key_test.py b/bin/key_test.py
2179index 2bd95f9..f94abd3 100755
2180--- a/bin/key_test.py
2181+++ b/bin/key_test.py
2182@@ -29,7 +29,7 @@ import termios
2183
2184 from gettext import gettext as _
2185
2186-from gi.repository import GObject
2187+from gi.repository import GLib
2188 from optparse import OptionParser
2189
2190
2191@@ -81,7 +81,7 @@ class Reporter(object):
2192 self.scancodes = scancodes
2193
2194 self.fileno = os.open("/dev/console", os.O_RDONLY)
2195- GObject.io_add_watch(self.fileno, GObject.IO_IN, self.on_key)
2196+ GLib.io_add_watch(self.fileno, GLib.IO_IN, self.on_key)
2197
2198 # Set terminal attributes
2199 self.saved_attributes = termios.tcgetattr(self.fileno)
2200@@ -122,9 +122,9 @@ class Reporter(object):
2201 index = 0
2202 length = len(raw_bytes)
2203 while index < length:
2204- if (index + 2 < length and (raw_bytes[index] & 0x7f) == 0
2205- and (raw_bytes[index + 1] & 0x80) != 0
2206- and (raw_bytes[index + 2] & 0x80) != 0):
2207+ if (index + 2 < length and (raw_bytes[index] & 0x7f) == 0 and
2208+ (raw_bytes[index + 1] & 0x80) != 0 and
2209+ (raw_bytes[index + 2] & 0x80) != 0):
2210 code = (((raw_bytes[index + 1] & 0x7f) << 7) |
2211 (raw_bytes[2] & 0x7f))
2212 index += 3
2213@@ -324,7 +324,8 @@ class GtkReporter(Reporter):
2214
2215 def found_key(self, key):
2216 super(GtkReporter, self).found_key(key)
2217- self.icons[key].set_from_stock(self.ICON_TESTED, size=self.ICON_SIZE)
2218+ self.icons[key].set_from_icon_name(
2219+ self.ICON_TESTED, size=self.ICON_SIZE)
2220
2221 self.check_keys()
2222
2223@@ -334,7 +335,7 @@ class GtkReporter(Reporter):
2224 stock_icon = self.ICON_UNTESTED
2225 else:
2226 stock_icon = self.ICON_NOT_REQUIRED
2227- self.icons[key].set_from_stock(stock_icon, self.ICON_SIZE)
2228+ self.icons[key].set_from_icon_name(stock_icon, self.ICON_SIZE)
2229
2230 self.check_keys()
2231
2232@@ -394,10 +395,10 @@ Hint to find codes:
2233 key = Key(codes, name)
2234 keys.append(key)
2235
2236- main_loop = GObject.MainLoop()
2237+ main_loop = GLib.MainLoop()
2238 try:
2239 reporter = reporter_factory(main_loop, keys, options.scancodes)
2240- except:
2241+ except OSError:
2242 parser.error("Failed to initialize interface: %s" % options.interface)
2243
2244 try:
2245@@ -408,5 +409,6 @@ Hint to find codes:
2246
2247 return reporter.exit_code
2248
2249+
2250 if __name__ == "__main__":
2251 sys.exit(main(sys.argv[1:]))
2252diff --git a/bin/keyboard_test.py b/bin/keyboard_test.py
2253index 1615106..e87dc2e 100755
2254--- a/bin/keyboard_test.py
2255+++ b/bin/keyboard_test.py
2256@@ -84,5 +84,6 @@ def main(args):
2257
2258 return 0
2259
2260+
2261 if __name__ == "__main__":
2262 sys.exit(main(sys.argv[1:]))
2263diff --git a/bin/lock_screen_watcher.py b/bin/lock_screen_watcher.py
2264index 1c30270..e4433c8 100755
2265--- a/bin/lock_screen_watcher.py
2266+++ b/bin/lock_screen_watcher.py
2267@@ -20,8 +20,8 @@ import dbus
2268 import gi
2269 from dbus.mainloop.glib import DBusGMainLoop
2270 gi.require_version('GLib', '2.0')
2271-from gi.repository import GObject
2272-from gi.repository import GLib
2273+from gi.repository import GObject # noqa: E402
2274+from gi.repository import GLib # noqa: E402
2275
2276
2277 def filter_cb(bus, message):
2278@@ -41,6 +41,7 @@ def on_timeout_expired():
2279 print("You have failed to perform the required manipulation in time")
2280 raise SystemExit(1)
2281
2282+
2283 DBusGMainLoop(set_as_default=True)
2284 bus = dbus.SessionBus()
2285 bus.add_match_string("type='signal',interface='com.ubuntu.Upstart0_6'")
2286diff --git a/bin/lsmod_info.py b/bin/lsmod_info.py
2287index 3b81542..cb7c0bc 100755
2288--- a/bin/lsmod_info.py
2289+++ b/bin/lsmod_info.py
2290@@ -36,5 +36,6 @@ def main():
2291 print('%s: %s' % (module, version))
2292 return 0
2293
2294+
2295 if __name__ == '__main__':
2296 sys.exit(main())
2297diff --git a/bin/mac_passthrough.py b/bin/mac_passthrough.py
2298index 92d2eb6..1707a1e 100755
2299--- a/bin/mac_passthrough.py
2300+++ b/bin/mac_passthrough.py
2301@@ -53,8 +53,8 @@ def get_pass_through_mac():
2302 for line in dsdt:
2303 if 'AUXMAC' in line:
2304 bios_mac = line.split('#')[1]
2305- print('Pass-through MAC address from DSDT table: '
2306- + bios_mac.lower())
2307+ print('Pass-through MAC address from DSDT table: ' +
2308+ bios_mac.lower())
2309 return bios_mac.lower()
2310 raise SystemExit('No AUXMAC is found in DSDT table, '
2311 'MAC address pass-through is not working.')
2312diff --git a/bin/manage_compiz_plugin.py b/bin/manage_compiz_plugin.py
2313index 03c0ed8..be9541f 100755
2314--- a/bin/manage_compiz_plugin.py
2315+++ b/bin/manage_compiz_plugin.py
2316@@ -29,11 +29,10 @@ from gettext import gettext as _
2317 import argparse
2318 import gettext
2319 import os
2320-import sys
2321 import subprocess
2322 import time
2323
2324-KEY="/org/compiz/profiles/unity/plugins/core/active-plugins"
2325+KEY = "/org/compiz/profiles/unity/plugins/core/active-plugins"
2326
2327 gettext.textdomain("com.canonical.certification.checkbox")
2328 gettext.bindtextdomain("com.canonical.certification.checkbox",
2329@@ -41,8 +40,9 @@ gettext.bindtextdomain("com.canonical.certification.checkbox",
2330
2331 plugins = eval(subprocess.check_output(["dconf", "read", KEY]))
2332
2333-parser = argparse.ArgumentParser(description=_("enable/disable compiz plugins"),
2334- epilog=_("Available plugins: {}").format(plugins))
2335+parser = argparse.ArgumentParser(
2336+ description=_("enable/disable compiz plugins"),
2337+ epilog=_("Available plugins: {}").format(plugins))
2338 parser.add_argument("plugin", type=str, help=_('Name of plugin to control'))
2339 parser.add_argument("action", type=str, choices=['enable', 'disable'],
2340 help=_("What to do with the plugin"))
2341diff --git a/bin/memory_compare.py b/bin/memory_compare.py
2342index 02e2def..aaf89f4 100755
2343--- a/bin/memory_compare.py
2344+++ b/bin/memory_compare.py
2345@@ -25,7 +25,6 @@
2346 import os
2347 import sys
2348 import re
2349-from math import log, copysign
2350 from subprocess import check_output, CalledProcessError, PIPE
2351
2352 from checkbox_support.helpers.human_readable_bytes import HumanReadableBytes
2353@@ -44,7 +43,7 @@ class LshwJsonResult:
2354 desc_regex = re.compile('System Memory', re.IGNORECASE)
2355
2356 def addHardware(self, hardware):
2357- if self.desc_regex.match(str(hardware.get('description',0))):
2358+ if self.desc_regex.match(str(hardware.get('description', 0))):
2359 self.memory_reported += int(hardware.get('size', 0))
2360 elif 'bank' in hardware['id']:
2361 self.banks_reported += int(hardware.get('size', 0))
2362@@ -134,5 +133,6 @@ def main():
2363 (difference, percentage, threshold), file=sys.stderr)
2364 return 1
2365
2366+
2367 if __name__ == "__main__":
2368 sys.exit(main())
2369diff --git a/bin/memory_test.py b/bin/memory_test.py
2370index 4cd6008..a472b71 100755
2371--- a/bin/memory_test.py
2372+++ b/bin/memory_test.py
2373@@ -75,8 +75,8 @@ class MemoryTest():
2374 self.process_memory = self.free_memory
2375 try:
2376 arch = self._command_out("arch").decode()
2377- if (re.match(r"(i[0-9]86|s390|arm.*)", arch)
2378- and self.free_memory > 1024):
2379+ if (re.match(r"(i[0-9]86|s390|arm.*)", arch) and
2380+ self.free_memory > 1024):
2381 self.is_process_limited = True
2382 self.process_memory = 1024 # MB, due to 32-bit address space
2383 print("%s arch, Limiting Process Memory: %u" % (
2384diff --git a/bin/network.py b/bin/network.py
2385index a646f9c..60f7b0a 100755
2386--- a/bin/network.py
2387+++ b/bin/network.py
2388@@ -255,14 +255,15 @@ class IPerfPerformanceTest(object):
2389 logging.warning("The network test against {} failed because:".
2390 format(self.target))
2391 if percent < self.fail_threshold:
2392- logging.error(" Transfer speed: {} Mb/s".
2393- format(throughput))
2394- logging.error(" {:03.2f}% of theoretical max {} Mb/s\n".
2395- format(percent, int(self.iface.max_speed)))
2396+ logging.error(" Transfer speed: {} Mb/s".format(throughput))
2397+ logging.error(
2398+ " {:03.2f}% of theoretical max {} Mb/s\n".format(
2399+ percent, int(self.iface.max_speed)))
2400 if cpu_load > self.cpu_load_fail_threshold:
2401 logging.error(" CPU load: {}%".format(cpu_load))
2402- logging.error(" CPU load is above {}% maximum\n".
2403- format(self.cpu_load_fail_threshold))
2404+ logging.error(
2405+ " CPU load is above {}% maximum\n".format(
2406+ self.cpu_load_fail_threshold))
2407 return 30
2408
2409 logging.debug("Passed benchmark against {}".format(self.target))
2410@@ -277,9 +278,11 @@ class StressPerformanceTest:
2411
2412 def run(self):
2413 if self.iperf3:
2414- iperf_cmd = 'timeout -k 1 320 iperf3 -c {} -t 300'.format(self.target)
2415+ iperf_cmd = 'timeout -k 1 320 iperf3 -c {} -t 300'.format(
2416+ self.target)
2417 else:
2418- iperf_cmd = 'timeout -k 1 320 iperf -c {} -t 300'.format(self.target)
2419+ iperf_cmd = 'timeout -k 1 320 iperf -c {} -t 300'.format(
2420+ self.target)
2421 print("Running iperf...")
2422 iperf = subprocess.Popen(shlex.split(iperf_cmd))
2423
2424@@ -365,14 +368,14 @@ class Interface(socket.socket):
2425 ethinfo = check_output(['ethtool', self.interface],
2426 universal_newlines=True,
2427 stderr=STDOUT).split(' ')
2428- expression = '(\\d+)(base)([A-Z]+)|(\d+)(Mb/s)'
2429+ expression = r'(\\d+)(base)([A-Z]+)|(\d+)(Mb/s)'
2430
2431 regex = re.compile(expression)
2432 if ethinfo:
2433 for i in ethinfo:
2434 hit = regex.search(i)
2435 if hit:
2436- speeds.append(int(re.sub("\D", "", hit.group(0))))
2437+ speeds.append(int(re.sub(r"\D", "", hit.group(0))))
2438 except CalledProcessError as e:
2439 logging.error('ethtool returned an error!')
2440 logging.error(e.output)
2441@@ -391,7 +394,7 @@ class Interface(socket.socket):
2442 for s in line.split(' '):
2443 hit = regex.search(s)
2444 if hit:
2445- speeds.append(int(re.sub("\D", "", hit.group(0))))
2446+ speeds.append(int(re.sub(r"\D", "", hit.group(0))))
2447 except FileNotFoundError:
2448 logging.warning('mii-tool not found! Unable to get max speed')
2449 except CalledProcessError as e:
2450diff --git a/bin/network_check.py b/bin/network_check.py
2451index 82c00d9..20b88d5 100755
2452--- a/bin/network_check.py
2453+++ b/bin/network_check.py
2454@@ -6,7 +6,9 @@ ubuntu.com
2455 from subprocess import call
2456 from argparse import ArgumentParser
2457 import http.client
2458-import urllib.request, urllib.error, urllib.parse
2459+import urllib.request
2460+import urllib.error
2461+import urllib.parse
2462 import sys
2463
2464
2465@@ -61,12 +63,14 @@ def main():
2466 try:
2467 call(command)
2468 except OSError:
2469- print("Zenity missing; unable to report test result:\n %s" % message)
2470+ print(
2471+ "Zenity missing; unable to report test result:\n %s" % message)
2472
2473 if any(results.values()):
2474 return 0
2475 else:
2476 return 1
2477
2478+
2479 if __name__ == "__main__":
2480 sys.exit(main())
2481diff --git a/bin/network_ntp_test.py b/bin/network_ntp_test.py
2482index 6e2ccf8..f7a2297 100755
2483--- a/bin/network_ntp_test.py
2484+++ b/bin/network_ntp_test.py
2485@@ -84,13 +84,13 @@ def StartStopNTPD(state, pid=0):
2486 SilentCall('/etc/init.d/ntp start')
2487 ntpd_status = CheckNTPD()
2488
2489- if status == 0:
2490+ if ntpd_status == 0:
2491 logging.debug('ntpd restarted with PID: %s' % ntpd_status[1])
2492 else:
2493 logging.error('ntpd restart failed for some reason')
2494 else:
2495- logging.error('%s is an unknown state, unable to start/stop ntpd' %
2496- state)
2497+ logging.error(
2498+ '%s is an unknown state, unable to start/stop ntpd' % state)
2499
2500
2501 def SyncTime(server):
2502@@ -141,7 +141,8 @@ def SkewTime():
2503
2504
2505 def main():
2506- description = 'Tests the ability to skew and sync the clock with an NTP server'
2507+ description = (
2508+ 'Tests the ability to skew and sync the clock with an NTP server')
2509 parser = ArgumentParser(description=description)
2510 parser.add_argument('--server',
2511 action='store',
2512@@ -173,7 +174,7 @@ def main():
2513 if args.debug:
2514 logger.setLevel(logging.DEBUG)
2515 logger.addHandler(handler)
2516-
2517+
2518 # Make sure NTP is installed
2519 if not os.access('/usr/sbin/ntpdate', os.F_OK):
2520 logging.error('NTP is not installed!')
2521@@ -208,5 +209,6 @@ def main():
2522 else:
2523 return 1
2524
2525+
2526 if __name__ == '__main__':
2527 sys.exit(main())
2528diff --git a/bin/network_reconnect_resume_test.py b/bin/network_reconnect_resume_test.py
2529index 8861eb6..17a220e 100755
2530--- a/bin/network_reconnect_resume_test.py
2531+++ b/bin/network_reconnect_resume_test.py
2532@@ -43,16 +43,17 @@ def get_wifi_reconnect_times():
2533 Returns a list of all the timestamps for wifi reconnects.
2534 """
2535 data = subprocess.check_output(['dmesg'], universal_newlines=True)
2536- syntax = re.compile("\[(.*)\] wlan.* associated")
2537+ syntax = re.compile(r"\[(.*)\] wlan.* associated")
2538 results = re.findall(syntax, data)
2539 return map(float, results)
2540
2541+
2542 def get_wired_reconnect_times():
2543 """
2544 Returns a list of all the timestamps for wired reconnects.
2545 """
2546 data = subprocess.check_output(['dmesg'], universal_newlines=True)
2547- syntax = re.compile("\[(.*)\].*eth.* Link is [uU]p")
2548+ syntax = re.compile(r"\[(.*)\].*eth.* Link is [uU]p")
2549 results = re.findall(syntax, data)
2550 return map(float, results)
2551
2552@@ -63,7 +64,7 @@ def get_resume_time():
2553 If no resume is found, None is returned.
2554 """
2555 data = subprocess.check_output(['dmesg'], universal_newlines=True)
2556- syntax = re.compile("\[(.*)\].ACPI: Waking up from system sleep state S3")
2557+ syntax = re.compile(r"\[(.*)\].ACPI: Waking up from system sleep state S3")
2558 results = re.findall(syntax, data)
2559 if not results:
2560 return None
2561@@ -85,7 +86,7 @@ def main():
2562 args = parser.parse_args()
2563
2564 timedif = get_time_difference(args.device)
2565-
2566+
2567 if not timedif:
2568 return 0
2569
2570@@ -98,5 +99,6 @@ def main():
2571 print("PASS: the network connected within the allotted time")
2572 return 0
2573
2574+
2575 if __name__ == "__main__":
2576 sys.exit(main())
2577diff --git a/bin/network_restart.py b/bin/network_restart.py
2578index 14c7357..63a99fb 100755
2579--- a/bin/network_restart.py
2580+++ b/bin/network_restart.py
2581@@ -96,7 +96,8 @@ class GtkApplication(Application):
2582 def __init__(self, address, times):
2583 Application.__init__(self, address, times)
2584
2585- dialog = Gtk.Dialog(title='Network restart',
2586+ dialog = Gtk.Dialog(
2587+ title='Network restart',
2588 buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL))
2589 dialog.set_default_size(300, 100)
2590
2591@@ -187,7 +188,8 @@ def ping(address):
2592 """
2593 logging.info('Pinging {0!r}...'.format(address))
2594 try:
2595- check_call('ping -c 1 -w 5 {0}'.format(address),
2596+ check_call(
2597+ 'ping -c 1 -w 5 {0}'.format(address),
2598 stdout=open(os.devnull, 'w'), stderr=STDOUT, shell=True)
2599 except CalledProcessError:
2600 return False
2601@@ -209,8 +211,9 @@ class Networking:
2602 """
2603 output = check_output(['/sbin/ifconfig', '-s', '-a'])
2604 lines = output.splitlines()[1:]
2605- interfaces = ([interface for interface in
2606- [line.split()[0] for line in lines] if interface != 'lo'])
2607+ interfaces = (
2608+ [interface for interface in
2609+ [line.split()[0] for line in lines] if interface != 'lo'])
2610 return interfaces
2611
2612 def restart(self):
2613@@ -287,21 +290,24 @@ def parse_args():
2614 """
2615 Parse command line options
2616 """
2617- parser = ArgumentParser('Reboot networking interface '
2618- 'and verify that is up again afterwards')
2619- parser.add_argument('-a', '--address', default='ubuntu.com',
2620+ parser = ArgumentParser(
2621+ 'Reboot networking interface and verify that is up again afterwards')
2622+ parser.add_argument(
2623+ '-a', '--address', default='ubuntu.com',
2624 help=('Address to ping to verify that network connection is up '
2625 "('%(default)s' by default)"))
2626 parser.add_argument('-o', '--output',
2627 default='/var/log',
2628 help='The path to the log directory. \
2629 Default is /var/log')
2630- parser.add_argument('-t', '--times',
2631+ parser.add_argument(
2632+ '-t', '--times',
2633 type=int, default=1,
2634 help=('Number of times that the network interface has to be restarted '
2635 '(%(default)s by default)'))
2636 log_levels = ['notset', 'debug', 'info', 'warning', 'error', 'critical']
2637- parser.add_argument('--log-level', dest='log_level_str', default='notset',
2638+ parser.add_argument(
2639+ '--log-level', dest='log_level_str', default='notset',
2640 choices=log_levels,
2641 help=('Log level. '
2642 'One of {0} or {1} (%(default)s by default)'
2643diff --git a/bin/optical_read_test.py b/bin/optical_read_test.py
2644index b3cf23d..7560db1 100755
2645--- a/bin/optical_read_test.py
2646+++ b/bin/optical_read_test.py
2647@@ -7,7 +7,7 @@ import filecmp
2648 import shutil
2649
2650 from argparse import ArgumentParser
2651-from subprocess import Popen, PIPE
2652+from subprocess import Popen, PIPE, SubprocessError
2653
2654 DEFAULT_DIR = '/tmp/checkbox.optical'
2655 DEFAULT_DEVICE_DIR = 'device'
2656@@ -18,11 +18,7 @@ CDROM_ID = '/lib/udev/cdrom_id'
2657
2658
2659 def _command(command, shell=True):
2660- proc = Popen(command,
2661- shell=shell,
2662- stdout=PIPE,
2663- stderr=PIPE
2664- )
2665+ proc = Popen(command, shell=shell, stdout=PIPE, stderr=PIPE)
2666 return proc
2667
2668
2669@@ -33,7 +29,7 @@ def _command_out(command, shell=True):
2670
2671 def compare_tree(source, target):
2672 for dirpath, dirnames, filenames in os.walk(source):
2673- #if both tree are empty return false
2674+ # if both tree are empty return false
2675 if dirpath == source and dirnames == [] and filenames == []:
2676 return False
2677 for name in filenames:
2678@@ -64,21 +60,21 @@ def read_test(device):
2679 mount = _command("mount -o ro %s %s" % (device, device_dir))
2680 mount.communicate()
2681 if mount.returncode != 0:
2682- print("Unable to mount %s to %s" %
2683- (device, device_dir), file=sys.stderr)
2684+ print("Unable to mount %s to %s" %
2685+ (device, device_dir), file=sys.stderr)
2686 return False
2687
2688 file_copy = _command("cp -dpR %s %s" % (device_dir, image_dir))
2689 file_copy.communicate()
2690 if file_copy.returncode != 0:
2691- print("Failed to copy files from %s to %s" %
2692- (device_dir, image_dir), file=sys.stderr)
2693+ print("Failed to copy files from %s to %s" %
2694+ (device_dir, image_dir), file=sys.stderr)
2695 return False
2696 if compare_tree(device_dir, image_dir):
2697 passed = True
2698- except:
2699- print("File Comparison failed while testing %s" % device,
2700- file=sys.stderr)
2701+ except (SubprocessError, OSError):
2702+ print("File Comparison failed while testing %s" % device,
2703+ file=sys.stderr)
2704 passed = False
2705 finally:
2706 _command("umount %s" % device_dir).communicate(3)
2707@@ -88,7 +84,7 @@ def read_test(device):
2708
2709 if passed:
2710 print("File Comparison passed (%s)" % device)
2711-
2712+
2713 return passed
2714
2715
2716@@ -127,8 +123,9 @@ def main():
2717 print("Testing %s on %s ... " % (test, device), file=sys.stdout)
2718 tester = "%s_test" % test
2719 return_values.append(globals()[tester](device))
2720-
2721+
2722 return False in return_values
2723
2724+
2725 if __name__ == "__main__":
2726 sys.exit(main())
2727diff --git a/bin/pm_log_check.py b/bin/pm_log_check.py
2728index cb75685..1d41ed6 100755
2729--- a/bin/pm_log_check.py
2730+++ b/bin/pm_log_check.py
2731@@ -36,8 +36,8 @@ class Parser(object):
2732 """
2733 Reboot test log file parser
2734 """
2735- is_logging_line = (re.compile('^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}')
2736- .search)
2737+ is_logging_line = (re.compile(
2738+ r'^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3}').search)
2739 is_getting_info_line = (re.compile('Gathering hardware information...$')
2740 .search)
2741 is_executing_line = (re.compile("Executing: '(?P<command>.*)'...$")
2742@@ -103,8 +103,10 @@ class Parser(object):
2743 if self.is_output_line(line):
2744 command_output = {}
2745 break
2746- if (self.is_executing_line(line)
2747- or self.is_getting_info_line(line)):
2748+ if (
2749+ self.is_executing_line(line) or
2750+ self.is_getting_info_line(line)
2751+ ):
2752 # Skip commands with no output
2753 iterator.unnext(line)
2754 return None
2755@@ -132,8 +134,10 @@ class Parser(object):
2756 # for the field value
2757 value = []
2758 for line in iterator:
2759- if (self.is_logging_line(line)
2760- or self.is_field_line(line)):
2761+ if (
2762+ self.is_logging_line(line) or
2763+ self.is_field_line(line)
2764+ ):
2765 iterator.unnext(line)
2766 break
2767
2768@@ -205,8 +209,8 @@ def compare_results(results):
2769 result_output = result[command]
2770
2771 error_messages = []
2772- fields = (set(baseline_output.keys())
2773- | set(result_output.keys()))
2774+ fields = (set(baseline_output.keys()) |
2775+ set(result_output.keys()))
2776 for field in fields:
2777 baseline_field = baseline_output.get(field, '')
2778 result_field = result_output.get(field, '')
2779diff --git a/bin/pm_test.py b/bin/pm_test.py
2780index 18cf97c..fcaf7d9 100755
2781--- a/bin/pm_test.py
2782+++ b/bin/pm_test.py
2783@@ -20,7 +20,7 @@ from configparser import ConfigParser
2784 from datetime import datetime, timedelta
2785 from time import localtime, time
2786 gi.require_version("Gtk", "3.0")
2787-from gi.repository import GObject, Gtk
2788+from gi.repository import GObject, Gtk # noqa: E402
2789
2790
2791 def main():
2792@@ -266,9 +266,9 @@ class PowerManagementOperation():
2793 count = count_s3 + count_s2idle
2794 if count != total_suspends_expected:
2795 problems = (
2796- "Found {} occurrences of '{}'. Expected {}".format(
2797- count, magic_line.strip(),
2798- total_suspends_expected))
2799+ "Found {} occurrences of S3/S2idle."
2800+ " Expected {}".format(
2801+ count, total_suspends_expected))
2802 except FileNotFoundError:
2803 problems = "Error opening {}".format(fwts_log_path)
2804 if problems:
2805@@ -367,13 +367,13 @@ class WakeUpAlarm():
2806 with open(cls.ALARM_FILENAME) as alarm_file:
2807 wakeup_time_stored_str = alarm_file.read()
2808
2809- if not re.match('\d+', wakeup_time_stored_str):
2810+ if not re.match(r'\d+', wakeup_time_stored_str):
2811 subprocess.check_call('echo "+%d" > %s'
2812 % (timeout, cls.ALARM_FILENAME),
2813 shell=True)
2814 with open(cls.ALARM_FILENAME) as alarm_file2:
2815 wakeup_time_stored_str = alarm_file2.read()
2816- if not re.match('\d+', wakeup_time_stored_str):
2817+ if not re.match(r'\d+', wakeup_time_stored_str):
2818 logging.error('Invalid wakeup time format: {0!r}'
2819 .format(wakeup_time_stored_str))
2820 sys.exit(1)
2821@@ -396,7 +396,7 @@ class WakeUpAlarm():
2822 sys.exit(1)
2823
2824 with open(cls.RTC_FILENAME) as rtc_file:
2825- separator_regex = re.compile('\s+:\s+')
2826+ separator_regex = re.compile(r'\s+:\s+')
2827 rtc_data = dict([separator_regex.split(line.rstrip())
2828 for line in rtc_file])
2829 logging.debug('RTC data:\n{0}'
2830@@ -582,14 +582,15 @@ class CountdownDialog(Gtk.Dialog):
2831 .run().stdout),
2832 ethernet=(Command('lspci | grep Ethernet')
2833 .run().stdout),
2834- ifconfig=(Command("ifconfig -a | grep -A1 '^\w'")
2835+ ifconfig=(Command(
2836+ r"ifconfig -a | grep -A1 '^\w'")
2837 .run().stdout),
2838- iwconfig=(Command("iwconfig | grep -A1 '^\w'")
2839+ iwconfig=(Command(r"iwconfig | grep -A1 '^\w'")
2840 .run().stdout)))
2841 logging.debug('Bluetooth Device:\n'
2842 '{hciconfig}'
2843- .format(hciconfig=(Command("hciconfig -a "
2844- "| grep -A2 '^\w'")
2845+ .format(hciconfig=(Command(r"hciconfig -a "
2846+ r"| grep -A2 '^\w'")
2847 .run().stdout)))
2848 logging.debug('Video Card:\n'
2849 '{lspci}'
2850@@ -770,7 +771,7 @@ Exec=sudo {script} -r {repetitions} -w {wakeup} --hardware-delay {hardware_delay
2851 Type=Application
2852 X-GNOME-Autostart-enabled=true
2853 Hidden=false
2854-"""
2855+""" # noqa: E501
2856
2857 def __init__(self, args, user=None):
2858 self.args = args
2859@@ -1012,7 +1013,7 @@ class MyArgumentParser():
2860 '{0}.{1}.{2}.log'.format(
2861 os.path.splitext(os.path.basename(__file__))[0],
2862 args.pm_operation,
2863- args.total)))
2864+ args.total))
2865 return args, extra_args
2866
2867
2868diff --git a/bin/process_wait.py b/bin/process_wait.py
2869index 6107d1b..1295991 100755
2870--- a/bin/process_wait.py
2871+++ b/bin/process_wait.py
2872@@ -36,14 +36,17 @@ def main(args):
2873
2874 usage = "Usage: %prog PROCESS [PROCESS...]"
2875 parser = OptionParser(usage=usage)
2876- parser.add_option("-s", "--sleep",
2877+ parser.add_option(
2878+ "-s", "--sleep",
2879 type="int",
2880 default=default_sleep,
2881 help="Number of seconds to sleep between checks.")
2882- parser.add_option("-t", "--timeout",
2883+ parser.add_option(
2884+ "-t", "--timeout",
2885 type="int",
2886 help="Number of seconds to timeout from sleeping.")
2887- parser.add_option("-u", "--uid",
2888+ parser.add_option(
2889+ "-u", "--uid",
2890 help="Effective user name or id of the running processes")
2891 (options, processes) = parser.parse_args(args)
2892
2893diff --git a/bin/pulse-active-port-change.py b/bin/pulse-active-port-change.py
2894index 90abed8..baf0152 100755
2895--- a/bin/pulse-active-port-change.py
2896+++ b/bin/pulse-active-port-change.py
2897@@ -71,20 +71,21 @@ class AudioPlugDetection:
2898 doc = parse_pactl_output(text)
2899 cfg = set()
2900 for record in doc.record_list:
2901- active_port = None
2902- port_availability = None
2903- # We go through the attribute list once to try to find an active port
2904- for attr in record.attribute_list:
2905- if attr.name == "Active Port":
2906- active_port = attr.value
2907- # If there is one, we retrieve its availability flag
2908- if active_port:
2909- for attr in record.attribute_list:
2910- if attr.name == "Ports":
2911- for port in attr.value:
2912- if port.name == active_port:
2913- port_availability = port.availability
2914- cfg.add((record.name, active_port, port_availability))
2915+ active_port = None
2916+ port_availability = None
2917+ # We go through the attribute list once to try to find
2918+ # an active port
2919+ for attr in record.attribute_list:
2920+ if attr.name == "Active Port":
2921+ active_port = attr.value
2922+ # If there is one, we retrieve its availability flag
2923+ if active_port:
2924+ for attr in record.attribute_list:
2925+ if attr.name == "Ports":
2926+ for port in attr.value:
2927+ if port.name == active_port:
2928+ port_availability = port.availability
2929+ cfg.add((record.name, active_port, port_availability))
2930 return cfg
2931
2932 def on_timeout(self, signum, frame):
2933diff --git a/bin/removable_storage_test.py b/bin/removable_storage_test.py
2934index 82f1595..4253cbf 100755
2935--- a/bin/removable_storage_test.py
2936+++ b/bin/removable_storage_test.py
2937@@ -15,26 +15,30 @@ import time
2938
2939 import gi
2940 gi.require_version('GUdev', '1.0')
2941-from gi.repository import GUdev
2942-
2943-from checkbox_support.dbus import connect_to_system_bus
2944-from checkbox_support.dbus.udisks2 import UDISKS2_BLOCK_INTERFACE
2945-from checkbox_support.dbus.udisks2 import UDISKS2_DRIVE_INTERFACE
2946-from checkbox_support.dbus.udisks2 import UDISKS2_FILESYSTEM_INTERFACE
2947-from checkbox_support.dbus.udisks2 import UDISKS2_LOOP_INTERFACE
2948-from checkbox_support.dbus.udisks2 import UDisks2Model, UDisks2Observer
2949-from checkbox_support.dbus.udisks2 import is_udisks2_supported
2950-from checkbox_support.dbus.udisks2 import lookup_udev_device
2951-from checkbox_support.dbus.udisks2 import map_udisks1_connection_bus
2952-from checkbox_support.heuristics.udisks2 import is_memory_card
2953-from checkbox_support.helpers.human_readable_bytes import HumanReadableBytes
2954-from checkbox_support.parsers.udevadm import CARD_READER_RE
2955-from checkbox_support.parsers.udevadm import GENERIC_RE
2956-from checkbox_support.parsers.udevadm import FLASH_RE
2957-from checkbox_support.parsers.udevadm import find_pkname_is_root_mountpoint
2958-from checkbox_support.udev import get_interconnect_speed
2959-from checkbox_support.udev import get_udev_block_devices
2960-from checkbox_support.udev import get_udev_xhci_devices
2961+from gi.repository import GUdev # noqa: E402
2962+
2963+from checkbox_support.dbus import connect_to_system_bus # noqa: E402
2964+from checkbox_support.dbus.udisks2 import (
2965+ UDISKS2_BLOCK_INTERFACE,
2966+ UDISKS2_DRIVE_INTERFACE,
2967+ UDISKS2_FILESYSTEM_INTERFACE,
2968+ UDISKS2_LOOP_INTERFACE,
2969+ UDisks2Model,
2970+ UDisks2Observer,
2971+ is_udisks2_supported,
2972+ lookup_udev_device,
2973+ map_udisks1_connection_bus) # noqa: E402
2974+from checkbox_support.heuristics.udisks2 import is_memory_card # noqa: E402
2975+from checkbox_support.helpers.human_readable_bytes import (
2976+ HumanReadableBytes) # noqa: E402
2977+from checkbox_support.parsers.udevadm import (
2978+ CARD_READER_RE,
2979+ GENERIC_RE,
2980+ FLASH_RE,
2981+ find_pkname_is_root_mountpoint) # noqa: E402
2982+from checkbox_support.udev import get_interconnect_speed # noqa: E402
2983+from checkbox_support.udev import get_udev_block_devices # noqa: E402
2984+from checkbox_support.udev import get_udev_xhci_devices # noqa: E402
2985
2986
2987 class ActionTimer():
2988@@ -109,8 +113,8 @@ def on_ubuntucore():
2989 snap = os.getenv("SNAP")
2990 if snap:
2991 with open(os.path.join(snap, 'meta/snap.yaml')) as f:
2992- for l in f.readlines():
2993- if l == "confinement: classic\n":
2994+ for line in f.readlines():
2995+ if line == "confinement: classic\n":
2996 return False
2997 return True
2998 return False
2999@@ -855,7 +859,6 @@ def main():
3000 # controller drivers.
3001 # This will raise KeyError for no
3002 # associated disk device was found.
3003- xhci_disks = test.get_disks_xhci()
3004 if test.get_disks_xhci().get(disk, '') != 'xhci':
3005 raise SystemExit(
3006 "\t\tDisk does not use xhci_hcd.")
3007diff --git a/bin/removable_storage_watcher.py b/bin/removable_storage_watcher.py
3008index d5a0722..c13439e 100755
3009--- a/bin/removable_storage_watcher.py
3010+++ b/bin/removable_storage_watcher.py
3011@@ -9,16 +9,21 @@ import sys
3012
3013 import gi
3014 gi.require_version('GUdev', '1.0')
3015-from gi.repository import GObject, GUdev
3016-
3017-from checkbox_support.dbus import connect_to_system_bus
3018-from checkbox_support.dbus.udisks2 import UDisks2Model, UDisks2Observer
3019-from checkbox_support.dbus.udisks2 import is_udisks2_supported
3020-from checkbox_support.dbus.udisks2 import lookup_udev_device
3021-from checkbox_support.dbus.udisks2 import map_udisks1_connection_bus
3022-from checkbox_support.heuristics.udisks2 import is_memory_card
3023-from checkbox_support.parsers.udevadm import CARD_READER_RE, GENERIC_RE, FLASH_RE
3024-from checkbox_support.udev import get_interconnect_speed, get_udev_block_devices
3025+from gi.repository import GObject, GUdev # noqa: E402
3026+
3027+from checkbox_support.dbus import connect_to_system_bus # noqa: E402
3028+from checkbox_support.dbus.udisks2 import UDisks2Model # noqa: E402
3029+from checkbox_support.dbus.udisks2 import UDisks2Observer # noqa: E402
3030+from checkbox_support.dbus.udisks2 import is_udisks2_supported # noqa: E402
3031+from checkbox_support.dbus.udisks2 import lookup_udev_device # noqa: E402
3032+from checkbox_support.dbus.udisks2 import (
3033+ map_udisks1_connection_bus) # noqa: E402
3034+from checkbox_support.heuristics.udisks2 import is_memory_card # noqa: E402
3035+from checkbox_support.parsers.udevadm import CARD_READER_RE # noqa: E402
3036+from checkbox_support.parsers.udevadm import GENERIC_RE # noqa: E402
3037+from checkbox_support.parsers.udevadm import FLASH_RE # noqa: E402
3038+from checkbox_support.udev import get_interconnect_speed # noqa: E402
3039+from checkbox_support.udev import get_udev_block_devices # noqa: E402
3040
3041 # Record representing properties of a UDisks1 Drive object needed by the
3042 # UDisks1 version of the watcher implementation
3043@@ -121,19 +126,24 @@ class UDisks1StorageDeviceListener:
3044 logging.debug("Desired bus devices: %s", desired_bus_devices)
3045 for dev in desired_bus_devices:
3046 if self._memorycard:
3047- if (dev.bus != 'sdio'
3048- and not FLASH_RE.search(dev.media)
3049- and not CARD_READER_RE.search(dev.model)
3050- and not GENERIC_RE.search(dev.vendor)):
3051- logging.debug("The device does not seem to be a memory"
3052- " card (bus: %r, model: %r), skipping",
3053- dev.bus, dev.model)
3054+ if (
3055+ dev.bus != 'sdio' and
3056+ not FLASH_RE.search(dev.media) and
3057+ not CARD_READER_RE.search(dev.model) and
3058+ not GENERIC_RE.search(dev.vendor)
3059+ ):
3060+ logging.debug(
3061+ "The device does not seem to be a memory"
3062+ " card (bus: %r, model: %r), skipping",
3063+ dev.bus, dev.model)
3064 return
3065 print(message % {'bus': 'memory card', 'file': dev.file})
3066 else:
3067- if (FLASH_RE.search(dev.media)
3068- or CARD_READER_RE.search(dev.model)
3069- or GENERIC_RE.search(dev.vendor)):
3070+ if (
3071+ FLASH_RE.search(dev.media) or
3072+ CARD_READER_RE.search(dev.model) or
3073+ GENERIC_RE.search(dev.vendor)
3074+ ):
3075 logging.debug("The device seems to be a memory"
3076 " card (bus: %r (model: %r), skipping",
3077 dev.bus, dev.model)
3078@@ -180,8 +190,7 @@ class UDisks1StorageDeviceListener:
3079 message = "Expected memory card device %(file)s inserted"
3080 else:
3081 message = "Expected %(bus)s device %(file)s inserted"
3082- self.verify_device_change(inserted_devices,
3083- message=message)
3084+ self.verify_device_change(inserted_devices, message=message)
3085
3086 def add_detected(self, added_path):
3087 logging.debug("UDisks1 reports device has been added: %s", added_path)
3088@@ -205,8 +214,9 @@ class UDisks1StorageDeviceListener:
3089 removed_devices = list(set(self._starting_devices) -
3090 set(current_devices))
3091 logging.debug("Computed removed devices: %s", removed_devices)
3092- self.verify_device_change(removed_devices,
3093- message="Removable %(bus)s device %(file)s has been removed")
3094+ self.verify_device_change(
3095+ removed_devices,
3096+ message="Removable %(bus)s device %(file)s has been removed")
3097
3098 def get_existing_devices(self):
3099 logging.debug("Getting existing devices from UDisks1")
3100@@ -221,12 +231,9 @@ class UDisks1StorageDeviceListener:
3101 device_props = dbus.Interface(device_obj,
3102 dbus.PROPERTIES_IFACE)
3103 udisks = 'org.freedesktop.UDisks.Device'
3104- _device_file = device_props.Get(udisks,
3105- "DeviceFile")
3106- _bus = device_props.Get(udisks,
3107- "DriveConnectionInterface")
3108- _speed = device_props.Get(udisks,
3109- "DriveConnectionSpeed")
3110+ _device_file = device_props.Get(udisks, "DeviceFile")
3111+ _bus = device_props.Get(udisks, "DriveConnectionInterface")
3112+ _speed = device_props.Get(udisks, "DriveConnectionSpeed")
3113 _parent_model = ''
3114 _parent_media = ''
3115 _parent_vendor = ''
3116@@ -411,7 +418,7 @@ class UDisks2StorageDeviceListener:
3117 UDISKS2_DRIVE_PROPERTY_CONNECTION_BUS = "ConnectionBus"
3118
3119 def __init__(self, system_bus, loop, action, devices, minimum_speed,
3120- memorycard, unmounted = False):
3121+ memorycard, unmounted=False):
3122 # Store the desired minimum speed of the device in Mbit/s. The argument
3123 # is passed as the number of bits per second so let's fix that.
3124 self._desired_minimum_speed = minimum_speed / 10 ** 6
3125@@ -581,43 +588,49 @@ class UDisks2StorageDeviceListener:
3126 continue
3127 # For devices with empty "ConnectionBus" property, don't
3128 # require the device to be mounted
3129- if (record.value.iface_name ==
3130- "org.freedesktop.UDisks2.Drive"
3131- and record.value.delta_type == DELTA_TYPE_PROP
3132- and record.value.prop_name == "ConnectionBus"
3133- and record.value.prop_value == ""):
3134+ if (
3135+ record.value.iface_name ==
3136+ "org.freedesktop.UDisks2.Drive" and
3137+ record.value.delta_type == DELTA_TYPE_PROP and
3138+ record.value.prop_name == "ConnectionBus" and
3139+ record.value.prop_value == ""
3140+ ):
3141 needs.remove('mounted')
3142 # Detect block devices designated for filesystems
3143- if (record.value.iface_name ==
3144- "org.freedesktop.UDisks2.Block"
3145- and record.value.delta_type == DELTA_TYPE_PROP
3146- and record.value.prop_name == "IdUsage"
3147- and record.value.prop_value == "filesystem"):
3148+ if (
3149+ record.value.iface_name ==
3150+ "org.freedesktop.UDisks2.Block" and
3151+ record.value.delta_type == DELTA_TYPE_PROP and
3152+ record.value.prop_name == "IdUsage" and
3153+ record.value.prop_value == "filesystem"
3154+ ):
3155 found.add('block-fs')
3156 # Memorize the block device path
3157- elif (record.value.iface_name ==
3158- "org.freedesktop.UDisks2.Block"
3159- and record.value.delta_type == DELTA_TYPE_PROP
3160- and record.value.prop_name == "PreferredDevice"):
3161+ elif (
3162+ record.value.iface_name ==
3163+ "org.freedesktop.UDisks2.Block" and
3164+ record.value.delta_type == DELTA_TYPE_PROP and
3165+ record.value.prop_name == "PreferredDevice"
3166+ ):
3167 object_block_device = record.value.prop_value
3168 # Ensure the device is a partition
3169 elif (record.value.iface_name ==
3170- "org.freedesktop.UDisks2.Partition"
3171- and record.value.delta_type == DELTA_TYPE_IFACE):
3172+ "org.freedesktop.UDisks2.Partition" and
3173+ record.value.delta_type == DELTA_TYPE_IFACE):
3174 found.add('partition')
3175 # Ensure the device is not empty
3176 elif (record.value.iface_name ==
3177- "org.freedesktop.UDisks2.Block"
3178- and record.value.delta_type == DELTA_TYPE_PROP
3179- and record.value.prop_name == "Size"
3180- and record.value.prop_value > 0):
3181+ "org.freedesktop.UDisks2.Block" and
3182+ record.value.delta_type == DELTA_TYPE_PROP and
3183+ record.value.prop_name == "Size" and
3184+ record.value.prop_value > 0):
3185 found.add('non-empty')
3186 # Ensure the filesystem is mounted
3187 elif (record.value.iface_name ==
3188- "org.freedesktop.UDisks2.Filesystem"
3189- and record.value.delta_type == DELTA_TYPE_PROP
3190- and record.value.prop_name == "MountPoints"
3191- and record.value.prop_value != []):
3192+ "org.freedesktop.UDisks2.Filesystem" and
3193+ record.value.delta_type == DELTA_TYPE_PROP and
3194+ record.value.prop_name == "MountPoints" and
3195+ record.value.prop_value != []):
3196 found.add('mounted')
3197 # On some systems partition are reported as mounted
3198 # filesystems, without 'partition' record
3199@@ -625,9 +638,9 @@ class UDisks2StorageDeviceListener:
3200 needs.remove('partition')
3201 # Finally memorize the drive the block device belongs to
3202 elif (record.value.iface_name ==
3203- "org.freedesktop.UDisks2.Block"
3204- and record.value.delta_type == DELTA_TYPE_PROP
3205- and record.value.prop_name == "Drive"):
3206+ "org.freedesktop.UDisks2.Block" and
3207+ record.value.delta_type == DELTA_TYPE_PROP and
3208+ record.value.prop_name == "Drive"):
3209 drive_object_path = record.value.prop_value
3210 logging.debug("Finished analyzing %s, found: %s, needs: %s"
3211 " drive_object_path: %s", object_path, found, needs,
3212@@ -845,8 +858,9 @@ def main():
3213 description = "Wait for the specified device to be inserted or removed."
3214 parser = argparse.ArgumentParser(description=description)
3215 parser.add_argument('action', choices=['insert', 'remove'])
3216- parser.add_argument('device', choices=['usb', 'sdio', 'firewire', 'scsi',
3217- 'ata_serial_esata'], nargs="+")
3218+ parser.add_argument(
3219+ 'device', choices=['usb', 'sdio', 'firewire', 'scsi',
3220+ 'ata_serial_esata'], nargs="+")
3221 memorycard_help = ("Memory cards devices on bus other than sdio require "
3222 "this parameter to identify them as such")
3223 parser.add_argument('--memorycard', action="store_true",
3224@@ -902,5 +916,6 @@ def main():
3225 except KeyboardInterrupt:
3226 return 1
3227
3228+
3229 if __name__ == "__main__":
3230 sys.exit(main())
3231diff --git a/bin/resolution_test.py b/bin/resolution_test.py
3232index 55a7828..77238ff 100755
3233--- a/bin/resolution_test.py
3234+++ b/bin/resolution_test.py
3235@@ -5,7 +5,7 @@ import sys
3236
3237 from argparse import ArgumentParser
3238 gi.require_version('Gdk', '3.0')
3239-from gi.repository import Gdk
3240+from gi.repository import Gdk # noqa: E402
3241
3242
3243 def check_resolution():
3244@@ -28,11 +28,13 @@ def compare_resolution(min_h, min_v):
3245
3246 def main():
3247 parser = ArgumentParser()
3248- parser.add_argument("--horizontal",
3249+ parser.add_argument(
3250+ "--horizontal",
3251 type=int,
3252 default=0,
3253 help="Minimum acceptable horizontal resolution.")
3254- parser.add_argument("--vertical",
3255+ parser.add_argument(
3256+ "--vertical",
3257 type=int,
3258 default=0,
3259 help="Minimum acceptable vertical resolution.")
3260diff --git a/bin/rotation_test.py b/bin/rotation_test.py
3261index 6bf90fd..de70f4a 100755
3262--- a/bin/rotation_test.py
3263+++ b/bin/rotation_test.py
3264@@ -27,7 +27,8 @@ import time
3265 import subprocess
3266
3267 gi.require_version('Gdk', '3.0')
3268-from gi.repository import Gdk
3269+from gi.repository import Gdk # noqa: E402
3270+
3271
3272 def main():
3273 """Run rotation cycling by running xrandr command."""
3274@@ -41,5 +42,6 @@ def main():
3275 ['xrandr', '--output', output, '--rotation', rotation])
3276 time.sleep(4)
3277
3278+
3279 if __name__ == '__main__':
3280 exit(main())
3281diff --git a/bin/sleep_test.py b/bin/sleep_test.py
3282index 423fd6c..3483951 100755
3283--- a/bin/sleep_test.py
3284+++ b/bin/sleep_test.py
3285@@ -184,19 +184,19 @@ class SuspendTest():
3286 if perf:
3287 for idx in range(0, len(loglist)):
3288 if 'PM: Syncing filesystems' in loglist[idx]:
3289- sleep_start_time = re.split('[\[\]]',
3290+ sleep_start_time = re.split(r'[\[\]]',
3291 loglist[idx])[1].strip()
3292 logging.debug('Sleep started at %s' % sleep_start_time)
3293 if 'ACPI: Low-level resume complete' in loglist[idx]:
3294- sleep_end_time = re.split('[\[\]]',
3295+ sleep_end_time = re.split(r'[\[\]]',
3296 loglist[idx - 1])[1].strip()
3297 logging.debug('Sleep ended at %s' % sleep_end_time)
3298- resume_start_time = re.split('[\[\]]',
3299+ resume_start_time = re.split(r'[\[\]]',
3300 loglist[idx])[1].strip()
3301 logging.debug('Resume started at %s' % resume_start_time)
3302 idx += 1
3303 if 'Restarting tasks' in loglist[idx]:
3304- resume_end_time = re.split('[\[\]]',
3305+ resume_end_time = re.split(r'[\[\]]',
3306 loglist[idx])[1].strip()
3307 logging.debug('Resume ended at %s' % resume_end_time)
3308 if self.end_marker in loglist[idx]:
3309@@ -395,5 +395,6 @@ def main():
3310 options.iterations)
3311 return 0
3312
3313+
3314 if __name__ == '__main__':
3315 sys.exit(main())
3316diff --git a/bin/sleep_test_log_check.py b/bin/sleep_test_log_check.py
3317index aae7556..350bbbb 100755
3318--- a/bin/sleep_test_log_check.py
3319+++ b/bin/sleep_test_log_check.py
3320@@ -138,8 +138,9 @@ def main():
3321
3322 logging.basicConfig(level=args.debug)
3323
3324- #Create a generator and get our lines
3325- log = (line.rstrip() for line in open(args.logfile, 'rt', encoding="UTF-8"))
3326+ # Create a generator and get our lines
3327+ log = (
3328+ line.rstrip() for line in open(args.logfile, 'rt', encoding="UTF-8"))
3329
3330 # End result will be a dictionary with a key per level, value is another
3331 # dictionary with a key per test (s3, s4, ...) and a list of all failures
3332@@ -166,9 +167,8 @@ def main():
3333
3334 # Report what I found
3335 for level in sorted(results.keys()):
3336- if results[level]: # Yes, we can have an empty level. We may have
3337- # seen the levelheader but had it report no
3338- # failures.
3339+ if results[level]: # Yes, we can have an empty level.
3340+ # We may have seen the levelheader but had it report no failures.
3341 print("{} failures:".format(level))
3342 for test in results[level].keys():
3343 print(" {}: {} failures".format(test,
3344@@ -184,8 +184,8 @@ def main():
3345 logging.error("No fwts test summaries found, "
3346 "possible malformed fwts log file")
3347 return_code = 2
3348- elif not results.keys(): # If it has no keys, means we didn't see any
3349- # FWTS levels
3350+ elif not results.keys():
3351+ # If it has no keys, means we didn't see any FWTS levels
3352 logging.error("None of the summaries contained failure levels, "
3353 "possible malformed fwts log file")
3354 return_code = 2
3355@@ -197,5 +197,6 @@ def main():
3356
3357 return return_code
3358
3359+
3360 if __name__ == '__main__':
3361 sys.exit(main())
3362diff --git a/bin/sleep_time_check.py b/bin/sleep_time_check.py
3363index f9513fa..90e1bc7 100755
3364--- a/bin/sleep_time_check.py
3365+++ b/bin/sleep_time_check.py
3366@@ -53,13 +53,18 @@ def main():
3367 print(e)
3368 return 1
3369
3370- if (sleep_time is None or resume_time is None) or \
3371- (len(sleep_times) != len(resume_times)):
3372+ if (
3373+ (sleep_time is None or resume_time is None) or
3374+ (len(sleep_times) != len(resume_times))
3375+ ):
3376 print("ERROR: One or more times was not reported correctly")
3377 return 1
3378
3379- print("Average time to enter sleep state: %.4f seconds" % mean(sleep_times))
3380- print("Average time to resume from sleep state: %.4f seconds" % mean(resume_times))
3381+ print(
3382+ "Average time to enter sleep state: %.4f seconds" % mean(sleep_times))
3383+ print(
3384+ "Average time to resume from sleep state: %.4f seconds" % mean(
3385+ resume_times))
3386
3387 failed = 0
3388 if sleep_time > args.sleep_threshold:
3389@@ -76,5 +81,6 @@ def main():
3390
3391 return failed
3392
3393+
3394 if __name__ == "__main__":
3395 sys.exit(main())
3396diff --git a/bin/stress_ng_test.py b/bin/stress_ng_test.py
3397index b8c2586..35aad2d 100755
3398--- a/bin/stress_ng_test.py
3399+++ b/bin/stress_ng_test.py
3400@@ -138,7 +138,7 @@ def num_numa_nodes():
3401 try:
3402 return int(run(['numactl', '--hardware'],
3403 stdout=PIPE).stdout.split()[1])
3404- except:
3405+ except (ValueError, OSError, IndexError):
3406 return 1
3407
3408
3409diff --git a/bin/test_bt_keyboard.py b/bin/test_bt_keyboard.py
3410index 1457a1d..782ae20 100755
3411--- a/bin/test_bt_keyboard.py
3412+++ b/bin/test_bt_keyboard.py
3413@@ -5,7 +5,7 @@
3414 # Written by:
3415 # Maciej Kisielewski <maciej.kisielewski@canonical.com>
3416
3417-import checkbox_support.bt_helper
3418+import checkbox_support.bt_helper as bt_helper
3419
3420
3421 def main():
3422diff --git a/bin/testlib.py b/bin/testlib.py
3423deleted file mode 100755
3424index 5f783f8..0000000
3425--- a/bin/testlib.py
3426+++ /dev/null
3427@@ -1,1450 +0,0 @@
3428-from __future__ import print_function
3429-#
3430-# testlib.py quality assurance test script
3431-# Copyright (C) 2008-2016 Canonical Ltd.
3432-#
3433-# This library is free software; you can redistribute it and/or
3434-# modify it under the terms of the GNU Library General Public
3435-# License as published by the Free Software Foundation; either
3436-# version 2 of the License.
3437-#
3438-# This library is distributed in the hope that it will be useful,
3439-# but WITHOUT ANY WARRANTY; without even the implied warranty of
3440-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
3441-# Library General Public License for more details.
3442-#
3443-# You should have received a copy of the GNU Library General Public
3444-# License along with this program. If not, see
3445-# <http://www.gnu.org/licenses/>.
3446-#
3447-
3448-'''Common classes and functions for package tests.'''
3449-
3450-import crypt
3451-import glob
3452-import grp
3453-import gzip
3454-import os
3455-import os.path
3456-import platform
3457-import pwd
3458-import random
3459-import re
3460-import shutil
3461-import socket
3462-import string
3463-import subprocess
3464-import sys
3465-import tempfile
3466-import time
3467-import unittest
3468-
3469-from stat import ST_SIZE
3470-
3471-# Don't make python-pexpect mandatory
3472-try:
3473- import pexpect
3474-except ImportError:
3475- pass
3476-
3477-import warnings
3478-warnings.filterwarnings('ignore', message=r'.*apt_pkg\.TagFile.*', category=DeprecationWarning)
3479-try:
3480- import apt_pkg
3481- # cope with apt_pkg api changes.
3482- if 'init_system' in dir(apt_pkg):
3483- apt_pkg.init_system()
3484- else:
3485- apt_pkg.InitSystem()
3486-except:
3487- # On non-Debian system, fall back to simple comparison without debianisms
3488- class apt_pkg(object):
3489- @staticmethod
3490- def version_compare(one, two):
3491- list_one = one.split('.')
3492- list_two = two.split('.')
3493- while len(list_one) > 0 and len(list_two) > 0:
3494- try:
3495- if int(list_one[0]) > int(list_two[0]):
3496- return 1
3497- if int(list_one[0]) < int(list_two[0]):
3498- return -1
3499- except:
3500- # ugh, non-numerics in the version, fall back to
3501- # string comparison, which will be wrong for e.g.
3502- # 3.2 vs 3.16rc1
3503- if list_one[0] > list_two[0]:
3504- return 1
3505- if list_one[0] < list_two[0]:
3506- return -1
3507- list_one.pop(0)
3508- list_two.pop(0)
3509- return 0
3510-
3511- @staticmethod
3512- def VersionCompare(one, two):
3513- return apt_pkg.version_compare(one, two)
3514-
3515-bogus_nxdomain = "208.69.32.132"
3516-
3517-# http://www.chiark.greenend.org.uk/ucgi/~cjwatson/blosxom/2009-07-02-python-sigpipe.html
3518-# This is needed so that the subprocesses that produce endless output
3519-# actually quit when the reader goes away.
3520-import signal
3521-def subprocess_setup():
3522- # Python installs a SIGPIPE handler by default. This is usually not what
3523- # non-Python subprocesses expect.
3524- signal.signal(signal.SIGPIPE, signal.SIG_DFL)
3525-
3526-
3527-class TimedOutException(Exception):
3528- def __init__(self, value="Timed Out"):
3529- self.value = value
3530-
3531- def __str__(self):
3532- return repr(self.value)
3533-
3534-
3535-def _restore_backup(path):
3536- pathbackup = path + '.autotest'
3537- if os.path.exists(pathbackup):
3538- shutil.move(pathbackup, path)
3539-
3540-
3541-def _save_backup(path):
3542- pathbackup = path + '.autotest'
3543- if os.path.exists(path) and not os.path.exists(pathbackup):
3544- shutil.copy2(path, pathbackup)
3545- # copy2 does not copy ownership, so do it here.
3546- # Reference: http://docs.python.org/library/shutil.html
3547- a = os.stat(path)
3548- os.chown(pathbackup, a[4], a[5])
3549-
3550-
3551-def config_copydir(path):
3552- if os.path.exists(path) and not os.path.isdir(path):
3553- raise OSError("'%s' is not a directory" % (path))
3554- _restore_backup(path)
3555-
3556- pathbackup = path + '.autotest'
3557- if os.path.exists(path):
3558- shutil.copytree(path, pathbackup, symlinks=True)
3559-
3560-
3561-def config_replace(path, contents, append=False):
3562- '''Replace (or append) to a config file'''
3563- _restore_backup(path)
3564- if os.path.exists(path):
3565- _save_backup(path)
3566- if append:
3567- with open(path) as fh:
3568- contents = fh.read() + contents
3569- with open(path, 'w') as fh:
3570- fh.write(contents)
3571-
3572-
3573-def config_comment(path, field):
3574- _save_backup(path)
3575- contents = ""
3576- with open(path) as fh:
3577- for line in fh:
3578- if re.search("^\s*%s\s*=" % (field), line):
3579- line = "#" + line
3580- contents += line
3581-
3582- with open(path + '.new', 'w') as new_fh:
3583- new_fh.write(contents)
3584- os.rename(path + '.new', path)
3585-
3586-
3587-def config_set(path, field, value, spaces=True):
3588- _save_backup(path)
3589- contents = ""
3590- if spaces:
3591- setting = '%s = %s\n' % (field, value)
3592- else:
3593- setting = '%s=%s\n' % (field, value)
3594- found = False
3595- with open(path) as fh:
3596- for line in fh:
3597- if re.search("^\s*%s\s*=" % (field), line):
3598- found = True
3599- line = setting
3600- contents += line
3601- if not found:
3602- contents += setting
3603-
3604- with open(path + '.new', 'w') as new_config:
3605- new_config.write(contents)
3606- os.rename(path + '.new', path)
3607-
3608-
3609-def config_patch(path, patch, depth=1):
3610- '''Patch a config file'''
3611- _restore_backup(path)
3612- _save_backup(path)
3613-
3614- handle, name = mkstemp_fill(patch)
3615- rc = subprocess.call(['/usr/bin/patch', '-p%s' % depth, path], stdin=handle, stdout=subprocess.PIPE)
3616- os.unlink(name)
3617- if rc != 0:
3618- raise Exception("Patch failed")
3619-
3620-
3621-def config_restore(path):
3622- '''Rename a replaced config file back to its initial state'''
3623- _restore_backup(path)
3624-
3625-
3626-def timeout(secs, f, *args):
3627- def handler(signum, frame):
3628- raise TimedOutException()
3629-
3630- old = signal.signal(signal.SIGALRM, handler)
3631- result = None
3632- signal.alarm(secs)
3633- try:
3634- result = f(*args)
3635- finally:
3636- signal.alarm(0)
3637- signal.signal(signal.SIGALRM, old)
3638-
3639- return result
3640-
3641-
3642-def require_nonroot():
3643- if os.geteuid() == 0:
3644- print("This series of tests should be run as a regular user with sudo access, not as root.", file=sys.stderr)
3645- sys.exit(1)
3646-
3647-
3648-def require_root():
3649- if os.geteuid() != 0:
3650- print("This series of tests should be run with root privileges (e.g. via sudo).", file=sys.stderr)
3651- sys.exit(1)
3652-
3653-
3654-def require_sudo():
3655- if os.geteuid() != 0 or os.environ.get('SUDO_USER', None) is None:
3656- print("This series of tests must be run under sudo.", file=sys.stderr)
3657- sys.exit(1)
3658- if os.environ['SUDO_USER'] == 'root':
3659- print('Please run this test using sudo from a regular user. (You ran sudo from root.)', file=sys.stderr)
3660- sys.exit(1)
3661-
3662-
3663-def random_string(length, lower=False):
3664- '''Return a random string, consisting of ASCII letters, with given
3665- length.'''
3666-
3667- s = ''
3668- selection = string.ascii_letters
3669- if lower:
3670- selection = string.ascii_lowercase
3671- maxind = len(selection) - 1
3672- for l in range(length):
3673- s += selection[random.randint(0, maxind)]
3674- return s
3675-
3676-
3677-def mkstemp_fill(contents, suffix='', prefix='testlib-', dir=None):
3678- '''As tempfile.mkstemp does, return a (file, name) pair, but with
3679- prefilled contents.'''
3680-
3681- handle, name = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)
3682- os.close(handle)
3683- handle = open(name, "w+")
3684- handle.write(contents)
3685- handle.flush()
3686- handle.seek(0)
3687-
3688- return handle, name
3689-
3690-
3691-def create_fill(path, contents, mode=0o644):
3692- '''Safely create a page'''
3693- # make the temp file in the same dir as the destination file so we
3694- # don't get invalid cross-device link errors when we rename
3695- handle, name = mkstemp_fill(contents, dir=os.path.dirname(path))
3696- handle.close()
3697- os.rename(name, path)
3698- os.chmod(path, mode)
3699-
3700-
3701-def login_exists(login):
3702- '''Checks whether the given login exists on the system.'''
3703-
3704- try:
3705- pwd.getpwnam(login)
3706- return True
3707- except KeyError:
3708- return False
3709-
3710-
3711-def group_exists(group):
3712- '''Checks whether the given login exists on the system.'''
3713-
3714- try:
3715- grp.getgrnam(group)
3716- return True
3717- except KeyError:
3718- return False
3719-
3720-
3721-def is_empty_file(path):
3722- '''test if file is empty, returns True if so'''
3723- with open(path) as fh:
3724- return (len(fh.read()) == 0)
3725-
3726-
3727-def recursive_rm(dirPath, contents_only=False):
3728- '''recursively remove directory'''
3729- names = os.listdir(dirPath)
3730- for name in names:
3731- path = os.path.join(dirPath, name)
3732- if os.path.islink(path) or not os.path.isdir(path):
3733- os.unlink(path)
3734- else:
3735- recursive_rm(path)
3736- if not contents_only:
3737- os.rmdir(dirPath)
3738-
3739-
3740-def check_pidfile(exe, pidfile):
3741- '''Checks if pid in pidfile is running'''
3742- if not os.path.exists(pidfile):
3743- return False
3744-
3745- # get the pid
3746- try:
3747- with open(pidfile, 'r') as fd:
3748- pid = fd.readline().rstrip('\n')
3749- except:
3750- return False
3751-
3752- return check_pid(exe, pid)
3753-
3754-
3755-def check_pid(exe, pid):
3756- '''Checks if pid is running'''
3757- cmdline = "/proc/%s/cmdline" % (str(pid))
3758- if not os.path.exists(cmdline):
3759- return False
3760-
3761- # get the command line
3762- try:
3763- with open(cmdline, 'r') as fd:
3764- tmp = fd.readline().split('\0')
3765- except:
3766- return False
3767-
3768- # this allows us to match absolute paths or just the executable name
3769- if re.match('^' + exe + '$', tmp[0]) or \
3770- re.match('.*/' + exe + '$', tmp[0]) or \
3771- re.match('^' + exe + ': ', tmp[0]) or \
3772- re.match('^\(' + exe + '\)', tmp[0]):
3773- return True
3774-
3775- return False
3776-
3777-
3778-def check_port(port, proto, ver=4):
3779- '''Check if something is listening on the specified port.
3780- WARNING: for some reason this does not work with a bind mounted /proc
3781- '''
3782- assert (port >= 1)
3783- assert (port <= 65535)
3784- assert (proto.lower() == "tcp" or proto.lower() == "udp")
3785- assert (ver == 4 or ver == 6)
3786-
3787- fn = "/proc/net/%s" % (proto)
3788- if ver == 6:
3789- fn += str(ver)
3790-
3791- rc, report = cmd(['cat', fn])
3792- assert (rc == 0)
3793-
3794- hport = "%0.4x" % port
3795-
3796- if re.search(': [0-9a-f]{8}:%s [0-9a-f]' % str(hport).lower(), report.lower()):
3797- return True
3798- return False
3799-
3800-
3801-def get_arch():
3802- '''Get the current architecture'''
3803- rc, report = cmd(['uname', '-m'])
3804- assert (rc == 0)
3805- return report.strip()
3806-
3807-
3808-def get_multiarch_tuple():
3809- '''Get the current debian multiarch tuple'''
3810-
3811- # XXX dpkg-architecture on Ubuntu 12.04 requires -q be adjacent to
3812- # the variable name
3813- rc, report = cmd(['dpkg-architecture', '-qDEB_HOST_MULTIARCH'])
3814- assert (rc == 0)
3815- return report.strip()
3816-
3817-
3818-def get_bits():
3819- '''return the default architecture number of bits (32 or 64, usually)'''
3820- return platform.architecture()[0][0:2]
3821-
3822-
3823-def get_memory():
3824- '''Gets total ram and swap'''
3825- meminfo = "/proc/meminfo"
3826- memtotal = 0
3827- swaptotal = 0
3828- if not os.path.exists(meminfo):
3829- return (False, False)
3830-
3831- try:
3832- fd = open(meminfo, 'r')
3833- for line in fd.readlines():
3834- splitline = line.split()
3835- if splitline[0] == 'MemTotal:':
3836- memtotal = int(splitline[1])
3837- elif splitline[0] == 'SwapTotal:':
3838- swaptotal = int(splitline[1])
3839- fd.close()
3840- except:
3841- return (False, False)
3842-
3843- return (memtotal, swaptotal)
3844-
3845-
3846-def is_running_in_vm():
3847- '''Check if running under a VM'''
3848- # add other virtualization environments here
3849- for search in ['QEMU Virtual CPU']:
3850- rc, report = cmd_pipe(['dmesg'], ['grep', search])
3851- if rc == 0:
3852- return True
3853- return False
3854-
3855-
3856-def ubuntu_release():
3857- '''Get the Ubuntu release'''
3858- f = "/etc/lsb-release"
3859- try:
3860- size = os.stat(f)[ST_SIZE]
3861- except:
3862- return "UNKNOWN"
3863-
3864- if size > 1024 * 1024:
3865- raise IOError('Could not open "%s" (too big)' % f)
3866-
3867- with open("/etc/lsb-release", 'r') as fh:
3868- lines = fh.readlines()
3869-
3870- pat = re.compile(r'DISTRIB_CODENAME')
3871- for line in lines:
3872- if pat.search(line):
3873- return line.split('=')[1].rstrip('\n').rstrip('\r')
3874-
3875- return "UNKNOWN"
3876-
3877-
3878-def cmd(command, input=None, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, stdin=None, timeout=None, env=None):
3879- '''Try to execute given command (array) and return its stdout, or return
3880- a textual error if it failed.'''
3881-
3882- try:
3883- sp = subprocess.Popen(command, stdin=stdin, stdout=stdout, stderr=stderr, close_fds=True, preexec_fn=subprocess_setup, env=env, universal_newlines=True)
3884- except OSError as e:
3885- return [127, str(e)]
3886-
3887- out, outerr = sp.communicate(input)
3888- # Handle redirection of stdout
3889- if out is None:
3890- out = ''
3891- # Handle redirection of stderr
3892- if outerr is None:
3893- outerr = ''
3894- return [sp.returncode, out + outerr]
3895-
3896-
3897-def cmd_pipe(command1, command2, input=None, stderr=subprocess.STDOUT, stdin=None):
3898- '''Try to pipe command1 into command2.'''
3899- try:
3900- sp1 = subprocess.Popen(command1, stdin=stdin, stdout=subprocess.PIPE, stderr=stderr, close_fds=True)
3901- sp2 = subprocess.Popen(command2, stdin=sp1.stdout, stdout=subprocess.PIPE, stderr=stderr, close_fds=True)
3902- except OSError as e:
3903- return [127, str(e)]
3904-
3905- out = sp2.communicate(input)[0]
3906- return [sp2.returncode, out]
3907-
3908-
3909-def cwd_has_enough_space(cdir, total_bytes):
3910- '''Determine if the partition of the current working directory has 'bytes'
3911- free.'''
3912- rc, df_output = cmd(['df'])
3913- if rc != 0:
3914- result = 'df failed, got exit code %d, expected %d\n' % (rc, 0)
3915- raise OSError(result)
3916- if rc != 0:
3917- return False
3918-
3919- kb = total_bytes / 1024
3920-
3921- mounts = dict()
3922- for line in df_output.splitlines():
3923- if '/' not in line:
3924- continue
3925- tmp = line.split()
3926- mounts[tmp[5]] = int(tmp[3])
3927-
3928- cdir = os.getcwd()
3929- while cdir != '/':
3930- if cdir not in mounts:
3931- cdir = os.path.dirname(cdir)
3932- continue
3933- return kb < mounts[cdir]
3934-
3935- return kb < mounts['/']
3936-
3937-
3938-def get_md5(filename):
3939- '''Gets the md5sum of the file specified'''
3940-
3941- (rc, report) = cmd(["/usr/bin/md5sum", "-b", filename])
3942- expected = 0
3943- assert (expected == rc)
3944-
3945- return report.split(' ')[0]
3946-
3947-
3948-def dpkg_compare_installed_version(pkg, check, version):
3949- '''Gets the version for the installed package, and compares it to the
3950- specified version.
3951- '''
3952- (rc, report) = cmd(["/usr/bin/dpkg", "-s", pkg])
3953- assert (rc == 0)
3954- assert ("Status: install ok installed" in report)
3955- installed_version = ""
3956- for line in report.splitlines():
3957- if line.startswith("Version: "):
3958- installed_version = line.split()[1]
3959-
3960- assert (installed_version != "")
3961-
3962- (rc, report) = cmd(["/usr/bin/dpkg", "--compare-versions", installed_version, check, version])
3963- assert (rc == 0 or rc == 1)
3964- if rc == 0:
3965- return True
3966- return False
3967-
3968-
3969-def _run_apt_command(pkg_list, apt_cmd='install'):
3970- env = os.environ.copy()
3971- env['DEBIAN_FRONTEND'] = 'noninteractive'
3972- # debugging version, but on precise doesn't actually run dpkg
3973- # command = ['apt-get', '-y', '--force-yes', '-o', 'Dpkg::Options::=--force-confold', '-o', 'Debug::pkgDPkgPM=true', apt_cmd]
3974- command = ['apt-get', '-y', '--force-yes', '-o', 'Dpkg::Options::=--force-confold', apt_cmd]
3975- command.extend(pkg_list)
3976- rc, report = cmd(command)
3977- return rc, report
3978-
3979-
3980-# note: for the following install_* functions, you probably want the
3981-# versions in the TestlibCase class (see below)
3982-def install_builddeps(src_pkg):
3983- rc, report = _run_apt_command([src_pkg], 'build-dep')
3984- assert(rc == 0)
3985-
3986-
3987-def install_package(package):
3988- rc, report = _run_apt_command([package], 'install')
3989- assert(rc == 0)
3990-
3991-
3992-def install_packages(pkg_list):
3993- rc, report = _run_apt_command(pkg_list, 'install')
3994- assert(rc == 0)
3995-
3996-
3997-def prepare_source(source, builder, cached_src, build_src, patch_system):
3998- '''Download and unpack source package, installing necessary build depends,
3999- adjusting the permissions for the 'builder' user, and returning the
4000- directory of the unpacked source. Patch system can be one of:
4001- - cdbs
4002- - dpatch
4003- - quilt
4004- - quiltv3
4005- - None (not the string)
4006-
4007- This is normally used like this:
4008-
4009- def setUp(self):
4010- ...
4011- self.topdir = os.getcwd()
4012- self.cached_src = os.path.join(os.getcwd(), "source")
4013- self.tmpdir = tempfile.mkdtemp(prefix='testlib', dir='/tmp')
4014- self.builder = testlib.TestUser()
4015- testlib.cmd(['chgrp', self.builder.login, self.tmpdir])
4016- os.chmod(self.tmpdir, 0o775)
4017-
4018- def tearDown(self):
4019- ...
4020- self.builder = None
4021- self.topdir = os.getcwd()
4022- if os.path.exists(self.tmpdir):
4023- testlib.recursive_rm(self.tmpdir)
4024-
4025- def test_suite_build(self):
4026- ...
4027- build_dir = testlib.prepare_source('foo', \
4028- self.builder, \
4029- self.cached_src, \
4030- os.path.join(self.tmpdir, \
4031- os.path.basename(self.cached_src)),
4032- "quilt")
4033- os.chdir(build_dir)
4034-
4035- # Example for typical build, adjust as necessary
4036- print("")
4037- print(" make clean")
4038- rc, report = testlib.cmd(['sudo', '-u', self.builder.login, 'make', 'clean'])
4039-
4040- print(" configure")
4041- rc, report = testlib.cmd(['sudo', '-u', self.builder.login, './configure', '--prefix=%s' % self.tmpdir, '--enable-debug'])
4042-
4043- print(" make (will take a while)")
4044- rc, report = testlib.cmd(['sudo', '-u', self.builder.login, 'make'])
4045-
4046- print(" make check (will take a while)",)
4047- rc, report = testlib.cmd(['sudo', '-u', self.builder.login, 'make', 'check'])
4048- expected = 0
4049- result = 'Got exit code %d, expected %d\n' % (rc, expected)
4050- self.assertEqual(expected, rc, result + report)
4051-
4052- def test_suite_cleanup(self):
4053- ...
4054- if os.path.exists(self.cached_src):
4055- testlib.recursive_rm(self.cached_src)
4056-
4057- It is up to the caller to clean up cached_src and build_src (as in the
4058- above example, often the build_src is in a tmpdir that is cleaned in
4059- tearDown() and the cached_src is cleaned in a one time clean-up
4060- operation (eg 'test_suite_cleanup()) which must be run after the build
4061- suite test (obviously).
4062- '''
4063-
4064- # Make sure we have a clean slate
4065- assert (os.path.exists(os.path.dirname(build_src)))
4066- assert (not os.path.exists(build_src))
4067-
4068- cdir = os.getcwd()
4069- if os.path.exists(cached_src):
4070- shutil.copytree(cached_src, build_src)
4071- os.chdir(build_src)
4072- else:
4073- # Only install the build dependencies on the initial setup
4074- install_builddeps(source)
4075- os.makedirs(build_src)
4076- os.chdir(build_src)
4077-
4078- # These are always needed
4079- pkgs = ['build-essential', 'dpkg-dev', 'fakeroot']
4080- install_packages(pkgs)
4081-
4082- rc, report = cmd(['apt-get', 'source', source])
4083- assert (rc == 0)
4084- shutil.copytree(build_src, cached_src)
4085- print("(unpacked %s)" % os.path.basename(glob.glob('%s_*.dsc' % source)[0]), end=' ')
4086-
4087- unpacked_dir = os.path.join(build_src, glob.glob('%s-*' % source)[0])
4088-
4089- # Now apply the patches. Do it here so that we don't mess up our cached
4090- # sources.
4091- os.chdir(unpacked_dir)
4092- assert (patch_system in ['cdbs', 'dpatch', 'quilt', 'quiltv3', None])
4093- if patch_system is not None and patch_system != "quiltv3":
4094- if patch_system == "quilt":
4095- os.environ.setdefault('QUILT_PATCHES', 'debian/patches')
4096- rc, report = cmd(['quilt', 'push', '-a'])
4097- assert (rc == 0)
4098- elif patch_system == "cdbs":
4099- rc, report = cmd(['./debian/rules', 'apply-patches'])
4100- assert (rc == 0)
4101- elif patch_system == "dpatch":
4102- rc, report = cmd(['dpatch', 'apply-all'])
4103- assert (rc == 0)
4104-
4105- cmd(['chown', '-R', '%s:%s' % (builder.uid, builder.gid), build_src])
4106- os.chdir(cdir)
4107-
4108- return unpacked_dir
4109-
4110-
4111-def get_changelog_version(source_dir):
4112- '''Extract a package version from a changelog'''
4113- package_version = ""
4114-
4115- changelog_file = os.path.join(source_dir, "debian/changelog")
4116-
4117- if os.path.exists(changelog_file):
4118- changelog = open(changelog_file, 'r')
4119- header = changelog.readline().split()
4120- package_version = header[1].strip('()')
4121-
4122- return package_version
4123-
4124-
4125-def _aa_status():
4126- '''Get aa-status output'''
4127- exe = "/usr/sbin/aa-status"
4128- assert (os.path.exists(exe))
4129- if os.geteuid() == 0:
4130- return cmd([exe])
4131- return cmd(['sudo', exe])
4132-
4133-
4134-def is_apparmor_loaded(path):
4135- '''Check if profile is loaded'''
4136- rc, report = _aa_status()
4137- if rc != 0:
4138- return False
4139-
4140- for line in report.splitlines():
4141- if line.endswith(path):
4142- return True
4143- return False
4144-
4145-
4146-def is_apparmor_confined(path):
4147- '''Check if application is confined'''
4148- rc, report = _aa_status()
4149- if rc != 0:
4150- return False
4151-
4152- for line in report.splitlines():
4153- if re.search('%s \(' % path, line):
4154- return True
4155- return False
4156-
4157-
4158-def check_apparmor(path, first_ubuntu_release, is_running=True):
4159- '''Check if path is loaded and confined for everything higher than the
4160- first Ubuntu release specified.
4161-
4162- Usage:
4163- rc, report = testlib.check_apparmor('/usr/sbin/foo', 8.04, is_running=True)
4164- if rc < 0:
4165- return self._skipped(report)
4166-
4167- expected = 0
4168- result = 'Got exit code %d, expected %d\n' % (rc, expected)
4169- self.assertEqual(expected, rc, result + report)
4170- '''
4171- global manager
4172- rc = -1
4173-
4174- if manager.lsb_release["Release"] < first_ubuntu_release:
4175- return (rc, "Skipped apparmor check")
4176-
4177- if not os.path.exists('/sbin/apparmor_parser'):
4178- return (rc, "Skipped (couldn't find apparmor_parser)")
4179-
4180- rc = 0
4181- msg = ""
4182- if not is_apparmor_loaded(path):
4183- rc = 1
4184- msg = "Profile not loaded for '%s'" % path
4185-
4186- # this check only makes sense it the 'path' is currently executing
4187- if is_running and rc == 0 and not is_apparmor_confined(path):
4188- rc = 1
4189- msg = "'%s' is not running in enforce mode" % path
4190-
4191- return (rc, msg)
4192-
4193-
4194-def get_gcc_version(gcc, full=True):
4195- gcc_version = 'none'
4196- if not gcc.startswith('/'):
4197- gcc = '/usr/bin/%s' % (gcc)
4198- if os.path.exists(gcc):
4199- gcc_version = 'unknown'
4200- lines = cmd([gcc, '-v'])[1].strip().splitlines()
4201- version_lines = [x for x in lines if x.startswith('gcc version')]
4202- if len(version_lines) == 1:
4203- gcc_version = " ".join(version_lines[0].split()[2:])
4204- if not full:
4205- return gcc_version.split()[0]
4206- return gcc_version
4207-
4208-
4209-def is_kdeinit_running():
4210- '''Test if kdeinit is running'''
4211- # applications that use kdeinit will spawn it if it isn't running in the
4212- # test. This is a problem because it does not exit. This is a helper to
4213- # check for it.
4214- rc, report = cmd(['ps', 'x'])
4215- if 'kdeinit4 Running' not in report:
4216- print("kdeinit not running (you may start/stop any KDE application then run this script again)", file=sys.stderr)
4217- return False
4218- return True
4219-
4220-
4221-def get_pkgconfig_flags(libs=[]):
4222- '''Find pkg-config flags for libraries'''
4223- assert (len(libs) > 0)
4224- rc, pkg_config = cmd(['pkg-config', '--cflags', '--libs'] + libs)
4225- expected = 0
4226- if rc != expected:
4227- print('Got exit code %d, expected %d\n' % (rc, expected), file=sys.stderr)
4228- assert(rc == expected)
4229- return pkg_config.split()
4230-
4231-
4232-def cap_to_name(cap_num):
4233- '''given an integer, return the capability name'''
4234- rc, output = cmd(['capsh', '--decode=%x' % cap_num])
4235- expected = 0
4236- if rc != expected:
4237- print('capsh: got exit code %d, expected %d\n' % (rc, expected), file=sys.stderr)
4238- cap_name = output.strip().split('=')[1]
4239- return cap_name
4240-
4241-
4242-def enumerate_capabilities():
4243- i = 0
4244- cap_list = []
4245- done = False
4246- while not done:
4247- cap_name = cap_to_name(pow(2, i))
4248- if cap_name == str(i):
4249- done = True
4250- else:
4251- cap_list.append(cap_name)
4252- i += 1
4253- if i > 64:
4254- done = True
4255- return cap_list
4256-
4257-
4258-class TestDaemon:
4259- '''Helper class to manage daemons consistently'''
4260- def __init__(self, init):
4261- '''Setup daemon attributes'''
4262- self.initscript = init
4263-
4264- def start(self):
4265- '''Start daemon'''
4266- rc, report = cmd([self.initscript, 'start'])
4267- expected = 0
4268- result = 'Got exit code %d, expected %d\n' % (rc, expected)
4269- time.sleep(2)
4270- if expected != rc:
4271- return (False, result + report)
4272-
4273- if "fail" in report:
4274- return (False, "Found 'fail' in report\n" + report)
4275-
4276- return (True, "")
4277-
4278- def stop(self):
4279- '''Stop daemon'''
4280- rc, report = cmd([self.initscript, 'stop'])
4281- expected = 0
4282- result = 'Got exit code %d, expected %d\n' % (rc, expected)
4283- if expected != rc:
4284- return (False, result + report)
4285-
4286- if "fail" in report:
4287- return (False, "Found 'fail' in report\n" + report)
4288-
4289- return (True, "")
4290-
4291- def reload(self):
4292- '''Reload daemon'''
4293- rc, report = cmd([self.initscript, 'force-reload'])
4294- expected = 0
4295- result = 'Got exit code %d, expected %d\n' % (rc, expected)
4296- if expected != rc:
4297- return (False, result + report)
4298-
4299- if "fail" in report:
4300- return (False, "Found 'fail' in report\n" + report)
4301-
4302- return (True, "")
4303-
4304- def restart(self):
4305- '''Restart daemon'''
4306- (res, str) = self.stop()
4307- if not res:
4308- return (res, str)
4309-
4310- (res, str) = self.start()
4311- if not res:
4312- return (res, str)
4313-
4314- return (True, "")
4315-
4316- def force_restart(self):
4317- '''Restart daemon even if already stopped'''
4318- (res, str) = self.stop()
4319-
4320- (res, str) = self.start()
4321- if not res:
4322- return (res, str)
4323-
4324- return (True, "")
4325-
4326- def status(self):
4327- '''Check daemon status'''
4328- rc, report = cmd([self.initscript, 'status'])
4329- expected = 0
4330- result = 'Got exit code %d, expected %d\n' % (rc, expected)
4331- if expected != rc:
4332- return (False, result + report)
4333-
4334- if "fail" in report:
4335- return (False, "Found 'fail' in report\n" + report)
4336-
4337- return (True, "")
4338-
4339-
4340-class TestlibManager(object):
4341- '''Singleton class used to set up per-test-run information'''
4342- def __init__(self):
4343- # Set glibc aborts to dump to stderr instead of the tty so test output
4344- # is more sane.
4345- os.environ.setdefault('LIBC_FATAL_STDERR_', '1')
4346-
4347- # check verbosity
4348- self.verbosity = False
4349- if (len(sys.argv) > 1 and '-v' in sys.argv[1:]):
4350- self.verbosity = True
4351-
4352- # Load LSB release file
4353- self.lsb_release = dict()
4354- if os.path.exists('/usr/bin/lsb_release') and not os.path.exists('/bin/lsb_release'):
4355- for line in subprocess.Popen(['lsb_release', '-a'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True).communicate()[0].splitlines():
4356- field, value = line.split(':', 1)
4357- value = value.strip()
4358- field = field.strip()
4359- # Convert numerics
4360- try:
4361- value = float(value)
4362- except:
4363- pass
4364- self.lsb_release.setdefault(field, value)
4365- if not self.lsb_release:
4366- self.lsb_release = {
4367- 'Distributor ID': 'Ubuntu Core',
4368- 'Description': 'Ubuntu Core 16',
4369- 'Release': 16,
4370- 'Codename': 'xenial',
4371- }
4372-
4373- # FIXME: hack OEM releases into known-Ubuntu versions
4374- if self.lsb_release['Distributor ID'] == "HP MIE (Mobile Internet Experience)":
4375- if self.lsb_release['Release'] == 1.0:
4376- self.lsb_release['Distributor ID'] = "Ubuntu"
4377- self.lsb_release['Release'] = 8.04
4378- else:
4379- raise OSError("Unknown version of HP MIE")
4380-
4381- # FIXME: hack to assume a most-recent release if we're not
4382- # running under Ubuntu.
4383- if self.lsb_release['Distributor ID'] not in ["Ubuntu", "Linaro"]:
4384- self.lsb_release['Release'] = 10000
4385- # Adjust Linaro release to pretend to be Ubuntu
4386- if self.lsb_release['Distributor ID'] in ["Linaro"]:
4387- self.lsb_release['Distributor ID'] = "Ubuntu"
4388- self.lsb_release['Release'] -= 0.01
4389-
4390- # Load arch
4391- if not os.path.exists('/usr/bin/dpkg'):
4392- machine = cmd(['uname', '-m'])[1].strip()
4393- if machine.endswith('86'):
4394- self.dpkg_arch = 'i386'
4395- elif machine.endswith('_64'):
4396- self.dpkg_arch = 'amd64'
4397- elif machine.startswith('arm'):
4398- self.dpkg_arch = 'armel'
4399- else:
4400- raise ValueError("Unknown machine type '%s'" % (machine))
4401- else:
4402- self.dpkg_arch = cmd(['dpkg', '--print-architecture'])[1].strip()
4403-
4404- # Find kernel version
4405- self.kernel_is_ubuntu = False
4406- self.kernel_version_signature = None
4407- self.kernel_version = cmd(["uname", "-r"])[1].strip()
4408- versig = '/proc/version_signature'
4409- if os.path.exists(versig):
4410- self.kernel_is_ubuntu = True
4411- self.kernel_version_signature = open(versig).read().strip()
4412- self.kernel_version_ubuntu = self.kernel_version
4413- elif os.path.exists('/usr/bin/dpkg'):
4414- # this can easily be inaccurate but is only an issue for Dapper
4415- rc, out = cmd(['dpkg', '-l', 'linux-image-%s' % (self.kernel_version)])
4416- if rc == 0:
4417- self.kernel_version_signature = out.strip().split('\n').pop().split()[2]
4418- self.kernel_version_ubuntu = self.kernel_version_signature
4419- if self.kernel_version_signature is None:
4420- # Attempt to fall back to something for non-Debian-based
4421- self.kernel_version_signature = self.kernel_version
4422- self.kernel_version_ubuntu = self.kernel_version
4423- # Build ubuntu version without hardware suffix
4424- try:
4425- self.kernel_version_ubuntu = "-".join([x for x in self.kernel_version_signature.split(' ')[1].split('-') if re.search('^[0-9]', x)])
4426- except:
4427- pass
4428-
4429- # Find gcc version
4430- self.gcc_version = get_gcc_version('gcc')
4431-
4432- # Find libc
4433- self.path_libc = [x.split()[2] for x in cmd(['ldd', '/bin/ls'])[1].splitlines() if x.startswith('\tlibc.so.')][0]
4434-
4435- # Report self
4436- if self.verbosity:
4437- kernel = self.kernel_version_ubuntu
4438- if kernel != self.kernel_version_signature:
4439- kernel += " (%s)" % (self.kernel_version_signature)
4440- print("Running test: '%s' distro: '%s %.2f' kernel: '%s' arch: '%s' uid: %d/%d SUDO_USER: '%s')" % (
4441- sys.argv[0],
4442- self.lsb_release['Distributor ID'],
4443- self.lsb_release['Release'],
4444- kernel,
4445- self.dpkg_arch,
4446- os.geteuid(), os.getuid(),
4447- os.environ.get('SUDO_USER', '')), file=sys.stdout)
4448- sys.stdout.flush()
4449-
4450- # Additional heuristics
4451- # if os.environ.get('SUDO_USER', os.environ.get('USER', '')) in ['mdeslaur']:
4452- # sys.stdout.write("Replying to Marc Deslauriers in http://launchpad.net/bugs/%d: " % random.randint(600000, 980000))
4453- # sys.stdout.flush()
4454- # time.sleep(0.5)
4455- # sys.stdout.write("destroyed\n")
4456- # time.sleep(0.5)
4457-
4458- def hello(self, msg):
4459- print("Hello from %s" % (msg), file=sys.stderr)
4460-# The central instance
4461-manager = TestlibManager()
4462-
4463-
4464-class TestlibCase(unittest.TestCase):
4465- def __init__(self, *args):
4466- '''This is called for each TestCase test instance, which isn't much better
4467- than SetUp.'''
4468-
4469- unittest.TestCase.__init__(self, *args)
4470-
4471- # Attach to and duplicate dicts from manager singleton
4472- self.manager = manager
4473- # self.manager.hello(repr(self) + repr(*args))
4474- self.my_verbosity = self.manager.verbosity
4475- self.lsb_release = self.manager.lsb_release
4476- self.dpkg_arch = self.manager.dpkg_arch
4477- self.kernel_version = self.manager.kernel_version
4478- self.kernel_version_signature = self.manager.kernel_version_signature
4479- self.kernel_version_ubuntu = self.manager.kernel_version_ubuntu
4480- self.kernel_is_ubuntu = self.manager.kernel_is_ubuntu
4481- self.gcc_version = self.manager.gcc_version
4482- self.path_libc = self.manager.path_libc
4483-
4484- def version_compare(self, one, two):
4485- if 'version_compare' in dir(apt_pkg):
4486- return apt_pkg.version_compare(one, two)
4487- else:
4488- return apt_pkg.VersionCompare(one, two)
4489-
4490- def assertFileType(self, filename, filetype, strict=True):
4491- '''Checks the file type of the file specified'''
4492-
4493- (rc, report, out) = self._testlib_shell_cmd(["/usr/bin/file", "-b", filename])
4494- out = out.strip()
4495- expected = 0
4496- # Absolutely no idea why this happens on Hardy
4497- if self.lsb_release['Release'] == 8.04 and rc == 255 and len(out) > 0:
4498- rc = 0
4499- result = 'Got exit code %d, expected %d:\n%s\n' % (rc, expected, report)
4500- self.assertEqual(expected, rc, result)
4501-
4502- if strict:
4503- filetype = '^%s$' % (filetype)
4504- else:
4505- # accept if the beginning of the line matches
4506- filetype = '^%s' % (filetype)
4507- result = 'File type reported by file: [%s], expected regex: [%s]\n' % (out, filetype)
4508- self.assertNotEqual(None, re.search(filetype, out), result)
4509-
4510- def yank_commonname_from_cert(self, certfile):
4511- '''Extract the commonName from a given PEM'''
4512- rc, out = cmd(['openssl', 'asn1parse', '-in', certfile])
4513- if rc == 0:
4514- ready = False
4515- for line in out.splitlines():
4516- if ready:
4517- return line.split(':')[-1]
4518- if ':commonName' in line:
4519- ready = True
4520- return socket.getfqdn()
4521-
4522- def announce(self, text):
4523- if self.my_verbosity:
4524- print("(%s) " % (text), file=sys.stderr, end='')
4525- sys.stdout.flush()
4526-
4527- def make_clean(self):
4528- rc, output = self.shell_cmd(['make', 'clean'])
4529- self.assertEqual(rc, 0, output)
4530-
4531- def get_makefile_compiler(self):
4532- # Find potential compiler name
4533- compiler = 'gcc'
4534- if os.path.exists('Makefile'):
4535- for line in open('Makefile'):
4536- if line.startswith('CC') and '=' in line:
4537- items = [x.strip() for x in line.split('=')]
4538- if items[0] == 'CC':
4539- compiler = items[1]
4540- break
4541- return compiler
4542-
4543- def make_target(self, target, expected=0):
4544- '''Compile a target and report output'''
4545-
4546- compiler = self.get_makefile_compiler()
4547- rc, output = self.shell_cmd(['make', target])
4548- self.assertEqual(rc, expected, 'rc(%d)!=%d:\n' % (rc, expected) + output)
4549- self.assertTrue('%s ' % (compiler) in output, 'Expected "%s":' % (compiler) + output)
4550- return output
4551-
4552- # call as return testlib.skipped()
4553- def _skipped(self, reason=""):
4554- '''Provide a visible way to indicate that a test was skipped'''
4555- if reason != "":
4556- reason = ': %s' % (reason)
4557- self.announce("skipped%s" % (reason))
4558- return False
4559-
4560- def _testlib_shell_cmd(self, args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=None):
4561- argstr = "'" + "', '".join(args).strip() + "'"
4562- rc, out = cmd(args, stdin=stdin, stdout=stdout, stderr=stderr, env=env)
4563- report = 'Command: ' + argstr + '\nOutput:\n' + out
4564- return rc, report, out
4565-
4566- def shell_cmd(self, args, stdin=None):
4567- return cmd(args, stdin=stdin)
4568-
4569- def assertShellExitEquals(self, expected, args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=None, msg="", bare_report=False):
4570- '''Test a shell command matches a specific exit code'''
4571- rc, report, out = self._testlib_shell_cmd(args, stdin=stdin, stdout=stdout, stderr=stderr, env=env)
4572- result = 'Got exit code %d, expected %d\n' % (rc, expected)
4573- self.assertEqual(expected, rc, msg + result + report)
4574- if bare_report:
4575- return out
4576- else:
4577- return report
4578-
4579- # make sure exit value is in a list of expected values
4580- def assertShellExitIn(self, expected, args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, msg=""):
4581- '''Test a shell command matches a specific exit code'''
4582- rc, report, out = self._testlib_shell_cmd(args, stdin=stdin, stdout=stdout, stderr=stderr)
4583- result = 'Got exit code %d, expected one of %s\n' % (rc, ', '.join(map(str, expected)))
4584- self.assertIn(rc, expected, msg + result + report)
4585-
4586- def assertShellExitNotEquals(self, unwanted, args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, msg=""):
4587- '''Test a shell command doesn't match a specific exit code'''
4588- rc, report, out = self._testlib_shell_cmd(args, stdin=stdin, stdout=stdout, stderr=stderr)
4589- result = 'Got (unwanted) exit code %d\n' % rc
4590- self.assertNotEqual(unwanted, rc, msg + result + report)
4591-
4592- def assertShellOutputContains(self, text, args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, msg="", invert=False, expected=None):
4593- '''Test a shell command contains a specific output'''
4594- rc, report, out = self._testlib_shell_cmd(args, stdin=stdin, stdout=stdout, stderr=stderr)
4595- result = 'Got exit code %d. Looking for text "%s"\n' % (rc, text)
4596- if not invert:
4597- self.assertTrue(text in out, msg + result + report)
4598- else:
4599- self.assertFalse(text in out, msg + result + report)
4600- if expected is not None:
4601- result = 'Got exit code %d. Expected %d (%s)\n' % (rc, expected, " ".join(args))
4602- self.assertEqual(rc, expected, msg + result + report)
4603-
4604- def assertShellOutputEquals(self, text, args, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, msg="", invert=False, expected=None):
4605- '''Test a shell command matches a specific output'''
4606- rc, report, out = self._testlib_shell_cmd(args, stdin=stdin, stdout=stdout, stderr=stderr)
4607- result = 'Got exit code %d. Looking for exact text "%s" (%s)\n' % (rc, text, " ".join(args))
4608- if not invert:
4609- self.assertEqual(text, out, msg + result + report)
4610- else:
4611- self.assertNotEqual(text, out, msg + result + report)
4612- if expected is not None:
4613- result = 'Got exit code %d. Expected %d (%s)\n' % (rc, expected, " ".join(args))
4614- self.assertEqual(rc, expected, msg + result + report)
4615-
4616- def _word_find(self, report, content, invert=False):
4617- '''Check for a specific string'''
4618- if invert:
4619- warning = 'Found "%s"\n' % content
4620- self.assertTrue(content not in report, warning + report)
4621- else:
4622- warning = 'Could not find "%s"\n' % content
4623- self.assertTrue(content in report, warning + report)
4624-
4625- def _test_sysctl_value(self, path, expected, msg=None, exists=True):
4626- sysctl = '/proc/sys/%s' % (path)
4627- self.assertEqual(exists, os.path.exists(sysctl), sysctl)
4628- value = None
4629- if exists:
4630- with open(sysctl) as sysctl_fd:
4631- value = int(sysctl_fd.read())
4632- report = "%s is not %d: %d" % (sysctl, expected, value)
4633- if msg:
4634- report += " (%s)" % (msg)
4635- self.assertEqual(value, expected, report)
4636- return value
4637-
4638- def set_sysctl_value(self, path, desired):
4639- sysctl = '/proc/sys/%s' % (path)
4640- self.assertTrue(os.path.exists(sysctl), "%s does not exist" % (sysctl))
4641- with open(sysctl, 'w') as sysctl_fh:
4642- sysctl_fh.write(str(desired))
4643- self._test_sysctl_value(path, desired)
4644-
4645- def kernel_at_least(self, introduced):
4646- return self.version_compare(self.kernel_version_ubuntu,
4647- introduced) >= 0
4648-
4649- def kernel_claims_cve_fixed(self, cve):
4650- changelog = "/usr/share/doc/linux-image-%s/changelog.Debian.gz" % (self.kernel_version)
4651- if os.path.exists(changelog):
4652- for line in gzip.open(changelog):
4653- if cve in line and "revert" not in line and "Revert" not in line:
4654- return True
4655- return False
4656-
4657- def install_builddeps(self, src_pkg):
4658- rc, report = _run_apt_command([src_pkg], 'build-dep')
4659- self.assertEqual(0, rc, 'Failed to install build-deps for %s\nOutput:\n%s' % (src_pkg, report))
4660-
4661- def install_package(self, package):
4662- rc, report = _run_apt_command([package], 'install')
4663- self.assertEqual(0, rc, 'Failed to install package %s\nOutput:\n%s' % (package, report))
4664-
4665- def install_packages(self, pkg_list):
4666- rc, report = _run_apt_command(pkg_list, 'install')
4667- self.assertEqual(0, rc, 'Failed to install packages %s\nOutput:\n%s' % (','.join(pkg_list), report))
4668-
4669-
4670-class TestGroup:
4671- '''Create a temporary test group and remove it again in the dtor.'''
4672-
4673- def __init__(self, group=None, lower=False):
4674- '''Create a new group'''
4675-
4676- self.group = None
4677- if group:
4678- if group_exists(group):
4679- raise ValueError('group name already exists')
4680- else:
4681- while(True):
4682- group = random_string(7, lower=lower)
4683- if not group_exists(group):
4684- break
4685-
4686- assert subprocess.call(['groupadd', group]) == 0
4687- self.group = group
4688- g = grp.getgrnam(self.group)
4689- self.gid = g[2]
4690-
4691- def __del__(self):
4692- '''Remove the created group.'''
4693-
4694- if self.group:
4695- rc, report = cmd(['groupdel', self.group])
4696- assert rc == 0
4697-
4698-
4699-class TestUser:
4700- '''Create a temporary test user and remove it again in the dtor.'''
4701-
4702- def __init__(self, login=None, home=True, group=None, uidmin=None, lower=False, shell=None):
4703- '''Create a new user account with a random password.
4704-
4705- By default, the login name is random, too, but can be explicitly
4706- specified with 'login'. By default, a home directory is created, this
4707- can be suppressed with 'home=False'.'''
4708-
4709- self.login = None
4710-
4711- if os.geteuid() != 0:
4712- raise ValueError("You must be root to run this test")
4713-
4714- if login:
4715- if login_exists(login):
4716- raise ValueError('login name already exists')
4717- else:
4718- while(True):
4719- login = 't' + random_string(7, lower=lower)
4720- if not login_exists(login):
4721- break
4722-
4723- self.salt = random_string(2)
4724- self.password = random_string(8, lower=lower)
4725- self.crypted = crypt.crypt(self.password, self.salt)
4726-
4727- creation = ['useradd', '-p', self.crypted]
4728- if home:
4729- creation += ['-m']
4730- if group:
4731- creation += ['-G', group]
4732- if uidmin:
4733- creation += ['-K', 'UID_MIN=%d' % uidmin]
4734- if shell:
4735- creation += ['-s', shell]
4736- creation += [login]
4737- assert subprocess.call(creation) == 0
4738- # Set GECOS
4739- assert subprocess.call(['usermod', '-c', 'Buddy %s' % (login), login]) == 0
4740-
4741- self.login = login
4742- p = pwd.getpwnam(self.login)
4743- self.uid = p[2]
4744- self.gid = p[3]
4745- self.gecos = p[4]
4746- self.home = p[5]
4747- self.shell = p[6]
4748-
4749- def __del__(self):
4750- '''Remove the created user account.'''
4751-
4752- if self.login:
4753- # sanity check the login name so we don't accidentally wipe too much
4754- if len(self.login) > 3 and '/' not in self.login:
4755- subprocess.call(['rm', '-rf', '/home/' + self.login, '/var/mail/' + self.login])
4756- rc, report = cmd(['userdel', '-f', self.login])
4757- assert rc == 0
4758-
4759- def add_to_group(self, group):
4760- '''Add user to the specified group name'''
4761- rc, report = cmd(['usermod', '-G', group, self.login])
4762- if rc != 0:
4763- print(report)
4764- assert rc == 0
4765-
4766-
4767-class AddUser:
4768- '''Create a temporary test user and remove it again in the dtor.'''
4769-
4770- def __init__(self, login=None, home=True, encrypt_home=False, group=None, lower=False, shell=None):
4771- '''Create a new user account with a random password.
4772-
4773- By default, the login name is random, too, but can be explicitly
4774- specified with 'login'. By default, a home directory is created, this
4775- can be suppressed with 'home=False'.
4776-
4777- This class differs from the TestUser class in that the adduser/deluser
4778- tools are used rather than the useradd/user/del tools. The adduser
4779- program is the only commandline program that can be used to add a new
4780- user with an encrypted home directory. It is possible that the AddUser
4781- class may replace the TestUser class in the future.'''
4782-
4783- self.login = None
4784-
4785- if os.geteuid() != 0:
4786- raise ValueError("You must be root to run this test")
4787-
4788- if login:
4789- if login_exists(login):
4790- raise ValueError('login name already exists')
4791- else:
4792- while(True):
4793- login = 't' + random_string(7, lower=True)
4794- if not login_exists(login):
4795- break
4796-
4797- self.password = random_string(8, lower=lower)
4798-
4799- creation = ['adduser', '--quiet']
4800-
4801- if not home:
4802- creation += ['--no-create-home']
4803- elif encrypt_home:
4804- creation += ['--encrypt-home']
4805-
4806- if shell:
4807- creation += ['--shell', shell]
4808-
4809- creation += ['--gecos', 'Buddy %s' % (login), login]
4810-
4811- child = pexpect.spawn(creation.pop(0), creation, timeout=5)
4812- assert child.expect('Enter new UNIX password:') == 0
4813- child.sendline(self.password)
4814- assert child.expect('Retype new UNIX password:') == 0
4815- child.sendline(self.password)
4816-
4817- child.wait()
4818- child.close()
4819- assert child.exitstatus == 0
4820- assert child.signalstatus is None
4821-
4822- self.login = login
4823-
4824- if group:
4825- assert self.add_to_group(group) == 0
4826-
4827- p = pwd.getpwnam(self.login)
4828- self.uid = p[2]
4829- self.gid = p[3]
4830- self.gecos = p[4]
4831- self.home = p[5]
4832- self.shell = p[6]
4833-
4834- def __del__(self):
4835- '''Remove the created user account.'''
4836-
4837- if self.login:
4838- # sanity check the login name so we don't accidentally wipe too much
4839- rc, report = cmd(['deluser', '--remove-home', self.login])
4840- assert rc == 0
4841-
4842- def add_to_group(self, group):
4843- '''Add user to the specified group name'''
4844- rc, report = cmd(['adduser', self.login, group])
4845- if rc != 0:
4846- print(report)
4847- assert rc == 0
4848-
4849-
4850-# Timeout handler using alarm() from John P. Speno's Pythonic Avocado
4851-class TimeoutFunctionException(Exception):
4852- """Exception to raise on a timeout"""
4853- pass
4854-
4855-
4856-class TimeoutFunction:
4857- def __init__(self, function, timeout):
4858- self.timeout = timeout
4859- self.function = function
4860-
4861- def handle_timeout(self, signum, frame):
4862- raise TimeoutFunctionException()
4863-
4864- def __call__(self, *args, **kwargs):
4865- old = signal.signal(signal.SIGALRM, self.handle_timeout)
4866- signal.alarm(self.timeout)
4867- try:
4868- result = self.function(*args, **kwargs)
4869- finally:
4870- signal.signal(signal.SIGALRM, old)
4871- signal.alarm(0)
4872- return result
4873-
4874-
4875-def main():
4876- print("hi")
4877- unittest.main()
4878diff --git a/bin/touchpad_driver_info.py b/bin/touchpad_driver_info.py
4879index 431b874..9f6278f 100755
4880--- a/bin/touchpad_driver_info.py
4881+++ b/bin/touchpad_driver_info.py
4882@@ -67,8 +67,8 @@ def main():
4883 if attributes:
4884 modinfo = TouchpadDriver(attributes['driver'])
4885 attributes['version'] = modinfo.driver_version
4886- print("%s: %s\n%s: %s\n%s: %s\n" %
4887- ('Device', attributes['product'],
4888+ print("%s: %s\n%s: %s\n%s: %s\n" % (
4889+ 'Device', attributes['product'],
4890 'Driver', attributes['driver'],
4891 'Driver Version', attributes['version']))
4892 else:
4893diff --git a/bin/touchpad_test.py b/bin/touchpad_test.py
4894index bc6a474..6ecde92 100755
4895--- a/bin/touchpad_test.py
4896+++ b/bin/touchpad_test.py
4897@@ -8,8 +8,8 @@ from gettext import gettext as _
4898 gi.require_version('Gdk', '3.0')
4899 gi.require_version('Gio', '2.0')
4900 gi.require_version("Gtk", "3.0")
4901-from gi.repository import Gio, Gtk, Gdk
4902-from optparse import OptionParser
4903+from gi.repository import Gio, Gtk, Gdk # noqa: E402
4904+from optparse import OptionParser # noqa: E402
4905
4906
4907 EXIT_WITH_FAILURE = 1
4908@@ -205,5 +205,6 @@ def main(args):
4909
4910 return scroller.exit_code
4911
4912+
4913 if __name__ == "__main__":
4914 sys.exit(main(sys.argv[1:]))
4915diff --git a/bin/virtualization.py b/bin/virtualization.py
4916index 2b7cd54..10b827b 100755
4917--- a/bin/virtualization.py
4918+++ b/bin/virtualization.py
4919@@ -330,7 +330,7 @@ class KVMTest(object):
4920
4921 # Attempt download
4922 try:
4923- resp = urllib.request.urlretrieve(full_url, cloud_iso)
4924+ urllib.request.urlretrieve(full_url, cloud_iso)
4925 except (IOError,
4926 OSError,
4927 urllib.error.HTTPError,
4928@@ -400,25 +400,6 @@ class KVMTest(object):
4929 Generate Cloud meta data and creates an iso object
4930 to be mounted as virtual device to instance during boot.
4931 """
4932-
4933- user_data = """\
4934-#cloud-config
4935-
4936-runcmd:
4937- - [ sh, -c, echo "========= CERTIFICATION TEST =========" ]
4938-
4939-power_state:
4940- mode: halt
4941- message: Bye
4942- timeout: 480
4943-
4944-final_message: CERTIFICATION BOOT COMPLETE
4945-"""
4946-
4947- meta_data = """\
4948-{ echo instance-id: iid-local01; echo local-hostname, certification; }
4949-"""
4950-
4951 for file in ['user-data', 'meta-data']:
4952 logging.debug("Creating cloud %s", file)
4953 with open(file, "wt") as data_file:
4954@@ -427,11 +408,11 @@ final_message: CERTIFICATION BOOT COMPLETE
4955
4956 # Create Data ISO hosting user & meta cloud config data
4957 try:
4958- iso_build = check_output(
4959+ check_output(
4960 ['genisoimage', '-output', 'seed.iso', '-volid',
4961 'cidata', '-joliet', '-rock', 'user-data', 'meta-data'],
4962 universal_newlines=True)
4963- except CalledProcessError as exception:
4964+ except CalledProcessError:
4965 logging.exception("Cloud data disk creation failed")
4966
4967 def log_check(self, stream):
4968@@ -483,7 +464,7 @@ final_message: CERTIFICATION BOOT COMPLETE
4969 self.create_cloud_disk()
4970
4971 # Boot Virtual Machine
4972- instance = self.boot_image(self.image)
4973+ self.boot_image(self.image)
4974
4975 # If running in console, reset console window to regain
4976 # control from VM Serial I/0
4977@@ -659,7 +640,7 @@ class LXDTest(object):
4978 logging.debug("Attempting download of {} from {}".format(filename,
4979 url))
4980 try:
4981- resp = urllib.request.urlretrieve(url, filename)
4982+ urllib.request.urlretrieve(url, filename)
4983 except (IOError,
4984 OSError,
4985 urllib.error.HTTPError,
4986diff --git a/bin/volume_test.py b/bin/volume_test.py
4987index a949f93..d1aeffd 100755
4988--- a/bin/volume_test.py
4989+++ b/bin/volume_test.py
4990@@ -8,12 +8,12 @@ from subprocess import check_output
4991
4992 TYPES = ("source", "sink")
4993
4994-active_entries_regex = re.compile("\* index.*?(?=properties)", re.DOTALL)
4995-entries_regex = re.compile("index.*?(?=properties)", re.DOTALL)
4996-index_regex = re.compile("(?<=index: )[0-9]*")
4997-muted_regex = re.compile("(?<=muted: ).*")
4998-volume_regex = re.compile("(?<=volume: 0: )\s*[0-9]*")
4999-name_regex = re.compile("(?<=name:).*")
5000+active_entries_regex = re.compile(r"\* index.*?(?=properties)", re.DOTALL)
The diff has been truncated for viewing.

Subscribers

People subscribed via source and target branches