from multiprocessing import Pool

import psutil


def watchdog():
    """
    Run psutil in a background to check what can be seen during the conversion.
    """
    while True:
        for process in psutil.process_iter():
            try:
                # For some reason the psutil catches subscription-manager in process.name()
                # as 'subscription-ma', thus using 'subscription' to catch it
                if "subscription" in process.name():
                    return process.cmdline()
            # psutil might raise an exception when trying to reach an already exited process
            # continue the loop when this happens
            except psutil.NoSuchProcess:
                continue


def test_passing_password_to_submgr_obfuscated(convert2rhel):
    """
    Verify that the password is not being passed through the command line to the subscription manager.
    """
    username = "testname"
    password = "EXAMPLE&hTYGHKPvU7Ewd"
    with convert2rhel(f"-y -u {username} -p {password} --debug") as c2r:
        # Just to be sure, try to run through all three tries
        # of the registration process in case the race condition applies
        for subscription_try in range(2):
            c2r.expect("Registering the system using subscription-manager ...")
            # Run watchdog function using multiprocessing pool
            # as soon as Convert2RHEL tries to call subscription-manager
            with Pool(processes=1) as pool:
                watcher = pool.apply_async(watchdog, ())
                # Check for the password not being passed to the subscription-manager
                print(watcher.get())
                assert not [cmdline for cmdline in watcher.get() if password in cmdline]

    assert c2r.exitstatus == 2


def test_passing_activation_key_to_submgr_obfuscated(convert2rhel):
    """
    Verify that the activation key is not being passed through the command line to the subscription manager.
    """
    organization = "testorg"
    activation_key = "mfaop90a23f_2%"
    with convert2rhel(f"-y -k {activation_key} -o {organization} --debug") as c2r:
        # Just to be sure, try to run through all three tries
        # of the registration process in case the race condition applies
        for subscription_try in range(2):
            c2r.expect("Registering the system using subscription-manager ...")
            # Run watchdog function using multiprocessing pool
            # as soon as Convert2RHEL tries to call subscription-manager
            with Pool(processes=1) as pool:
                watcher = pool.apply_async(watchdog, ())
                # Check for the password not being passed to the subscription-manager
                print(watcher.get())
                assert not [cmdline for cmdline in watcher.get() if activation_key in cmdline]

    assert c2r.exitstatus == 2
