Example #1
0
def test_special_floats():
    x = float("infinity")
    y = float("nan")
    z = float("-infinity")
    vars = jsonpickle.decode(pickle_user_vars(locals()))
    assert vars["x"] == "Infinity"
    assert vars["y"] == "NaN"
    assert vars["z"] == "-Infinity"
Example #2
0
def test_jsonpickle_err_doesnt_break_arepl():
    class foo:
        def __getstate__(self):
            a

    f = foo()

    assert jsonpickle.decode(pickle_user_vars(
        locals()))["f"] == "AREPL could not pickle this object"
Example #3
0
def test_custom_filter_function():
    def arepl_filter_function(userVariables):
        userVariables["a"] = 3
        return userVariables

    vars = jsonpickle.decode(pickle_user_vars(locals()))

    assert vars["a"] == 3
    assert "arepl_filter_function" not in vars
Example #4
0
def test_custom_type_filter():
    arepl_filter_type = ["<class 'str'>"]
    dog = ""
    cat = 2
    vars = jsonpickle.decode(pickle_user_vars(locals()))

    assert vars["cat"] == 2
    assert "dog" not in vars
    assert "arepl_filter_type" not in vars
Example #5
0
def test_custom_filter():
    arepl_filter = ["dog"]
    dog = 1
    cat = 2
    vars = jsonpickle.decode(pickle_user_vars(locals()))

    assert vars["cat"] == 2
    assert "dog" not in vars
    assert "arepl_filter" not in vars
Example #6
0
def test_default_type_filter():
    def foo():
        return 3

    cat = 2
    vars = jsonpickle.decode(pickle_user_vars(locals()))

    assert vars["cat"] == 2
    assert "foo" not in vars
Example #7
0
    def __init__(self,
                 exc_obj: BaseException,
                 exc_tb: TracebackType,
                 varsSoFar={},
                 execTime=0):
        # skip arepl traceback - the user should just see their own error
        exc_tb = exc_tb.tb_next

        self.traceback_exception = TracebackException(type(exc_obj), exc_obj,
                                                      exc_tb)
        self.friendly_message = "".join(self.traceback_exception.format())
        self.varsSoFar = pickle_user_vars(varsSoFar,
                                          get_settings().default_filter_vars,
                                          get_settings().default_filter_types)
        self.execTime = execTime

        # stack is empty in event of a syntax error
        # This is problematic because frontend has to handle syntax/regular error differently
        # to make it easier populate stack so frontend can handle them the same way
        if self.traceback_exception.exc_type is SyntaxError:
            self.traceback_exception.stack.append(
                FrameSummary(self.traceback_exception.filename,
                             int(self.traceback_exception.lineno), ""))
Example #8
0
def exec_input(exec_args: ExecArgs):
    """
    returns info about the executed code (local vars, errors, and timing)
    :rtype: returnInfo
    """
    global eval_locals
    global run_context

    argv[0] = exec_args.filePath
    # see https://docs.python.org/3/library/sys.html#sys.argv
    saved.starting_locals["__file__"] = exec_args.filePath
    if exec_args.filePath:
        saved.starting_locals["__loader__"].path = os.path.basename(
            exec_args.filePath)

    if not exec_args.usePreviousVariables:
        eval_locals = saved.get_eval_locals(exec_args.savedCode)

    # re-import imports. (pickling imports from saved code was unfortunately not possible)
    exec_args.evalCode = saved.copy_saved_imports_to_exec(
        exec_args.evalCode, exec_args.savedCode)

    # clear new modules from last run each run has same fresh start
    current_module_names = set([module_name for module_name in modules])
    new_modules = current_module_names - modules_to_keep
    for module_name in new_modules:
        del modules[module_name]

    # not sure why i need to do this when module was deleted
    # but if I don't next run will say event loop closed
    asyncio.set_event_loop(asyncio.new_event_loop())

    with script_path(os.path.dirname(exec_args.filePath)):
        if not exec_args.usePreviousVariables and run_context is not None:
            run_context = contextvars.Context()
        try:
            start = time()
            if run_context is not None:
                run_context.run(exec, exec_args.evalCode, eval_locals)
            else:
                # python 3.6 fallback
                exec(exec_args.evalCode, eval_locals)
            execTime = time() - start
        except BaseException:
            execTime = time() - start
            _, exc_obj, exc_tb = exc_info()
            if not get_settings().show_global_vars:
                raise UserError(exc_obj, exc_tb, noGlobalVarsMsg, execTime)
            else:
                raise UserError(exc_obj, exc_tb, eval_locals, execTime)

        finally:

            if sys.stdout.flush and callable(sys.stdout.flush):
                # a normal program will flush at the end of the run
                # arepl never stops so we have to do it manually
                sys.stdout.flush()

            saved.arepl_store = eval_locals.get("arepl_store")

            # clear mock stdin for next run
            arepl_overloads.arepl_input_iterator = None

    if get_settings().show_global_vars:
        userVariables = pickle_user_vars(
            eval_locals,
            get_settings().default_filter_vars,
            get_settings().default_filter_types,
        )
    else:
        userVariables = pickle_user_vars(
            noGlobalVarsMsg,
            get_settings().default_filter_vars,
            get_settings().default_filter_types,
        )

    return ReturnInfo("", userVariables, execTime, None)
def exec_input(exec_args: ExecArgs):
    """
    returns info about the executed code (local vars, errors, and timing)
    :rtype: returnInfo
    """
    global eval_locals

    argv[0] = exec_args.filePath  # see https://docs.python.org/3/library/sys.html#sys.argv
    saved.starting_locals["__file__"] = exec_args.filePath
    if(exec_args.filePath):
        saved.starting_locals["__loader__"].path = os.path.basename(exec_args.filePath)

    if not exec_args.usePreviousVariables:
        eval_locals = saved.get_eval_locals(exec_args.savedCode)

    # re-import imports. (pickling imports from saved code was unfortunately not possible)
    exec_args.evalCode = saved.copy_saved_imports_to_exec(exec_args.evalCode, exec_args.savedCode)

    # repoen revent loop in case user closed it in last run
    asyncio.set_event_loop(asyncio.new_event_loop())

    with script_path(os.path.dirname(exec_args.filePath)):
        try:
            start = time()
            exec(exec_args.evalCode, eval_locals)
            execTime = time() - start
        except BaseException:
            execTime = time() - start
            _, exc_obj, exc_tb = exc_info()
            if not get_settings().showGlobalVars:
                raise UserError(exc_obj, exc_tb, noGlobalVarsMsg, execTime)
            else:
                raise UserError(exc_obj, exc_tb, eval_locals, execTime)

        finally:

            saved.arepl_store = eval_locals.get("arepl_store")

            try:
                # arepl_dump library keeps state internally
                # because python caches imports the state is kept inbetween runs
                # we do not want that, arepl_dump should reset each run
                del modules["arepl_dump"]
            except KeyError:
                pass  # they have not imported it, whatever

            importedModules = set(modules) - origModules
            userModules = importedModules - nonUserModules

            # user might have changed user module inbetween arepl runs
            # so we clear them to reload import each time
            for userModule in userModules:
                try:
                    # #70: nonUserModules does not list submodules
                    # so we have to extract base module and use that
                    # to skip any nonUserModules
                    baseModule = userModule.split(".")[0]
                    if len(baseModule) > 1:
                        if baseModule in nonUserModules:
                            continue
                    del modules[userModule]
                except KeyError:
                    pass  # it's not worth failing AREPL over

            # clear mock stdin for next run
            arepl_overloads.arepl_input_iterator = None

    if get_settings().showGlobalVars:
        userVariables = pickle_user_vars(
            eval_locals, get_settings().default_filter_vars, get_settings().default_filter_types
        )
    else:
        userVariables = pickle_user_vars(
            noGlobalVarsMsg, get_settings().default_filter_vars, get_settings().default_filter_types
        )

    return ReturnInfo("", userVariables, execTime, None)