File: test_command_runner.py

package info (click to toggle)
python-command-runner 1.7.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 272 kB
  • sloc: python: 1,838; makefile: 5
file content (1053 lines) | stat: -rw-r--r-- 36,444 bytes parent folder | download
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
#! /usr/bin/env python
#  -*- coding: utf-8 -*-
#
# This file is part of command_runner module

"""
command_runner is a quick tool to launch commands from Python, get exit code
and output, and handle most errors that may happen

Versioning semantics:
    Major version: backward compatibility breaking changes
    Minor version: New functionality
    Patch version: Backwards compatible bug fixes

"""

__intname__ = "command_runner_tests"
__author__ = "Orsiris de Jong"
__copyright__ = "Copyright (C) 2015-2025 Orsiris de Jong"
__licence__ = "BSD 3 Clause"
__build__ = "2025090901"


import sys
import os
import platform
import re
import threading
import logging
import collections

try:
    from command_runner import *
except ImportError:  # would be ModuleNotFoundError in Python 3+
    # In case we run tests without actually having installed command_runner
    sys.path.insert(0, os.path.abspath(os.path.join(__file__, os.pardir, os.pardir)))
    from command_runner import *

# Python 2.7 compat where datetime.now() does not have .timestamp() method
if sys.version_info[0] < 3 or sys.version_info[1] < 4:
    # python version < 3.3
    import time

    def timestamp(date):
        return time.mktime(date.timetuple())

else:

    def timestamp(date):
        return date.timestamp()


# We need a logging unit here
logger = logging.getLogger()
logger.setLevel(logging.WARNING)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.WARNING)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger.addHandler(handler)

streams = ["stdout", "stderr"]
methods = ["monitor", "poller"]

TEST_FILENAME = "README.md"
if os.name == "nt":
    ENCODING = "cp437"
    PING_CMD = "ping 127.0.0.1 -n 4"
    PING_CMD_10S = "ping 127.0.0.1 -n 10"
    PING_CMD_REDIR = PING_CMD + " 1>&2"
    # Make sure we run the failure command first so end result is okay
    PING_CMD_AND_FAILURE = "ping 0.0.0.0 -n 2 1>&2 & ping 127.0.0.1 -n 2"
    PING_FAILURE = "ping 0.0.0.0 -n 2 1>&2"

    PRINT_FILE_CMD = "type {}".format(TEST_FILENAME)
    # On widows, we cannot print binary files to console, type would transliterate it into text
    # This is a dummy test on windows
    PRINT_BINARY_FILE_CMD = "type C:\\Windows\\System32\\cmd.exe"
else:
    ENCODING = "utf-8"
    PING_CMD = ["ping", "-c", "4", "127.0.0.1"]
    PING_CMD_10S = ["ping", "-c", "10", "127.0.0.1"]
    PING_CMD_REDIR = "ping -c 4 127.0.0.1 1>&2"
    PING_CMD_AND_FAILURE = "ping -c 2 0.0.0.0 1>&2; ping -c 2 127.0.0.1"
    PRINT_FILE_CMD = "cat {}".format(TEST_FILENAME)
    PRINT_BINARY_FILE_CMD = "cat /bin/sh"
    PING_FAILURE = "ping -c 2 0.0.0.0 1>&2"


ELAPSED_TIME = timestamp(datetime.now())
PROCESS_ID = None
STREAM_OUTPUT = ""
PROC = None
ON_EXIT_CALLED = False


def reset_elapsed_time():
    global ELAPSED_TIME
    ELAPSED_TIME = timestamp(datetime.now())


def get_elapsed_time():
    return timestamp(datetime.now()) - ELAPSED_TIME


def running_on_github_actions():
    """
    This is set in github actions workflow with
          env:
        RUNNING_ON_GITHUB_ACTIONS: true
    """
    return os.environ.get("RUNNING_ON_GITHUB_ACTIONS") == "true"  # bash 'true'


def is_pypy():
    """
    Checks interpreter
    """
    return True if platform.python_implementation().lower() == "pypy" else False


def is_macos():
    """
    Checks if under Mac OS
    """
    return platform.system().lower() == "darwin"


def test_standard_ping_with_encoding():
    """
    Test command_runner with a standard ping and encoding parameter
    """
    for method in methods:
        print("method={}".format(method))
        exit_code, output = command_runner(PING_CMD, encoding=ENCODING, method=method)
        print(output)
        assert (
            exit_code == 0
        ), "Exit code should be 0 for ping command with method {}".format(method)


def test_standard_ping_with_default_encoding():
    """
    Without encoding, iter(stream.readline, '') will hang since the expected sentinel char would be b'':
    This could only happen on python <3.6 since command_runner decides to use an encoding anyway
    """
    for method in methods:
        exit_code, output = command_runner(PING_CMD, encoding=None, method=method)
        print(output)
        assert (
            exit_code == 0
        ), "Exit code should be 0 for ping command with method {}".format(method)


def test_standard_ping_with_encoding_disabled():
    """
    Without encoding disabled, we should have binary output
    """
    for method in methods:
        exit_code, output = command_runner(PING_CMD, encoding=False, method=method)
        print(output)
        assert (
            exit_code == 0
        ), "Exit code should be 0 for ping command with method {}".format(method)
        assert isinstance(output, bytes), "Output should be binary."


def test_direct_binary_output_to_stdout():
    """
    Without encoding disabled, we should have binary output
    """
    for method in methods:
        exit_code, output = command_runner(PRINT_BINARY_FILE_CMD, encoding=False, shell=True, method=method)
        print(output)
        assert (
            exit_code == 0
        ), "Exit code should be 0 for ping command with method {}".format(method)
        assert isinstance(output, bytes), "Output should be binary."

def test_timeout():
    """
    Test command_runner with a timeout
    """
    for method in methods:
        begin_time = datetime.now()
        exit_code, output = command_runner(PING_CMD, timeout=1, method=method)
        print(output)
        end_time = datetime.now()
        assert (
            end_time - begin_time
        ).total_seconds() < 2, "It took more than 2 seconds for a timeout=1 command to finish with method {}".format(
            method
        )
        assert (
            exit_code == -254
        ), "Exit code should be -254 on timeout with method {}".format(method)
        assert "Timeout" in output, "Output should have timeout with method {}".format(
            method
        )


def test_timeout_with_subtree_killing():
    """
    Launch a subtree of long commands and see if timeout actually kills them in time
    """
    if os.name != "nt":
        cmd = 'echo "test" && sleep 5 && echo "done"'
    else:
        cmd = "echo test && {} && echo done".format(PING_CMD)

    for method in methods:
        begin_time = datetime.now()
        exit_code, output = command_runner(cmd, shell=True, timeout=1, method=method)
        print(output)
        end_time = datetime.now()
        elapsed_time = (end_time - begin_time).total_seconds()
        assert (
            elapsed_time < 4
        ), "It took more than 2 seconds for a timeout=1 command to finish with method {}".format(
            method
        )
        assert (
            exit_code == -254
        ), "Exit code should be -254 on timeout with method {}".format(method)
        assert "Timeout" in output, "Output should have timeout with method {}".format(
            method
        )


def test_no_timeout():
    """
    Test with setting timeout=None
    """
    for method in methods:
        exit_code, output = command_runner(PING_CMD, timeout=None, method=method)
        print(output)
        assert (
            exit_code == 0
        ), "Without timeout, command should have run with method {}".format(method)


def test_live_output():
    """
    Test command_runner with live output to stdout
    """
    for method in methods:
        exit_code, _ = command_runner(
            PING_CMD, stdout=PIPE, encoding=ENCODING, method=method
        )
        assert (
            exit_code == 0
        ), "Exit code should be 0 for ping command with method {}".format(method)


def test_not_found():
    """
    Test command_runner with an unexisting command
    """
    for method in methods:
        print("The following command should fail with method {}".format(method))
        exit_code, output = command_runner("unknown_command_nowhere_to_be_found_1234")
        assert (
            exit_code == -253
        ), "Unknown command should trigger a -253 exit code with method {}".format(
            method
        )
        assert "failed" in output, "Error code -253 should be Command x failed, reason"


def test_file_output():
    """
    Test command_runner with file output instead of stdout
    """
    for method in methods:
        stdout_filename = "temp.test"
        stderr_filename = "temp.test.err"
        print("The following command should timeout")
        exit_code, output = command_runner(
            PING_CMD,
            timeout=1,
            stdout=stdout_filename,
            stderr=stderr_filename,
            method=method,
        )
        assert os.path.isfile(
            stdout_filename
        ), "Log file does not exist with method {}".format(method)

        # We don't have encoding argument in Python 2, yet we need it for PyPy
        if sys.version_info[0] < 3:
            with open(stdout_filename, "r") as file_handle:
                output = file_handle.read()
        else:
            with open(stdout_filename, "r", encoding=ENCODING) as file_handle:
                output = file_handle.read()

        assert os.path.isfile(
            stderr_filename
        ), "stderr log file does not exist with method {}".format(method)
        assert (
            exit_code == -254
        ), "Exit code should be -254 for timeouts with method {}".format(method)
        assert "Timeout" in output, "Output should have timeout with method {}".format(
            method
        )

        # arbitrary time to make sure file handle was closed
        sleep(3)
        os.remove(stdout_filename)
        os.remove(stderr_filename)


def test_valid_exit_codes():
    """
    Test command_runner with a failed ping but that should not trigger an error

    # WIP We could improve tests here by capturing logs
    """
    valid_exit_codes = [0, 1, 2]
    if is_macos():
        valid_exit_codes.append(68)  # ping non-existent exits with such on Mac
    for method in methods:

        exit_code, _ = command_runner(
            "ping nonexistent_host",
            shell=True,
            valid_exit_codes=valid_exit_codes,
            method=method,
        )
        assert (
            exit_code in valid_exit_codes
        ), "Exit code not in valid list with method {}".format(method)

        exit_code, _ = command_runner(
            "ping nonexistent_host", shell=True, valid_exit_codes=True, method=method
        )
        assert exit_code != 0, "Exit code should not be equal to 0"

        exit_code, _ = command_runner(
            "ping nonexistent_host", shell=True, valid_exit_codes=False, method=method
        )
        assert exit_code != 0, "Exit code should not be equal to 0"

        exit_code, _ = command_runner(
            "ping nonexistent_host", shell=True, valid_exit_codes=None, method=method
        )
        assert exit_code != 0, "Exit code should not be equal to 0"


def test_unix_only_split_command():
    """
    This test is specifically written when command_runner receives a str command instead of a list on unix
    """
    if os.name == "posix":
        for method in methods:
            exit_code, _ = command_runner(" ".join(PING_CMD), method=method)
            assert (
                exit_code == 0
            ), "Non split command should not trigger an error with method {}".format(
                method
            )


def test_create_no_window():
    """
    Only used on windows, when we don't want to create a cmd visible windows
    """
    for method in methods:
        exit_code, _ = command_runner(PING_CMD, windows_no_window=True, method=method)
        assert exit_code == 0, "Should have worked too with method {}".format(method)


def test_read_file():
    """
    Read a couple of times the same file to be sure we don't get garbage from _read_pipe()
    This is a random failure detection test
    """

    # We don't have encoding argument in Python 2, yet we need it for PyPy
    if sys.version_info[0] < 3:
        with open(TEST_FILENAME, "r") as file:
            file_content = file.read()
    else:
        with open(TEST_FILENAME, "r", encoding=ENCODING) as file:
            file_content = file.read()
    for method in methods:
        # pypy is quite slow with poller method on github actions.
        # Lets lower rounds
        max_rounds = 100 if is_pypy() else 1000
        print("\nSetting up test_read_file for {} rounds".format(max_rounds))
        for round in range(0, max_rounds):
            print("Comparison round {} with method {}".format(round, method))
            exit_code, output = command_runner(
                PRINT_FILE_CMD, shell=True, method=method
            )
            if os.name == "nt":
                output = output.replace("\r\n", "\n")

            assert (
                exit_code == 0
            ), "Did not succeed to read {}, method={}, exit_code: {}, output: {}".format(
                TEST_FILENAME, method, exit_code, output
            )
            assert (
                file_content == output
            ), "Round {} File content and output are not identical, method={}".format(
                round, method
            )


def test_stop_on_argument():
    expected_output_regex = "Command .* was stopped because stop_on function returned True. Original output was:"

    def stop_on():
        """
        Simple function that returns True two seconds after reset_elapsed_time() has been called
        """
        if get_elapsed_time() > 2:
            return True

    for method in methods:
        reset_elapsed_time()
        print("method={}".format(method))
        exit_code, output = command_runner(PING_CMD, stop_on=stop_on, method=method)

        # On github actions only with Python 2.7.18, we sometimes get -251 failed because of OS: [Error 5] Access is denied
        # when os.kill(pid) is called in kill_childs_mod
        # On my windows platform using the same Python version, it works...
        # well nothing I can debug on github actions
        if running_on_github_actions() and os.name == "nt" and sys.version_info[0] < 3:
            assert exit_code in [
                -253,
                -251,
            ], "Not as expected, we should get a permission error on github actions windows platform"
        else:
            assert (
                exit_code == -251
            ), "Monitor mode should have been stopped by stop_on with exit_code -251. method={}, exit_code: {}, output: {}".format(
                method, exit_code, output
            )
            assert (
                re.match(expected_output_regex, output, re.MULTILINE) is not None
            ), "stop_on output is bogus. method={}, exit_code: {}, output: {}".format(
                method, exit_code, output
            )


def test_process_callback():
    def callback(process_id):
        global PROCESS_ID
        PROCESS_ID = process_id

    for method in methods:
        exit_code, output = command_runner(
            PING_CMD, method=method, process_callback=callback
        )
        assert (
            exit_code == 0
        ), "Wrong exit code. method={}, exit_code: {}, output: {}".format(
            method, exit_code, output
        )
        assert isinstance(
            PROCESS_ID, subprocess.Popen
        ), 'callback did not work properly. PROCESS_ID="{}"'.format(PROCESS_ID)


def test_stream_callback():
    global STREAM_OUTPUT

    def stream_callback(string):
        global STREAM_OUTPUT
        STREAM_OUTPUT += string
        print("CALLBACK: ", string)

    for stream in streams:
        stream_args = {stream: stream_callback}
        for method in methods:
            STREAM_OUTPUT = ""
            try:
                print("Method={}, stream={}, output=callback".format(method, stream))
                exit_code, output = command_runner(
                    PING_CMD_REDIR, shell=True, method=method, **stream_args
                )
            except ValueError:
                if method == "poller":
                    assert False, "ValueError should not be produced in poller mode."
            if method == "poller":
                assert (
                    exit_code == 0
                ), "Wrong exit code. method={}, exit_code: {}, output: {}".format(
                    method, exit_code, output
                )

                # Since we redirect STDOUT to STDERR
                assert (
                    STREAM_OUTPUT == output
                ), "Callback stream should contain same result as output"
            else:
                assert (
                    exit_code == -250
                ), "stream_callback exit_code is bogus. method={}, exit_code: {}, output: {}".format(
                    method, exit_code, output
                )


def test_queue_output():
    """
    Thread command runner and get it's output queue
    """

    if sys.version_info[0] < 3:
        print("Queue test uses concurrent futures. Won't run on python 2.7, sorry.")
        return

    # pypy is quite slow with poller method on github actions.
    # Lets lower rounds
    max_rounds = 100 if is_pypy() else 1000
    print("\nSetting up test_read_file for {} rounds".format(max_rounds))
    for i in range(0, max_rounds):
        for stream in streams:
            for method in methods:
                if method == "monitor" and i > 1:
                    # Dont bother to repeat the test for monitor mode more than once
                    continue
                output_queue = queue.Queue()
                stream_output = ""
                stream_args = {stream: output_queue}
                print(
                    "Round={}, Method={}, stream={}, output=queue".format(
                        i, method, stream
                    )
                )
                thread_result = command_runner_threaded(
                    PRINT_FILE_CMD, shell=True, method=method, **stream_args
                )

                read_queue = True
                while read_queue:
                    try:
                        line = output_queue.get(timeout=0.1)
                    except queue.Empty:
                        pass
                    else:
                        if line is None:
                            break
                        else:
                            stream_output += line

                exit_code, output = thread_result.result()

                if method == "poller":
                    assert (
                        exit_code == 0
                    ), "Wrong exit code. method={}, exit_code: {}, output: {}".format(
                        method, exit_code, output
                    )
                    # Since we redirect STDOUT to STDERR
                    if stream == "stdout":
                        assert (
                            stream_output == output
                        ), "stdout queue output should contain same result as output"
                    if stream == "stderr":
                        assert (
                            len(stream_output) == 0
                        ), "stderr queue output should be empty"
                else:
                    assert (
                        exit_code == -250
                    ), "stream_queue exit_code is bogus. method={}, exit_code: {}, output: {}".format(
                        method, exit_code, output
                    )


def test_queue_non_threaded_command_runner():
    """
    Test case for Python 2.7 without proper threading return values
    """

    def read_queue(output_queue, stream_output):
        """
        Read the queue as thread
        Our problem here is that the thread can live forever if we don't check a global value, which is...well ugly
        """
        read_queue = True
        while read_queue:
            try:
                line = output_queue.get(timeout=1)
            except queue.Empty:
                pass
            else:
                # The queue reading can be stopped once 'None' is received.
                if line is None:
                    read_queue = False
                else:
                    stream_output["value"] += line
                    # ADD YOUR LIVE CODE HERE
        return stream_output

    for i in range(0, 20):
        for cmd in [PING_CMD, PRINT_FILE_CMD]:
            if cmd == PRINT_FILE_CMD:
                shell_args = {"shell": True}
            else:
                shell_args = {"shell": False}
            # Create a new queue that command_runner will fill up
            output_queue = queue.Queue()
            stream_output = {"value": ""}
            # Create a thread of read_queue() in order to read the queue while command_runner executes the command
            read_thread = threading.Thread(
                target=read_queue, args=(output_queue, stream_output)
            )
            read_thread.daemon = True  # thread dies with the program
            read_thread.start()

            # Launch command_runner
            print("Round={}, cmd={}".format(i, cmd))
            exit_code, output = command_runner(
                cmd, stdout=output_queue, method="poller", **shell_args
            )
            assert (
                exit_code == 0
            ), "PING_CMD Exit code is not okay. exit_code={}, output={}".format(
                exit_code, output
            )

            # Wait until we are sure that we emptied the queue
            while not output_queue.empty():
                sleep(0.1)

            assert stream_output["value"] == output, "Output should be identical"


def test_double_queue_threaded_stop():
    """
    Use both stdout and stderr queues and make them stop
    """

    if sys.version_info[0] < 3:
        print("Queue test uses concurrent futures. Won't run on python 2.7, sorry.")
        return

    stdout_queue = queue.Queue()
    stderr_queue = queue.Queue()
    thread_result = command_runner_threaded(
        PING_CMD_AND_FAILURE,
        method="poller",
        shell=True,
        stdout=stdout_queue,
        stderr=stderr_queue,
    )

    print("Begin to read queues")
    read_stdout = read_stderr = True
    while read_stdout or read_stderr:
        try:
            stdout_line = stdout_queue.get(timeout=0.1)
        except queue.Empty:
            pass
        else:
            if stdout_line is None:
                read_stdout = False
                print("stdout is finished")
            else:
                print("STDOUT:", stdout_line)

        try:
            stderr_line = stderr_queue.get(timeout=0.1)
        except queue.Empty:
            pass
        else:
            if stderr_line is None:
                read_stderr = False
                print("stderr is finished")
            else:
                print("STDERR:", stderr_line)

    while True:
        done = thread_result.done()
        print("Thread is done:", done)
        if done:
            break
        sleep(1)

    exit_code, _ = thread_result.result()
    assert exit_code == 0, "We did not succeed in running the thread"


def test_deferred_command():
    """
    Using deferred_command in order to run a command after a given timespan
    """
    test_filename = "deferred_test_file"
    if os.path.isfile(test_filename):
        os.remove(test_filename)
    deferred_command("echo test > {}".format(test_filename), defer_time=5)
    assert os.path.isfile(test_filename) is False, "File should not exist yet"
    sleep(6)
    assert os.path.isfile(test_filename) is True, "File should exist now"
    os.remove(test_filename)


def test_powershell_output():
    # Don't bother to test powershell on other platforms than windows
    if os.name != "nt":
        return
    """
    Parts from windows_tools.powershell are used here
    """

    powershell_interpreter = None
    # Try to guess powershell path if no valid path given
    interpreter_executable = "powershell.exe"
    for syspath in ["sysnative", "system32"]:
        try:
            # Let's try native powershell (64 bit) first or else
            # Import-Module may fail when running 32 bit powershell on 64 bit arch
            best_guess = os.path.join(
                os.environ.get("SYSTEMROOT", "C:"),
                syspath,
                "WindowsPowerShell",
                "v1.0",
                interpreter_executable,
            )
            if os.path.isfile(best_guess):
                powershell_interpreter = best_guess
                break
        except KeyError:
            pass
    if powershell_interpreter is None:
        try:
            ps_paths = os.path.dirname(os.environ["PSModulePath"]).split(";")
            for ps_path in ps_paths:
                if ps_path.endswith("Modules"):
                    ps_path = ps_path.strip("Modules")
                possible_ps_path = os.path.join(ps_path, interpreter_executable)
                if os.path.isfile(possible_ps_path):
                    powershell_interpreter = possible_ps_path
                    break
        except KeyError:
            pass

    if powershell_interpreter is None:
        raise OSError("Could not find any valid powershell interpreter")

    # Do not add -NoProfile so we don't end up in a path we're not supposed to
    command = powershell_interpreter + " -NonInteractive -NoLogo %s" % PING_CMD
    exit_code, output = command_runner(command, encoding="unicode_escape")
    print("powershell: ", exit_code, output)
    assert exit_code == 0, "Powershell execution failed."


def test_null_redir():
    for method in methods:
        print("method={}".format(method))
        exit_code, output = command_runner(PING_CMD, stdout=False)
        print(exit_code)
        print("OUTPUT:", output)
        assert output is None, "We should not have any output here"

        exit_code, output = command_runner(
            PING_CMD_AND_FAILURE, shell=True, stderr=False
        )
        print(exit_code)
        print("OUTPUT:", output)
        assert "0.0.0.0" not in output, "We should not get error output from here"

    for method in methods:
        print("method={}".format(method))
        exit_code, stdout, stderr = command_runner(
            PING_CMD, split_streams=True, stdout=False, stderr=False
        )
        print(exit_code)
        print("STDOUT:", stdout)
        print("STDERR:", stderr)
        assert stdout is None, "We should not have any output from stdout"
        assert stderr is None, "We should not have any output from stderr"

        exit_code, stdout, stderr = command_runner(
            PING_CMD_AND_FAILURE,
            shell=True,
            split_streams=True,
            stdout=False,
            stderr=False,
        )
        print(exit_code)
        print("STDOUT:", stdout)
        print("STDERR:", stderr)
        assert stdout is None, "We should not have any output from stdout"
        assert stderr is None, "We should not have any output from stderr"


def test_split_streams():
    """
    Test replacing output with stdout and stderr output
    """
    for cmd in [PING_CMD, PING_CMD_AND_FAILURE]:
        for method in methods:
            print("cmd={}, method={}".format(cmd, method))

            try:
                exit_code, _ = command_runner(
                    cmd, method=method, shell=True, split_streams=True
                )
            except ValueError:
                # Should generate a valueError
                pass
            except Exception as exc:
                assert (
                    False
                ), "We should have too many values to unpack here: {}".format(exc)

            exit_code, stdout, stderr = command_runner(
                cmd, method=method, shell=True, split_streams=True
            )
            print("exit_code:", exit_code)
            print("STDOUT:", stdout)
            print("STDERR:", stderr)
            if cmd == PING_CMD:
                assert (
                    exit_code == 0
                ), "Exit code should be 0 for ping command with method {}".format(
                    method
                )
                assert "127.0.0.1" in stdout
                assert stderr is None
            if cmd == PING_CMD_AND_FAILURE:
                assert (
                    exit_code == 0
                ), "Exit code should be 0 for ping command with method {}".format(
                    method
                )
                assert "127.0.0.1" in stdout
                assert "0.0.0.0" in stderr


def test_on_exit():
    def on_exit():
        global ON_EXIT_CALLED
        ON_EXIT_CALLED = True

    exit_code, _ = command_runner(PING_CMD, on_exit=on_exit)
    assert exit_code == 0, "Exit code is not null"
    assert ON_EXIT_CALLED is True, "On exit was never called"


def test_no_close_queues():
    """
    Test no_close_queues
    """

    if sys.version_info[0] < 3:
        print("Queue test uses concurrent futures. Won't run on python 2.7, sorry.")
        return

    stdout_queue = queue.Queue()
    stderr_queue = queue.Queue()
    thread_result = command_runner_threaded(
        PING_CMD_AND_FAILURE,
        method="poller",
        shell=True,
        stdout=stdout_queue,
        stderr=stderr_queue,
        no_close_queues=True,
    )

    print("Begin to read queues")
    read_stdout = read_stderr = True
    wait_period = 50  # let's have 100 rounds of 2x timeout 0.1s = 10 seconds, which should be enough for exec to terminate
    while read_stdout or read_stderr:
        try:
            stdout_line = stdout_queue.get(timeout=0.1)
        except queue.Empty:
            pass
        else:
            if stdout_line is None:
                assert False, "STDOUT queue has been closed with no_close_queues"
            else:
                print("STDOUT:", stdout_line)

        try:
            stderr_line = stderr_queue.get(timeout=0.1)
        except queue.Empty:
            pass
        else:
            if stderr_line is None:
                assert False, "STDOUT queue has been closed with no_close_queues"
            else:
                print("STDERR:", stderr_line)
        wait_period -= 1
        if wait_period < 1:
            break

    while True:
        done = thread_result.done()
        print("Thread is done:", done)
        if done:
            break
        sleep(1)

    exit_code, _ = thread_result.result()
    assert exit_code == 0, "We did not succeed in running the thread"


def test_low_priority():
    def check_low_priority(process):
        niceness = psutil.Process(process.pid).nice()
        io_niceness = psutil.Process(process.pid).ionice()
        if os.name == "nt":
            assert niceness == 16384, "Process low prio niceness not properly set: {}".format(
                niceness
            )
            assert io_niceness == 1, "Process low prio io niceness not set properly: {}".format(
                io_niceness
            )
        else:
            assert niceness == 15, "Process low prio niceness not properly set: {}".format(
                niceness
            )
            assert io_niceness == 3, "Process low prio io niceness not set properly: {}".format(
                io_niceness
            )
        print("Nice !")

    def command_runner_thread():
        return command_runner_threaded(
            PING_CMD,
            priority="low",
            io_priority="low",
            process_callback=check_low_priority,
        )

    thread = threading.Thread(target=command_runner_thread, args=())
    thread.daemon = True  # thread dies with the program
    thread.start()


def test_high_priority():
    def check_high_priority(process):
        niceness = psutil.Process(process.pid).nice()
        io_niceness = psutil.Process(process.pid).ionice()
        if os.name == "nt":
            assert niceness == 128, "Process high prio niceness not properly set: {}".format(
                niceness
            )
            # So se actually don't test this here, since high prio cannot be set on Windows unless
            # we have NtSetInformationProcess privilege
            # assert io_niceness == 3, "Process high prio io niceness not set properly: {}".format(
            #    io_niceness
            # )
        else:
            assert niceness == -15, "Process high prio niceness not properly set: {}".format(
                niceness
            )
            assert io_niceness == 1, "Process high prio io niceness not set properly: {}".format(
                io_niceness
            )
        print("Nice !")

    def command_runner_thread():
        return command_runner_threaded(
            PING_CMD,
            priority="high",
            # io_priority="high",
            process_callback=check_high_priority,
        )

    thread = threading.Thread(target=command_runner_thread, args=())
    thread.daemon = True  # thread dies with the program
    thread.start()


def test_heartbeat():
    # Log capture class, blatantly copied from https://stackoverflow.com/a/37967421/2635443
    class TailLogHandler(logging.Handler):

        def __init__(self, log_queue):
            logging.Handler.__init__(self)
            self.log_queue = log_queue

        def emit(self, record):
            self.log_queue.append(self.format(record))


    class TailLogger(object):

        def __init__(self, maxlen):
            self._log_queue = collections.deque(maxlen=maxlen)
            self._log_handler = TailLogHandler(self._log_queue)

        def contents(self):
            return "\n".join(self._log_queue)

        @property
        def log_handler(self):
            return self._log_handler

    tail = TailLogger(10)

    formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    )

    log_handler = tail.log_handler
    log_handler.setFormatter(formatter)
    logger.addHandler(log_handler)  # Add the handler to the logger
    logger.setLevel(logging.INFO)

    exit_code, output = command_runner(
        PING_CMD_10S, heartbeat=2, shell=False
    )
    log_contents = tail.contents()
    print("LOGS:\n", log_contents)
    print("END LOGS")
    print("COMMAND_OUTPUT:\n", output)
    assert exit_code == 0, "Exit code should be 0 for ping command with heartbeat"
    # We should have a modulo 2 heeatbeat
    assert (
        "Still running command after 4 seconds" in log_contents
    ), "Output should have heartbeat"


if __name__ == "__main__":
    print("Example code for %s, %s" % (__intname__, __build__))

    test_standard_ping_with_encoding()
    test_standard_ping_with_default_encoding()
    test_standard_ping_with_encoding_disabled()
    test_timeout()
    test_timeout_with_subtree_killing()
    test_no_timeout()
    test_live_output()
    test_not_found()
    test_file_output()
    test_valid_exit_codes()
    test_unix_only_split_command()
    test_create_no_window()
    test_read_file()
    test_stop_on_argument()
    test_process_callback()
    test_stream_callback()
    test_queue_output()
    test_queue_non_threaded_command_runner()
    test_double_queue_threaded_stop()
    test_deferred_command()
    test_powershell_output()
    test_null_redir()
    test_split_streams()
    test_on_exit()
    test_no_close_queues()
    test_low_priority()
    test_high_priority()
    test_heartbeat()