From 487d1c55afb923670daa4505f221d31b6c3df3fa Mon Sep 17 00:00:00 2001 From: Mike Salvatore Date: Tue, 10 May 2022 13:23:50 -0400 Subject: [PATCH] Common: Add queue_to_list() --- monkey/common/utils/code_utils.py | 15 +++++++++++++ .../common/utils/test_code_utils.py | 22 +++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 monkey/tests/unit_tests/common/utils/test_code_utils.py diff --git a/monkey/common/utils/code_utils.py b/monkey/common/utils/code_utils.py index 810fbb0d7..251ce9375 100644 --- a/monkey/common/utils/code_utils.py +++ b/monkey/common/utils/code_utils.py @@ -1,3 +1,7 @@ +import queue +from typing import Any, List + + class abstractstatic(staticmethod): __slots__ = () @@ -15,3 +19,14 @@ class Singleton(type): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] + + +def queue_to_list(q: queue.Queue) -> List[Any]: + list_ = [] + try: + while True: + list_.append(q.get_nowait()) + except queue.Empty: + pass + + return list_ diff --git a/monkey/tests/unit_tests/common/utils/test_code_utils.py b/monkey/tests/unit_tests/common/utils/test_code_utils.py new file mode 100644 index 000000000..411b07a63 --- /dev/null +++ b/monkey/tests/unit_tests/common/utils/test_code_utils.py @@ -0,0 +1,22 @@ +from queue import Queue + +from common.utils.code_utils import queue_to_list + + +def test_empty_queue_to_empty_list(): + q = Queue() + + list_ = queue_to_list(q) + + assert len(list_) == 0 + + +def test_queue_to_list(): + expected_list = [8, 6, 7, 5, 3, 0, 9] + q = Queue() + for i in expected_list: + q.put(i) + + list_ = queue_to_list(q) + + assert list_ == expected_list