File: integration_test.py

package info (click to toggle)
power-profiles-daemon 0.30-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 776 kB
  • sloc: ansic: 4,204; python: 2,383; xml: 107; sh: 35; makefile: 11
file content (2817 lines) | stat: -rw-r--r-- 112,337 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
#!/usr/bin/python3

# power-profiles-daemon integration test suite
#
# Run in built tree to test local built binaries, or from anywhere else to test
# system installed binaries.
#
# Copyright: (C) 2011 Martin Pitt <martin.pitt@ubuntu.com>
# (C) 2020 Bastien Nocera <hadess@hadess.net>
# (C) 2021 David Redondo <kde@david-redondo.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

import os
import subprocess
import signal
import sys
import tempfile
import time
import unittest

import dbus

import platform

try:
    import gi
    from gi.repository import GLib
    from gi.repository import Gio
except ImportError as e:
    sys.stderr.write(
        f"Skipping tests, PyGobject not available for Python 3, or missing GI typelibs: {str(e)}\n"
    )
    sys.exit(77)

try:
    gi.require_version("UMockdev", "1.0")
    from gi.repository import UMockdev
except ImportError:
    sys.stderr.write("Skipping tests, umockdev not available.\n")
    sys.stderr.write("(https://github.com/martinpitt/umockdev)\n")
    sys.exit(77)

try:
    import dbusmock
except ImportError:
    sys.stderr.write("Skipping tests, python-dbusmock not available.\n")
    sys.stderr.write("(http://pypi.python.org/pypi/python-dbusmock)")
    sys.exit(77)


# pylint: disable=too-many-public-methods,too-many-instance-attributes
class Tests(dbusmock.DBusTestCase):
    """Dbus based integration unit tests"""

    PP = "org.freedesktop.UPower.PowerProfiles"
    PP_PATH = "/org/freedesktop/UPower/PowerProfiles"
    PP_INTERFACE = "org.freedesktop.UPower.PowerProfiles"

    @classmethod
    def setUpClass(cls):
        # run from local build tree if we are in one, otherwise use system instance
        builddir = os.getenv("top_builddir", ".")
        if os.access(os.path.join(builddir, "src", "power-profiles-daemon"), os.X_OK):
            cls.daemon_path = os.path.join(builddir, "src", "power-profiles-daemon")
            print(f"Testing binaries from local build tree {cls.daemon_path}")
        elif os.environ.get("UNDER_JHBUILD", False):
            jhbuild_prefix = os.environ["JHBUILD_PREFIX"]
            cls.daemon_path = os.path.join(
                jhbuild_prefix, "libexec", "power-profiles-daemon"
            )
            print(f"Testing binaries from JHBuild {cls.daemon_path}")
        else:
            cls.daemon_path = None
            with open(
                "/usr/lib/systemd/system/power-profiles-daemon.service",
                encoding="utf-8",
            ) as tmpf:
                for line in tmpf:
                    if line.startswith("ExecStart="):
                        cls.daemon_path = line.split("=", 1)[1].strip()
                        break
            assert (
                cls.daemon_path
            ), "could not determine daemon path from systemd .service file"
            print(f"Testing installed system binary {cls.daemon_path}")

        # fail on CRITICALs on client and server side
        GLib.log_set_always_fatal(
            GLib.LogLevelFlags.LEVEL_WARNING
            | GLib.LogLevelFlags.LEVEL_ERROR
            | GLib.LogLevelFlags.LEVEL_CRITICAL
        )
        os.environ["G_DEBUG"] = "fatal_warnings"

        # set up a fake system D-BUS
        cls.start_system_bus()
        cls.dbus = Gio.bus_get_sync(Gio.BusType.SYSTEM, None)

    def start_dbus_template(self, template, parameters):
        process, dbus_object = self.spawn_server_template(
            template, parameters, stdout=subprocess.PIPE
        )

        def stop_template():
            process.stdout.close()
            try:
                process.kill()
            except OSError:
                pass
            process.wait()

        self.addCleanup(stop_template)
        self.assertTrue(process)
        self.assertTrue(dbus_object)

        return process, dbus_object, stop_template

    def setUp(self):
        """Set up a local umockdev testbed.

        The testbed is initially empty.
        """
        self.testbed = UMockdev.Testbed.new()

        def del_testbed():
            del self.testbed

        self.addCleanup(del_testbed)
        self.proxy = None
        self.props_proxy = None
        self.log = None
        self.daemon = None
        self.changed_properties = {}

        # Used for dytc devices
        self.tp_acpi = None

        self.polkitd, self.obj_polkit, _ = self.start_dbus_template("polkitd", {})
        self.obj_polkit.SetAllowed(
            [
                "org.freedesktop.UPower.PowerProfiles.switch-profile",
                "org.freedesktop.UPower.PowerProfiles.hold-profile",
                "org.freedesktop.UPower.PowerProfiles.configure-action",
                "org.freedesktop.UPower.PowerProfiles.configure-battery-aware",
            ]
        )

    def run(self, result=None):
        super().run(result)
        if not result or not self.log:
            return
        if len(result.errors) + len(result.failures) or os.getenv("PPD_TEST_VERBOSE"):
            with open(self.log.name, encoding="utf-8") as tmpf:
                sys.stderr.write("\n-------------- daemon log: ----------------\n")
                sys.stderr.write(tmpf.read())
                sys.stderr.write("------------------------------\n")

    #
    # Daemon control and D-BUS I/O
    #

    def start_daemon(self, args=None):
        """Start daemon and create DBus proxy.

        When done, this sets self.proxy as the Gio.DBusProxy for power-profiles-daemon.
        """
        env = os.environ.copy()
        env["G_DEBUG"] = "fatal-criticals"
        env["G_MESSAGES_DEBUG"] = "all"
        # note: Python doesn't propagate the setenv from Testbed.new(), so we
        # have to do that ourselves
        env["UMOCKDEV_DIR"] = self.testbed.get_root_dir()
        env["LD_PRELOAD"] = os.getenv("PPD_LD_PRELOAD") + " " + os.getenv("LD_PRELOAD")
        self.log = tempfile.NamedTemporaryFile()  # pylint: disable=consider-using-with
        daemon_path = [self.daemon_path, "-vv"]
        if args:
            daemon_path += args
        if os.getenv("PPD_TEST_WRAPPER"):
            daemon_path = os.getenv("PPD_TEST_WRAPPER").split(" ") + daemon_path
        elif os.getenv("VALGRIND"):
            daemon_path = ["valgrind"] + daemon_path

        # pylint: disable=consider-using-with
        self.daemon = subprocess.Popen(
            daemon_path, env=env, stdout=self.log, stderr=sys.stderr
        )
        self.addCleanup(self.stop_daemon, delete_profile=True)

        def on_proxy_connected(_, res):
            try:
                self.proxy = Gio.DBusProxy.new_finish(res)
                print(f"Proxy to {self.proxy.get_name()} connected")
            except GLib.Error as exc:
                self.fail(exc)

        cancellable = Gio.Cancellable()
        self.addCleanup(cancellable.cancel)
        Gio.DBusProxy.new(
            self.dbus,
            Gio.DBusProxyFlags.DO_NOT_AUTO_START,
            None,
            self.PP,
            self.PP_PATH,
            self.PP_INTERFACE,
            cancellable,
            on_proxy_connected,
        )

        # wait until the daemon gets online
        wait_time = 20 if "valgrind" in daemon_path[0] else 5
        self.assert_eventually(
            lambda: self.proxy and self.proxy.get_name_owner(),
            timeout=wait_time * 1000,
            message=lambda: f"daemon did not start in {wait_time} seconds: "
            + f"proxy is {self.proxy} and owner "
            + f"{self.proxy.get_name_owner() if self.proxy else 'None'}",
        )

        def properties_changed_cb(_, changed_properties, invalidated):
            self.changed_properties.update(changed_properties.unpack())

        self.addCleanup(
            self.proxy.disconnect,
            self.proxy.connect("g-properties-changed", properties_changed_cb),
        )

        self.assertEqual(self.daemon.poll(), None, "daemon crashed")

    def ensure_dbus_properties_proxies(self):
        self.props_proxy = Gio.DBusProxy.new_sync(
            self.dbus,
            Gio.DBusProxyFlags.DO_NOT_AUTO_START
            | Gio.DBusProxyFlags.DO_NOT_AUTO_START_AT_CONSTRUCTION
            | Gio.DBusProxyFlags.DO_NOT_LOAD_PROPERTIES
            | Gio.DBusProxyFlags.DO_NOT_CONNECT_SIGNALS,
            None,
            self.PP,
            self.PP_PATH,
            "org.freedesktop.DBus.Properties",
            None,
        )

    def stop_daemon(self, delete_profile=False):
        """Stop the daemon if it is running."""

        if self.daemon:
            try:
                self.daemon.terminate()
            except OSError:
                pass
            self.assertEqual(self.daemon.wait(timeout=3000), 0)

        if delete_profile:
            try:
                os.remove(self.testbed.get_root_dir() + "/" + "ppd_test_conf.ini")
            except (AttributeError, FileNotFoundError):
                pass

        self.daemon = None
        self.proxy = None

    def get_dbus_property(self, name):
        """Get property value from daemon D-Bus interface."""
        self.ensure_dbus_properties_proxies()
        return self.props_proxy.Get("(ss)", self.PP, name)

    def set_dbus_property(self, name, value):
        """Set property value on daemon D-Bus interface."""
        self.ensure_dbus_properties_proxies()
        return self.props_proxy.Set("(ssv)", self.PP, name, value)

    def call_dbus_method(self, name, parameters):
        """Call a method of the daemon D-Bus interface."""
        return self.proxy.call_sync(
            name, parameters, Gio.DBusCallFlags.NO_AUTO_START, -1, None
        )

    def have_text_in_log(self, text):
        return self.count_text_in_log(text) > 0

    def count_text_in_log(self, text):
        with open(self.log.name, encoding="utf-8") as tmpf:
            return tmpf.read().count(text)

    def read_file_contents(self, path):
        """Get the contents of a file"""
        with open(path, "rb") as tmpf:
            return tmpf.read()

    def read_sysfs_file(self, path):
        return self.read_file_contents(
            self.testbed.get_root_dir() + "/" + path
        ).rstrip()

    def read_sysfs_attr(self, device, attribute):
        return self.read_sysfs_file(device + "/" + attribute)

    def get_mtime(self, device, attribute):
        return os.path.getmtime(
            self.testbed.get_root_dir() + "/" + device + "/" + attribute
        )

    def write_file_contents(self, path, contents):
        """Set the contents of a file"""
        with open(path, "wb") as tmpf:
            return tmpf.write(
                contents if isinstance(contents, bytes) else contents.encode("utf-8")
            )

    def write_sysfs_file(self, path, contents):
        """Writes a sysfs file"""
        return self.write_file_contents(
            self.testbed.get_root_dir() + "/" + path, contents
        )

    def write_sysfs_attr(self, device, attribute, contents):
        """Writes a sysfs attribute"""
        return self.write_sysfs_file(device + "/" + attribute, contents)

    def change_immutable(self, fname, enable):
        attr = "-"
        if enable:
            os.chmod(fname, 0o444)
            self.addCleanup(self.change_immutable, fname, False)
            attr = "+"
        if os.geteuid() == 0:
            if not GLib.find_program_in_path("chattr"):
                self.skipTest("chattr is not found")

            try:
                subprocess.check_output(["chattr", f"{attr}i", fname])
            except subprocess.CalledProcessError as error:
                self.skipTest(f"chattr is not supported: {error.output}")
        if not enable:
            os.chmod(fname, 0o666)

    def create_dytc_device(self):
        self.tp_acpi = self.testbed.add_device(
            "platform",
            "thinkpad_acpi",
            None,
            ["dytc_lapmode", "0\n"],
            ["DEVPATH", "/devices/platform/thinkpad_acpi"],
        )
        self.addCleanup(self.testbed.remove_device, self.tp_acpi)

    def create_amd_apu(self):
        proc_dir = os.path.join(self.testbed.get_root_dir(), "proc/")
        os.makedirs(proc_dir)
        self.write_file_contents(
            os.path.join(proc_dir, "cpuinfo"), "vendor_id	: AuthenticAMD\n"
        )

    def create_empty_platform_profile(self):
        acpi_dir = os.path.join(self.testbed.get_root_dir(), "sys/firmware/acpi/")
        os.makedirs(acpi_dir)
        self.write_file_contents(os.path.join(acpi_dir, "platform_profile"), "\n")
        self.write_file_contents(
            os.path.join(acpi_dir, "platform_profile_choices"), "\n"
        )

    def create_platform_profile(self):
        acpi_dir = os.path.join(self.testbed.get_root_dir(), "sys/firmware/acpi/")
        os.makedirs(acpi_dir, exist_ok=True)
        self.write_file_contents(
            os.path.join(acpi_dir, "platform_profile"), "performance\n"
        )
        self.write_file_contents(
            os.path.join(acpi_dir, "platform_profile_choices"),
            "low-power balanced performance\n",
        )

    def create_custom_platform_profile(self):
        acpi_dir = os.path.join(self.testbed.get_root_dir(), "sys/firmware/acpi/")
        os.makedirs(acpi_dir, exist_ok=True)
        self.write_file_contents(os.path.join(acpi_dir, "platform_profile"), "custom\n")
        self.write_file_contents(
            os.path.join(acpi_dir, "platform_profile_choices"),
            "low-power balanced performance custom\n",
        )

    def remove_platform_profile(self):
        acpi_dir = os.path.join(self.testbed.get_root_dir(), "sys/firmware/acpi/")
        os.remove(os.path.join(acpi_dir, "platform_profile_choices"))
        os.remove(os.path.join(acpi_dir, "platform_profile"))
        os.removedirs(acpi_dir)

    def powerprofilesctl_path(self):
        builddir = os.getenv("top_builddir", ".")
        return os.path.join(builddir, "src", "powerprofilesctl")

    def python_coverage_commands(self):
        coverage = os.getenv("PPD_PYTHON_COVERAGE")
        if not coverage:
            return []

        builddir = os.getenv("top_builddir", ".")
        data_file = os.path.join(builddir, "python-coverage", self.id() + ".coverage")
        # We also may need to use "--parallel-mode" if running with
        # meson test --repeat, but this is not a priority for now.
        return [
            coverage,
            "run",
            f"--data-file={data_file}",
            f"--include={builddir}/*",
        ]

    def powerprofilesctl_command(self):
        return self.python_coverage_commands() + [self.powerprofilesctl_path()]

    def assert_eventually(self, condition, message=None, timeout=5000, keep_checking=0):
        """Assert that condition function eventually returns True.

        Timeout is in milliseconds, defaulting to 5000 (5 seconds). message is
        printed on failure.
        """
        if not keep_checking:
            if condition():
                return

        done = False

        def on_timeout_reached():
            nonlocal done
            done = True

        source = GLib.timeout_add(timeout, on_timeout_reached)
        while not done:
            if condition():
                GLib.source_remove(source)
                if keep_checking > 0:
                    self.assert_condition_persists(
                        condition, message, timeout=keep_checking
                    )
                return
            GLib.MainContext.default().iteration(False)

        self.fail(message() if message else f"timed out waiting for {condition}")

    def assert_condition_persists(self, condition, message=None, timeout=1000):
        done = False

        def on_timeout_reached():
            nonlocal done
            done = True

        source = GLib.timeout_add(timeout, on_timeout_reached)
        while not done:
            if not condition():
                GLib.source_remove(source)
                self.fail(
                    message() if message else f"Condition is not persisting {condition}"
                )
            GLib.MainContext.default().iteration(False)

    def assert_file_eventually_contains(
        self, path, contents, timeout=800, keep_checking=0
    ):
        """Asserts that file contents eventually matches expectations"""
        encoded = contents.encode("utf-8")
        return self.assert_eventually(
            lambda: self.read_file_contents(path) == encoded,
            timeout=timeout,
            keep_checking=keep_checking,
            message=lambda: f"file '{path}' does not contain '{contents}', "
            + f"but '{self.read_file_contents(path)}'",
        )

    # pylint: disable=too-many-arguments,unknown-option-value,too-many-positional-arguments
    def assert_sysfs_attr_eventually_is(
        self, device, attribute, contents, timeout=800, keep_checking=0
    ):
        """Asserts that file contents eventually matches expectations"""
        encoded = contents.encode("utf-8")
        return self.assert_eventually(
            lambda: self.read_sysfs_attr(device, attribute) == encoded,
            timeout=timeout,
            keep_checking=keep_checking,
            message=lambda: f"file {device} '{attribute}' does not contain '{contents}', "
            + f"but '{self.read_sysfs_attr(device, attribute)}'",
        )

    def assert_dbus_property_eventually_is(
        self, prop, value, timeout=1200, keep_checking=0
    ):
        """Asserts that a dbus property eventually is what expected"""
        return self.assert_eventually(
            lambda: self.get_dbus_property(prop) == value,
            timeout=timeout,
            keep_checking=keep_checking,
            message=lambda: f"property '{prop}' is not '{value}', but "
            + f"'{self.get_dbus_property(prop)}'",
        )

    def _assert_action_boolean(self, name, value):
        for action in self.get_dbus_property("ActionsInfo"):
            if action["Name"] != name:
                continue
            self.assertEqual(action["Enabled"], value)

    def assert_action_disabled(self, name):
        """Assert that a PPD action is disabled"""
        if self.PP_INTERFACE == "org.freedesktop.UPower.PowerProfiles":
            self._assert_action_boolean(name, False)
        else:
            self.assertNotIn(name, self.get_dbus_property("Actions"))

    def assert_action_enabled(self, name):
        """Assert that a PPD action is enabled"""
        if self.PP_INTERFACE == "org.freedesktop.UPower.PowerProfiles":
            self._assert_action_boolean(name, True)
        else:
            self.assertIn(name, self.get_dbus_property("Actions"))

    #
    # Actual test cases
    #
    def test_dbus_startup_error(self):
        """D-Bus startup error"""

        self.start_daemon()
        daemon_path = [self.daemon_path]
        if os.getenv("PPD_TEST_WRAPPER"):
            daemon_path = os.getenv("PPD_TEST_WRAPPER").split(" ") + daemon_path
        out = subprocess.run(
            daemon_path,
            env={
                "LD_PRELOAD": os.getenv("PPD_LD_PRELOAD")
                + " "
                + os.getenv("LD_PRELOAD")
            },
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            check=False,
        )
        self.assertEqual(
            out.returncode, 1, "power-profile-daemon started but should have failed"
        )
        self.stop_daemon()

    def test_no_performance_driver(self):
        """no performance driver"""

        self.start_daemon()
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")
        self.assertEqual(self.get_dbus_property("PerformanceDegraded"), "")

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 2)
        self.assertEqual(profiles[1]["Driver"], "placeholder")
        self.assertEqual(profiles[1]["PlatformDriver"], "placeholder")
        self.assertEqual(profiles[0]["PlatformDriver"], "placeholder")
        self.assertEqual(profiles[1]["Profile"], "balanced")
        self.assertEqual(profiles[0]["Profile"], "power-saver")

        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")

        with self.assertRaises(gi.repository.GLib.GError):
            self.set_dbus_property(
                "ActiveProfile", GLib.Variant.new_string("performance")
            )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")

        with self.assertRaises(gi.repository.GLib.GError):
            cookie = self.call_dbus_method(
                "HoldProfile",
                GLib.Variant("(sss)", ("performance", "testReason", "testApplication")),
            )
            assert cookie

        self.stop_daemon()

    def test_invalid_property(self):
        """Test behavior for requesting an invalid property"""

        self.start_daemon()

        with self.assertRaises(gi.repository.GLib.GError):
            self.get_dbus_property("Foothebar")

    def test_inhibited_property(self):
        """Test that the inhibited property exists"""

        self.create_dytc_device()
        self.create_platform_profile()
        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(self.get_dbus_property("PerformanceInhibited"), "")

    def test_multi_degredation(self):
        """Test handling of degradation from multiple drivers"""
        self.create_dytc_device()
        self.create_platform_profile()

        # Create CPU with preference
        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        self.write_file_contents(os.path.join(dir1, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir1, "energy_performance_preference"), "performance\n"
        )

        # Create Intel P-State configuration
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/intel_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "no_turbo"), "0\n")
        self.write_file_contents(os.path.join(pstate_dir, "turbo_pct"), "1\n")
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        self.start_daemon()

        # Set performance mode
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("performance"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")

        # Degraded CPU
        self.write_file_contents(os.path.join(pstate_dir, "no_turbo"), "1\n")
        self.assert_eventually(
            lambda: self.have_text_in_log("File monitor change happened for ")
        )

        self.assertEqual(
            self.get_dbus_property("PerformanceDegraded"), "high-operating-temperature"
        )

        # Degraded DYTC
        lapmode = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/thinkpad_acpi/dytc_lapmode"
        )
        self.write_file_contents(lapmode, "1\n")
        self.assert_eventually(lambda: self.have_text_in_log("dytc_lapmode is now on"))
        self.assertEqual(
            self.get_dbus_property("PerformanceDegraded"),
            "high-operating-temperature,lap-detected",
        )

    def test_degraded_transition(self):
        """Test that transitions work as expected when degraded"""

        self.create_dytc_device()
        self.create_platform_profile()
        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("performance"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")

        # Degraded
        lapmode = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/thinkpad_acpi/dytc_lapmode"
        )
        self.write_file_contents(lapmode, "1\n")
        self.assert_eventually(lambda: self.have_text_in_log("dytc_lapmode is now on"))
        self.assertEqual(self.get_dbus_property("PerformanceDegraded"), "lap-detected")
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")

        # Switch to non-performance
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")

    def test_intel_pstate(self):
        """Intel P-State driver (no UPower)"""

        # Create 2 CPUs with preferences
        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        self.write_file_contents(os.path.join(dir1, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir1, "energy_performance_preference"), "performance\n"
        )
        dir2 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy1/"
        )
        os.makedirs(dir2)
        self.write_file_contents(os.path.join(dir2, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir2, "energy_performance_preference"), "performance\n"
        )

        # Create Intel P-State configuration
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/intel_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "no_turbo"), "0\n")
        self.write_file_contents(os.path.join(pstate_dir, "turbo_pct"), "1\n")
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(profiles[0]["Driver"], "multiple")
        self.assertEqual(profiles[0]["CpuDriver"], "intel_pstate")
        self.assertEqual(profiles[0]["Profile"], "power-saver")

        energy_prefs = os.path.join(dir2, "energy_performance_preference")
        self.assert_file_eventually_contains(energy_prefs, "balance_performance")

        # Set performance mode
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("performance"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")

        self.assert_file_eventually_contains(energy_prefs, "performance")

        # Disable turbo
        self.write_file_contents(os.path.join(pstate_dir, "no_turbo"), "1\n")

        self.assert_eventually(
            lambda: self.have_text_in_log("File monitor change happened for ")
        )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")
        self.assertEqual(
            self.get_dbus_property("PerformanceDegraded"), "high-operating-temperature"
        )

        self.stop_daemon()

        # Verify that Lenovo DYTC and Intel P-State drivers are loaded
        self.create_platform_profile()
        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(profiles[0]["Driver"], "multiple")
        self.assertEqual(profiles[0]["CpuDriver"], "intel_pstate")
        self.assertEqual(profiles[0]["PlatformDriver"], "platform_profile")

    def test_intel_pstate_balance(self):
        """Intel P-State driver (balance)"""

        # Create CPU with preference
        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        gov_path = os.path.join(dir1, "scaling_governor")
        self.write_file_contents(gov_path, "performance\n")
        self.write_file_contents(
            os.path.join(dir1, "energy_performance_preference"), "performance\n"
        )
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/intel_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        self.start_dbus_template(
            "upower",
            {"DaemonVersion": "0.99", "OnBattery": False},
        )

        self.start_daemon()

        self.assert_file_eventually_contains(gov_path, "powersave")

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(profiles[0]["Driver"], "multiple")
        self.assertEqual(profiles[0]["CpuDriver"], "intel_pstate")
        self.assertEqual(profiles[0]["Profile"], "power-saver")

        self.assert_file_eventually_contains(
            os.path.join(dir1, "energy_performance_preference"), "balance_performance"
        )

    def test_intel_pstate_reapply_on_resume_from_sleep_disable_logind(self):
        # Create CPU with preference
        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        gov_path = os.path.join(dir1, "scaling_governor")
        self.write_file_contents(gov_path, "performance\n")
        energy_prefs = os.path.join(dir1, "energy_performance_preference")
        self.write_file_contents(energy_prefs, "performance\n")
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/intel_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        _, obj_logind, _ = self.start_dbus_template("logind", {})

        self.start_daemon(["--disable-logind"])
        self.assert_dbus_property_eventually_is(
            "ActiveProfile", "balanced", keep_checking=100
        )

        # Simulate system changing to performance mode just before going to suspend
        self.write_file_contents(energy_prefs, "performance\n")
        self.assert_file_eventually_contains(
            energy_prefs, "performance\n", keep_checking=500
        )

        obj_logind.EmitSignal(
            "org.freedesktop.login1.Manager", "PrepareForSleep", "b", [True]
        )
        self.assert_file_eventually_contains(
            energy_prefs, "performance\n", keep_checking=500
        )

        # Check that on resume the value stays.
        obj_logind.EmitSignal(
            "org.freedesktop.login1.Manager", "PrepareForSleep", "b", [False]
        )

        self.assert_file_eventually_contains(
            energy_prefs, "performance\n", timeout=3000, keep_checking=100
        )

    def test_intel_pstate_reapply_on_resume_from_sleep(self):
        # Create CPU with preference
        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        gov_path = os.path.join(dir1, "scaling_governor")
        self.write_file_contents(gov_path, "performance\n")
        energy_prefs = os.path.join(dir1, "energy_performance_preference")
        self.write_file_contents(energy_prefs, "performance\n")
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/intel_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        _, obj_logind, _ = self.start_dbus_template("logind", {})

        self.start_daemon()
        self.assert_dbus_property_eventually_is(
            "ActiveProfile", "balanced", keep_checking=100
        )

        # Simulate system changing to performance mode just before going to suspend
        self.write_file_contents(energy_prefs, "performance\n")
        self.assert_file_eventually_contains(
            energy_prefs, "performance\n", keep_checking=500
        )

        obj_logind.EmitSignal(
            "org.freedesktop.login1.Manager", "PrepareForSleep", "b", [True]
        )
        self.assert_file_eventually_contains(
            energy_prefs, "performance\n", keep_checking=500
        )

        # Check that on resume the value is reset to the expected one.
        obj_logind.EmitSignal(
            "org.freedesktop.login1.Manager", "PrepareForSleep", "b", [False]
        )

        self.assert_file_eventually_contains(
            energy_prefs, "balance_performance", timeout=3000, keep_checking=100
        )

    def test_intel_pstate_error(self):
        """Intel P-State driver in error state"""

        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/intel_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        self.write_file_contents(os.path.join(dir1, "scaling_governor"), "powersave\n")
        pref_path = os.path.join(dir1, "energy_performance_preference")
        old_umask = os.umask(0o333)
        self.write_file_contents(pref_path, "balance_performance\n")
        os.umask(old_umask)
        # Make file non-writable to root
        self.change_immutable(pref_path, True)

        self.start_daemon()

        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        # Error when setting performance mode
        with self.assertRaises(gi.repository.GLib.GError):
            self.set_dbus_property(
                "ActiveProfile", GLib.Variant.new_string("performance")
            )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        energy_prefs = os.path.join(dir1, "energy_performance_preference")
        self.assert_file_eventually_contains(energy_prefs, "balance_performance\n")

    def test_intel_pstate_passive(self):
        """Intel P-State in passive mode -> placeholder"""

        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        self.write_file_contents(os.path.join(dir1, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir1, "energy_performance_preference"), "performance\n"
        )

        # Create Intel P-State configuration
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/intel_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "no_turbo"), "0\n")
        self.write_file_contents(os.path.join(pstate_dir, "turbo_pct"), "1\n")
        self.write_file_contents(os.path.join(pstate_dir, "status"), "passive\n")

        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 2)
        self.assertEqual(profiles[0]["Driver"], "placeholder")
        self.assertEqual(profiles[0]["PlatformDriver"], "placeholder")
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        energy_prefs = os.path.join(dir1, "energy_performance_preference")
        self.assert_file_eventually_contains(energy_prefs, "performance\n")

        # Set performance mode
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")

        energy_prefs = os.path.join(dir1, "energy_performance_preference")
        self.assert_file_eventually_contains(energy_prefs, "performance\n")

    def test_intel_pstate_passive_with_epb(self):
        """Intel P-State in passive mode (no HWP) with energy_perf_bias"""

        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        self.write_file_contents(os.path.join(dir1, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir1, "energy_performance_preference"), "performance\n"
        )
        dir2 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpu0/power/"
        )
        os.makedirs(dir2)
        self.write_file_contents(os.path.join(dir2, "energy_perf_bias"), "6")

        # Create Intel P-State configuration
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/intel_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "no_turbo"), "0\n")
        self.write_file_contents(os.path.join(pstate_dir, "turbo_pct"), "1\n")
        self.write_file_contents(os.path.join(pstate_dir, "status"), "passive\n")

        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(profiles[0]["Driver"], "multiple")
        self.assertEqual(profiles[0]["CpuDriver"], "intel_pstate")
        self.assertEqual(profiles[0]["PlatformDriver"], "placeholder")
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        # Set power-saver mode
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")

        energy_perf_bias = os.path.join(dir2, "energy_perf_bias")
        self.assert_file_eventually_contains(energy_perf_bias, "15")

        # Set performance mode
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("performance"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")

        self.assert_file_eventually_contains(energy_perf_bias, "0")

    def test_action_blocklist(self):
        """Test action blocklist works"""
        self.start_daemon(["--block-action", "trickle_charge"])
        self.assert_action_disabled("trickle_charge")

    def test_driver_blocklist(self):
        """Test driver blocklist works"""
        # Create 2 CPUs with preferences
        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        scaling_governor = os.path.join(dir1, "scaling_governor")
        self.write_file_contents(scaling_governor, "powersave\n")

        prefs1 = os.path.join(dir1, "energy_performance_preference")
        self.write_file_contents(prefs1, "performance\n")

        dir2 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy1/"
        )
        os.makedirs(dir2)
        scaling_governor = os.path.join(dir2, "scaling_governor")
        self.write_file_contents(scaling_governor, "powersave\n")
        prefs2 = os.path.join(
            dir2,
            "energy_performance_preference",
        )
        self.write_file_contents(prefs2, "prformance\n")

        # Create AMD P-State configuration
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/amd_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        # create ACPI platform profile
        self.create_platform_profile()
        profile = os.path.join(
            self.testbed.get_root_dir(), "sys/firmware/acpi/platform_profile"
        )
        self.assertNotEqual(profile, None)

        # block platform profile
        self.start_daemon(["--block-driver", "platform_profile"])
        # Verify that only amd-pstate is loaded
        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(profiles[0]["Driver"], "multiple")
        self.assertEqual(profiles[0]["CpuDriver"], "amd_pstate")
        self.assertEqual(profiles[0]["PlatformDriver"], "placeholder")

        self.stop_daemon()

        # block both drivers
        self.start_daemon(
            ["--block-driver", "amd_pstate", "--block-driver", "platform_profile"]
        )
        # Verify that only placeholder is loaded
        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 2)
        self.assertEqual(profiles[0]["PlatformDriver"], "placeholder")

    # pylint: disable=too-many-statements
    def test_multi_driver_flows(self):
        """Test corner cases associated with multiple drivers"""

        # Create 2 CPUs with preferences
        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        self.write_file_contents(os.path.join(dir1, "scaling_governor"), "powersave\n")
        prefs1 = os.path.join(dir1, "energy_performance_preference")
        self.write_file_contents(prefs1, "performance\n")

        dir2 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy1/"
        )
        os.makedirs(dir2)
        self.write_file_contents(os.path.join(dir2, "scaling_governor"), "powersave\n")
        prefs2 = os.path.join(dir2, "energy_performance_preference")
        self.write_file_contents(prefs2, "performance\n")

        # Create AMD P-State configuration
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/amd_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        # create ACPI platform profile
        self.create_platform_profile()
        profile = os.path.join(
            self.testbed.get_root_dir(), "sys/firmware/acpi/platform_profile"
        )

        self.start_daemon()

        # Verify that both drivers are loaded
        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(profiles[0]["Driver"], "multiple")
        self.assertEqual(profiles[0]["CpuDriver"], "amd_pstate")
        self.assertEqual(profiles[0]["PlatformDriver"], "platform_profile")

        # test both drivers can switch to power-saver
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")

        # test both drivers can switch to performance
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("performance"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")

        # test both drivers can switch to balanced
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("balanced"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        # test when CPU driver fails to write
        self.change_immutable(prefs1, True)
        with self.assertRaises(gi.repository.GLib.GError):
            self.set_dbus_property(
                "ActiveProfile", GLib.Variant.new_string("power-saver")
            )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")
        self.assertEqual(
            self.read_sysfs_file("sys/firmware/acpi/platform_profile"), b"balanced"
        )
        self.change_immutable(prefs1, False)

        # test when platform driver fails to write
        self.change_immutable(profile, True)
        with self.assertRaises(gi.repository.GLib.GError):
            self.set_dbus_property(
                "ActiveProfile", GLib.Variant.new_string("power-saver")
            )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        # make sure CPU was undone since platform failed
        self.assertEqual(
            self.read_sysfs_file(
                "sys/devices/system/cpu/cpufreq/policy0/energy_performance_preference"
            ),
            b"balance_performance",
        )
        self.assertEqual(
            self.read_sysfs_file(
                "sys/devices/system/cpu/cpufreq/policy1/energy_performance_preference"
            ),
            b"balance_performance",
        )

    # pylint: disable=too-many-statements
    def test_amd_pstate_state_machine(self):
        # Create 2 CPUs with preferences
        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        self.write_file_contents(os.path.join(dir1, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir1, "energy_performance_preference"), "performance\n"
        )
        dir2 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy1/"
        )
        os.makedirs(dir2)
        self.write_file_contents(os.path.join(dir2, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir2, "energy_performance_preference"), "performance\n"
        )

        # Create AMD P-State configuration
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/amd_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)

        self.assertEqual(profiles[0]["Driver"], "multiple")
        self.assertEqual(profiles[0]["CpuDriver"], "amd_pstate")
        self.assertEqual(profiles[0]["Profile"], "power-saver")

        energy_prefs = os.path.join(dir2, "energy_performance_preference")
        scaling_governor = os.path.join(dir2, "scaling_governor")

        self.assert_file_eventually_contains(energy_prefs, "balance_performance")
        self.assert_file_eventually_contains(scaling_governor, "powersave")

        self.write_file_contents(os.path.join(pstate_dir, "status"), "passive\n")

        # Set performance mode
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("performance"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")

        # ensure nothing changed
        self.assert_file_eventually_contains(energy_prefs, "balance_performance")
        self.assert_file_eventually_contains(scaling_governor, "powersave")

    # pylint: disable=too-many-statements
    def test_amd_pstate(self):
        """AMD P-State driver (no UPower)"""

        # Create 2 CPUs with preferences
        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        self.write_file_contents(os.path.join(dir1, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir1, "energy_performance_preference"), "performance\n"
        )
        dir2 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy1/"
        )
        os.makedirs(dir2)
        self.write_file_contents(os.path.join(dir2, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir2, "energy_performance_preference"), "performance\n"
        )

        # Create AMD P-State configuration
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/amd_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)

        self.assertEqual(profiles[0]["Driver"], "multiple")
        self.assertEqual(profiles[0]["CpuDriver"], "amd_pstate")
        self.assertEqual(profiles[0]["Profile"], "power-saver")

        energy_prefs = os.path.join(dir2, "energy_performance_preference")
        scaling_governor = os.path.join(dir2, "scaling_governor")

        self.assert_file_eventually_contains(energy_prefs, "balance_performance")
        self.assert_file_eventually_contains(scaling_governor, "powersave")

        # Set performance mode
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("performance"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")

        self.assert_file_eventually_contains(energy_prefs, "performance")
        self.assert_file_eventually_contains(scaling_governor, "performance")

        # Set powersave mode
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")

        self.assert_file_eventually_contains(energy_prefs, "power")
        self.assert_file_eventually_contains(scaling_governor, "powersave")

    # pylint: disable=too-many-statements
    def test_amd_pstate_min_freq(self):
        """AMD P-State driver min freq support"""
        # Create 2 CPUs with preferences
        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        self.write_file_contents(os.path.join(dir1, "cpuinfo_min_freq"), "400000\n")
        self.write_file_contents(os.path.join(dir1, "scaling_min_freq"), "400000\n")
        self.write_file_contents(
            os.path.join(dir1, "amd_pstate_lowest_nonlinear_freq"), "1114000\n"
        )
        self.write_file_contents(os.path.join(dir1, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir1, "energy_performance_preference"), "performance\n"
        )
        dir2 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy1/"
        )
        os.makedirs(dir2)
        self.write_file_contents(os.path.join(dir2, "cpuinfo_min_freq"), "400000\n")
        self.write_file_contents(os.path.join(dir2, "scaling_min_freq"), "400000\n")
        self.write_file_contents(
            os.path.join(dir2, "amd_pstate_lowest_nonlinear_freq"), "1114000\n"
        )
        self.write_file_contents(os.path.join(dir2, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir2, "energy_performance_preference"), "performance\n"
        )

        # Create AMD P-State configuration
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/amd_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)

        self.assertEqual(profiles[0]["Driver"], "multiple")
        self.assertEqual(profiles[0]["CpuDriver"], "amd_pstate")
        self.assertEqual(profiles[0]["Profile"], "power-saver")

        energy_prefs = os.path.join(dir2, "energy_performance_preference")
        scaling_governor = os.path.join(dir2, "scaling_governor")
        scaling_min_freq = os.path.join(dir2, "scaling_min_freq")

        self.assert_file_eventually_contains(energy_prefs, "balance_performance")
        self.assert_file_eventually_contains(scaling_governor, "powersave")
        self.assert_file_eventually_contains(scaling_min_freq, "1114000")

        # Set performance mode
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("performance"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")

        self.assert_file_eventually_contains(energy_prefs, "performance")
        self.assert_file_eventually_contains(scaling_governor, "performance")
        self.assert_file_eventually_contains(scaling_min_freq, "1114000")

        # Set powersave mode
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")

        self.assert_file_eventually_contains(energy_prefs, "power")
        self.assert_file_eventually_contains(scaling_governor, "powersave")
        self.assert_file_eventually_contains(scaling_min_freq, "400000")

    # pylint: disable=too-many-statements
    def test_amd_pstate_boost(self):
        """AMD P-State driver boost support"""

        # Create 2 CPUs with preferences
        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        self.write_file_contents(os.path.join(dir1, "boost"), "1\n")
        self.write_file_contents(os.path.join(dir1, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir1, "energy_performance_preference"), "performance\n"
        )
        dir2 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy1/"
        )
        os.makedirs(dir2)
        self.write_file_contents(os.path.join(dir2, "boost"), "1\n")
        self.write_file_contents(os.path.join(dir2, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir2, "energy_performance_preference"), "performance\n"
        )

        # Create AMD P-State configuration
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/amd_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)

        self.assertEqual(profiles[0]["Driver"], "multiple")
        self.assertEqual(profiles[0]["CpuDriver"], "amd_pstate")
        self.assertEqual(profiles[0]["Profile"], "power-saver")

        energy_prefs = os.path.join(dir2, "energy_performance_preference")
        scaling_governor = os.path.join(dir2, "scaling_governor")
        boost = os.path.join(dir2, "boost")

        self.assert_file_eventually_contains(energy_prefs, "balance_performance")
        self.assert_file_eventually_contains(scaling_governor, "powersave")

        # Set performance mode
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("performance"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")

        self.assert_file_eventually_contains(energy_prefs, "performance")
        self.assert_file_eventually_contains(scaling_governor, "performance")
        self.assert_file_eventually_contains(boost, "1")

        # Set powersave mode
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")

        self.assert_file_eventually_contains(energy_prefs, "power")
        self.assert_file_eventually_contains(scaling_governor, "powersave")
        self.assert_file_eventually_contains(boost, "0")

    def test_amd_pstate_balance(self):
        """AMD P-State driver (balance)"""

        # Create CPU with preference
        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        gov_path = os.path.join(dir1, "scaling_governor")
        self.write_file_contents(gov_path, "performance\n")
        self.write_file_contents(
            os.path.join(dir1, "energy_performance_preference"), "performance\n"
        )
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/amd_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        self.start_dbus_template(
            "upower",
            {"DaemonVersion": "0.99", "OnBattery": False},
        )

        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(profiles[0]["Driver"], "multiple")
        self.assertEqual(profiles[0]["CpuDriver"], "amd_pstate")
        self.assertEqual(profiles[0]["Profile"], "power-saver")

        # This matches what's written by ppd-driver-amd-pstate.c
        energy_prefs = os.path.join(dir1, "energy_performance_preference")
        self.assert_file_eventually_contains(energy_prefs, "balance_performance")

        scaling_governor = os.path.join(dir1, "scaling_governor")
        self.assert_file_eventually_contains(scaling_governor, "powersave")

    def test_amd_pstate_error(self):
        """AMD P-State driver in error state"""

        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/amd_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        self.write_file_contents(os.path.join(dir1, "scaling_governor"), "powersave\n")
        pref_path = os.path.join(dir1, "energy_performance_preference")
        old_umask = os.umask(0o333)
        self.write_file_contents(pref_path, "balance_performance\n")
        os.umask(old_umask)
        # Make file non-writable to root
        self.change_immutable(pref_path, True)

        self.start_daemon()

        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        # Error when setting performance mode
        with self.assertRaises(gi.repository.GLib.GError):
            self.set_dbus_property(
                "ActiveProfile", GLib.Variant.new_string("performance")
            )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        energy_prefs = os.path.join(dir1, "energy_performance_preference")
        self.assert_file_eventually_contains(energy_prefs, "balance_performance\n")

    def test_amd_pstate_passive(self):
        """AMD P-State in passive mode -> placeholder"""

        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        self.write_file_contents(os.path.join(dir1, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir1, "energy_performance_preference"), "balance_performance\n"
        )

        # Create AMD P-State configuration
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/amd_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "status"), "passive\n")

        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(profiles[0]["Driver"], "multiple")
        self.assertEqual(profiles[0]["PlatformDriver"], "placeholder")
        self.assertEqual(profiles[0]["CpuDriver"], "amd_pstate")
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        # Set performance mode
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("performance"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")

        # Shouldn't have updated
        energy_prefs = os.path.join(dir1, "energy_performance_preference")
        self.assert_file_eventually_contains(energy_prefs, "balance_performance")

    def test_dytc_performance_driver(self):
        """Lenovo DYTC performance driver"""

        self.create_dytc_device()
        self.create_platform_profile()
        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(profiles[0]["Driver"], "platform_profile")
        self.assertEqual(profiles[0]["PlatformDriver"], "platform_profile")
        self.assertEqual(profiles[0]["Profile"], "power-saver")
        self.assertEqual(profiles[2]["PlatformDriver"], "platform_profile")
        self.assertEqual(profiles[2]["Profile"], "performance")
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("performance"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")

        # lapmode detected
        lapmode = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/thinkpad_acpi/dytc_lapmode"
        )
        self.write_file_contents(lapmode, "1\n")
        self.assert_dbus_property_eventually_is("PerformanceDegraded", "lap-detected")
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")

        # Reset lapmode
        self.write_file_contents(lapmode, "0\n")
        self.assert_dbus_property_eventually_is("PerformanceDegraded", "")

        # Performance mode didn't change
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")

        # Switch to power-saver mode
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assert_eventually(
            lambda: self.read_sysfs_file("sys/firmware/acpi/platform_profile")
            == b"low-power"
        )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")

        # And mimic a user pressing a Fn+H
        platform_profile = os.path.join(
            self.testbed.get_root_dir(), "sys/firmware/acpi/platform_profile"
        )
        self.write_file_contents(platform_profile, "performance\n")
        self.assert_dbus_property_eventually_is("ActiveProfile", "performance")

    def test_fake_driver(self):
        """Test that the fake driver works"""

        os.environ["POWER_PROFILE_DAEMON_FAKE_DRIVER"] = "1"
        self.start_daemon()
        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.stop_daemon()

        del os.environ["POWER_PROFILE_DAEMON_FAKE_DRIVER"]
        self.start_daemon()
        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 2)

    def test_amd_pstate_upower(self):
        """Switching between balance_power and balance_performance based on battery"""
        # Create 2 CPUs with preferences
        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        self.write_file_contents(os.path.join(dir1, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir1, "energy_performance_preference"), "performance\n"
        )
        dir2 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy1/"
        )
        os.makedirs(dir2)
        self.write_file_contents(os.path.join(dir2, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir2, "energy_performance_preference"), "performance\n"
        )

        # Create AMD P-State configuration
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/amd_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        _, _, stop_upowerd = self.start_dbus_template(
            "upower",
            {"DaemonVersion": "0.99", "OnBattery": True},
        )

        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)

        self.assertEqual(profiles[0]["Driver"], "multiple")
        self.assertEqual(profiles[0]["CpuDriver"], "amd_pstate")
        self.assertEqual(profiles[0]["Profile"], "power-saver")

        energy_prefs = os.path.join(dir2, "energy_performance_preference")
        scaling_governor = os.path.join(dir2, "scaling_governor")

        self.assert_file_eventually_contains(energy_prefs, "balance_power")
        self.assert_file_eventually_contains(scaling_governor, "powersave")

        stop_upowerd()

        self.assert_file_eventually_contains(energy_prefs, "balance_performance")

        _, upowerd_obj, stop_upowerd = self.start_dbus_template(
            "upower",
            {"DaemonVersion": "0.99", "OnBattery": False},
        )

        self.assert_file_eventually_contains(energy_prefs, "balance_performance")

        upowerd_obj.Set("org.freedesktop.UPower", "OnBattery", True)
        self.assert_file_eventually_contains(energy_prefs, "balance_power")

        # Ensure that changing some other property doesn't change the state.
        upowerd_obj.Set("org.freedesktop.UPower", "LidIsClosed", True)
        self.assert_file_eventually_contains(
            energy_prefs, "balance_power", keep_checking=800
        )

        upowerd_obj.Set("org.freedesktop.UPower", "OnBattery", False)
        self.assert_file_eventually_contains(energy_prefs, "balance_performance")

        self.stop_daemon()

        # start upower after the daemon
        stop_upowerd()

        self.start_daemon()

        self.assert_file_eventually_contains(energy_prefs, "balance_performance")

        _, upowerd_obj, _ = self.start_dbus_template(
            "upower",
            {"DaemonVersion": "0.99", "OnBattery": False},
        )
        self.assert_file_eventually_contains(energy_prefs, "balance_performance")

        upowerd_obj.Set("org.freedesktop.UPower", "OnBattery", True)
        self.assert_file_eventually_contains(energy_prefs, "balance_power")

    def test_amdgpu_dpm_manual(self):
        """Verify AMDGPU dpm power actions avoid manual"""
        amdgpu_dpm = "device/power_dpm_force_performance_level"
        card = self.testbed.add_device(
            "drm",
            "card0",
            None,
            [amdgpu_dpm, "manual\n"],
            ["DEVTYPE", "drm_minor"],
        )
        self.create_amd_apu()

        self.start_daemon()

        self.call_dbus_method(
            "SetActionEnabled", GLib.Variant("(sb)", ("amdgpu_dpm", True))
        )

        self.assert_action_enabled("amdgpu_dpm")

        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("balanced"))
        self.assert_sysfs_attr_eventually_is(card, amdgpu_dpm, "manual")

        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assert_sysfs_attr_eventually_is(card, amdgpu_dpm, "manual")

    def test_amdgpu_dpm(self):
        """Verify AMDGPU dpm power actions"""
        amdgpu_dpm = "device/power_dpm_force_performance_level"
        card = self.testbed.add_device(
            "drm",
            "card0",
            None,
            [amdgpu_dpm, "auto\n"],
            ["DEVTYPE", "drm_minor"],
        )
        self.create_amd_apu()

        self.start_daemon()

        self.call_dbus_method(
            "SetActionEnabled", GLib.Variant("(sb)", ("amdgpu_dpm", True))
        )

        self.assert_action_enabled("amdgpu_dpm")

        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("balanced"))
        self.assert_sysfs_attr_eventually_is(card, amdgpu_dpm, "auto")

        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assert_sysfs_attr_eventually_is(card, amdgpu_dpm, "low")

    def test_amdgpu_panel_power(self):
        """Verify AMDGPU Panel power actions"""
        amdgpu_panel_power_savings = "amdgpu/panel_power_savings"
        edp = self.testbed.add_device(
            "drm",
            "card1-eDP",
            None,
            ["status", "connected\n", amdgpu_panel_power_savings, "0"],
            ["DEVTYPE", "drm_connector"],
        )

        self.create_amd_apu()

        self.start_daemon()

        # verify it starts off disabled
        self.assert_action_disabled("amdgpu_panel_power")

        # verify it is now enabled
        self.call_dbus_method(
            "SetActionEnabled", GLib.Variant("(sb)", ("amdgpu_panel_power", True))
        )
        self.assert_action_enabled("amdgpu_panel_power")

        # verify it hasn't been updated yet due to missing upower
        self.assert_sysfs_attr_eventually_is(edp, amdgpu_panel_power_savings, "0")

        # start upower and try again
        self.stop_daemon()
        _, obj, _ = self.start_dbus_template(
            "upower",
            {"DaemonVersion": "0.99", "OnBattery": True},
        )

        def set_battery_level(percentage):
            obj.SetDeviceProperties(
                "/org/freedesktop/UPower/devices/DisplayDevice",
                {"Percentage": dbus.Double(percentage, variant_level=1)},
            )

        set_battery_level(50)
        self.start_daemon()

        self.call_dbus_method(
            "SetActionEnabled", GLib.Variant("(sb)", ("amdgpu_panel_power", True))
        )

        # verify balanced has it off at half battery
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("balanced"))
        self.assert_sysfs_attr_eventually_is(edp, amdgpu_panel_power_savings, "0")

        # verify balanced turned it on when less than third battery
        set_battery_level(29)
        self.assert_sysfs_attr_eventually_is(edp, amdgpu_panel_power_savings, "1")

        # switch to power saver with a large battery, make sure off
        set_battery_level(70)
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assert_sysfs_attr_eventually_is(edp, amdgpu_panel_power_savings, "0")

        # # set power saver with less than half battery, should turn on
        set_battery_level(49)
        self.assert_sysfs_attr_eventually_is(edp, amdgpu_panel_power_savings, "1")

        # set power saver with very little battery, should turn on at 3
        set_battery_level(15)
        self.assert_sysfs_attr_eventually_is(edp, amdgpu_panel_power_savings, "3")

        # add another device that supports the feature
        edp2 = self.testbed.add_device(
            "drm",
            "card2-eDP",
            None,
            ["status", "connected\n", amdgpu_panel_power_savings, "0"],
            ["DEVTYPE", "drm_connector"],
        )

        # verify power saver got updated for it
        self.assert_sysfs_attr_eventually_is(edp2, amdgpu_panel_power_savings, "3")

        # add another device that supports the feature, but panel is disconnected
        edp3 = self.testbed.add_device(
            "drm",
            "card3-eDP",
            None,
            ["status", "disconnected\n", amdgpu_panel_power_savings, "0"],
            ["DEVTYPE", "drm_connector"],
        )

        # verify power saver didn't get updated for it
        self.assert_sysfs_attr_eventually_is(edp3, amdgpu_panel_power_savings, "0")

    def test_custom_trickle_charge_device(self):
        """Attempt to Trickle power_supply charge type, but already set to Custom"""

        fastcharge = self.testbed.add_device(
            "power_supply",
            "bq24190-charger",
            None,
            ["charge_type", "Custom", "scope", "Device"],
            [],
        )

        self.start_daemon()

        self.assert_action_enabled("trickle_charge")

        # Verify that charge-type stays untouched
        self.assertEqual(self.read_sysfs_attr(fastcharge, "charge_type"), b"Custom")

        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assert_sysfs_attr_eventually_is(fastcharge, "charge_type", "Custom")
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("balanced"))
        self.assert_sysfs_attr_eventually_is(fastcharge, "charge_type", "Custom")

        # verify charge type is touched again
        self.write_sysfs_attr(fastcharge, "charge_type", "Fast")
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assert_sysfs_attr_eventually_is(fastcharge, "charge_type", "Trickle")
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("balanced"))
        self.assert_sysfs_attr_eventually_is(fastcharge, "charge_type", "Standard")

        # verify it's not touched again
        self.write_sysfs_attr(fastcharge, "charge_type", "Custom")
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assert_sysfs_attr_eventually_is(fastcharge, "charge_type", "Custom")

        # verify it's not touched again
        self.write_sysfs_attr(fastcharge, "charge_type", "Adaptive")
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("balanced"))
        self.assert_sysfs_attr_eventually_is(fastcharge, "charge_type", "Adaptive")

    def test_trickle_charge_system(self):
        """Trickle power_supply charge type"""

        fastcharge = self.testbed.add_device(
            "power_supply",
            "bq24190-charger",
            None,
            ["charge_type", "Trickle", "scope", "System"],
            [],
        )

        self.start_daemon()

        self.assert_action_enabled("trickle_charge")

        # Verify that charge-type stays untouched
        self.assertEqual(self.read_sysfs_attr(fastcharge, "charge_type"), b"Trickle")

        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assertEqual(self.read_sysfs_attr(fastcharge, "charge_type"), b"Trickle")

    def test_trickle_charge_mode_no_change(self):
        """Trickle power_supply charge type"""

        fastcharge = self.testbed.add_device(
            "power_supply",
            "MFi Fastcharge",
            None,
            ["charge_type", "Standard", "scope", "Device"],
            [],
        )

        mtime = self.get_mtime(fastcharge, "charge_type")
        self.start_daemon()

        self.assert_action_enabled("trickle_charge")

        # Verify that charge-type didn't get touched
        self.assert_sysfs_attr_eventually_is(fastcharge, "charge_type", "Standard")
        self.assertEqual(self.get_mtime(fastcharge, "charge_type"), mtime)

    def test_trickle_charge_mode(self):
        """Trickle power_supply charge type"""

        idevice = self.testbed.add_device(
            "usb",
            "iDevice",
            None,
            [],
            ["ID_MODEL", "iDevice", "DRIVER", "apple-mfi-fastcharge"],
        )
        fastcharge = self.testbed.add_device(
            "power_supply",
            "MFi Fastcharge",
            idevice,
            ["charge_type", "Trickle", "scope", "Device"],
            [],
        )

        self.start_daemon()

        self.assert_action_enabled("trickle_charge")

        # Verify that charge-type got changed to Standard on startup
        self.assert_sysfs_attr_eventually_is(fastcharge, "charge_type", "Standard")

        # Verify that charge-type got changed to Trickle when power saving
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assert_sysfs_attr_eventually_is(fastcharge, "charge_type", "Trickle")

        # FIXME no performance mode
        # Verify that charge-type got changed to Fast in a non-default, non-power save mode
        # self.set_dbus_property('ActiveProfile', GLib.Variant.new_string('performance'))
        # self.assert_sysfs_attr_eventually_is(fastcharge, "charge_type", "Fast")

    def test_platform_driver_late_load(self):
        """Test that we can handle the platform_profile driver getting loaded late"""
        self.create_empty_platform_profile()
        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 2)

        acpi_dir = os.path.join(self.testbed.get_root_dir(), "sys/firmware/acpi/")
        self.write_file_contents(
            os.path.join(acpi_dir, "platform_profile_choices"),
            "low-power\nbalanced\nperformance\n",
        )
        self.write_file_contents(
            os.path.join(acpi_dir, "platform_profile"), "performance\n"
        )

        # Wait for profiles to get reloaded
        self.assert_eventually(lambda: len(self.get_dbus_property("Profiles")) == 3)
        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        # Was set in platform_profile before we loaded the drivers
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")
        self.assertEqual(self.get_dbus_property("PerformanceDegraded"), "")

    def test_hp_wmi(self):
        # Uses cool instead of low-power
        acpi_dir = os.path.join(self.testbed.get_root_dir(), "sys/firmware/acpi/")
        os.makedirs(acpi_dir)
        self.write_file_contents(os.path.join(acpi_dir, "platform_profile"), "cool\n")
        self.write_file_contents(
            os.path.join(acpi_dir, "platform_profile_choices"),
            "cool balanced performance\n",
        )

        self.start_daemon()
        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(profiles[0]["Driver"], "platform_profile")
        self.assertEqual(profiles[0]["PlatformDriver"], "platform_profile")
        self.assertEqual(profiles[0]["Profile"], "power-saver")
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")
        self.assertEqual(
            self.read_sysfs_file("sys/firmware/acpi/platform_profile"), b"cool"
        )
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")
        self.assertEqual(
            self.read_sysfs_file("sys/firmware/acpi/platform_profile"), b"cool"
        )

        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("performance"))
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("balanced"))
        self.assertEqual(
            self.read_sysfs_file("sys/firmware/acpi/platform_profile"), b"balanced"
        )

    def test_quiet(self):
        # Uses quiet instead of low-power
        acpi_dir = os.path.join(self.testbed.get_root_dir(), "sys/firmware/acpi/")
        os.makedirs(acpi_dir)
        self.write_file_contents(os.path.join(acpi_dir, "platform_profile"), "quiet\n")
        self.write_file_contents(
            os.path.join(acpi_dir, "platform_profile_choices"),
            "quiet balanced balanced-performance performance\n",
        )

        self.start_daemon()
        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(profiles[0]["Driver"], "platform_profile")
        self.assertEqual(profiles[0]["PlatformDriver"], "platform_profile")
        self.assertEqual(profiles[0]["Profile"], "power-saver")
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")
        self.assertEqual(
            self.read_sysfs_file("sys/firmware/acpi/platform_profile"), b"balanced"
        )
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")
        self.assertEqual(
            self.read_sysfs_file("sys/firmware/acpi/platform_profile"), b"quiet"
        )

    def test_custom_acpi_platform_profile(self):
        self.create_custom_platform_profile()
        self.start_daemon()
        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(profiles[0]["PlatformDriver"], "platform_profile")

        # make sure PPD overrides it
        self.assertEqual(
            self.read_sysfs_file("sys/firmware/acpi/platform_profile"), b"balanced"
        )

    def test_hold_release_profile(self):
        self.create_platform_profile()
        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)

        cookie = self.call_dbus_method(
            "HoldProfile",
            GLib.Variant("(sss)", ("performance", "testReason", "testApplication")),
        )
        self.assert_eventually(
            lambda: self.changed_properties.get("ActiveProfile") == "performance"
        )
        self.assert_eventually(
            lambda: self.changed_properties.get("ActiveProfileHolds")
            == [
                {
                    "ApplicationId": "testApplication",
                    "Profile": "performance",
                    "Reason": "testReason",
                }
            ]
        )

        released_cookie = None

        def signal_cb(_, sender, signal_name, params):
            nonlocal released_cookie
            if signal_name == "ProfileReleased":
                released_cookie = params

        self.addCleanup(
            self.proxy.disconnect, self.proxy.connect("g-signal", signal_cb)
        )

        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")
        profile_holds = self.get_dbus_property("ActiveProfileHolds")
        self.assertEqual(len(profile_holds), 1)
        self.assertEqual(profile_holds[0]["Profile"], "performance")
        self.assertEqual(profile_holds[0]["Reason"], "testReason")
        self.assertEqual(profile_holds[0]["ApplicationId"], "testApplication")

        self.call_dbus_method("ReleaseProfile", GLib.Variant("(u)", cookie))
        self.assert_eventually(lambda: released_cookie == cookie)
        self.assert_eventually(
            lambda: self.changed_properties.get("ActiveProfile") == "balanced"
        )
        self.assert_eventually(
            lambda: self.changed_properties.get("ActiveProfileHolds") == []
        )
        profile_holds = self.get_dbus_property("ActiveProfileHolds")
        self.assertEqual(len(profile_holds), 0)
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        # When the profile is changed manually, holds should be released a
        self.call_dbus_method(
            "HoldProfile", GLib.Variant("(sss)", ("performance", "", ""))
        )
        self.assertEqual(len(self.get_dbus_property("ActiveProfileHolds")), 1)
        self.assert_eventually(
            lambda: self.changed_properties.get("ActiveProfile") == "performance"
        )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")

        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("balanced"))
        self.assert_eventually(
            lambda: self.changed_properties.get("ActiveProfile") == "balanced"
        )
        self.assertEqual(len(self.get_dbus_property("ActiveProfileHolds")), 0)
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        # When all holds are released, the last manually selected profile should be activated
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.assert_eventually(
            lambda: self.changed_properties.get("ActiveProfile") == "power-saver"
        )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")
        cookie = self.call_dbus_method(
            "HoldProfile", GLib.Variant("(sss)", ("performance", "", ""))
        )
        self.assert_eventually(
            lambda: self.changed_properties.get("ActiveProfileHolds")
            == [
                {
                    "ApplicationId": "",
                    "Profile": "performance",
                    "Reason": "",
                }
            ]
        )
        self.assert_eventually(
            lambda: self.changed_properties.get("ActiveProfile") == "performance"
        )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")
        self.call_dbus_method("ReleaseProfile", GLib.Variant("(u)", cookie))
        self.assert_eventually(lambda: released_cookie == cookie)
        self.assert_eventually(
            lambda: self.changed_properties.get("ActiveProfileHolds") == []
        )
        self.assert_eventually(
            lambda: self.changed_properties.get("ActiveProfile") == "power-saver"
        )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")

    def test_launch_arguments_redirection(self):
        self.create_platform_profile()
        self.start_daemon()
        self.assert_eventually(lambda: self.get_dbus_property("ActiveProfile"))

        with tempfile.NamedTemporaryFile(mode="+rt") as tmpf:
            subprocess.check_call(
                self.powerprofilesctl_command()
                + [
                    "launch",
                    "sh",
                    "-c",
                    f'echo "$@" > {tmpf.name}',
                    "--",
                    "--foo",
                    "--bar",
                    "-v",
                    "arg",
                ]
            )
            self.assertEqual(tmpf.readlines(), ["--foo --bar -v arg\n"])

    def test_unknown_action(self):
        self.create_platform_profile()
        self.start_daemon()
        self.assert_eventually(lambda: self.get_dbus_property("ActiveProfile"))

        with self.assertRaises(subprocess.CalledProcessError):
            tool_cmd = self.powerprofilesctl_command()
            subprocess.check_output(
                tool_cmd + ["hopefully-invalid-action"], stderr=subprocess.PIPE
            )

    def test_unknown_list_argument(self):
        self.create_platform_profile()
        self.start_daemon()
        self.assert_eventually(lambda: self.get_dbus_property("ActiveProfile"))

        with self.assertRaises(subprocess.CalledProcessError):
            subprocess.check_output(
                self.powerprofilesctl_command() + ["list", "--invalid-argument"],
                stderr=subprocess.PIPE,
            )

    def test_launch_arguments_invalid(self):
        self.create_platform_profile()
        self.start_daemon()
        self.assert_eventually(lambda: self.get_dbus_property("ActiveProfile"))

        with self.assertRaises(subprocess.CalledProcessError):
            tool_cmd = self.powerprofilesctl_command()
            subprocess.check_output(
                tool_cmd + ["--foo-arg", "launch", "true"], stderr=subprocess.PIPE
            )

    def test_launch_with_command_failure(self):
        self.create_platform_profile()
        self.start_daemon()
        self.assert_eventually(lambda: self.get_dbus_property("ActiveProfile"))

        tool_cmd = self.powerprofilesctl_command()
        cmd = subprocess.run(tool_cmd + ["launch", "false"], check=False)
        self.assertEqual(cmd.returncode, 1)

        cmd = subprocess.run(tool_cmd + ["launch", "sh", "-c", "exit 55"], check=False)
        self.assertEqual(cmd.returncode, 55)

    def test_launch_with_command_signaled(self):
        self.create_platform_profile()
        self.start_daemon()
        self.assert_eventually(lambda: self.get_dbus_property("ActiveProfile"))

        tool_cmd = self.powerprofilesctl_command()
        cmd = subprocess.run(
            tool_cmd + ["launch", "sh", "-c", f"kill -{signal.SIGKILL} $$"], check=False
        )
        self.assertEqual(cmd.returncode, -signal.SIGKILL)

        cmd = subprocess.run(
            tool_cmd + ["launch", "sh", "-c", f"kill -{signal.SIGINT} $$"], check=False
        )
        self.assertEqual(cmd.returncode, -signal.SIGINT)

    def test_vanishing_hold(self):
        self.create_platform_profile()
        self.start_daemon()
        self.assert_eventually(lambda: self.get_dbus_property("ActiveProfile"))

        tool_cmd = self.powerprofilesctl_command()
        with subprocess.Popen(
            tool_cmd + ["launch", "-p", "power-saver", "sleep", "3600"],
            stdout=sys.stdout,
            stderr=sys.stderr,
        ) as launch_process:
            self.assertTrue(launch_process)
            if platform.machine() == 'riscv64':
                time.sleep(3)
            else:
                time.sleep(1)
            holds = self.get_dbus_property("ActiveProfileHolds")
            self.assertEqual(len(holds), 1)
            hold = holds[0]
            self.assertEqual(hold["Profile"], "power-saver")

            # Make sure to handle vanishing clients
            launch_process.terminate()
            retcode = launch_process.wait()
            self.assertEqual(retcode, -signal.SIGTERM)

        self.assert_eventually(
            lambda: len(self.get_dbus_property("ActiveProfileHolds")) == 0,
            message=lambda: f"Holds are {self.get_dbus_property('ActiveProfileHolds')}",
        )

    def test_launch_sigint_wrapper(self):
        self.create_platform_profile()
        self.start_daemon()
        self.assert_eventually(lambda: self.get_dbus_property("ActiveProfile"))

        with subprocess.Popen(
            self.powerprofilesctl_command() + ["launch", "sleep", "3600"],
        ) as launch_process:
            time.sleep(1)
            launch_process.send_signal(signal.SIGINT)
            retcode = launch_process.wait()
            self.assertEqual(retcode, -signal.SIGINT)

    def test_launch_sigabrt_wrapper(self):
        self.create_platform_profile()
        self.start_daemon()
        self.assert_eventually(lambda: self.get_dbus_property("ActiveProfile"))

        with subprocess.Popen(
            self.powerprofilesctl_command() + ["launch", "sleep", "3600"],
        ) as launch_process:
            time.sleep(1)
            launch_process.send_signal(signal.SIGABRT)
            retcode = launch_process.wait()
            self.assertEqual(retcode, -signal.SIGABRT)

    def test_hold_priority(self):
        """power-saver should take priority over performance"""
        self.create_platform_profile()
        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        # Test every order of holding and releasing power-saver and performance
        # hold performance and then power-saver, release in the same order
        performance_cookie = self.call_dbus_method(
            "HoldProfile", GLib.Variant("(sss)", ("performance", "", ""))
        )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")
        powersaver_cookie = self.call_dbus_method(
            "HoldProfile", GLib.Variant("(sss)", ("power-saver", "", ""))
        )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")
        self.call_dbus_method("ReleaseProfile", GLib.Variant("(u)", performance_cookie))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")
        self.call_dbus_method("ReleaseProfile", GLib.Variant("(u)", powersaver_cookie))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        # hold performance and then power-saver, but release power-saver first
        performance_cookie = self.call_dbus_method(
            "HoldProfile", GLib.Variant("(sss)", ("performance", "", ""))
        )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")
        powersaver_cookie = self.call_dbus_method(
            "HoldProfile", GLib.Variant("(sss)", ("power-saver", "", ""))
        )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")
        self.call_dbus_method("ReleaseProfile", GLib.Variant("(u)", powersaver_cookie))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")
        self.call_dbus_method("ReleaseProfile", GLib.Variant("(u)", performance_cookie))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        # hold power-saver and then performance, release in the same order
        powersaver_cookie = self.call_dbus_method(
            "HoldProfile", GLib.Variant("(sss)", ("power-saver", "", ""))
        )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")
        performance_cookie = self.call_dbus_method(
            "HoldProfile", GLib.Variant("(sss)", ("performance", "", ""))
        )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")
        self.call_dbus_method("ReleaseProfile", GLib.Variant("(u)", powersaver_cookie))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")
        self.call_dbus_method("ReleaseProfile", GLib.Variant("(u)", performance_cookie))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        # hold power-saver and then performance, but release performance first
        powersaver_cookie = self.call_dbus_method(
            "HoldProfile", GLib.Variant("(sss)", ("power-saver", "", ""))
        )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")
        performance_cookie = self.call_dbus_method(
            "HoldProfile", GLib.Variant("(sss)", ("performance", "", ""))
        )
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")
        self.call_dbus_method("ReleaseProfile", GLib.Variant("(u)", performance_cookie))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")
        self.call_dbus_method("ReleaseProfile", GLib.Variant("(u)", powersaver_cookie))
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

    def test_save_profile(self):
        """save profile across runs"""

        self.create_platform_profile()

        self.start_daemon()
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.stop_daemon()

        # sys.stderr.write('\n-------------- config file: ----------------\n')
        # with open(self.testbed.get_root_dir() + '/' + 'ppd_test_conf.ini') as tmpf:
        #   sys.stderr.write(tmpf.read())
        # sys.stderr.write('------------------------------\n')

        self.start_daemon()
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")
        # Programmatically set profile aren't saved
        performance_cookie = self.call_dbus_method(
            "HoldProfile", GLib.Variant("(sss)", ("performance", "", ""))
        )
        self.assertTrue(performance_cookie)
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "performance")
        self.stop_daemon()

        self.start_daemon()
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")

    def test_save_deferred_load(self):
        """save profile across runs, but kernel driver loaded after start"""

        self.create_platform_profile()
        self.start_daemon()
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")
        self.set_dbus_property("ActiveProfile", GLib.Variant.new_string("power-saver"))
        self.stop_daemon()
        self.remove_platform_profile()

        # We could verify the contents of the configuration file here

        self.create_empty_platform_profile()
        self.start_daemon()
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        acpi_dir = os.path.join(self.testbed.get_root_dir(), "sys/firmware/acpi/")
        self.write_file_contents(
            os.path.join(acpi_dir, "platform_profile_choices"),
            "low-power\nbalanced\nperformance\n",
        )
        self.write_file_contents(
            os.path.join(acpi_dir, "platform_profile"), "performance\n"
        )

        self.assert_dbus_property_eventually_is("ActiveProfile", "power-saver")

    def test_not_allowed_profile(self):
        """Check that we get errors when trying to change a profile and not allowed"""

        self.obj_polkit.SetAllowed(dbus.Array([], signature="s"))
        self.start_daemon()
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        proxy = Gio.DBusProxy.new_sync(
            self.dbus,
            Gio.DBusProxyFlags.DO_NOT_AUTO_START,
            None,
            self.PP,
            self.PP_PATH,
            "org.freedesktop.DBus.Properties",
            None,
        )
        with self.assertRaises(gi.repository.GLib.GError) as error:
            proxy.Set(
                "(ssv)",
                self.PP,
                "ActiveProfile",
                GLib.Variant.new_string("power-saver"),
            )
        self.assertIn("AccessDenied", str(error.exception))

    def test_not_allowed_hold(self):
        """Check that we get an error when trying to hold a profile and not allowed"""

        self.obj_polkit.SetAllowed(dbus.Array([], signature="s"))
        self.start_daemon()
        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        with self.assertRaises(gi.repository.GLib.GError) as error:
            self.call_dbus_method(
                "HoldProfile", GLib.Variant("(sss)", ("performance", "", ""))
            )
        self.assertIn("AccessDenied", str(error.exception))

        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")
        self.assertEqual(len(self.get_dbus_property("ActiveProfileHolds")), 0)

    def test_get_version_prop(self):
        """Checks that the version property is advertised"""
        self.start_daemon()
        self.assertTrue(self.get_dbus_property("Version"))

    def test_intel_pstate_disabled_upower(self):
        # Create CPU with preference
        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        self.write_file_contents(os.path.join(dir1, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir1, "energy_performance_preference"), "performance\n"
        )

        # Create Intel P-State configuration
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/intel_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "no_turbo"), "1\n")
        self.write_file_contents(os.path.join(pstate_dir, "turbo_pct"), "0\n")
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        _, _, stop_upowerd = self.start_dbus_template(
            "upower",
            {"DaemonVersion": "0.99", "OnBattery": False},
        )

        self.start_daemon(["--disable-upower"])

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(self.get_dbus_property("PerformanceDegraded"), "")

        energy_prefs = os.path.join(dir1, "energy_performance_preference")
        scaling_governor = os.path.join(dir1, "scaling_governor")

        self.assert_file_eventually_contains(energy_prefs, "balance_performance")
        self.assert_file_eventually_contains(scaling_governor, "powersave")

        stop_upowerd()

        self.assert_file_eventually_contains(energy_prefs, "balance_performance")

    def test_intel_pstate_upower(self):
        # Create CPU with preference
        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        self.write_file_contents(os.path.join(dir1, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir1, "energy_performance_preference"), "performance\n"
        )

        # Create Intel P-State configuration
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/intel_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "no_turbo"), "1\n")
        self.write_file_contents(os.path.join(pstate_dir, "turbo_pct"), "0\n")
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        _, _, stop_upowerd = self.start_dbus_template(
            "upower",
            {"DaemonVersion": "0.99", "OnBattery": True},
        )

        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(self.get_dbus_property("PerformanceDegraded"), "")

        energy_prefs = os.path.join(dir1, "energy_performance_preference")
        scaling_governor = os.path.join(dir1, "scaling_governor")

        self.assert_file_eventually_contains(energy_prefs, "balance_power")
        self.assert_file_eventually_contains(scaling_governor, "powersave")

        stop_upowerd()

        self.assert_file_eventually_contains(energy_prefs, "balance_performance")

        _, upowerd_obj, stop_upowerd = self.start_dbus_template(
            "upower",
            {"DaemonVersion": "0.99", "OnBattery": False},
        )

        self.assert_file_eventually_contains(energy_prefs, "balance_performance")

        upowerd_obj.Set("org.freedesktop.UPower", "OnBattery", True)
        self.assert_file_eventually_contains(energy_prefs, "balance_power")

        upowerd_obj.Set("org.freedesktop.UPower", "OnBattery", False)
        self.assert_file_eventually_contains(energy_prefs, "balance_performance")

        self.stop_daemon()

        # start upower after the daemon
        stop_upowerd()

        self.start_daemon()

        self.assert_file_eventually_contains(energy_prefs, "balance_performance")

        _, upowerd_obj, _ = self.start_dbus_template(
            "upower",
            {"DaemonVersion": "0.99", "OnBattery": False},
        )
        self.assert_file_eventually_contains(energy_prefs, "balance_performance")

        upowerd_obj.Set("org.freedesktop.UPower", "OnBattery", True)
        self.assert_file_eventually_contains(energy_prefs, "balance_power")

    def test_intel_pstate_noturbo(self):
        """Intel P-State driver (balance)"""

        # Create CPU with preference
        dir1 = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/cpufreq/policy0/"
        )
        os.makedirs(dir1)
        self.write_file_contents(os.path.join(dir1, "scaling_governor"), "powersave\n")
        self.write_file_contents(
            os.path.join(dir1, "energy_performance_preference"), "performance\n"
        )

        # Create Intel P-State configuration
        pstate_dir = os.path.join(
            self.testbed.get_root_dir(), "sys/devices/system/cpu/intel_pstate"
        )
        os.makedirs(pstate_dir)
        self.write_file_contents(os.path.join(pstate_dir, "no_turbo"), "1\n")
        self.write_file_contents(os.path.join(pstate_dir, "turbo_pct"), "0\n")
        self.write_file_contents(os.path.join(pstate_dir, "status"), "active\n")

        self.start_daemon()

        profiles = self.get_dbus_property("Profiles")
        self.assertEqual(len(profiles), 3)
        self.assertEqual(self.get_dbus_property("PerformanceDegraded"), "")

    def test_powerprofilesctl_configure_battery_aware_command(self):
        """Check powerprofilesctl configure-battery-aware command works"""

        self.start_dbus_template(
            "upower",
            {"DaemonVersion": "0.99", "OnBattery": False},
        )

        self.start_daemon()

        # verify argument is required
        cmd = subprocess.run(
            self.powerprofilesctl_command() + ["configure-battery-aware"],
            capture_output=True,
            check=False,
        )
        self.assertEqual(cmd.returncode, 1)

        # check possible arguments
        for key, value in {"--disable": "False", "--enable": "True"}.items():
            cmd = subprocess.run(
                self.powerprofilesctl_command() + ["configure-battery-aware", key],
                capture_output=True,
                check=True,
            )
            self.assertEqual(cmd.returncode, 0)

            cmd = subprocess.run(
                self.powerprofilesctl_command() + ["query-battery-aware"],
                capture_output=True,
                check=True,
            )
            self.assertEqual(cmd.returncode, 0)
            self.assertIn(
                f"Dynamic changes from charger and battery events: {value}",
                cmd.stdout.decode("utf-8"),
            )

        # make sure can't be enabled twice
        cmd = subprocess.run(
            self.powerprofilesctl_command() + ["configure-battery-aware", "--enable"],
            capture_output=True,
            check=False,
        )
        self.assertEqual(cmd.returncode, 1)

    def test_powerprofilesctl_configure_action_command(self):
        """Check powerprofilesctl configure-action command works"""

        self.start_daemon()

        for key, value in {"--disable": "False", "--enable": "True"}.items():
            with self.subTest(flag=key):
                cmd = subprocess.run(
                    self.powerprofilesctl_command()
                    + ["configure-action", "trickle_charge", key],
                    capture_output=True,
                    check=True,
                )
            self.assertEqual(cmd.returncode, 0)
            self.assertIn(
                f"action: trickle_charge, enable: {value}", cmd.stdout.decode("utf-8")
            )

    def test_powerprofilesctl_list_actions_command(self):
        """Check powerprofilesctl list-actions command works"""

        self.start_daemon()

        cmd = subprocess.run(
            self.powerprofilesctl_command() + ["list-actions"],
            capture_output=True,
            check=True,
        )
        self.assertEqual(cmd.returncode, 0)
        self.assertIn("trickle_charge", cmd.stdout.decode("utf-8"))

    def test_powerprofilesctl_version_command(self):
        """Check powerprofilesctl version command works"""

        self.start_daemon()

        cmd = subprocess.run(self.powerprofilesctl_command() + ["version"], check=True)
        self.assertEqual(cmd.returncode, 0)

    def test_powerprofilesctl_list_command(self):
        """Check powerprofilesctl list command works"""

        self.start_daemon()

        tool_cmd = self.powerprofilesctl_command()
        cmd = subprocess.run(tool_cmd + ["list"], capture_output=True, check=True)
        self.assertEqual(cmd.returncode, 0)
        self.assertIn("* balanced", cmd.stdout.decode("utf-8"))

    def test_powerprofilesctl_set_get_commands(self):
        """Check powerprofilesctl set/get command works"""

        self.start_daemon()

        self.assertEqual(self.get_dbus_property("ActiveProfile"), "balanced")

        tool_cmd = self.powerprofilesctl_command()
        cmd = subprocess.run(tool_cmd + ["get"], capture_output=True, check=True)
        self.assertEqual(cmd.returncode, 0)
        self.assertEqual(cmd.stdout, b"balanced\n")

        cmd = subprocess.run(
            tool_cmd + ["set", "power-saver"], capture_output=True, check=True
        )
        self.assertEqual(cmd.returncode, 0)

        self.assertEqual(self.get_dbus_property("ActiveProfile"), "power-saver")

        cmd = subprocess.run(tool_cmd + ["get"], capture_output=True, check=True)
        self.assertEqual(cmd.returncode, 0)
        self.assertEqual(cmd.stdout, b"power-saver\n")

    def test_powerprofilesctl_error(self):
        """Check that powerprofilesctl returns 1 rather than an exception on error"""

        tool_cmd = self.powerprofilesctl_command()
        with self.assertRaises(subprocess.CalledProcessError) as error:
            subprocess.check_output(
                tool_cmd + ["list"], stderr=subprocess.PIPE, universal_newlines=True
            )
        self.assertNotIn("Traceback", error.exception.stderr)

        with self.assertRaises(subprocess.CalledProcessError) as error:
            subprocess.check_output(
                tool_cmd + ["get"], stderr=subprocess.PIPE, universal_newlines=True
            )
        self.assertNotIn("Traceback", error.exception.stderr)

        with self.assertRaises(subprocess.CalledProcessError) as error:
            subprocess.check_output(
                tool_cmd + ["set", "not-a-profile"],
                stderr=subprocess.PIPE,
                universal_newlines=True,
            )
        self.assertNotIn("Traceback", error.exception.stderr)

        with self.assertRaises(subprocess.CalledProcessError) as error:
            subprocess.check_output(
                tool_cmd + ["list-holds"],
                stderr=subprocess.PIPE,
                universal_newlines=True,
            )
        self.assertNotIn("Traceback", error.exception.stderr)

        with self.assertRaises(subprocess.CalledProcessError) as error:
            subprocess.check_output(
                tool_cmd + ["launch", "-p", "power-saver", "sleep", "1"],
                stderr=subprocess.PIPE,
                universal_newlines=True,
            )
        self.assertNotIn("Traceback", error.exception.stderr)

        self.start_daemon()
        with self.assertRaises(subprocess.CalledProcessError) as error:
            subprocess.check_output(
                tool_cmd + ["set", "not-a-profile"],
                stderr=subprocess.PIPE,
                universal_newlines=True,
            )
        self.assertNotIn("Traceback", error.exception.stderr)

    #
    # Helper methods
    #

    @classmethod
    def _props_to_str(cls, properties):
        """Convert a properties dictionary to uevent text representation."""

        prop_str = ""
        if properties:
            for key, val in properties.items():
                prop_str += f"{key}={val}\n"
        return prop_str


class LegacyDBusNameTests(Tests):
    """This will repeats all the tests in the Tests class using the legacy dbus name"""

    PP = "net.hadess.PowerProfiles"
    PP_PATH = "/net/hadess/PowerProfiles"
    PP_INTERFACE = "net.hadess.PowerProfiles"

    def test_vanishing_hold(self):
        # Let's not block because of this CI failure, the test isn't relying on
        # the old name anyways.
        pass

    def test_amdgpu_dpm(self):
        amdgpu_dpm = "device/power_dpm_force_performance_level"
        self.testbed.add_device(
            "drm",
            "card0",
            None,
            [amdgpu_dpm, "auto\n"],
            ["DEVTYPE", "drm_minor"],
        )
        self.create_amd_apu()

        self.start_daemon()

        # verify can't enable it on legacy interface
        with self.assertRaises(gi.repository.GLib.GError) as error:
            self.call_dbus_method(
                "SetActionEnabled", GLib.Variant("(sb)", ("amdgpu_dpm", True))
            )
        self.assertIn("UnknownMethod", str(error.exception))

    def test_amdgpu_dpm_manual(self):
        # should fail same way as test_amdgpu_dpm
        self.test_amdgpu_dpm()

    def test_amdgpu_panel_power(self):
        amdgpu_panel_power_savings = "amdgpu/panel_power_savings"
        self.testbed.add_device(
            "drm",
            "card1-eDP",
            None,
            ["status", "connected\n", amdgpu_panel_power_savings, "0"],
            ["DEVTYPE", "drm_connector"],
        )

        self.create_amd_apu()

        self.start_daemon()

        # verify it starts off disabled
        self.assert_action_disabled("amdgpu_panel_power")

        # verify can't enable it on legacy interface
        with self.assertRaises(gi.repository.GLib.GError) as error:
            self.call_dbus_method(
                "SetActionEnabled", GLib.Variant("(sb)", ("amdgpu_panel_power", True))
            )
        self.assertIn("UnknownMethod", str(error.exception))


if __name__ == "__main__":
    # run ourselves under umockdev
    if "umockdev" not in os.environ.get("LD_PRELOAD", ""):
        os.execvp("umockdev-wrapper", ["umockdev-wrapper", sys.executable] + sys.argv)

    prog = unittest.main(exit=False)
    if prog.result.errors or prog.result.failures:
        sys.exit(1)

    # Translate to skip error
    if prog.result.testsRun == len(prog.result.skipped):
        sys.exit(77)