1+ import os
2+ import sys
3+
4+ import pytest
5+ import pytest_subprocess
6+
7+ currentdir = os .path .dirname (os .path .realpath (__file__ ))
8+ parentdir = os .path .dirname (currentdir )
9+ sys .path .append (parentdir )
10+
11+ from uhubctl import *
12+
13+ class MockHub (Hub ):
14+ def __init__ (self , path : str , num_ports : int = 5 ) -> None :
15+ self .path = path
16+ self .num_ports = num_ports
17+ self .status = []
18+
19+ # initialize status
20+ for _ in range (self .num_ports ):
21+ self .status .append (True )
22+
23+ super ().__init__ (path , False )
24+
25+ def __stdout (self , prefix : str = "Current" , port_filter : int = None ):
26+ stdout = [
27+ f"{ prefix } status for hub { self .path } [0424:9512, USB 2.00, { self .num_ports } ports, ppps]" .encode ()]
28+
29+ for idx in range (self .num_ports ):
30+ if port_filter is not None and idx + 1 != int (port_filter ):
31+ continue
32+
33+ stdout .append (f" Port { idx + 1 } : 0100 { self .__power_status (idx )} " .encode ())
34+
35+ return stdout
36+
37+ def __status (self , status : bool ):
38+ if status :
39+ return "power"
40+ else :
41+ return "off"
42+
43+ def __power_status (self , port_number : int ):
44+ assert port_number <= self .num_ports
45+
46+ return self .__status (self .status [port_number ])
47+
48+ def cmd (self , fp : pytest_subprocess .FakeProcess , port_number : int = None , new_status : bool = None ) -> None :
49+ if port_number is not None :
50+ assert port_number <= self .num_ports
51+
52+ cmd = ["uhubctl" , "-N" , "-l" , str (self .path )]
53+ stdout = self .__stdout (port_filter = port_number )
54+
55+ if port_number is not None :
56+ cmd += [ "-p" , str (port_number )]
57+
58+ if new_status is not None :
59+ self .status [port_number ] = new_status
60+
61+ cmd .append ("-a" )
62+ cmd .append (self .__status (new_status ))
63+
64+ stdout .append ("Sent power on request" .encode ())
65+ stdout += self .__stdout ("New" , port_filter = port_number )
66+
67+ fp .register (cmd , stdout = stdout )
68+
69+ @pytest .fixture
70+ def mock_hub ():
71+ path = "1-2"
72+ num_ports = 5
73+ hub = MockHub (path , num_ports )
74+
75+ return hub
0 commit comments