예제 #1
0
def test_format_tb():
    try:
        raise NameError("You dun goofed now")
    except Exception:
        x = color.format_tb(sys.exc_info())
        assert x
        assert x != color.format_tb(sys.exc_info(), start=1)
예제 #2
0
파일: __main__.py 프로젝트: banteg/brownie
def main():

    print(f"Brownie v{__version__} - Python development framework for Ethereum\n")

    # remove options before calling docopt
    if len(sys.argv) > 1 and sys.argv[1][0] != "-":
        idx = next((sys.argv.index(i) for i in sys.argv if i.startswith("-")), len(sys.argv))
        opts = sys.argv[idx:]
        sys.argv = sys.argv[:idx]
    args = docopt(__doc__)
    sys.argv += opts

    cmd_list = [i.stem for i in Path(__file__).parent.glob('[!_]*.py')]
    if args['<command>'] not in cmd_list:
        sys.exit("Invalid command. Try 'brownie --help' for available commands.")

    ARGV['cli'] = args['<command>']
    sys.modules['brownie'].a = network.accounts
    sys.modules['brownie'].__all__.append('a')

    try:
        importlib.import_module("brownie.cli."+args['<command>']).main()
    except ProjectNotFound:
        notify("ERROR", "Brownie environment has not been initiated for this folder.")
        print("Type 'brownie init' to create the file structure.")
    except Exception:
        print(color.format_tb(sys.exc_info()))
예제 #3
0
파일: run.py 프로젝트: AndrewBezold/brownie
def main():
    args = docopt(__doc__)
    name = args['<filename>'].replace(".py", "")
    fn = args['<function>'] or "main"
    if not Path(CONFIG['folders']['project']).joinpath(
            'scripts/{}.py'.format(name)):
        sys.exit(
            "{0[error]}ERROR{0}: Cannot find {0[module]}scripts/{1}.py{0}".
            format(color, name))
    network.connect(config.ARGV['network'], True)
    module = importlib.import_module("scripts." + name)
    if not hasattr(module, fn):
        sys.exit(
            "{0[error]}ERROR{0}: {0[module]}scripts/{1}.py{0} has no '{0[callable]}{2}{0}' function."
            .format(color, name, fn))
    print("Running '{0[module]}{1}{0}.{0[callable]}{2}{0}'...".format(
        color, name, fn))
    try:
        getattr(module, fn)()
        print(
            "\n{0[success]}SUCCESS{0}: script '{0[module]}{1}{0}' completed.".
            format(color, name))
    except Exception as e:
        if CONFIG['logging']['exc'] >= 2:
            print("\n" + color.format_tb(sys.exc_info()))
        print(
            "\n{0[error]}ERROR{0}: Script '{0[module]}{1}{0}' failed from unhandled {2}: {3}"
            .format(color, name,
                    type(e).__name__, e))
예제 #4
0
def _run_test(module, fn_name, count, total):
    fn = getattr(module, fn_name)
    desc = fn.__doc__ or fn_name
    sys.stdout.write("   {1} - {0} ({1}/{2})...  ".format(desc, count, total))
    sys.stdout.flush()
    if fn.__defaults__:
        args = dict(zip(
            fn.__code__.co_varnames[:len(fn.__defaults__)],
            fn.__defaults__
        ))
        if 'skip' in args and args['skip']:
            sys.stdout.write(
                "\r {0[pending]}\u229d{0[dull]} {1} ".format(color, desc) +
                "({0[pending]}skipped{0[dull]}){0}\n".format(color)
            )
            return []
    else:
        args = {}
    try:
        stime = time.time()
        fn()
        if 'pending' in args and args['pending']:
            raise ExpectedFailing("Test was expected to fail")
        sys.stdout.write("\r {0[success]}\u2713{0} {3} - {1} ({2:.4f}s)\n".format(
            color, desc, time.time()-stime, count
        ))
        sys.stdout.flush()
        return []
    except Exception as e:
        if type(e) != ExpectedFailing and 'pending' in args and args['pending']:
            c = [color('success'), color('dull'), color()]
        else:
            c = [color('error'), color('dull'), color()]
        sys.stdout.write("\r {0[0]}{1}{0[1]} {2} ({0[0]}{3}{0[1]}){0[2]}\n".format(
            c,
            '\u2717' if type(e) in (
                AssertionError,
                VirtualMachineError
            ) else '\u203C',
            desc,
            type(e).__name__,
        ))
        sys.stdout.flush()
        if type(e) != ExpectedFailing and 'pending' in args and args['pending']:
            return []
        filename = str(Path(module.__file__).relative_to(CONFIG['folders']['project']))
        fn_name = filename[:-2]+fn_name
        return [(fn_name, color.format_tb(sys.exc_info(), filename))]
예제 #5
0
def main():

    print("Brownie v{} - Python development framework for Ethereum\n".format(__version__))

    if len(sys.argv) > 1 and sys.argv[1][0] != "-":
        try:
            idx = next(sys.argv.index(i) for i in sys.argv if i[0] == "-")
            opts = sys.argv[idx:]
            sys.argv = sys.argv[:idx]
        except StopIteration:
            opts = []

    args = docopt(__doc__)
    sys.argv += opts


    cmd_list = [i.name[:-3] for i in Path(__file__).parent.glob('*.py') if i.name[0] != "_"]
    if args['<command>'] not in cmd_list:
        sys.exit("Invalid command. Try 'brownie --help' for available commands.")

    if args['<command>'] not in ("init", "bake"):
        path = project.check_for_project('.')
        if not path:
            sys.exit(
                "ERROR: Brownie environment has not been initiated for this folder."
                "\nType 'brownie init' to create the file structure."
            )
        for container in project.load(path):
            setattr(brownie, container._name, container)
            brownie.__all__.append(container._name)
        brownie.a = brownie.accounts
        brownie.__all__.append('a')

    try:
        importlib.import_module("brownie.cli."+args['<command>']).main()
    except Exception:
        print(color.format_tb(sys.exc_info()))
예제 #6
0
 def _run(self):
     local_ = {}
     builtins.print = self._print
     multiline = False
     while True:
         try:
             if not multiline:
                 cmd = self._input(self._prompt)
                 if not cmd.strip():
                     continue
                 compile(cmd, '<stdin>', 'exec')
             else:
                 new_cmd = self._input("... ")
                 cmd += "\n" + new_cmd
                 if len(compile(cmd, '<stdin>',
                                'exec').co_consts) > 2 and new_cmd:
                     continue
         except SyntaxError as e:
             if e.msg != "unexpected EOF while parsing":
                 self._prompt = ""
                 print(color.format_tb(sys.exc_info(), start=1))
                 multiline = False
                 self._prompt = ">>> "
                 continue
             if not multiline:
                 multiline = True
                 self._prompt = "... "
                 continue
             try:
                 compile(cmd + ".", '<stdin>', 'exec')
             except IndentationError:
                 pass
             except SyntaxError:
                 continue
         except KeyboardInterrupt:
             sys.stdout.write("\nKeyboardInterrupt\n")
             sys.stdout.flush()
             multiline = False
             self._prompt = ">>> "
             continue
         multiline = False
         self._prompt = ""
         try:
             try:
                 local_['_result'] = None
                 exec('_result = ' + cmd, self.__dict__, local_)
                 r = local_['_result']
                 if r is not None:
                     if type(r) in (dict, StrictDict) and r:
                         color.pretty_dict(r)
                     elif type(r) in (list, tuple, KwargTuple):
                         color.pretty_list(r)
                     elif type(r) is str:
                         print(r)
                     elif hasattr(r, '_console_repr'):
                         try:
                             print(r._console_repr())
                         except TypeError:
                             print(repr(r))
                     else:
                         print(repr(r))
             except SyntaxError:
                 exec(cmd, self.__dict__, local_)
             except SystemExit:
                 return
         except Exception:
             print(color.format_tb(sys.exc_info(), start=1))
         self._prompt = ">>> "