def test_windows_ask(monkeypatch):
    if os.name == "nt":
        import msvcrt

        class MockMsvcrt(object):
            def __init__(self, outcome=True):
                self.run = outcome
                self.output_chars = ["y", "e", "s", "\r"] if outcome else ["n", "o", "\r"]
                self.output = self._output()

            @staticmethod
            def kbhit():
                return True

            def _output(self):
                for _chr in self.output_chars:
                    yield _chr.encode()

            def getche(self):
                return next(self.output)

        mock_msvcrt = MockMsvcrt(outcome=True)
        monkeypatch.setattr(msvcrt, "getche", mock_msvcrt.getche)
        monkeypatch.setattr(msvcrt, "kbhit", mock_msvcrt.kbhit)
        assert br.ask("test")

        mock_msvcrt = MockMsvcrt(outcome=False)
        monkeypatch.setattr(msvcrt, "getche", mock_msvcrt.getche)
        monkeypatch.setattr(msvcrt, "kbhit", mock_msvcrt.kbhit)
        assert not br.ask("test")

        # Timeout possitive
        monkeypatch.setattr(msvcrt, "kbhit", lambda *_: False)
        assert br.ask("test", timeout=1)
        assert not br.ask("test", timeout=1, default="no")
Exemple #2
0
def uninstall():
    if br.ask("Are you sure you want to completely remove BuddySuite from your system y/[n]? ", default="no"):
        # Need to run os.path.split() twice to get to the actual install dir
        install_dir, toss = os.path.split(buddysuite.__file__)
        install_dir, toss = os.path.split(install_dir)
        # Delete all custom shortcuts
        config = br.config_values()
        for shortcut in config["shortcuts"]:
            try:
                os.remove(shortcut)
            except FileNotFoundError:
                pass

        # Delete all gateway programs
        for buddy in ['seqbuddy', 'alignbuddy', 'phylobuddy', 'databasebuddy', 'buddysuite']:
            try:
                os.remove(shutil.which(buddy))
            except FileNotFoundError:
                pass

        # Delete the main site-packages module
        try:
            shutil.rmtree(install_dir)
        except FileNotFoundError:
            pass
    return
Exemple #3
0
def test_ask_unix(monkeypatch):
    if os.name != "nt":

        def wait(*args, **kwargs):
            print(args, kwargs)
            sleep(2)
            return 'yes'

        monkeypatch.setattr(builtins, "input", wait)
        assert not br.ask("test", timeout=1)

        fake_input = mock.Mock(return_value="yes")
        monkeypatch.setattr(builtins, "input", fake_input)
        assert br.ask("test")

        fake_input = mock.Mock(return_value="no")
        monkeypatch.setattr(builtins, "input", fake_input)
        assert not br.ask("test")

        fake_input = mock.Mock(return_value="abort")
        monkeypatch.setattr(builtins, "input", fake_input)
        assert not br.ask("test")

        fake_input = mock.Mock(side_effect=["dkjsfaksd", "fsdjgdfgdf", "no"])
        monkeypatch.setattr(builtins, "input", fake_input)
        assert not br.ask("test", timeout=1)

        fake_input = mock.Mock(return_value="")
        monkeypatch.setattr(builtins, "input", fake_input)
        assert br.ask("test", default="yes")

        fake_input = mock.Mock(return_value="")
        monkeypatch.setattr(builtins, "input", fake_input)
        assert not br.ask("test", default="no")
Exemple #4
0
def setup():  # ToDo: Check permissions?
    print("\033[1mWelcome to BuddySuite!\033[m\nLet's configure your installation:\n")

    install_dir, toss = os.path.split(buddysuite.__file__)
    os.makedirs("%s/buddy_data" % install_dir, exist_ok=True)
    if not os.path.isfile("%s/buddy_data/config.ini" % install_dir):
        open("%s/buddy_data/config.ini" % install_dir, "w").close()

    if not os.path.isfile("%s/buddy_data/cmd_history" % install_dir):
        open("%s/buddy_data/cmd_history" % install_dir, "w").close()

    if not os.path.isfile("%s/buddy_data/buddysuite_usage.json" % install_dir):
        with open("%s/buddy_data/buddysuite_usage.json" % install_dir, "w") as ofile:
            ofile.write("{}")

    config = ConfigParser()
    config.read("%s/buddy_data/config.ini" % install_dir)
    options = {"email": None,
               "diagnostics": None,
               "user_hash": None,
               "shortcuts": None}

    for key in options:
        try:
            if key in ['diagnostics']:
                options[key] = config.getboolean('DEFAULT', key)
            else:
                options[key] = config.get('DEFAULT', key)
        except NoOptionError:
            pass

    # Set Email
    print("\033[1mProviding a valid email address is recommended if accessing public databases with "
          "BuddySuite.\nThe maintainers of those resources may attempt to contact you before "
          "blocking your IP if you are not adhering to their usage limitations.\033[m")

    if options['email'] in [None, "*****@*****.**"]:
        email = input("Email address (optional): ")
        email = email if re.search(r"[^@]+@[^@]+\.[^@]+", email) else "*****@*****.**"
    else:
        email = input("Update email address (currently '%s'): " % options['email'])
        email = email if re.search(r"[^@]+@[^@]+\.[^@]+", email) and email not in ['', options['email']] \
            else options['email']
    options['email'] = email

    # Set up software improvement
    print("\n\033[1mBuddySuite is able to automatically send anonymized usage statistics and crash reports to the "
          "developers as part of the software improvement program.\033[m")

    question = "join" if not options['diagnostics'] else "remain in"
    options['diagnostics'] = br.ask("Would you like to %s our Software Improvement Program? [y]/n: " % question)

    # Create user hash id   'dXruTa0qkW'
    if not options["user_hash"]:
        options['user_hash'] = "".join([random.choice(string.ascii_letters + string.digits) for _ in range(10)])

    # ToDo: set up aliases or links
    # Set up shortcuts
    # print("\n\033[1mAdding shortcuts to your system PATH can make it much quicker to call the BuddySuite tools\033[m")
    options['shortcuts'] = ""

    # Write config file
    config['DEFAULT'] = options
    with open("%s/buddy_data/config.ini" % install_dir, 'w') as config_file:
        config.write(config_file)

    print("""\

\033[1mSuccess! You're all set.\033[m
    Email address:     %s
    Send diagnostics:  %s

These choices can be changed at any time by re-running setup.
Enjoy the BuddySuite!
""" % (options['email'], options['diagnostics']))
    return