Пример #1
0
 def test_create(self):
     parser = configparser.ConfigParser()
     parser.read_string('''[section]
                        unit=seconds
                        value=13''')
     check = Periodic.create('name', parser['section'])
     assert check._delta == timedelta(seconds=13)
Пример #2
0
 def test_create_wrong_unit(self):
     parser = configparser.ConfigParser()
     parser.read_string('''[section]
                        unit=asdfasdf
                        value=13''')
     with pytest.raises(ConfigurationError):
         Periodic.create('name', parser['section'])
Пример #3
0
    def test_not_enabled(self, mocker) -> None:
        mock_class = mocker.patch("autosuspend.checks.activity.Mpd")
        mock_class.create.return_value = mocker.MagicMock(
            spec=autosuspend.Activity)

        parser = configparser.ConfigParser()
        parser.read_string("""
            [check.Foo]
            class = Mpd
            enabled = False
            """)

        assert not autosuspend.set_up_checks(
            parser,
            "check",
            "activity",
            autosuspend.Activity,  # type: ignore
        )

        with pytest.raises(autosuspend.ConfigurationError):
            autosuspend.set_up_checks(
                parser,
                "check",
                "activity",
                autosuspend.Activity,  # type: ignore
                error_none=True,
            )
Пример #4
0
    def test_not_enabled_continues_with_next(self, mocker) -> None:
        mock_mpd = mocker.patch("autosuspend.checks.activity.Mpd")
        mock_mpd.create.return_value = mocker.MagicMock(
            spec=autosuspend.Activity)
        mock_xidletime = mocker.patch("autosuspend.checks.activity.XIdleTime")
        mock_xidletime.create.return_value = mocker.MagicMock(
            spec=autosuspend.Activity)

        parser = configparser.ConfigParser()
        parser.read_string("""
            [check.Foo]
            class = Mpd
            enabled = False
            [check.Bar]
            class = XIdleTime
            enabled = True
            """)

        assert (len(
            autosuspend.set_up_checks(
                parser,
                "check",
                "activity",
                autosuspend.Activity,  # type: ignore
            )) == 1)
Пример #5
0
 def test_create_not_numeric(self):
     parser = configparser.ConfigParser()
     parser.read_string('''[section]
                        unit=seconds
                        value=asdfasd''')
     with pytest.raises(ConfigurationError):
         Periodic.create('name', parser['section'])
Пример #6
0
 def test_create(self):
     parser = configparser.ConfigParser()
     parser.read_string('''[section]
                        xpath=/valid
                        url=nourl
                        timeout=20''')
     check = XPath.create('name', parser['section'])
     assert check._xpath == '/valid'
Пример #7
0
 def test_create(self) -> None:
     parser = configparser.ConfigParser()
     parser.read_string(
         """[section]
                           path = /tmp/test"""
     )
     check = File.create("name", parser["section"])
     assert check._path == "/tmp/test"
Пример #8
0
 def test_create_float(self) -> None:
     parser = configparser.ConfigParser()
     parser.read_string(
         """
         [section]
         unit=seconds
         value=21312.12
         """
     )
     Periodic.create("name", parser["section"])
Пример #9
0
 def test_create_no_unit(self) -> None:
     parser = configparser.ConfigParser()
     parser.read_string(
         """
         [section]
         value=asdfasd
         """
     )
     with pytest.raises(ConfigurationError):
         Periodic.create("name", parser["section"])
Пример #10
0
def _extract_pathogen_repos(repo_contents):
    """Extracts Pathogen plugin repos from a GitHub dotfiles repository.

    This currently just extracts plugins if they are checked in as submodules,
    because it's easy to extract repo URLs from the .gitmodules file but
    difficult to determine the repo URL of a plugin that's just cloned in.

    Arguments:
        repo_contents: API response from GitHub of a directory or repo's
            contents.

    Returns:
        A list of tuples (owner, repo_name) referencing GitHub repos.
    """
    gitmodules = filter(
        lambda f: f['type'] == 'file' and f['name'].lower() == '.gitmodules',
        repo_contents)

    if not gitmodules:
        return []

    _, file_contents = get_api_page(gitmodules[0]['url'])
    contents_decoded = base64.b64decode(file_contents.get('content', ''))
    contents_unicode = unicode(contents_decoded, 'utf-8', errors='ignore')

    parser = configparser.ConfigParser(interpolation=None)

    try:
        parser.read_string(unicode(contents_unicode))
    except configparser.Error:
        logging.exception(
            colored(
                'Could not parse the .gitmodules file of %s.' %
                file_contents['url'], 'red'))
        return []

    plugin_repos = []
    for section, config in parser.items():
        if not _SUBMODULE_IS_BUNDLE_REGEX.search(section):
            continue

        if not config.get('url'):
            continue

        # The parser sometimes over-parses the value
        url = config['url'].split('\n')[0]
        match = _BUNDLE_OWNER_REPO_REGEX.search(url)
        if match and len(match.groups()) == 2 and match.group(1):
            owner, repo = match.groups()
            plugin_repos.append((owner, repo))
        else:
            logging.error(
                colored('Failed to extract owner/repo from "%s"' % url, 'red'))

    return plugin_repos
Пример #11
0
 def test_create(self) -> None:
     parser = configparser.ConfigParser()
     parser.read_string(
         """
         [section]
         unit=seconds
         value=13
         """
     )
     check = Periodic.create("name", parser["section"])
     assert check._delta == timedelta(seconds=13)
Пример #12
0
def _extract_pathogen_repos(repo_contents):
    """Extracts Pathogen plugin repos from a GitHub dotfiles repository.

    This currently just extracts plugins if they are checked in as submodules,
    because it's easy to extract repo URLs from the .gitmodules file but
    difficult to determine the repo URL of a plugin that's just cloned in.

    Arguments:
        repo_contents: API response from GitHub of a directory or repo's
            contents.

    Returns:
        A list of tuples (owner, repo_name) referencing GitHub repos.
    """
    gitmodules = filter(lambda f: f['type'] == 'file' and
            f['name'].lower() == '.gitmodules', repo_contents)

    if not gitmodules:
        return []

    _, file_contents = get_api_page(gitmodules[0]['url'])
    contents_decoded = base64.b64decode(file_contents.get('content', ''))
    contents_unicode = unicode(contents_decoded, 'utf-8', errors='ignore')

    parser = configparser.ConfigParser(interpolation=None)

    try:
        parser.read_string(unicode(contents_unicode))
    except configparser.Error:
        logging.exception(colored(
                'Could not parse the .gitmodules file of %s.' %
                file_contents['url'], 'red'))
        return []

    plugin_repos = []
    for section, config in parser.items():
        if not _SUBMODULE_IS_BUNDLE_REGEX.search(section):
            continue

        if not config.get('url'):
            continue

        # The parser sometimes over-parses the value
        url = config['url'].split('\n')[0]
        match = _BUNDLE_OWNER_REPO_REGEX.search(url)
        if match and len(match.groups()) == 2 and match.group(1):
            owner, repo = match.groups()
            plugin_repos.append((owner, repo))
        else:
            logging.error(colored(
                    'Failed to extract owner/repo from "%s"' % url, 'red'))

    return plugin_repos
Пример #13
0
 def test_create(self):
     parser = configparser.ConfigParser()
     parser.read_string('''[section]
                           url = url
                           username = user
                           password = pass
                           timeout = 42''')
     check = Calendar.create('name', parser['section'])
     assert check._url == 'url'
     assert check._username == 'user'
     assert check._password == 'pass'
     assert check._timeout == 42
Пример #14
0
 def test_create(self) -> None:
     parser = configparser.ConfigParser()
     parser.read_string(
         """
         [section]
         xpath=/valid
         url=nourl
         timeout=20
         """
     )
     check: XPath = XPath.create("name", parser["section"])  # type: ignore
     assert check._xpath == "/valid"
Пример #15
0
 def test_create_wrong_unit(self) -> None:
     parser = configparser.ConfigParser()
     parser.read_string(
         """
         [section]
         xpath=/valid
         url=nourl
         timeout=20
         unit=unknown
         """
     )
     with pytest.raises(ConfigurationError):
         XPathDelta.create("name", parser["section"])
Пример #16
0
 def test_create(self) -> None:
     parser = configparser.ConfigParser()
     parser.read_string(
         """
         [section]
         xpath=/valid
         url=nourl
         timeout=20
         unit=weeks
         """
     )
     check = XPathDelta.create("name", parser["section"])
     assert check._unit == "weeks"
Пример #17
0
 def test_no_such_class(self, mocker) -> None:
     parser = configparser.ConfigParser()
     parser.read_string("""
         [check.Foo]
         class = FooBarr
         enabled = True
         """)
     with pytest.raises(autosuspend.ConfigurationError):
         autosuspend.set_up_checks(
             parser,
             "check",
             "activity",
             autosuspend.Activity  # type: ignore
         )
Пример #18
0
 def test_minimal_config(self, mocker) -> None:
     parser = configparser.ConfigParser()
     parser.read_string("""
         [general]
         suspend_cmd = suspend
         wakeup_cmd = wakeup
         """)
     args = mocker.MagicMock(spec=argparse.Namespace)
     type(args).all_checks = mocker.PropertyMock(return_value=True)
     processor = autosuspend.configure_processor(args, parser, [], [])
     assert processor._idle_time == 300
     assert processor._min_sleep_time == 1200
     assert processor._wakeup_delta == 30
     assert processor._all_activities
Пример #19
0
 def test_create(self) -> None:
     parser = configparser.ConfigParser()
     parser.read_string(
         """
         [section]
         url = url
         username = user
         password = pass
         timeout = 42
         """
     )
     check: Calendar = Calendar.create(
         "name", parser["section"],
     )  # type: ignore
     assert check._url == "url"
     assert check._username == "user"
     assert check._password == "pass"
     assert check._timeout == 42
Пример #20
0
    def test_external_class(self, mocker) -> None:
        mock_class = mocker.patch("os.path.TestCheck", create=True)
        mock_class.create.return_value = mocker.MagicMock(
            spec=autosuspend.checks.Activity)
        parser = configparser.ConfigParser()
        parser.read_string("""
            [check.Foo]
            class = os.path.TestCheck
            enabled = True
            """)

        autosuspend.set_up_checks(
            parser,
            "check",
            "activity",
            autosuspend.Activity  # type: ignore
        )

        mock_class.create.assert_called_once_with("Foo", parser["check.Foo"])
Пример #21
0
    def test_not_a_check(self, mocker) -> None:
        mock_class = mocker.patch("autosuspend.checks.activity.Mpd")
        mock_class.create.return_value = mocker.MagicMock()

        parser = configparser.ConfigParser()
        parser.read_string("""
            [check.Foo]
            class = Mpd
            enabled = True
            """)

        with pytest.raises(autosuspend.ConfigurationError):
            autosuspend.set_up_checks(
                parser,
                "check",
                "activity",
                autosuspend.Activity  # type: ignore
            )

        mock_class.create.assert_called_once_with("Foo", parser["check.Foo"])
Пример #22
0
    def test_passwords_redacted(self, mocker, caplog) -> None:
        mock_class = mocker.patch("autosuspend.checks.activity.Mpd")
        mock_class.create.return_value = mocker.MagicMock(
            spec=autosuspend.checks.Activity)

        parser = configparser.ConfigParser()
        parser.read_string("""
            [check.Foo]
            class = Mpd
            enabled = True
            password = THEPASS
            """)

        with caplog.at_level(logging.DEBUG):
            autosuspend.set_up_checks(
                parser,
                "check",
                "activity",
                autosuspend.Activity  # type: ignore
            )

            assert "THEPASS" not in caplog.text
Пример #23
0
 def test_create(self):
     parser = configparser.ConfigParser()
     parser.read_string('''[section]
                           path = /tmp/test''')
     check = File.create('name', parser['section'])
     assert check._path == '/tmp/test'
Пример #24
0
 def test_create_float(self):
     parser = configparser.ConfigParser()
     parser.read_string('''[section]
                        unit=seconds
                        value=21312.12''')
     Periodic.create('name', parser['section'])
Пример #25
0
 def test_create_no_path(self):
     parser = configparser.ConfigParser()
     parser.read_string('''[section]''')
     with pytest.raises(ConfigurationError):
         File.create('name', parser['section'])
Пример #26
0
 def test_create_no_path(self) -> None:
     parser = configparser.ConfigParser()
     parser.read_string("""[section]""")
     with pytest.raises(ConfigurationError):
         File.create("name", parser["section"])