Coverage for src/probable_fiesta/command/builder/command_queue.py: 75%

76 statements  

« prev     ^ index     » next       coverage.py v7.1.0, created at 2023-01-30 18:57 -0500

1"""Command Queue class.""" 

2from .command_factory import CommandFactory 

3from .command import Command 

4 

5class CommandQueue(): 

6 

7 def __init__(self): 

8 self.queue = [] 

9 self.history = [] 

10 self.length = 0 

11 

12 def add_command(self, command): 

13 if command is not None: 

14 self.queue.append(command) 

15 self.length += 1 

16 

17 def add_new_command(self, name, function, *args): 

18 c = CommandFactory().new_command(name, function, *args) 

19 if c is not None: 

20 self.queue.append(c) 

21 self.length += 1 

22 

23 def remove(self, command): 

24 removed = self.queue.remove(command) 

25 if removed: 

26 self.length -= 1 

27 

28 def clear(self): 

29 self.queue = [] 

30 self.length = 0 

31 

32 def run_command(self, command): 

33 self.length -= 1 

34 self.history.append(command.invoke()) 

35 return self 

36 

37 def run_all(self): 

38 if self.length <= 0: 

39 print("No commands in queue") 

40 return None 

41 elif self.length == 1: 

42 self.run_command(self.queue.pop()) 

43 else: 

44 for c in self.queue: 

45 self.run_command(c) 

46 return self 

47 

48 def get_history(self): 

49 "Get history and clears it." 

50 if len(self.history) <= 0: 

51 print("No commands in history") 

52 return None 

53 elif len(self.history) == 1: 

54 return self.history.pop() 

55 else: 

56 temp = self.history 

57 self.history = [] 

58 return temp 

59 

60 def show(self): 

61 return self.queue 

62 

63 def __str__(self): 

64 return f'CommandQueue: loaded commands: {self.length} executed commands: {self.history} ' 

65 

66 def print_queue(self): 

67 for c in self.queue: 

68 print(c) 

69 

70 @staticmethod 

71 def new_empty(): 

72 return CommandQueue() 

73 

74 @staticmethod 

75 def new(queue): 

76 command_queue = CommandQueue() 

77 if queue is not None: 

78 if isinstance(queue, list): 

79 for command in queue: 

80 if not isinstance(command, Command): 

81 print("Invalid command type: %s", type(command)) 

82 else: 

83 command_queue.add_command(command) 

84 elif isinstance(queue, CommandQueue): 

85 command_queue = queue 

86 elif isinstance(queue, Command): 

87 command_queue.add_command(queue) 

88 else: 

89 print("Invalid queue type: %s", type(queue)) 

90 else: 

91 print("Creating empty queue: %s", queue) 

92 return command_queue 

93 

94 class Factory(): 

95 @staticmethod 

96 def new_command_queue(command_or_queue): 

97 return CommandQueue().new(command_or_queue) 

98 

99 factory = Factory()