# Path: test/cfg.py
# class ApiType(Enum):
#     JENKINS = 0
#     SCRIPT = 1
#     MOCK = 2
# 
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
#         username=None, password=None):
# 
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
#     """Assert that `*expected_lines` occur in order in the lines of `text`.
# 
#     Args:
#         *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
#             If `expected_line` has a match method it is called and must return True for a line in `text`.
#             Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
#             Otherwise `expected line` must simply occur in a line in `text`
#     """
# 
#     assert isinstance(api_type, test_cfg.ApiType)
#     assert text
#     assert expected_lines
# 
#     return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
# 
# def kill_current_msg(api, job_name, num):
#     return "Killing build: " + repr(job_name) + " - " + console_url(api, job_name, num)
# 
# Path: test/framework/killer.py
# def kill(api, sleep_time, num_kills):
#     """Kill this process"""
#     pid = os.getpid()
#     ff = __file__.replace('.pyc', '.py')
#     log_file_name = api.func_name.replace('test_', '')
#     args = [sys.executable, ff, repr(pid), repr(sleep_time), repr(num_kills), log_file_name]
#     with open(log_file_name, 'w') as log_file:
#         logt(log_file, "Invoking kill subprocess.", args)
# 
#     subprocess.Popen(args)


import os, re
import pytest
from pytest import raises, xfail
from jenkinsflow.flow import serial, FailedChildJobException, FinalResultException, BuildResult
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in, kill_current_msg
from .framework.killer import kill
        # Set a long sleep here, when heaviliy loaded it can take time for the flow to get started
        kill(api, 35, 1)

        # TODO: shouldn't we expect a FailedChildJobsException here?
        with raises(FinalResultException) as exinfo:
            with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=0.05) as ctrl1:
                with ctrl1.parallel() as ctrl2:
                    ctrl2.invoke('j1')
                    with ctrl2.serial() as ctrl3:
                        ctrl3.invoke('j2')
                        ctrl3.invoke('j3')
                    ctrl2.invoke('j4')
                    ctrl2.invoke_unchecked('j5')
                    for ii in range(0, num_j6_invocations):
                         # Queue a lot of jobs
                        ctrl2.invoke('j6', a=ii)
                with ctrl1.parallel() as ctrl4:
                    ctrl4.invoke('j7')

        assert exinfo.value.result == BuildResult.FAILURE  # TODO? Note that ABORTED on child job propagates as FAILURE to the flow

        if not capsys:
            return

        sout, _ = capsys.readouterr()
        assert lines_in(
            api_type, sout,
            "^Got SIGTERM: Killing all builds belonging to current flow",
            kill_current_msg(api, 'jenkinsflow_test__kill_current__j1', 1),
            kill_current_msg(api, 'jenkinsflow_test__kill_current__j3', 1),

# Path: test/cfg.py
# class ApiType(Enum):
#     JENKINS = 0
#     SCRIPT = 1
#     MOCK = 2
# 
# Path: test/framework/api_select.py
# def api(file_name, api_type, login=None, fixed_prefix=None, url_or_dir=None, fake_public_uri=None, invocation_class=None,
#         username=None, password=None):
# 
# Path: test/framework/utils.py
# def lines_in(api_type, text, *expected_lines):
#     """Assert that `*expected_lines` occur in order in the lines of `text`.
# 
#     Args:
#         *expected_lines (str or RegexObject (hasattr `match`)): For each `expected_line` in expected_lines:
#             If `expected_line` has a match method it is called and must return True for a line in `text`.
#             Otherwise, if the `expected_line` starts with '^', a line in `text` must start with `expected_line[1:]`
#             Otherwise `expected line` must simply occur in a line in `text`
#     """
# 
#     assert isinstance(api_type, test_cfg.ApiType)
#     assert text
#     assert expected_lines
# 
#     return generic_lines_in(text, partial(replace_host_port, api_type), *expected_lines)
# 
# def kill_current_msg(api, job_name, num):
#     return "Killing build: " + repr(job_name) + " - " + console_url(api, job_name, num)
# 
# Path: test/framework/killer.py
# def kill(api, sleep_time, num_kills):
#     """Kill this process"""
#     pid = os.getpid()
#     ff = __file__.replace('.pyc', '.py')
#     log_file_name = api.func_name.replace('test_', '')
#     args = [sys.executable, ff, repr(pid), repr(sleep_time), repr(num_kills), log_file_name]
#     with open(log_file_name, 'w') as log_file:
#         logt(log_file, "Invoking kill subprocess.", args)
# 
#     subprocess.Popen(args)


# Path: test/kill_test.py
import os, re
import pytest
from pytest import raises, xfail
from jenkinsflow.flow import serial, FailedChildJobException, FinalResultException, BuildResult
from .cfg import ApiType
from .framework import api_select
from .framework.utils import lines_in, kill_current_msg
from .framework.killer import kill

        # Set a long sleep here, when heaviliy loaded it can take time for the flow to get started
        kill(api, 35, 1)

        # TODO: shouldn't we expect a FailedChildJobsException here?
        with raises(FinalResultException) as exinfo:
            with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=0.05) as ctrl1:
                with ctrl1.parallel() as ctrl2:
                    ctrl2.invoke('j1')
                    with ctrl2.serial() as ctrl3:
                        ctrl3.invoke('j2')
                        ctrl3.invoke('j3')
                    ctrl2.invoke('j4')
                    ctrl2.invoke_unchecked('j5')
                    for ii in range(0, num_j6_invocations):
                         # Queue a lot of jobs
                        ctrl2.invoke('j6', a=ii)
                with ctrl1.parallel() as ctrl4:
                    ctrl4.invoke('j7')

        assert exinfo.value.result == BuildResult.FAILURE  # TODO? Note that ABORTED on child job propagates as FAILURE to the flow

        if not capsys:
            return

        sout, _ = capsys.readouterr()
        assert lines_in(
            api_type, sout,
            "^Got SIGTERM: Killing all builds belonging to current flow",
            kill_current_msg(api, 'jenkinsflow_test__kill_current__j1', 1),
            kill_current_msg(api, 'jenkinsflow_test__kill_current__j3', 1),

            kill_current_msg(api, 'jenkinsflow_test__kill_current__j5', 1),