Пример #1
0
def test_socialist():
    with messenger() as (msg, stdout, stderr, logfile):
        with pytest.raises(SystemExit) as exception:
            try:
                raise Error(
                    'Hey now!', 'Hey now!',
                    codicil=(
                        'Aiko aiko all day',
                        'jockomo feeno na na nay',
                        'jockomo feena nay'
                    ),
                    informant=fatal
                )
            except Error as e:
                e.report()
            assert msg.errors_accrued() == 1
            assert errors_accrued(True) == 1
            assert exception.value.args == (1,)
            assert strip(stdout) == dedent('''
                error: Hey now! Hey now!
                    Aiko aiko all day
                    jockomo feeno na na nay
                    jockomo feena nay
            ''').strip()
            assert strip(stderr) == ''
Пример #2
0
def test_crocodile():
    with messenger() as (msg, stdout, stderr, logfile):
        try:
            try:
                raise Error(
                    'Hey now!', 'Hey now!',
                    codicil=(
                        'Aiko aiko all day',
                        'jockomo feeno na na nay',
                        'jockomo feena nay'
                    )
                )
            except Error as e:
                e.reraise(culprit='I said')
        except Error as e:
            e.report()
        assert msg.errors_accrued() == 1
        assert errors_accrued(True) == 1
        assert strip(stdout) == dedent('''
            error: I said: Hey now! Hey now!
                Aiko aiko all day
                jockomo feeno na na nay
                jockomo feena nay
        ''').strip()
        assert strip(stderr) == ''
Пример #3
0
def test_stripy():
    with messenger() as (msg, stdout, stderr, logfile):
        expected = dedent('''
            error: de Finibus Bonorum et Malorum
                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
                eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
                minim veniam, quis nostrud exercitation ullamco laboris nisi ut
                aliquip ex ea commodo consequat. Duis aute irure dolor in
                reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
                pariatur. Excepteur sint occaecat cupidatat non proident, sunt in
                culpa qui officia deserunt mollit anim id est laborum.
        ''').strip()
        try:
            raise Error('de Finibus Bonorum et Malorum', codicil=lorum_ipsum, wrap=True)
        except Error as e:
            e.report()
        assert msg.errors_accrued() == 1
        assert errors_accrued() == 1
        assert strip(stdout) == expected
        assert strip(stderr) == ''
        assert log_strip(logfile) == dedent('''
            ack: invoked as: <exe>
            ack: invoked on: <date>
            {expected}
        ''').strip().format(expected=expected)
Пример #4
0
def test_wring():
    with messenger() as (msg, stdout, stderr, logfile):
        output('hey now!', flush=True)
        codicil('baby', 'bird', sep='\n')
        msg.flush_logfile()
        expected = dedent('''
            hey now!
            baby
            bird
        ''').strip()

        assert msg.errors_accrued() == 0
        assert errors_accrued() == 0
        assert strip(stdout) == expected
        assert strip(stderr) == ''
        assert log_strip(logfile) == dedent('''
            ack: invoked as: <exe>
            ack: invoked on: <date>
            {expected}
        ''').strip().format(expected=expected)

        try:
            terminate_if_errors()
            assert True
        except SystemExit:
            assert False
Пример #5
0
def test_franc():
    with messenger() as (msg, stdout, stderr, logfile):
        display('fuzzy', file=stdout, flush=True)
        assert msg.errors_accrued() == 0
        assert errors_accrued(True) == 0
        assert strip(stdout) == 'fuzzy'
        assert strip(stderr) == ''
Пример #6
0
def test_fabricate():
    with messenger(hanging_indent=False) as (msg, stdout, stderr, logfile):
        error('hey now!')
        codicil('baby', 'bird', sep='\n')
        error('uh-huh\nuh-huh',
              culprit='yep yep yep yep yep yep yep yep yep yep yep'.split())
        expected = dedent('''
            error: hey now!
                baby
                bird
            error: yep, yep, yep, yep, yep, yep, yep, yep, yep, yep, yep:
                uh-huh
                uh-huh
        ''').strip()

        assert msg.errors_accrued() == 2
        assert errors_accrued(True) == 2
        assert msg.errors_accrued() == 0
        assert strip(stdout) == expected
        assert strip(stderr) == ''
        assert log_strip(logfile) == dedent('''
            ack: invoked as: <exe>
            ack: log opened on <date>
            {expected}
        ''').strip().format(expected=expected)
Пример #7
0
def test_cameraman():
    with messenger() as (msg, stdout, stderr, logfile):
        try:
            raise Error('Hey now.', informant=error)
        except Error as e:
            e.report()
        assert msg.errors_accrued() == 1
        assert errors_accrued(True) == 1
        assert strip(stdout) == 'error: Hey now.'
        assert strip(stderr) == ''
Пример #8
0
def test_periphery():
    with messenger() as (msg, stdout, stderr, logfile):
        try:
            raise Error('Hey now.', informant=warn)
        except Error as e:
            e.report()
        assert msg.errors_accrued() == 0
        assert errors_accrued(True) == 0
        assert strip(stdout) == 'warning: Hey now.'
        assert strip(stderr) == ''
Пример #9
0
def test_tramp():
    with messenger() as (msg, stdout, stderr, logfile):
        try:
            raise Error('Hey now.', informant=display)
        except Error as e:
            e.report()
        assert msg.errors_accrued() == 0
        assert errors_accrued(True) == 0
        assert strip(stdout) == 'Hey now.'
        assert strip(stderr) == ''
Пример #10
0
def test_guitar():
    with messenger() as (msg, stdout, stderr, logfile):
        try:
            raise Error('Hey now!')
        except Error as e:
            e.report()
        assert msg.errors_accrued() == 1
        assert errors_accrued(True) == 1
        assert strip(stdout) == 'error: Hey now!'
        assert strip(stderr) == ''
Пример #11
0
def test_fathead():
    with messenger() as (msg, stdout, stderr, logfile):
        display('aaa bbb ccc', codicil=('000 111 222', '!!! @@@ ###'))
        assert msg.errors_accrued() == 0
        assert errors_accrued(True) == 0
        assert strip(stdout) == dedent('''
            aaa bbb ccc
            000 111 222
            !!! @@@ ###
        ''').strip()
        assert strip(stderr) == ''
Пример #12
0
def test_showing():
    with messenger() as (msg, stdout, stderr, logfile):
        error('aaa bbb ccc', codicil=('000 111 222', '!!! @@@ ###'))
        assert msg.errors_accrued() == 1
        assert errors_accrued(True) == 1
        assert strip(stdout) == dedent('''
            error: aaa bbb ccc
                000 111 222
                !!! @@@ ###
        ''').strip()
        assert strip(stderr) == ''
Пример #13
0
def test_roadway():
    with messenger() as (msg, stdout, stderr, logfile):
        with pytest.raises(Error) as exception:
            try:
                raise Error('Hey now!')
            except Error as e:
                e.reraise(culprit='bux')
        exception.value.report()
        assert msg.errors_accrued() == 1
        assert errors_accrued(True) == 1
        assert strip(stdout) == 'error: bux: Hey now!'
        assert strip(stderr) == ''
Пример #14
0
def test_toboggan():
    with messenger() as (msg, stdout, stderr, logfile):
        warn('aaa bbb ccc')
        codicil('000 111 222')
        codicil('!!! @@@ ###')
        assert msg.errors_accrued() == 0
        assert errors_accrued(True) == 0
        assert strip(stdout) == dedent('''
            warning: aaa bbb ccc
                000 111 222
                !!! @@@ ###
        ''').strip()
        assert strip(stderr) == ''
Пример #15
0
def test_grove():
    with messenger() as (msg, stdout, stderr, logfile):
        stimulus = 'hey now!'
        log(stimulus)
        assert msg.errors_accrued() == 0
        assert errors_accrued() == 0
        assert strip(stdout) == ''
        assert strip(stderr) == ''
        assert log_strip(logfile) == dedent('''
            ack: invoked as: <exe>
            ack: invoked on: <date>
            {expected}
        ''').strip().format(expected=stimulus)
Пример #16
0
def test_culprits(culprits, culprits_as_str):
    with messenger(culprit_sep='.') as (msg, stdout, stderr, logfile):
        stimulus = 'hey now!'
        expected = 'warning: {}{}'.format(culprits_as_str, stimulus)
        warn(stimulus, culprit=culprits)
        assert msg.errors_accrued() == 0
        assert errors_accrued() == 0
        assert strip(stdout) == expected
        assert strip(stderr) == ''
        assert log_strip(logfile) == dedent('''
            ack: invoked as: <exe>
            ack: log opened on <date>
            {expected}
        ''').strip().format(expected=expected)
Пример #17
0
def test_vapor():
    with messenger() as (msg, stdout, stderr, logfile):
        report = InformantFactory(clone=display)
        stimulus = 'hey now!'
        report(stimulus)
        assert msg.errors_accrued() == 0
        assert errors_accrued() == 0
        assert strip(stdout) == stimulus
        assert strip(stderr) == ''
        assert log_strip(logfile) == dedent('''
            ack: invoked as: <exe>
            ack: log opened on <date>
            {expected}
        ''').strip().format(expected=stimulus)
Пример #18
0
def test_jumper():
    with messenger() as (msg, stdout, stderr, logfile):
        report = InformantFactory(clone=display,
                                  severity='forbidden',
                                  is_error=True)
        stimulus = 'hey now!'
        expected = 'forbidden: {}'.format(stimulus)
        report(stimulus)
        assert msg.errors_accrued() == 1
        assert errors_accrued() == 1
        assert strip(stdout) == expected
        assert strip(stderr) == ''
        assert log_strip(logfile) == dedent('''
            ack: invoked as: <exe>
            ack: log opened on <date>
            {expected}
        ''').strip().format(expected=expected)
Пример #19
0
def test_possess():
    with messenger(stream_policy='header') as (msg, stdout, stderr, logfile):
        out = [
            'hey now!',
            'hey now!',
        ]
        err = [
            'Aiko aiko all day',
            'jockomo feeno na na nay',
            'jockomo feena nay.',
        ]
        display(*out)
        warn(*err, sep=', ')

        assert msg.errors_accrued() == 0
        assert errors_accrued(True) == 0
        assert strip(stdout) == ' '.join(out)
        assert strip(stderr) == 'warning: ' + ', '.join(err)
Пример #20
0
def test_unbuckle():
    with messenger() as (msg, stdout, stderr, logfile):
        msg.set_stream_policy(lambda i, so, se: se if i.severity else so)
        out = [
            'hey now!',
            'hey now!',
        ]
        err = [
            'Aiko aiko all day',
            'jockomo feeno na na nay',
            'jockomo feena nay.',
        ]
        display(*out)
        warn(*err, sep=', ')

        assert msg.errors_accrued() == 0
        assert errors_accrued(True) == 0
        assert strip(stdout) == ' '.join(out)
        assert strip(stderr) == 'warning: ' + ', '.join(err)
Пример #21
0
def test_billfold():
    with messenger() as (msg, stdout, stderr, logfile):
        display('hey now!', culprit=('yo', 'ho'))
        display('yep,\nYEP!', culprit='yep yep yep yep yep yep yep yep yep yep yep')
        expected = dedent('''
            yo, ho: hey now!
            yep yep yep yep yep yep yep yep yep yep yep:
                yep,
                YEP!
        ''').strip()

        assert msg.errors_accrued() == 0
        assert errors_accrued() == 0
        assert strip(stdout) == expected
        assert strip(stderr) == ''
        assert log_strip(logfile) == dedent('''
            ack: invoked as: <exe>
            ack: invoked on: <date>
            {expected}
        ''').strip().format(expected=expected)
Пример #22
0
    def resolve_patterns(self, borg_opts, skip_checks=False):
        roots = self.src_dirs[:]

        patterns = self.values("patterns")
        if patterns:
            for pattern in check_patterns(patterns,
                                          roots,
                                          self.working_dir,
                                          "patterns",
                                          skip_checks=skip_checks):
                borg_opts.extend(["--pattern", pattern])

        excludes = self.values("excludes")
        if excludes:
            for exclude in check_excludes(excludes, roots, "excludes"):
                borg_opts.extend(["--exclude", exclude])

        patterns_froms = self.as_paths("patterns_from", must_exist=True)
        if patterns_froms:
            check_patterns_files(patterns_froms,
                                 roots,
                                 self.working_dir,
                                 skip_checks=skip_checks)
            for patterns_from in patterns_froms:
                borg_opts.extend(["--patterns-from", patterns_from])

        exclude_froms = self.as_paths("exclude_from", must_exist=True)
        if exclude_froms:
            check_excludes_files(exclude_froms, roots)
            for exclude_from in exclude_froms:
                borg_opts.extend(["--exclude-from", exclude_from])

        if not skip_checks:
            check_roots(roots, self.working_dir)

        if errors_accrued():
            raise Error("stopping due to previously reported errors.")
        self.roots = roots
Пример #23
0
def test_cartwheel():
    with messenger() as (msg, stdout, stderr, logfile):
        warn('hey now!', culprit='yo')
        codicil('baby', 'bird', sep='\n')
        warn('uh-huh\nuh-huh', culprit='yep yep yep yep yep yep yep yep yep yep yep')
        expected = dedent('''
            warning: yo: hey now!
                baby
                bird
            warning: yep yep yep yep yep yep yep yep yep yep yep:
                uh-huh
                uh-huh
        ''').strip()

        assert msg.errors_accrued() == 0
        assert errors_accrued(True) == 0
        assert strip(stdout) == expected
        assert strip(stderr) == ''
        assert log_strip(logfile) == dedent('''
            ack: invoked as: <exe>
            ack: invoked on: <date>
            {expected}
        ''').strip().format(expected=expected)
Пример #24
0
    def borg_options(self, cmd, borg_opts, emborg_opts, strip_prefix=True):
        if not borg_opts:
            borg_opts = []

        # handle special cases first {{{3
        if self.value("verbose"):
            emborg_opts = list(emborg_opts)
            emborg_opts.append("verbose")
        if "verbose" in emborg_opts:
            borg_opts.append("--verbose")
        if "dry-run" in emborg_opts and cmd in borg_commands_with_dryrun:
            borg_opts.append("--dry-run")

        if cmd == "create":
            if "verbose" in emborg_opts and "--list" not in borg_opts:
                borg_opts.append("--list")
            roots = self.src_dirs
            patterns = self.values("patterns")
            if patterns:
                for pattern in check_patterns(patterns, roots,
                                              self.working_dir, "patterns"):
                    borg_opts.extend(["--pattern", pattern])
            excludes = self.values("excludes")
            if excludes:
                for exclude in check_excludes(excludes, roots, "excludes"):
                    borg_opts.extend(["--exclude", exclude])
            patterns_froms = self.as_paths("patterns_from", must_exist=True)
            if patterns_froms:
                check_patterns_files(patterns_froms, roots, self.working_dir)
                for patterns_from in patterns_froms:
                    borg_opts.extend(["--patterns-from", patterns_from])
            exclude_froms = self.as_paths("exclude_from", must_exist=True)
            if exclude_froms:
                check_excludes_files(exclude_froms, roots)
                for exclude_from in exclude_froms:
                    borg_opts.extend(["--exclude-from", exclude_from])
            check_roots(roots, self.working_dir)
            if errors_accrued():
                raise Error("stopping due to previously reported errors.")
            self.roots = roots

        elif cmd == "extract":
            if "verbose" in emborg_opts:
                borg_opts.append("--list")

        elif cmd == "init":
            if self.passphrase or self.passcommand or self.avendesora_account:
                encryption = self.encryption if self.encryption else "repokey"
                borg_opts.append(f"--encryption={encryption}")
                if encryption == "none":
                    warn(
                        "passphrase given but not needed as encryption set to none."
                    )
                if encryption.startswith("keyfile"):
                    warn(
                        dedent("""
                            you should use 'borg key export' to export the
                            encryption key, and then keep that key in a safe
                            place.  You can do this with emborg using 'emborg
                            borg key export @repo <outfile>'.  If you lose the
                            key you will lose access to, your backups.
                            """).strip(),
                        wrap=True,
                    )
            else:
                encryption = self.encryption if self.encryption else "none"
                if encryption != "none":
                    raise Error("passphrase not specified.")
                borg_opts.append(f"--encryption={encryption}")

        if (cmd in ["create", "delete", "prune"]
                and "dry-run" not in emborg_opts
                and "--list" not in borg_opts):
            # By default we ask for stats to go in the log file.  However if
            # opts contains --list, then the stats will be displayed to user
            # rather than going to logfile, in this case, do not request stats
            # automatically, require user to do it manually.
            borg_opts.append("--stats")

        # add the borg command line options appropriate to this command {{{3
        for name, attrs in BORG_SETTINGS.items():
            if strip_prefix and name == "prefix":
                continue
            if cmd in attrs["cmds"] or "all" in attrs["cmds"]:
                opt = convert_name_to_option(name)
                val = self.value(name)
                if val:
                    if "arg" in attrs and attrs["arg"]:
                        borg_opts.extend([opt, str(val)])
                    else:
                        borg_opts.extend([opt])
        return borg_opts
Пример #25
0
def test_pardon():
    with messenger() as (msg, stdout, stderr, logfile):
        try:
            terminate()
            assert False
        except SystemExit as e:
            assert e.args == (0,)

        try:
            raise Error('hey now!', culprit='nutz', extra='foo', codicil='putz')
            assert False
        except Error as err:
            assert err.get_message() == 'hey now!'
            assert err.get_culprit() == ('nutz',)
            assert err.get_codicil() == ('putz',)
            assert join_culprit(err.get_culprit()) == 'nutz'
            assert err.extra == 'foo'
            assert str(err) == 'nutz: hey now!'
            assert errors_accrued() == 0  # errors don't accrue until reported

        try:
            raise Error(
                'hey now!',
                culprit=('nutz',  'crunch'),
                extra='foo',
                codicil=('putz',  'toodle'),
            )
            assert False
        except Error as err:
            assert err.get_message() == 'hey now!'
            assert err.get_culprit() == ('nutz', 'crunch')
            assert err.get_codicil() == ('putz', 'toodle')
            assert join_culprit(err.get_culprit()) == 'nutz, crunch'
            assert err.extra == 'foo'
            assert str(err) == 'nutz, crunch: hey now!'
            assert err.get_message() == 'hey now!'
            assert err.get_message('{extra}, {}') == 'foo, hey now!'
            assert err.render() == 'nutz, crunch: hey now!'
            assert err.render('{extra}, {}') == 'nutz, crunch: foo, hey now!'
            assert errors_accrued() == 0  # errors don't accrue until reported
            try:
                err.terminate()
                assert False
            except SystemExit as e:
                assert e.args == (1,)

            try:
                done()
                assert False
            except SystemExit as e:
                assert e.args == (0,)

            try:
                rv = done(exit=False)
                assert rv == 0
            except SystemExit as e:
                assert False

            try:
                terminate()
                assert False
            except SystemExit as e:
                assert e.args == (1,)

            try:
                rv = terminate(exit=False)
                assert rv == 1
            except SystemExit as e:
                assert False

            try:
                rv = terminate(True, exit=False)
                assert rv == 1
            except SystemExit as e:
                assert False

            try:
                rv = terminate('fuxit', exit=False)
                assert rv == 1
            except SystemExit as e:
                assert False

            try:
                rv = terminate(6, exit=False)
                assert rv == 6
            except SystemExit as e:
                assert False

            try:
                terminate_if_errors()
                assert False
            except SystemExit as e:
                assert e.args == (1,)
                assert True

            try:
                rv = terminate_if_errors(exit=False)
                assert rv == 1
            except SystemExit as e:
                assert False

        try:
            raise Error('hey now', culprit=('nutz', 347))
            assert False
        except Error as err:
            assert err.get_message() == 'hey now'
            assert err.get_culprit() == ('nutz', 347)
            assert join_culprit(err.get_culprit()) == 'nutz, 347'
            assert join_culprit(err.get_culprit(66)) == '66, nutz, 347'
            assert join_culprit(err.get_culprit(('a', 'b'))) == 'a, b, nutz, 347'
            assert str(err) == 'nutz, 347: hey now'