Пример #1
0
def predict(files):
    if len(files) == 1:
        # add model caching aspect
        with aspectlib.weave(get_model, model_cache):
            predictions = predict_single_file(files[0])
        if predictions[0] < 0.1:
            return 0, 0, 0
        else:
            subtype = np.argmax(predictions[1:])
            return predictions[0], subtype, predictions[subtype]
    else:
        # add model caching aspect
        with aspectlib.weave(get_model, model_cache):
            sequence_predictions = predict_file_sequence(files)
        has_hemorrhage_prob = 0
        for seq in sequence_predictions:
            if seq[0] >= 0.1 and seq[0] > has_hemorrhage_prob:
                has_hemorrhage_prob = seq[0]
        if has_hemorrhage_prob < 0.1:
            return 0, 0, 0
        else:
            max_prob = 0
            sequence_nr = 0
            sequence_idx = 0
            for i in range(len(sequence_predictions)):
                seq = sequence_predictions[i][1:]
                max_index = np.argmax(seq)
                if seq[max_index] > max_prob:
                    max_prob = seq[max_index]
                    sequence_idx = max_index
                    sequence_nr = i
            return sequence_predictions[sequence_nr][
                0], sequence_idx, sequence_predictions[sequence_nr][
                    sequence_idx]
Пример #2
0
def test_weave_old_style_method_no_warn_patch_module():
    calls = []
    with aspectlib.weave("warnings.warn", record(calls=calls)):
        with aspectlib.weave("test_aspectlib.LegacyTestClass.foobar", mock("stuff")):
            assert LegacyTestClass().foobar() == "stuff"

    assert calls == []
Пример #3
0
def test_weave_old_style_method_no_warn_patch_module():
    calls = []
    with aspectlib.weave('warnings.warn', record(calls=calls)):
        with aspectlib.weave('test_aspectlib.LegacyTestClass.foobar', mock('stuff')):
            assert LegacyTestClass().foobar() == 'stuff'

    assert calls == []
Пример #4
0
def enable_aspectlib_maybe():                               # pragma: debugging
    """For debugging, we can use aspectlib to trace execution.

    Define COVERAGE_ASPECTLIB to enable and configure aspectlib to trace
    execution::

        $ export COVERAGE_LOG=covaspect.txt
        $ export COVERAGE_ASPECTLIB=coverage.Coverage:coverage.data.CoverageData
        $ coverage run blah.py ...

    This will trace all the public methods on Coverage and CoverageData,
    writing the information to covaspect.txt.

    """
    aspects = os.environ.get("COVERAGE_ASPECTLIB", "")
    if not aspects:
        return

    import aspectlib                            # pylint: disable=import-error
    import aspectlib.debug                      # pylint: disable=import-error

    filename = os.environ.get("COVERAGE_LOG", "/tmp/covlog.txt")
    filters = [add_pid_and_tid, filter_aspectlib_frames]
    aspects_file = DebugOutputFile.the_one(open(filename, "a"), show_process=True, filters=filters)
    aspect_log = aspectlib.debug.log(
        print_to=aspects_file, attributes=['id'], stacktrace=30, use_logging=False
    )
    public_methods = re.compile(r'^(__init__|[a-zA-Z].*)$')
    for aspect in aspects.split(':'):
        aspectlib.weave(aspect, aspect_log, methods=public_methods)
Пример #5
0
def enable_aspectlib_maybe():  # pragma: debugging
    """For debugging, we can use aspectlib to trace execution.

    Define COVERAGE_ASPECTLIB to enable and configure aspectlib to trace
    execution::

        $ export COVERAGE_LOG=covaspect.txt
        $ export COVERAGE_ASPECTLIB=coverage.Coverage:coverage.data.CoverageData
        $ coverage run blah.py ...

    This will trace all the public methods on Coverage and CoverageData,
    writing the information to covaspect.txt.

    """
    aspects = os.environ.get("COVERAGE_ASPECTLIB", "")
    if not aspects:
        return

    import aspectlib  # pylint: disable=import-error
    import aspectlib.debug  # pylint: disable=import-error

    aspects_file = DebugOutputFile.the_one()
    aspect_log = aspectlib.debug.log(print_to=aspects_file,
                                     attributes=['id'],
                                     stacktrace=30,
                                     use_logging=False)
    public_methods = re.compile(r'^(__init__|[a-zA-Z].*)$')
    for aspect in aspects.split(':'):
        aspectlib.weave(aspect, aspect_log, methods=public_methods)
Пример #6
0
def test_weave_class_old_style_all_magic():
    history = []

    @aspectlib.Aspect
    def aspect(*args):
        history.append(args)
        yield aspectlib.Proceed

    inst = LegacyTestClass()

    with aspectlib.weave(LegacyTestClass, aspect, subclasses=False):
        with aspectlib.weave(LegacyTestSubClass, aspect, subclasses=False):
            with aspectlib.weave(LegacyTestSubSubClass, aspect, subclasses=False):
                inst = LegacyTestClass("stuff")
                assert history == [(inst, "stuff"), (LegacyTestClass, "stuff"), ("stuff",)]
                del history[:]

                inst = LegacyTestSubClass("stuff")
                assert history == [(inst, "stuff"), (LegacyTestSubClass, "stuff"), ("stuff",)]
                del history[:]

                inst = LegacyTestSubSubClass("stuff")
                assert history == [(inst, "stuff"), (LegacyTestSubSubClass, "stuff"), ("stuff",)]
                del history[:]

    inst = LegacyTestClass("stuff")
    inst = LegacyTestSubClass("stuff")
    inst = LegacyTestSubSubClass("stuff")

    assert history == []
Пример #7
0
def main(template, target, no_input, checkout, verbose):
    if verbose:
        logging.basicConfig(format='%(levelname)s %(filename)s: %(message)s',
                            level=logging.DEBUG)
    else:
        logging.basicConfig(format='%(levelname)s: %(message)s',
                            level=logging.INFO)

    try:
        DEFAULT_CONFIG.setdefault('cookiecutter', {})
        src = os.path.join(target, '.cookiecutterrc')
        if os.path.exists(src):
            logger.info("Loading config from %r", src)
            extra_context = get_config(src)
            logger.debug("Loaded %r", extra_context)
            extra_context = extra_context.get(
                'cookiecutter') or extra_context.get('default_context')
            logger.debug("Loaded %r", extra_context)
        else:
            logger.info("No .cookiecutterrc in %r", target)
            extra_context = None

        with weave('cookiecutter.main.generate_files', save_context):
            with weave('cookiecutter.generate.rmtree', complain):
                cookiecutter(
                    template,
                    checkout,
                    no_input,
                    overwrite_if_exists=True,
                    output_dir=os.path.dirname(target),
                    extra_context=extra_context,
                )
    except (OutputDirExistsException, InvalidModeException) as e:
        click.echo(e)
        sys.exit(1)
Пример #8
0
def test_weave_wrong_module():
    calls = []
    with aspectlib.weave('warnings.warn', record(calls=calls)):
        aspectlib.weave(AliasedGlobal, mock('stuff'), lazy=True)
    assert calls == [(None, (
        "Setting test_aspectlib.MissingGlobal to <class 'test_aspectlib.MissingGlobal'>. "
        "There was no previous definition, probably patching the wrong module.",
    ), {})]
Пример #9
0
def test_list_of_aspects():
    with aspectlib.weave(module_func, [mock('foobar'), record]):
        assert module_func(1, 2, 3) == 'foobar'
        assert module_func.calls == [(None, (1, 2, 3), {})]

    with aspectlib.weave(module_func, [mock('foobar', call=True), record]):
        raises(TypeError, module_func, 1, 2, 3)
        assert module_func.calls == [(None, (1, 2, 3), {})]
def mop_for_crack_detection():
    @aspectlib.Aspect
    def load_files_aspect(*args):
        print("********** Load files aspect **********")
        m = args[0]
        path = m.TRAINING_PATH

        files_path = os.path.join(path, "Positive")
        remove_png_files_from_path(files_path)

        files_path = os.path.join(path, "Negative")
        remove_png_files_from_path(files_path)

        yield aspectlib.Proceed

    @aspectlib.Aspect
    def train_aspect(*args):
        print("********** Start training aspect **********")
        m = args[0]
        if m.train_datagen is None:
            print("Train datagen is null. Reload the files")
            m.load_training_dataset()
        if m.training_set is None:
            print("Train dataset is null. Reload the files")
            m.load_training_dataset()

        yield aspectlib.Proceed

    @aspectlib.Aspect
    def save_model_aspect(*args):
        print("********** Save model aspect **********")
        m = args[0]
        path = args[1]
        if not os.path.exists(path):
            print("The argument path is invalid. Save model to default path")
            default_path = "C:\Master\TAIP\MOP\models"
            m.save_model(default_path)
        yield aspectlib.Proceed

    with aspectlib.weave(CnnClassifier.load_training_dataset,
                         load_files_aspect,
                         subclasses=False):
        model = CnnClassifier()
        model.load_training_dataset()

    with aspectlib.weave(CnnClassifier.train, train_aspect, subclasses=False):
        model = CnnClassifier()
        # model.load_training_dataset()
        # model.train()

    with aspectlib.weave(CnnClassifier.save_model,
                         save_model_aspect,
                         subclasses=False):
        model = CnnClassifier()
        # model.load_training_dataset()
        model.save_model(SAVE_MODEL_PATH)
Пример #11
0
def test_weave_wrong_module():
    calls = []
    with aspectlib.weave('warnings.warn', record(calls=calls)):
        aspectlib.weave(AliasedGlobal, mock('stuff'), lazy=True)
    assert calls == [
        (None,
         ("Setting test_aspectlib.MissingGlobal to <class 'test_aspectlib.MissingGlobal'>. "
          "There was no previous definition, probably patching the wrong module.",),
         {})
    ]
Пример #12
0
def test_weave_class_all_magic():
    history = []

    @aspectlib.Aspect
    def aspect(*args):
        history.append(args)
        yield aspectlib.Proceed

    inst = NormalTestClass()

    with aspectlib.weave(NormalTestClass, aspect, methods=aspectlib.ALL_METHODS):
        inst = NormalTestClass("stuff")
        assert history == [(inst, "stuff"), (inst, "stuff"), (NormalTestClass, "stuff"), ("stuff",)]
        del history[:]

        inst = NormalTestSubClass("stuff")
        assert history == [(inst, "stuff"), (inst, "stuff"), (NormalTestSubClass, "stuff"), ("stuff",)]
        del history[:]

        inst = NormalTestSubSubClass("stuff")
        assert history == [(inst, "stuff"), (inst, "stuff"), (NormalTestSubSubClass, "stuff"), ("stuff",)]
        del history[:]

    inst = NormalTestClass("stuff")
    inst = NormalTestSubClass("stuff")
    inst = NormalTestSubSubClass("stuff")

    assert history == []
Пример #13
0
def test_weave_class_meth_no_aliases_unsupported_on_py3():
    with aspectlib.weave(Global.meth, mock('stuff')):
        assert Global().meth() == 'stuff'
        assert Global2().meth() == 'stuff'

    assert Global().meth() == 'base'
    assert Global2().meth() == 'base'
Пример #14
0
 def __enter__(self):
     self._rollback = weave(
         self._logger,
         record(callback=self._callback, extended=True, iscalled=True),
         methods='_log$'
     )
     return self
Пример #15
0
 def __enter__(self):
     self._rollback = weave(self._logger,
                            record(callback=self._callback,
                                   extended=True,
                                   iscalled=True),
                            methods='_log$')
     return self
Пример #16
0
def test_weave_str_class_meth_target():
    with aspectlib.weave('test_pkg1.test_pkg2.test_mod.Stuff.meth', mock('foobar')):
        from test_pkg1.test_pkg2.test_mod import Stuff
        assert Stuff().meth() == 'foobar'

    from test_pkg1.test_pkg2.test_mod import Stuff
    assert Stuff().meth() is None
Пример #17
0
def test_weave_str_target():
    with aspectlib.weave('test_pkg1.test_pkg2.test_mod.target', mock('foobar')):
        from test_pkg1.test_pkg2.test_mod import target
        assert target() == 'foobar'

    from test_pkg1.test_pkg2.test_mod import target
    assert target() is None
Пример #18
0
 def __enter__(self):
     self._rollback = weave(
         self._logger,
         record(callback=self._callback, extended=True, iscalled=True),
         methods=('debug', 'info', 'warning', 'error', 'exception', 'critical', 'log')
     )
     return self
Пример #19
0
def main(template, target, no_input, checkout, verbose):
    if verbose:
        logging.basicConfig(
            format='%(levelname)s %(filename)s: %(message)s',
            level=logging.DEBUG
        )
    else:
        logging.basicConfig(
            format='%(levelname)s: %(message)s',
            level=logging.INFO
        )

    try:
        src = os.path.join(target, '.cookiecutterrc')
        if os.path.exists(src):
            logger.info("Loading config from %r", src)
            extra_context = get_config(src)
            logger.debug("Loaded %r", extra_context)
            extra_context = extra_context.get('cookiecutter') or extra_context.get('default_context')
            logger.debug("Loaded %r", extra_context)
        else:
            logger.info("No .cookiecutterrc in %r", target)
            extra_context = None

        with weave('cookiecutter.main.generate_files', save_context):
            cookiecutter(
                template, checkout, no_input,
                overwrite_if_exists=True,
                output_dir=os.path.dirname(target),
                extra_context=extra_context,
            )
    except (OutputDirExistsException, InvalidModeException) as e:
        click.echo(e)
        sys.exit(1)
Пример #20
0
def test_weave_multiple():
    with aspectlib.weave((module_func, module_func2), mock('foobar')):
        assert module_func() == 'foobar'
        assert module_func2() == 'foobar'

    assert module_func() is None
    assert module_func2() is None
Пример #21
0
def test_weave_class_meth_no_aliases_unsupported_on_py3():
    with aspectlib.weave(Global.meth, mock("stuff")):
        assert Global().meth() == "stuff"
        assert Global2().meth() == "stuff"

    assert Global().meth() == "base"
    assert Global2().meth() == "base"
Пример #22
0
def upload_file():
    if request.method == 'POST':
        uploaded_files = request.files.getlist("files")
        if len(uploaded_files) == 1:
            if len(uploaded_files[0].filename) == 0:
                flash('No files selected!')
                return redirect(request.url)
        current_files = list()
        for file in uploaded_files:
            if os.path.splitext(file.filename)[1] == '.dcm':
                save_path = os.path.join(UPLOAD_FOLDER, file.filename)
                file.save(save_path)
                current_files.append(save_path)
        if len(current_files):
            # add logger aspect
            with aspectlib.weave(predict, model_log):
                any_prob, subtype, subtype_prob = predict(current_files)
            any_prob, subtype_prob = round(any_prob * 100,
                                           2), round(subtype_prob * 100, 2)
            for num, hemorrhageType in enumerate(HemorrhageTypes, start=0):
                if num == subtype:
                    subtype = hemorrhageType.value
                    break
            images = prepare_gallery(current_files)
            clean(current_files)
            print(any_prob, subtype, subtype_prob)
            return render_template('result.html',
                                   any_prob=any_prob,
                                   subtype=subtype,
                                   subtype_prob=subtype_prob,
                                   images=images)
        flash('No dcm files selected!')
        return redirect(request.url)
    return render_template('ihd.html')
Пример #23
0
def aop_svm():
    @aspectlib.Aspect
    def create_features(*args):
        print("********** Create a feature aspect **********")
        remove_png_files_from_path(OUTPUT_FOLDER)

        yield aspectlib.Proceed

    @aspectlib.Aspect
    def create_features_mop(*args):
        print("********** Create a mop features aspect **********")
        if args[1] is None:
            img_features = model.create_features(new_img, BLOCK_NORM)

        yield aspectlib.Proceed

    with aspectlib.weave(SVM.create_features, create_features, subclasses=False):
        model = SVM()

        img_array = image_to_array(IMG_PATH)
        print(img_array.shape)
        new_img = img_array[350:450, 0:100, :]

        Image.fromarray(new_img, mode='RGB').save('temp.jpg')

        plt.imshow(img_array)
        plt.imshow(new_img)
        plt.show()

        img_features = model.create_features(new_img, None)

    with aspectlib.weave(SVM.create_features, create_features_mop, subclasses=False):
        model = SVM()

        img_array = image_to_array(IMG_PATH)
        print(img_array.shape)
        new_img = img_array[350:450, 0:100, :]

        Image.fromarray(new_img, mode='RGB').save('temp.jpg')

        plt.imshow(img_array)
        plt.imshow(new_img)
        plt.show()

        img_features = model.create_features(new_img)

# aop_svm()
Пример #24
0
def test_simple():
    buf = StringIO()
    with aspectlib.weave(some_meth, aspectlib.debug.log(print_to=buf, module=False, stacktrace=10)):
        some_meth(1, 2, 3, a=4)

    assert re.match(LOG_TEST_SIMPLE, buf.getvalue())
    some_meth(1, 2, 3, a=4)
    assert re.match(LOG_TEST_SIMPLE, buf.getvalue())
Пример #25
0
 def __enter__(self):
     self._options.setdefault('methods', ALL_METHODS)
     self.__entanglement = weave(
         self._target,
         partial(self._FunctionWrapper, handle=self._handle),
         **self._options
     )
     return self
Пример #26
0
 def __enter__(self):
     self._options.setdefault('methods', ALL_METHODS)
     self.__entanglement = weave(
         self._target,
         partial(self._FunctionWrapper, handle=self._handle),
         **self._options
     )
     return self
Пример #27
0
def test_weave_class_meth_no_aliases():
    with aspectlib.weave(Global.meth, mock("stuff"), aliases=False, lazy=True):
        assert Global().meth() == "stuff"
        assert Global2 is not Global
        assert Global2().meth() == "base"

    assert Global().meth() == "base"
    assert Global2 is Global
    assert Global2().meth() == "base"
Пример #28
0
def weave_memoize():
    source = inspect.getsource(sys.modules['__main__'])
    # print(source)
    tree = ast.parse(source)

    for statement in tree.body:
        # print(statement)
        # for e in dir(statement):
        #     print(e)
        if isinstance(statement, ast.FunctionDef):
            weave('__main__.' + statement.name, memoize_aspect)
            # print(statement)
            # for e in dir(statement):
            #     print(e)
    

    # print("new src")
    # print(astor.to_source(tree))
Пример #29
0
def test_weave_str_target():
    with aspectlib.weave("test_pkg1.test_pkg2.test_mod.target", mock("foobar")):
        from test_pkg1.test_pkg2.test_mod import target

        assert target() == "foobar"

    from test_pkg1.test_pkg2.test_mod import target

    assert target() is None
Пример #30
0
def test_weave_class_no_aliases():
    with aspectlib.weave(Global, mock('stuff'), aliases=False, lazy=True):
        assert Global().meth() == 'stuff'
        assert Global2 is not Global
        assert Global2().meth() == 'base'

    assert Global().meth() == 'base'
    assert Global2 is Global
    assert Global2().meth() == 'base'
Пример #31
0
def test_weave_no_aliases():
    with aspectlib.weave(module_func2, mock('stuff'), aliases=False):
        assert module_func2() == 'stuff'
        assert module_func2 is not module_func3
        assert module_func3() is None

    assert module_func2() is None
    assert module_func3() is None
    assert module_func2 is module_func3
Пример #32
0
def test_weave_str_class_meth_target():
    with aspectlib.weave("test_pkg1.test_pkg2.test_mod.Stuff.meth", mock("foobar")):
        from test_pkg1.test_pkg2.test_mod import Stuff

        assert Stuff().meth() == "foobar"

    from test_pkg1.test_pkg2.test_mod import Stuff

    assert Stuff().meth() is None
Пример #33
0
def enable_aspectlib_maybe():                               # pragma: debugging
    """For debugging, we can use aspectlib to trace execution.

    Define COVERAGE_ASPECTLIB to enable and configure aspectlib to trace
    execution::

        COVERAGE_ASPECTLIB=covaspect.txt:coverage.Coverage:coverage.data.CoverageData program...

    This will trace all the public methods on Coverage and CoverageData,
    writing the information to covaspect.txt.

    """
    aspects = os.environ.get("COVERAGE_ASPECTLIB", "")
    if not aspects:
        return

    import aspectlib                            # pylint: disable=import-error
    import aspectlib.debug                      # pylint: disable=import-error

    class AspectlibOutputFile(object):
        """A file-like object that includes pid and cwd information."""
        def __init__(self, outfile):
            self.outfile = outfile
            self.cwd = None

        def write(self, text):
            """Just like file.write"""
            cwd = os.getcwd()
            if cwd != self.cwd:
                self._write("cwd is now {0!r}\n".format(cwd))
                self.cwd = cwd
            self._write(text)

        def _write(self, text):
            """The raw text-writer, so that we can use it ourselves."""
            self.outfile.write("{0:5d}: {1}".format(os.getpid(), text))

    aspects = aspects.split(':')
    aspects_file = AspectlibOutputFile(open(aspects[0], "a"))
    aspect_log = aspectlib.debug.log(print_to=aspects_file, use_logging=False)
    aspects = aspects[1:]
    public_methods = re.compile(r'^(__init__|[a-zA-Z].*)$')
    for aspect in aspects:
        aspectlib.weave(aspect, aspect_log, methods=public_methods)
Пример #34
0
def enable_aspectlib_maybe():
    """For debugging, we can use aspectlib to trace execution.

    Define COVERAGE_ASPECTLIB to enable and configure aspectlib to trace
    execution::

        COVERAGE_ASPECTLIB=covaspect.txt:coverage.Coverage:coverage.data.CoverageData program...

    This will trace all the public methods on Coverage and CoverageData,
    writing the information to covaspect.txt.

    """
    aspects = os.environ.get("COVERAGE_ASPECTLIB", "")
    if not aspects:
        return

    import aspectlib  # pylint: disable=import-error
    import aspectlib.debug  # pylint: disable=import-error

    class AspectlibOutputFile(object):
        """A file-like object that includes pid and cwd information."""
        def __init__(self, outfile):
            self.outfile = outfile
            self.cwd = None

        def write(self, text):
            """Just like file.write"""
            cwd = os.getcwd()
            if cwd != self.cwd:
                self._write("cwd is now {0!r}\n".format(cwd))
                self.cwd = cwd
            self._write(text)

        def _write(self, text):
            """The raw text-writer, so that we can use it ourselves."""
            self.outfile.write("{0:5d}: {1}".format(os.getpid(), text))

    aspects = aspects.split(':')
    aspects_file = AspectlibOutputFile(open(aspects[0], "a"))
    aspect_log = aspectlib.debug.log(print_to=aspects_file, use_logging=False)
    aspects = aspects[1:]
    public_methods = re.compile(r'^(__init__|[a-zA-Z].*)$')
    for aspect in aspects:
        aspectlib.weave(aspect, aspect_log, methods=public_methods)
Пример #35
0
def test_weave_class_old_style_all_magic():
    history = []

    @aspectlib.Aspect
    def aspect(*args):
        history.append(args)
        yield aspectlib.Proceed

    inst = LegacyTestClass()

    with aspectlib.weave(LegacyTestClass, aspect, subclasses=False):
        with aspectlib.weave(LegacyTestSubClass, aspect, subclasses=False):
            with aspectlib.weave(LegacyTestSubSubClass,
                                 aspect,
                                 subclasses=False):
                inst = LegacyTestClass('stuff')
                assert history == [
                    (inst, 'stuff'),
                    (LegacyTestClass, 'stuff'),
                    ('stuff', ),
                ]
                del history[:]

                inst = LegacyTestSubClass('stuff')
                assert history == [
                    (inst, 'stuff'),
                    (LegacyTestSubClass, 'stuff'),
                    ('stuff', ),
                ]
                del history[:]

                inst = LegacyTestSubSubClass('stuff')
                assert history == [
                    (inst, 'stuff'),
                    (LegacyTestSubSubClass, 'stuff'),
                    ('stuff', ),
                ]
                del history[:]

    inst = LegacyTestClass('stuff')
    inst = LegacyTestSubClass('stuff')
    inst = LegacyTestSubSubClass('stuff')

    assert history == []
Пример #36
0
def test_invalid_string_target():
    raises(SyntaxError, aspectlib.weave, "inva lid", mock(None))
    raises(SyntaxError, aspectlib.weave, "os.inva lid", mock(None))
    raises(SyntaxError, aspectlib.weave, "os.2invalid", mock(None))
    raises(SyntaxError, aspectlib.weave, "os.some,junk", mock(None))
    raises(SyntaxError, aspectlib.weave, "os.some?junk", mock(None))
    raises(SyntaxError, aspectlib.weave, "os.some*junk", mock(None))

    with aspectlib.weave("test_aspectlib._internal", mock("stuff")):
        assert _internal() == "stuff"
Пример #37
0
def test_invalid_string_target():
    raises(SyntaxError, aspectlib.weave, 'inva lid', mock(None))
    raises(SyntaxError, aspectlib.weave, 'os.inva lid', mock(None))
    raises(SyntaxError, aspectlib.weave, 'os.2invalid', mock(None))
    raises(SyntaxError, aspectlib.weave, 'os.some,junk', mock(None))
    raises(SyntaxError, aspectlib.weave, 'os.some?junk', mock(None))
    raises(SyntaxError, aspectlib.weave, 'os.some*junk', mock(None))

    with aspectlib.weave('test_aspectlib._internal', mock('stuff')):
        assert _internal() == 'stuff'
Пример #38
0
def test_no_stack():
    buf = StringIO()
    with aspectlib.weave(MyStuff, aspectlib.debug.log(
        print_to=buf,
        stacktrace=None,
        attributes=('foo', 'bar()')
    ), methods='(?!bar)(?!__.*__$)'):
        MyStuff('bar').stuff()
    print(buf.getvalue())
    assert "{test_aspectlib_debug.MyStuff foo='bar' bar='foo'}.stuff()\n{test_aspectlib_debug.MyStuff foo='bar' bar='foo'}.stuff => bar\n" == buf.getvalue()
Пример #39
0
def test_weave_module(strmod=None):
    calls = []
    from test_pkg1.test_pkg2 import test_mod
    with aspectlib.weave(strmod or test_mod, record(calls=calls,
                                                    extended=True)):
        test_mod.target()
        obj = test_mod.Stuff()
        obj.meth()
    assert calls == [(None, 'test_pkg1.test_pkg2.test_mod.target', (), {}),
                     (obj, 'test_pkg1.test_pkg2.test_mod.meth', (), {})]
Пример #40
0
def test_socket_all_methods():
    buf = StringIO()
    with aspectlib.weave(
        socket.socket,
        aspectlib.debug.log(print_to=buf, stacktrace=False),
        lazy=True,
        methods=aspectlib.ALL_METHODS
    ):
        s = socket.socket()

    assert "}.__init__ => None" in buf.getvalue()
Пример #41
0
def test_weave_os_module():
    calls = []

    with aspectlib.weave('os', record(calls=calls, extended=True), methods="getenv|walk"):
        os.getenv('BUBU', 'bubu')
        os.walk('.')

    assert calls == [
        (None, 'os.getenv', ('BUBU', 'bubu'), {}),
        (None, 'os.walk', ('.',), {})
    ]
Пример #42
0
def test_fork():
    with aspectlib.weave('os.fork', mock('foobar')):
        pid = os.fork()
        if not pid:
            os._exit(0)
        assert pid == 'foobar'

    pid = os.fork()
    if not pid:
        os._exit(0)
    assert pid != 'foobar'
Пример #43
0
def test_socket_meth(meth=socket.socket.close):
    calls = []
    with aspectlib.weave(meth, record(calls=calls)):
        s = socket.socket()
        assert s.close() is None
    assert calls == [(s, (), {})]
    del calls[:]

    s = socket.socket()
    assert s.close() is None
    assert calls == []
Пример #44
0
def test_weave_module(strmod=None):
    calls = []
    from test_pkg1.test_pkg2 import test_mod
    with aspectlib.weave(strmod or test_mod, record(calls=calls, extended=True)):
        test_mod.target()
        obj = test_mod.Stuff()
        obj.meth()
    assert calls == [
        (None, 'test_pkg1.test_pkg2.test_mod.target', (), {}),
        (obj, 'test_pkg1.test_pkg2.test_mod.meth', (), {})
    ]
Пример #45
0
def test_attributes():
    buf = StringIO()
    with aspectlib.weave(MyStuff, aspectlib.debug.log(
        print_to=buf,
        stacktrace=10,
        attributes=('foo', 'bar()')
    ), methods='(?!bar)(?!__.*__$)'):
        MyStuff('bar').stuff()
    print(buf.getvalue())
    assert re.match(r"^\{test_aspectlib_debug.MyStuff foo='bar' bar='foo'\}.stuff\(\) +<<< .*tests/test_aspectlib_debug.py:\d+:test_attributes.*\n\{test_aspectlib_debug.MyStuff foo='bar' bar='foo'\}.stuff => bar\n$", buf.getvalue())
    MyStuff('bar').stuff()
    assert re.match(r"^\{test_aspectlib_debug.MyStuff foo='bar' bar='foo'\}.stuff\(\) +<<< .*tests/test_aspectlib_debug.py:\d+:test_attributes.*\n\{test_aspectlib_debug.MyStuff foo='bar' bar='foo'\}.stuff => bar\n$", buf.getvalue())