Exemple #1
0
def test_inline_cursor(calc):
    monkeypatch().setattr(config, 'IMAGES_ROOT', os.path.join(config.PROJECT_ROOT, 'tests/files/cursors'))
    
    f = open(os.path.join(config.PROJECT_ROOT, 'tests/files/cursors/fake.base64.txt'), 'rb')
    font_base64 = f.read()
    f.close()
    assert 'url(data:image/cur;base64,%s)' % font_base64 == calc('inline_image("/fake.cur")').render()
Exemple #2
0
def test_inline_cursor(calc):
    monkeypatch().setattr(config, 'IMAGES_ROOT', os.path.join(config.PROJECT_ROOT, 'tests/files/cursors'))

    f = open(os.path.join(config.PROJECT_ROOT, 'tests/files/cursors/fake.base64.txt'), 'rb')
    font_base64 = f.read()
    f.close()
    assert 'url(data:image/cur;base64,%s)' % font_base64 == calc('inline_image("/fake.cur")').render()
Exemple #3
0
    def is_called(self, method, test_func, *args, **kwargs):
        from _pytest.monkeypatch import monkeypatch

        def called_func(*args, **kwargs):
            self.called[method] = True
        self.called[method] = False
        monkeypatch().setattr(method, called_func)
        test_func(*args, **kwargs)
        return self.called[method]
Exemple #4
0
def monkeypatch_sess(request):
    """Like `monkeypatch` fixture, but for sessions.
    """
    from _pytest import monkeypatch
    if pytest.__version__ < "3":
        mpatch = monkeypatch.monkeypatch()
    else:
        mpatch = monkeypatch.monkeypatch(request)
    request.addfinalizer(mpatch.undo)
    return mpatch
Exemple #5
0
def monkeypatch_sess(request):
    """Like `monkeypatch` fixture, but for sessions.
    """
    from _pytest import monkeypatch
    if pytest.__version__ < "3":
        mpatch = monkeypatch.monkeypatch()
    else:
        mpatch = monkeypatch.monkeypatch(request)
    request.addfinalizer(mpatch.undo)
    return mpatch
Exemple #6
0
def test_inline_font_files(calc):
    """
    @author: funvit
    @note: adapted from  compass / test / units / sass_extensions_test.rb
    """
    monkeypatch().setattr(config, 'FONTS_ROOT', os.path.join(config.PROJECT_ROOT, 'tests/files/fonts'))

    with open(os.path.join(config.PROJECT_ROOT, 'tests/files/fonts/bgrove.base64.txt'), 'r') as f:
        font_base64 = ''.join((f.readlines()))

    assert 'url(data:font/truetype;base64,%s) format("truetype")' % font_base64 == calc('inline_font_files("/bgrove.ttf", truetype)').render()
Exemple #7
0
def test_inline_image(calc):
    monkeypatch().setattr(
        config, 'IMAGES_ROOT',
        os.path.join(config.PROJECT_ROOT, 'tests/files/images'))

    with open(
            os.path.join(config.PROJECT_ROOT,
                         'tests/files/images/test-qr.base64.txt'), 'r') as f:
        font_base64 = f.read()
    assert 'url(data:image/png;base64,%s)' % font_base64 == calc(
        'inline_image("/test-qr.png")').render()
Exemple #8
0
def pytest_configure(config):
    mode = config.getvalue("assertmode")
    if config.getvalue("noassert") or config.getvalue("nomagic"):
        mode = "plain"
    if mode == "rewrite":
        try:
            import ast
        except ImportError:
            mode = "reinterp"
        else:
            if sys.platform.startswith('java'):
                mode = "reinterp"
    if mode != "plain":
        _load_modules(mode)
        m = monkeypatch()
        config._cleanup.append(m.undo)
        m.setattr(py.builtin.builtins, 'AssertionError',
                  reinterpret.AssertionError)
    hook = None
    if mode == "rewrite":
        hook = rewrite.AssertionRewritingHook()
        sys.meta_path.insert(0, hook)
    warn_about_missing_assertion(mode)
    config._assertstate = AssertionState(config, mode)
    config._assertstate.hook = hook
    config._assertstate.trace("configured with mode set to %r" % (mode, ))
def pytest_configure(config):
    mode = config.getvalue("assertmode")
    if config.getvalue("noassert") or config.getvalue("nomagic"):
        mode = "plain"
    if mode == "rewrite":
        try:
            import ast
        except ImportError:
            mode = "reinterp"
        else:
            # Both Jython and CPython 2.6.0 have AST bugs that make the
            # assertion rewriting hook malfunction.
            if (sys.platform.startswith('java') or
                sys.version_info[:3] == (2, 6, 0)):
                mode = "reinterp"
    if mode != "plain":
        _load_modules(mode)
        m = monkeypatch()
        config._cleanup.append(m.undo)
        m.setattr(py.builtin.builtins, 'AssertionError',
                  reinterpret.AssertionError)
    hook = None
    if mode == "rewrite":
        hook = rewrite.AssertionRewritingHook()
        sys.meta_path.insert(0, hook)
    warn_about_missing_assertion(mode)
    config._assertstate = AssertionState(config, mode)
    config._assertstate.hook = hook
    config._assertstate.trace("configured with mode set to %r" % (mode,))
Exemple #10
0
 def getfuncargvalue(self, argname):
     """ Retrieve a function argument by name for this test
     function invocation.  This allows one function argument factory
     to call another function argument factory.  If there are two
     funcarg factories for the same test function argument the first
     factory may use ``getfuncargvalue`` to call the second one and
     do something additional with the resource.
     """
     try:
         return self._funcargs[argname]
     except KeyError:
         pass
     if argname not in self._name2factory:
         self._name2factory[argname] = self.config.pluginmanager.listattr(
                 plugins=self._plugins,
                 attrname=self._argprefix + str(argname)
         )
     #else: we are called recursively
     if not self._name2factory[argname]:
         self._raiselookupfailed(argname)
     funcargfactory = self._name2factory[argname].pop()
     oldarg = self._currentarg
     mp = monkeypatch()
     mp.setattr(self, '_currentarg', argname)
     try:
         param = self._pyfuncitem.callspec.getparam(argname)
     except (AttributeError, ValueError):
         pass
     else:
         mp.setattr(self, 'param', param, raising=False)
     try:
         self._funcargs[argname] = res = funcargfactory(request=self)
     finally:
         mp.undo()
     return res
    def setup(self):
        from _pytest.monkeypatch import monkeypatch
        patch = monkeypatch()
        patch.setattr('pymongo.MongoClient', mongomock.MongoClient)

        from helga_karma import plugin
        self.plugin = plugin
Exemple #12
0
 def _prepare(self):
     self.counters = {}
     basename = None
     cli_tempdir_basename = self.config.getvalue('tempdir_basename')
     if cli_tempdir_basename is not None:
         basename = cli_tempdir_basename
     else:
         # Let's see if we have a pytest_tempdir_basename hook implementation
         basename = self.config.hook.pytest_tempdir_basename()
     if basename is None:
         # If by now, basename is still None, use the current directory name
         basename = os.path.basename(py.path.local().strpath)  # pylint: disable=no-member
     mpatch = monkeypatch()
     temproot = py.path.local.get_temproot()  # pylint: disable=no-member
     # Let's get the full real path to the tempdir
     tempdir = temproot.join(basename).realpath()
     if tempdir.exists():
         # If it exists, it's a stale tempdir. Remove it
         log.warning('Removing stale tempdir: %s', tempdir.strpath)
         tempdir.remove(rec=True, ignore_errors=True)
     # Make sure the tempdir is created
     tempdir.ensure(dir=True)
     # Store a reference the tempdir for cleanup purposes when ending the test
     # session
     mpatch.setattr(self.config, '_tempdir', self, raising=False)
     # Register the cleanup actions
     self.config._cleanup.extend([mpatch.undo, self._clean_up_tempdir])
     self.tempdir = tempdir
Exemple #13
0
def pytest_configure(config):
    mode = config.getvalue("assertmode")
    if config.getvalue("noassert") or config.getvalue("nomagic"):
        mode = "plain"
    if mode == "rewrite":
        try:
            import ast  # noqa
        except ImportError:
            mode = "reinterp"
        else:
            # Both Jython and CPython 2.6.0 have AST bugs that make the
            # assertion rewriting hook malfunction.
            if (sys.platform.startswith('java')
                    or sys.version_info[:3] == (2, 6, 0)):
                mode = "reinterp"
    if mode != "plain":
        _load_modules(mode)
        m = monkeypatch()
        config._cleanup.append(m.undo)
        m.setattr(py.builtin.builtins, 'AssertionError',
                  reinterpret.AssertionError)  # noqa
    hook = None
    if mode == "rewrite":
        hook = rewrite.AssertionRewritingHook()  # noqa
        sys.meta_path.insert(0, hook)
    warn_about_missing_assertion(mode)
    config._assertstate = AssertionState(config, mode)
    config._assertstate.hook = hook
    config._assertstate.trace("configured with mode set to %r" % (mode, ))
Exemple #14
0
def setup():
    mp = monkeypatch()
    mp.setattr(
        client,
        '_make_authenticated_request',
        fake_make_authenticated_request
    )
Exemple #15
0
def pytest_configure(config):
    warn_about_missing_assertion()
    mode = config.getvalue("assertmode")
    if config.getvalue("noassert") or config.getvalue("nomagic"):
        if mode not in ("off", "default"):
            raise pytest.UsageError("assertion options conflict")
        mode = "off"
    elif mode == "default":
        mode = "on"
    if mode != "off":
        def callbinrepr(op, left, right):
            hook_result = config.hook.pytest_assertrepr_compare(
                config=config, op=op, left=left, right=right)
            for new_expl in hook_result:
                if new_expl:
                    return '\n~'.join(new_expl)
        m = monkeypatch()
        config._cleanup.append(m.undo)
        m.setattr(py.builtin.builtins, 'AssertionError',
                  reinterpret.AssertionError)
        m.setattr(util, '_reprcompare', callbinrepr)
    if mode == "on" and rewrite_asserts is None:
        mode = "old"
    config._assertstate = AssertionState(config, mode)
    config._assertstate.trace("configured with mode set to %r" % (mode,))
Exemple #16
0
def pytest_funcarg__mock_ia(request):
    """py.test funcarg to mock openlibrary.core.ia module.

        from openlibrary.core import ia

        def test_ia(mock_ia):
            assert ia.get_meta_xml("foo") == {}

            mock_ia.set_meta_xml("foo", {"collection": ["a", "b"]})
            assert ia.get_meta_xml("foo") == {"collection": ["a", "b"]}
    """
    m = monkeypatch()
    request.addfinalizer(m.undo)

    metaxml = {}

    class IA:
        def set_meta_xml(self, itemid, meta):
            metaxml[itemid] = meta

        def get_meta_xml(self, itemid):
            return metaxml.get(itemid, {})

    mock_ia = IA()
    m.setattr(ia, "get_meta_xml", ia.get_meta_xml)

    return mock_ia
Exemple #17
0
def pytest_configure(config):
    mode = config.getvalue("assertmode")
    if config.getvalue("noassert") or config.getvalue("nomagic"):
        mode = "plain"
    if mode == "rewrite":
        try:
            import ast
        except ImportError:
            mode = "reinterp"
        else:
            if sys.platform.startswith('java'):
                mode = "reinterp"
    if mode != "plain":
        _load_modules(mode)
        m = monkeypatch()
        config._cleanup.append(m.undo)
        m.setattr(py.builtin.builtins, 'AssertionError',
                  reinterpret.AssertionError)
    hook = None
    if mode == "rewrite":
        hook = rewrite.AssertionRewritingHook()
        sys.meta_path.insert(0, hook)
    warn_about_missing_assertion(mode)
    config._assertstate = AssertionState(config, mode)
    config._assertstate.hook = hook
    config._assertstate.trace("configured with mode set to %r" % (mode,))
Exemple #18
0
    def _get_test_ccu(self, API):
        self._monkeypatch = monkeypatch()
        self._monkeypatch.setattr(pmatic.api, 'init', lambda: None)

        ccu = pmatic.CCU()
        ccu.api = API
        return ccu
Exemple #19
0
 def getfuncargvalue(self, argname):
     """ Retrieve a function argument by name for this test
     function invocation.  This allows one function argument factory
     to call another function argument factory.  If there are two
     funcarg factories for the same test function argument the first
     factory may use ``getfuncargvalue`` to call the second one and
     do something additional with the resource.
     """
     try:
         return self._funcargs[argname]
     except KeyError:
         pass
     if argname not in self._name2factory:
         self._name2factory[argname] = self.config.pluginmanager.listattr(
                 plugins=self._plugins,
                 attrname=self._argprefix + str(argname)
         )
     #else: we are called recursively
     if not self._name2factory[argname]:
         self._raiselookupfailed(argname)
     funcargfactory = self._name2factory[argname].pop()
     oldarg = self._currentarg
     mp = monkeypatch()
     mp.setattr(self, '_currentarg', argname)
     try:
         param = self._pyfuncitem.callspec.getparam(argname)
     except (AttributeError, ValueError):
         pass
     else:
         mp.setattr(self, 'param', param, raising=False)
     try:
         self._funcargs[argname] = res = funcargfactory(request=self)
     finally:
         mp.undo()
     return res
Exemple #20
0
def pytest_funcarg__mock_ia(request):
    """py.test funcarg to mock openlibrary.core.ia module.

        from openlibrary.core import ia

        def test_ia(mock_ia):
            assert ia.get_meta_xml("foo") == {}

            mock_ia.set_meta_xml("foo", {"collection": ["a", "b"]})
            assert ia.get_meta_xml("foo") == {"collection": ["a", "b"]}
    """
    m = monkeypatch()
    request.addfinalizer(m.undo)

    metaxml = {}

    class IA:
        def set_meta_xml(self, itemid, meta):
            metaxml[itemid] = meta

        def get_meta_xml(self, itemid):
            return metaxml.get(itemid, {})

    mock_ia = IA()
    m.setattr(ia, "get_meta_xml", ia.get_meta_xml)

    return mock_ia
Exemple #21
0
    def _get_test_ccu(self, API):
        self._monkeypatch = monkeypatch()
        self._monkeypatch.setattr(pmatic.api, 'init', lambda: None)

        ccu = pmatic.CCU()
        ccu.api = API
        return ccu
Exemple #22
0
def pytest_configure(config):
    warn_about_missing_assertion()
    mode = config.getvalue("assertmode")
    if config.getvalue("noassert") or config.getvalue("nomagic"):
        if mode not in ("off", "default"):
            raise pytest.UsageError("assertion options conflict")
        mode = "off"
    elif mode == "default":
        mode = "on"
    if mode != "off":

        def callbinrepr(op, left, right):
            hook_result = config.hook.pytest_assertrepr_compare(config=config,
                                                                op=op,
                                                                left=left,
                                                                right=right)
            for new_expl in hook_result:
                if new_expl:
                    return '\n~'.join(new_expl)

        m = monkeypatch()
        config._cleanup.append(m.undo)
        m.setattr(py.builtin.builtins, 'AssertionError',
                  reinterpret.AssertionError)
        m.setattr(util, '_reprcompare', callbinrepr)
    if mode == "on" and rewrite_asserts is None:
        mode = "old"
    config._assertstate = AssertionState(config, mode)
    config._assertstate.trace("configured with mode set to %r" % (mode, ))
Exemple #23
0
def install_pytest_asserts():
    try:
        import ast  # noqa
    except ImportError as e:
        print('Can not use py.test asserts - import ast failed!')
        return
    else:
        # Both Jython and CPython 2.6.0 have AST bugs that make the
        # assertion rewriting hook malfunction.
        if (sys.platform.startswith('java')
                or sys.version_info[:3] == (2, 6, 0)):
            print(
                'Can not use py.test asserts - no compatible python interpreter'
            )
            return

    from _pytest.assertion import reinterpret  # noqa
    from _pytest.assertion import rewrite  # noqa

    m = monkeypatch()
    m.setattr(py.builtin.builtins, 'AssertionError',
              reinterpret.AssertionError)  # noqa

    hook = rewrite.AssertionRewritingHook()  # noqa
    sys.meta_path.insert(0, hook)
Exemple #24
0
    def setup(self):
        from _pytest.monkeypatch import monkeypatch
        patch = monkeypatch()
        patch.setattr('pymongo.MongoClient', mongomock.MongoClient)

        from helga_karma.data import KarmaRecord
        from helga.db import db
        self.KarmaRecord = KarmaRecord
        self.db = db
Exemple #25
0
def pytest_configure(config):
    """Create a TempdirFactory and attach it to the config object.

    This is to comply with existing plugins which expect the handler to be
    available at pytest_configure time, but ideally should be moved entirely
    to the tmpdir_factory session fixture.
    """
    mp = monkeypatch()
    t = TempdirFactory(config)
    config._cleanup.extend([mp.undo, t.finish])
    mp.setattr(config, '_tmpdirhandler', t, raising=False)
    mp.setattr(pytest, 'ensuretemp', t.ensuretemp, raising=False)
Exemple #26
0
def mock_build_commands(request):
    from upaas.commands import execute as real_execute

    def mock_execute(cmd, *args, **kwargs):
        executable = cmd.split(' ')[0]
        if executable in ['git', 'chown', 'gem', 'rake', 'bundle']:
            return 0, []
        else:
            return real_execute(cmd, *args, **kwargs)

    mpatch = monkeypatch()
    mpatch.setattr('upaas.commands.execute', mock_execute)
    request.addfinalizer(mpatch.undo)
Exemple #27
0
def mock_build_commands(request):
    from upaas.commands import execute as real_execute

    def mock_execute(cmd, *args, **kwargs):
        executable = cmd.split(" ")[0]
        if executable in ["git", "chown", "gem", "rake", "bundle"]:
            return 0, []
        else:
            return real_execute(cmd, *args, **kwargs)

    mpatch = monkeypatch()
    mpatch.setattr("upaas.commands.execute", mock_execute)
    request.addfinalizer(mpatch.undo)
    def pytest_configure(self, config):
        if not config.getoption('ast_as_python'):
            return

        mp = monkeypatch()
        mp.setattr('_pytest.assertion.rewrite.rewrite_asserts',
                   make_replacement_rewrite_asserts(self.store))

        # written pyc files will bypass our patch, so disable reading them
        mp.setattr('_pytest.assertion.rewrite._read_pyc',
                   lambda source, pyc, trace=None: None)

        config._cleanup.append(mp.undo)
Exemple #29
0
def mock_chroot(request):
    class MockChroot(object):
        def __init__(self, *args, **kwargs):
            pass

        def __enter__(self):
            pass

        def __exit__(self, type, value, traceback):
            pass

    mpatch = monkeypatch()
    mpatch.setattr('upaas.chroot.Chroot', MockChroot)
    mpatch.setattr('upaas.builder.builder.Chroot', MockChroot)
    request.addfinalizer(mpatch.undo)
Exemple #30
0
    def test_u2f_valid(self):
        m = monkeypatch.monkeypatch()
        m.setattr("u2flib_server.u2f.verify_authenticate", lambda *args, **kwargs: True)
        m.setattr("u2flib_server.u2f.start_authenticate",
                  lambda *args, **kwargs: JSONDict({'authenticateRequests': []}))
        d = U2FDevice.objects.create(user=self.user, name='test', json_data="{}")

        response = self.client.get('/control/login/2fa')
        assert 'token' in response.rendered_content
        response = self.client.post('/control/login/2fa'.format(d.pk), {
            'token': '{"response": "true"}'
        })
        self.assertEqual(response.status_code, 302)
        self.assertIn('/control/', response['Location'])

        m.undo()
Exemple #31
0
def pytest_configure(config):
    # The _pytesthook attribute on the AssertionError is used by
    # py._code._assertionnew to detect this plugin was loaded and in
    # turn call the hooks defined here as part of the
    # DebugInterpreter.
    config._monkeypatch = m = monkeypatch()
    if not config.getvalue("noassert") and not config.getvalue("nomagic"):
        warn_about_missing_assertion()
        def callbinrepr(op, left, right):
            hook_result = config.hook.pytest_assertrepr_compare(
                config=config, op=op, left=left, right=right)
            for new_expl in hook_result:
                if new_expl:
                    return '\n~'.join(new_expl)
        m.setattr(py.builtin.builtins,
                  'AssertionError', py.code._AssertionError)
        m.setattr(py.code, '_reprcompare', callbinrepr)
Exemple #32
0
    def test_u2f_valid(self):
        m = monkeypatch.monkeypatch()
        m.setattr("u2flib_server.u2f.verify_authenticate",
                  lambda *args, **kwargs: True)
        m.setattr(
            "u2flib_server.u2f.start_authenticate",
            lambda *args, **kwargs: JSONDict({'authenticateRequests': []}))
        d = U2FDevice.objects.create(user=self.user,
                                     name='test',
                                     json_data="{}")

        response = self.client.get('/control/login/2fa')
        assert 'token' in response.rendered_content
        response = self.client.post('/control/login/2fa'.format(d.pk),
                                    {'token': '{"response": "true"}'})
        self.assertEqual(response.status_code, 302)
        self.assertIn('/control/', response['Location'])

        m.undo()
Exemple #33
0
    def API(self, request):
        self._monkeypatch = monkeypatch()
        if not is_testing_with_real_ccu():
            # First hook into urlopen to fake the HTTP responses
            self._monkeypatch.setattr(pmatic.api, 'urlopen', fake_urlopen)
        else:
            # When executed with real ccu we wrap urlopen for enabling recording
            self._monkeypatch.setattr(pmatic.api, 'urlopen', wrap_urlopen)

        API = pmatic.api.RemoteAPI(
            address="http://192.168.1.26",
            credentials=("Admin", "EPIC-SECRET-PW"),
            connect_timeout=5,
            #log_level=pmatic.DEBUG,
        )

        request.addfinalizer(API.close)

        return API
Exemple #34
0
    def API(self, request):
        self._monkeypatch = monkeypatch()
        if not is_testing_with_real_ccu():
            # First hook into urlopen to fake the HTTP responses
            self._monkeypatch.setattr(pmatic.api, 'urlopen', fake_urlopen)
        else:
            # When executed with real ccu we wrap urlopen for enabling recording
            self._monkeypatch.setattr(pmatic.api, 'urlopen', wrap_urlopen)

        API = pmatic.api.RemoteAPI(
            address="http://192.168.1.26",
            credentials=("Admin", "EPIC-SECRET-PW"),
            connect_timeout=5,
            #log_level=pmatic.DEBUG,
        )

        request.addfinalizer(API.close)

        return API
Exemple #35
0
    def test_confirm_u2f_success(self):
        with mocker_context() as mocker:
            mocker.patch('django.http.request.HttpRequest.is_secure')
            self.client.post('/control/settings/2fa/add', {
                'devicetype': 'u2f',
                'name': 'Foo'
            }, follow=True)

        m = monkeypatch.monkeypatch()
        m.setattr("u2flib_server.u2f.complete_register", lambda *args, **kwargs: (JSONDict({}), None))

        d = U2FDevice.objects.first()
        r = self.client.post('/control/settings/2fa/u2f/{}/confirm'.format(d.pk), {
            'token': 'FOO'
        }, follow=True)
        d.refresh_from_db()
        assert d.confirmed
        assert 'alert-success' in r.rendered_content

        m.undo()
Exemple #36
0
def pytest_funcarg__mock_memcache(request):
    """This patches all the existing memcache connections to use mock memcache instance.
    """
    m = monkeypatch()
    request.addfinalizer(m.undo)
    
    mock_memcache = Client()
    
    
    def proxy(name):
        method = getattr(mock_memcache, name)
        def f(self, *a, **kw):
            return method(*a, **kw)
        return f
    
    m.setattr(memcache.Client, "get", proxy("get"))
    m.setattr(memcache.Client, "set", proxy("set"))
    m.setattr(memcache.Client, "add", proxy("add"))
    
    return mock_memcache
Exemple #37
0
def pytest_configure(config):
    # The _pytesthook attribute on the AssertionError is used by
    # py._code._assertionnew to detect this plugin was loaded and in
    # turn call the hooks defined here as part of the
    # DebugInterpreter.
    config._monkeypatch = m = monkeypatch()
    if not config.getvalue("noassert") and not config.getvalue("nomagic"):
        warn_about_missing_assertion()

        def callbinrepr(op, left, right):
            hook_result = config.hook.pytest_assertrepr_compare(config=config,
                                                                op=op,
                                                                left=left,
                                                                right=right)
            for new_expl in hook_result:
                if new_expl:
                    return '\n~'.join(new_expl)

        m.setattr(py.builtin.builtins, 'AssertionError',
                  py.code._AssertionError)
        m.setattr(py.code, '_reprcompare', callbinrepr)
Exemple #38
0
def pytest_funcarg__mock_memcache(request):
    """This patches all the existing memcache connections to use mock memcache instance.
    """
    m = monkeypatch()
    request.addfinalizer(m.undo)

    mock_memcache = Client()

    def proxy(name):
        method = getattr(mock_memcache, name)

        def f(self, *a, **kw):
            return method(*a, **kw)

        return f

    m.setattr(memcache.Client, "get", proxy("get"))
    m.setattr(memcache.Client, "set", proxy("set"))
    m.setattr(memcache.Client, "add", proxy("add"))

    return mock_memcache
Exemple #39
0
    def test_confirm_u2f_success(self):
        with mocker_context() as mocker:
            mocker.patch('django.http.request.HttpRequest.is_secure')
            self.client.post('/control/settings/2fa/add', {
                'devicetype': 'u2f',
                'name': 'Foo'
            },
                             follow=True)

        m = monkeypatch.monkeypatch()
        m.setattr("u2flib_server.u2f.complete_register",
                  lambda *args, **kwargs: (JSONDict({}), None))

        d = U2FDevice.objects.first()
        r = self.client.post('/control/settings/2fa/u2f/{}/confirm'.format(
            d.pk), {'token': 'FOO'},
                             follow=True)
        d.refresh_from_db()
        assert d.confirmed
        assert 'alert-success' in r.rendered_content

        m.undo()
Exemple #40
0
def install_pytest_asserts():
    try:
        import ast  # noqa
    except ImportError as e:
        print('Can not use py.test asserts - import ast failed!')
        return
    else:
        # Both Jython and CPython 2.6.0 have AST bugs that make the
        # assertion rewriting hook malfunction.
        if (sys.platform.startswith('java') or
                sys.version_info[:3] == (2, 6, 0)):
            print('Can not use py.test asserts - no compatible python interpreter')
            return

    from _pytest.assertion import reinterpret  # noqa
    from _pytest.assertion import rewrite  # noqa

    m = monkeypatch()
    m.setattr(py.builtin.builtins, 'AssertionError',
              reinterpret.AssertionError)  # noqa

    hook = rewrite.AssertionRewritingHook()  # noqa
    sys.meta_path.insert(0, hook)
 def __init__(self, fake_call_impl_any):
     self.fake_call_impl_any = fake_call_impl_any
     self.monkey = monkeypatch()
Exemple #42
0
from _pytest.monkeypatch import monkeypatch

from selvpcclient.httpclient import HTTPClient

monkeypatch().setenv("SEL_URL", "http://api")
client = HTTPClient(base_url="http://api/v2", headers={})
Exemple #43
0
 def __init__(self, tty=True):
     self.monkey = monkeypatch()
     self.tty = tty
     self.output = []
Exemple #44
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2014 Evernote Corporation
#
# This file is part of Pootle.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
"""Monkeypatching fixtures."""


# HACKISH: monkeypatching decorator here, should be cleaner to do it in a
# fixture, but pytest's `monkeypatch` decorator is function-scoped, and by
# the time it's run the decorators have already been applied to the
# functions, therefore the patching has no effect
from _pytest.monkeypatch import monkeypatch

mp = monkeypatch()
mp.setattr('pootle_misc.util.cached_property', property)
Exemple #45
0
 def setUp(self):
     self.m = monkeypatch()
Exemple #46
0
def monkeypatch_session(request):
    mp = monkeypatch(request)
    request.addfinalizer(mp.undo)
    return mp
Exemple #47
0
def pytest_configure(config):
    config._mp = mp = monkeypatch()
    t = TempdirHandler(config)
    mp.setattr(config, '_tmpdirhandler', t, raising=False)
    mp.setattr(pytest, 'ensuretemp', t.ensuretemp, raising=False)
Exemple #48
0
def pytest_configure(config):
    mp = monkeypatch()
    t = TempdirHandler(config)
    config._cleanup.extend([mp.undo, t.finish])
    mp.setattr(config, '_tmpdirhandler', t, raising=False)
    mp.setattr(pytest, 'ensuretemp', t.ensuretemp, raising=False)
Exemple #49
0
def pytest_configure(config):
    mp = monkeypatch()
    t = TempdirHandler(config)
    config._cleanup.extend([mp.undo, t.finish])
    mp.setattr(config, '_tmpdirhandler', t, raising=False)
    mp.setattr(pytest, 'ensuretemp', t.ensuretemp, raising=False)
Exemple #50
0
 def __init__(self, tty=True):
     self.monkey = monkeypatch()
     self.tty = tty
     self.output = []
Exemple #51
0
import json

import mock
from selvpcclient.client import Client
from selvpcclient.shell import CLI

from _pytest.monkeypatch import monkeypatch

monkeypatch().setenv("SEL_URL", "http://selvpcapi")
monkeypatch().setenv("SEL_TOKEN", "5ba50055-ff2e-4145-a8cf-f03e9fbd5ee6")


def prepare_to_run_command(cmd):
    pass


class FakeStdout(object):
    def __init__(self):
        self.content = []

    def write(self, text):
        self.content.append(text)

    def make_string(self):
        pass


def run_cmd(args, client, json_output=False, print_output=True):
    if json_output:
        args.extend(['-f', 'json'])
    stdout = FakeStdout()
Exemple #52
0
 def __init__(self, fake_call_impl_any):
     self.fake_call_impl_any = fake_call_impl_any
     self.monkey = monkeypatch()
Exemple #53
0
def pytest_configure(config):
    if pytest.__version__ != "2.7.2":
        from _pytest.monkeypatch import monkeypatch
        import reinterpret
        m = next(monkeypatch())
        m.setattr(py.builtin.builtins, 'AssertionError',
                  reinterpret.AssertionError)  # noqa

        config.option.continue_on_collection_errors = True

    config.from_ya_test = "YA_TEST_RUNNER" in os.environ
    config.test_logs = collections.defaultdict(dict)
    config.test_metrics = {}
    context = {
        "project_path": config.option.project_path,
        "test_stderr": config.option.test_stderr,
        "test_debug": config.option.test_debug,
        "build_type": config.option.build_type,
        "test_traceback": config.option.tbstyle,
        "flags": config.option.flags,
        "sanitize": config.option.sanitize,
    }
    config.ya = Ya(
        config.option.mode,
        config.option.source_root,
        config.option.build_root,
        config.option.dep_roots,
        config.option.output_dir,
        config.option.test_params,
        context,
        config.option.python_path,
        config.option.valgrind_path,
        config.option.gdb_path,
        config.option.data_root,
    )
    config.option.test_log_level = {
        "critical": logging.CRITICAL,
        "error": logging.ERROR,
        "warning": logging.WARN,
        "info": logging.INFO,
        "debug": logging.DEBUG,
    }[config.option.test_log_level]

    if not config.option.collectonly:
        setup_logging(os.path.join(config.ya.output_dir, "run.log"),
                      config.option.test_log_level)
    config.current_item_nodeid = None
    config.current_test_name = None
    config.test_cores_count = 0
    config.collect_cores = config.option.collect_cores
    config.sanitizer_extra_checks = config.option.sanitizer_extra_checks

    if config.sanitizer_extra_checks:
        for envvar in ['LSAN_OPTIONS', 'ASAN_OPTIONS']:
            if envvar in os.environ:
                os.environ.pop(envvar)
            if envvar + '_ORIGINAL' in os.environ:
                os.environ[envvar] = os.environ[envvar + '_ORIGINAL']

    config.coverage = None
    cov_prefix = os.environ.get('PYTHON_COVERAGE_PREFIX')
    if cov_prefix:
        config.coverage_data_dir = os.path.dirname(cov_prefix)

        import coverage
        cov = coverage.Coverage(
            data_file=cov_prefix,
            concurrency=['multiprocessing', 'thread'],
            auto_data=True,
            # debug=['pid', 'trace', 'sys', 'config'],
        )
        config.coverage = cov
        config.coverage.start()
        logging.info("Coverage will be collected during testing. pid: %d",
                     os.getpid())

    if config.option.root_dir:
        config.rootdir = config.invocation_dir = py.path.local(
            config.option.root_dir)

    # Arcadia paths from the test DEPENDS section of CMakeLists.txt
    sys.path.insert(
        0, os.path.join(config.option.source_root, config.option.project_path))
    sys.path.extend([
        os.path.join(config.option.source_root, d)
        for d in config.option.dep_roots
    ])
    sys.path.extend([
        os.path.join(config.option.build_root, d)
        for d in config.option.dep_roots
    ])

    # Build root is required for correct import of protobufs, because imports are related to the root
    # (like import devtools.dummy_arcadia.protos.lib.my_proto_pb2)
    sys.path.append(config.option.build_root)
    os.environ["PYTHONPATH"] = os.pathsep.join(
        os.environ.get("PYTHONPATH", "").split(os.pathsep) + sys.path)

    if not config.option.collectonly:
        if config.option.ya_trace_path:
            config.ya_trace_reporter = TraceReportGenerator(
                config.option.ya_trace_path)
        else:
            config.ya_trace_reporter = DryTraceReportGenerator(
                config.option.ya_trace_path)
    config.ya_version = config.option.ya_version

    sys.meta_path.append(
        CustomImporter([config.option.build_root] + [
            os.path.join(config.option.build_root, dep)
            for dep in config.option.dep_roots
        ]))
    if config.option.pdb_on_sigusr1:
        configure_pdb_on_demand()
Exemple #54
0
def pytest_configure(config):
    config._mp = mp = monkeypatch()
    t = TempdirHandler(config)
    mp.setattr(config, '_tmpdirhandler', t, raising=False)
    mp.setattr(pytest, 'ensuretemp', t.ensuretemp, raising=False)
Exemple #55
0
def setup():
    os.environ.clear()
    mp = monkeypatch()
    mp.setattr(register, 'put_host', fake_put_host)
    mp.setattr(register, '_get_local_ipv4', fake_get_local_ipv4)
def setup():
    mp = monkeypatch()
    mp.setattr('os.getlogin', lambda: 'pytest')
    mp.setattr('socket.gethostname', lambda: 'bar.desktop.local')