Python pytest.skip() Examples

The following are 30 code examples of pytest.skip(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pytest , or try the search function .
Example #1
Source File: conftest.py    From py-solc with MIT License 6 votes vote down vote up
def pytest_runtest_setup(item):
    if (item.get_marker('requires_standard_json') is not None and
        not solc_supports_standard_json_interface()):
        pytest.skip('requires `--standard-json` support') 
Example #2
Source File: test_svnauth.py    From py with MIT License 6 votes vote down vote up
def __init__(self, request):
        if not svnbin:
            py.test.skip("svn binary required")
        if not request.config.option.runslowtests:
            py.test.skip('use --runslowtests to run these tests')

        tmpdir = request.getfuncargvalue("tmpdir")
        repodir = tmpdir.join("repo")
        py.process.cmdexec('svnadmin create %s' % repodir)
        if sys.platform == 'win32':
            repodir = '/' + str(repodir).replace('\\', '/')
        self.repo = py.path.svnurl("file://%s" % repodir)
        if sys.platform == 'win32':
            # remove trailing slash...
            repodir = repodir[1:]
        self.repopath = py.path.local(repodir)
        self.temppath = tmpdir.mkdir("temppath")
        self.auth = SvnAuth('johnny', 'foo', cache_auth=False,
                                    interactive=False)
        make_repo_auth(self.repopath, {'johnny': ('foo', 'rw')})
        self.port, self.pid = serve_bg(self.repopath.dirpath())
        # XXX caching is too global
        py.path.svnurl._lsnorevcache._dict.clear()
        request.addfinalizer(lambda: py.process.kill(self.pid)) 
Example #3
Source File: test_svnauth.py    From py with MIT License 6 votes vote down vote up
def test_switch(self, setup):
        import pytest
        try:
            import xdist
            pytest.skip('#160: fails under xdist')
        except ImportError:
            pass
        wc = py.path.svnwc(setup.temppath, auth=setup.auth)
        svnurl = 'svn://localhost:%s/%s' % (setup.port, setup.repopath.basename)
        wc.checkout(svnurl)
        wc.ensure('foo', dir=True).ensure('foo.txt').write('foo')
        wc.commit('added foo dir with foo.txt file')
        wc.ensure('bar', dir=True)
        wc.commit('added bar dir')
        bar = wc.join('bar')
        bar.switch(svnurl + '/foo')
        assert bar.join('foo.txt') 
Example #4
Source File: test_api.py    From normandy with Mozilla Public License 2.0 6 votes vote down vote up
def test_console_log(conf, requests_session):
    r = requests_session.get(conf.getoption("server") + "/api/v1/action/")
    r.raise_for_status()
    response = r.json()

    # Verify we have at least one response and then grab the first record
    assert len(response) >= 1

    # Look for any console-log actions
    cl_records = [record for record in response if record["name"] == "console-log"]

    if len(cl_records) == 0:
        pytest.skip("No console-log actions found")
        return

    record = cl_records[0]
    # Does an 'action' have all the required fields?
    expected_action_fields = ["name", "implementation_url", "arguments_schema"]
    for field in record:
        assert field in expected_action_fields

    check_action_schema_format(record) 
Example #5
Source File: test_api.py    From normandy with Mozilla Public License 2.0 6 votes vote down vote up
def test_show_heartbeat(conf, requests_session):
    r = requests_session.get(conf.getoption("server") + "/api/v1/action/")
    r.raise_for_status()
    response = r.json()

    # Verify we have at least one response and then grab the first record
    assert len(response) >= 1

    # Let's find at least one record that is a 'show-heartbeat'
    sh_records = [record for record in response if record["name"] == "show-heartbeat"]

    if len(sh_records) == 0:
        pytest.skip("No show-heartbeat actions found")
        return

    record = sh_records[0]
    expected_action_fields = ["name", "implementation_url", "arguments_schema"]
    for field in record:
        assert field in expected_action_fields

    check_action_schema_format(record) 
Example #6
Source File: test_functional.py    From shopify_python with MIT License 6 votes vote down vote up
def setUp(self):
        if self._should_be_skipped_due_to_version():
            pytest.skip('Test cannot run with Python %s.' % (sys.version.split(' ')[0],))
        missing = []
        for req in self._test_file.options['requires']:
            try:
                __import__(req)
            except ImportError:
                missing.append(req)
        if missing:
            pytest.skip('Requires %s to be present.' % (','.join(missing),))
        if self._test_file.options['except_implementations']:
            implementations = [
                item.strip() for item in
                self._test_file.options['except_implementations'].split(",")
            ]
            implementation = platform.python_implementation()
            if implementation in implementations:
                pytest.skip(
                    'Test cannot run with Python implementation %r'
                    % (implementation, )) 
Example #7
Source File: test_api.py    From normandy with Mozilla Public License 2.0 6 votes vote down vote up
def test_recipe_history(conf, requests_session):
    r = requests_session.get(conf.getoption("server") + "/api/v1/recipe/")
    r.raise_for_status()
    data = r.json()

    if len(data) == 0:
        pytest.skip("No recipes found.")

    for item in data:
        endpoint = f'/api/v1/recipe/{item["id"]}/history/'
        r = requests_session.get(conf.getoption("server") + endpoint)
        r.raise_for_status()
        history = r.json()

        last_date = datetime.now()
        for revision in history:
            created = datetime.strptime(revision["date_created"], "%Y-%m-%dT%H:%M:%S.%fZ")
            assert created < last_date
            last_date = created 
Example #8
Source File: conftest.py    From smbprotocol with MIT License 6 votes vote down vote up
def smb_real():
    # for these tests to work the server at SMB_SERVER must support dialect
    # 3.1.1, without this some checks will fail as we test 3.1.1 specific
    # features
    username = os.environ.get('SMB_USER', None)
    password = os.environ.get('SMB_PASSWORD', None)
    server = os.environ.get('SMB_SERVER', None)
    port = os.environ.get('SMB_PORT', 445)
    share = os.environ.get('SMB_SHARE', 'share')

    if username and password and server:
        share = r"\\%s\%s" % (server, share)
        encrypted_share = "%s-encrypted" % share
        return username, password, server, int(port), share, encrypted_share
    else:
        pytest.skip("SMB_USER, SMB_PASSWORD, SMB_PORT, SMB_SHARE, "
                    "environment variables were not set, integration tests "
                    "will be skipped") 
Example #9
Source File: conftest.py    From custodia with GNU General Public License v3.0 6 votes vote down vote up
def pytest_runtest_setup(item):
    skip_servertest = item.config.getoption(SKIP_SERVERTEST)
    skiptest = False
    if skip_servertest:
        # pytest < 4
        if hasattr(item, 'get_marker'):
            if item.get_marker("servertest"):
                skiptest = True
        # pytest >= 4
        elif item.get_closest_marker("servertest"):
            skiptest = True

    if skiptest:
        # args has --skip-servertests and test is marked as servertest
        pytest.skip("Skip integration test") 
Example #10
Source File: test_miscwidgets.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def test_adjust_size(self, old_window_size, preferred_size,
                         new_window_size, exp_inspector_size,
                         position, splitter, fake_inspector, qtbot):
        def resize(dim):
            size = (QSize(dim, 666) if splitter.orientation() == Qt.Horizontal
                    else QSize(666, dim))
            splitter.resize(size)
            if splitter.size() != size:
                pytest.skip("Resizing window failed")

        splitter.set_inspector(fake_inspector, position)
        splitter.show()
        resize(old_window_size)

        handle_width = 4
        splitter.setHandleWidth(handle_width)

        splitter_idx = 1
        if position in [inspector.Position.left, inspector.Position.top]:
            splitter_pos = preferred_size - handle_width//2
        else:
            splitter_pos = old_window_size - preferred_size - handle_width//2
        splitter.moveSplitter(splitter_pos, splitter_idx)

        resize(new_window_size)

        sizes = splitter.sizes()
        inspector_size = sizes[splitter._inspector_idx]
        main_size = sizes[splitter._main_idx]
        exp_main_size = new_window_size - exp_inspector_size

        exp_main_size -= handle_width // 2
        exp_inspector_size -= handle_width // 2

        assert (inspector_size, main_size) == (exp_inspector_size,
                                               exp_main_size) 
Example #11
Source File: test_async.py    From mmdetection with Apache License 2.0 6 votes vote down vote up
def test_simple_inference(self):
            if not torch.cuda.is_available():
                import pytest

                pytest.skip('test requires GPU and torch+cuda')

            ori_grad_enabled = torch.is_grad_enabled()
            root_dir = os.path.dirname(os.path.dirname(__name__))
            model_config = os.path.join(
                root_dir, 'configs/mask_rcnn/mask_rcnn_r50_fpn_1x_coco.py')
            detector = MaskRCNNDetector(model_config)
            await detector.init()
            img_path = os.path.join(root_dir, 'demo/demo.jpg')
            bboxes, _ = await detector.apredict(img_path)
            self.assertTrue(bboxes)
            # asy inference detector will hack grad_enabled,
            # so restore here to avoid it to influence other tests
            torch.set_grad_enabled(ori_grad_enabled) 
Example #12
Source File: test_recipe_read.py    From normandy with Mozilla Public License 2.0 6 votes vote down vote up
def test_recipe_read(conf, requests_session):
    # Get random recipe and make sure it's valid
    response = requests_session.get(urljoin(conf.getoption("server"), "/api/v3/recipe/"))
    data = response.json()

    if len(data["results"]) == 0:
        pytest.skip("Could not find any recipes")

    element = randint(0, len(data["results"]) - 1)
    recipe_id = data["results"][element]["id"]
    response = requests_session.get(
        urljoin(conf.getoption("server"), "/api/v3/recipe/{}".format(recipe_id))
    )
    data = response.json()
    assert response.status_code != 404
    assert_valid_schema(response.json()) 
Example #13
Source File: test_put_get_user_stage.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def test_get_data_user_stage(is_public_test, tmpdir, conn_cnx, db_parameters):
    """SNOW-20927: Tests Get failure with 404 error."""
    if is_public_test or 'AWS_ACCESS_KEY_ID' not in os.environ:
        pytest.skip('This test requires to change the internal parameter')

    default_s3bucket = os.getenv('SF_AWS_USER_BUCKET',
                                 "sfc-dev1-regression/{}/reg".format(
                                     getuser()))
    test_data = [
        {
            's3location':
                '{}/{}'.format(
                    default_s3bucket, db_parameters['name'] + '_stage'),
            'stage_name': db_parameters['name'] + '_stage1',
            'data_file_name': 'data.txt',
        },
    ]
    for elem in test_data:
        _put_list_rm_files_in_stage(tmpdir, conn_cnx, db_parameters, elem) 
Example #14
Source File: test_utils.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def freezer(request, monkeypatch):
    if request.param and not getattr(sys, 'frozen', False):
        monkeypatch.setattr(sys, 'frozen', True, raising=False)
        monkeypatch.setattr(sys, 'executable', qutebrowser.__file__)
    elif not request.param and getattr(sys, 'frozen', False):
        # Want to test unfrozen tests, but we are frozen
        pytest.skip("Can't run with sys.frozen = True!") 
Example #15
Source File: test_pdfjs.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def test_generate_pdfjs_page(available, snippet, monkeypatch):
    if available == 'force':
        monkeypatch.setattr(pdfjs, 'is_available', lambda: True)
        monkeypatch.setattr(pdfjs, 'get_pdfjs_res',
                            lambda filename: b'fake PDF.js')
    elif available:
        if not pdfjs.is_available():
            pytest.skip("PDF.js unavailable")
        monkeypatch.setattr(pdfjs, 'is_available', lambda: True)
    else:
        monkeypatch.setattr(pdfjs, 'is_available', lambda: False)

    content = pdfjs.generate_pdfjs_page('example.pdf', QUrl())
    print(content)
    assert snippet in content 
Example #16
Source File: test_utils.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def test_libgl_workaround(monkeypatch, skip):
    if skip:
        monkeypatch.setenv('QUTE_SKIP_LIBGL_WORKAROUND', '1')
    utils.libgl_workaround()  # Just make sure it doesn't crash. 
Example #17
Source File: test_webengine_cookies.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def filter_request():
    try:
        request = QWebEngineCookieStore.FilterRequest()
        request.firstPartyUrl = QUrl('https://example.com')
        return request
    except AttributeError:
        pytest.skip("FilterRequest not available") 
Example #18
Source File: test_extension_read.py    From normandy with Mozilla Public License 2.0 5 votes vote down vote up
def test_extension_read(conf, requests_session):
    response = requests_session.get(urljoin(conf.getoption("server"), "/api/v3/extension/"))
    assert response.status_code != 404
    details = response.json()

    # Get the ID of the first record in the list and read it
    if len(details["results"]) == 0:
        pytest.skip("No extensions results were found")

    extension_id = details["results"][0]["id"]
    response = requests_session.get(
        urljoin(conf.getoption("server"), "/api/v3/extension/{}".format(extension_id))
    )
    assert_valid_schema(response.json()) 
Example #19
Source File: test_recipe_history.py    From normandy with Mozilla Public License 2.0 5 votes vote down vote up
def test_recipe_history(conf, requests_session):
    # Get the ID of a random recipe and grab it's history
    response = requests_session.get(urljoin(conf.getoption("server"), "/api/v3/recipe/"))
    data = response.json()

    if len(data["results"]) == 0:
        pytest.skip("Could not find any recipe history")

    idx = randint(0, len(data["results"]) - 1)
    id = data["results"][idx]["id"]
    response = requests_session.get(
        urljoin(conf.getoption("server"), "/api/v3/recipe/{}/history/".format(id))
    )
    assert response.status_code != 404
    assert_valid_schema(response.json()) 
Example #20
Source File: conftest.py    From normandy with Mozilla Public License 2.0 5 votes vote down vote up
def geolocation():
    """Fixture to load geolocation data."""
    geolocation_module.load_geoip_database()
    if geolocation_module.geoip_reader is None:
        pytest.skip()
    else:
        return geolocation_module 
Example #21
Source File: test_editor.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def unwritable_tmp_path(self, tmp_path):
        tmp_path.chmod(0)
        if os.access(str(tmp_path), os.W_OK):
            # Docker container or similar
            pytest.skip("File was still writable")

        yield tmp_path

        tmp_path.chmod(0o755) 
Example #22
Source File: test_qtutils.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def test_seek_unsupported(self, pyqiodev):
        """Test seeking with unsupported whence arguments."""
        # pylint: disable=no-member,useless-suppression
        if hasattr(os, 'SEEK_HOLE'):
            whence = os.SEEK_HOLE
        elif hasattr(os, 'SEEK_DATA'):
            whence = os.SEEK_DATA
        # pylint: enable=no-member,useless-suppression
        else:
            pytest.skip("Needs os.SEEK_HOLE or os.SEEK_DATA available.")
        pyqiodev.open(QIODevice.ReadOnly)
        with pytest.raises(io.UnsupportedOperation):
            pyqiodev.seek(0, whence) 
Example #23
Source File: test_version.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def test_real_file(self, data_tmpdir):
        """Test against the real file if pdfjs was found."""
        try:
            pdfjs.get_pdfjs_res_and_path('build/pdf.js')
        except pdfjs.PDFJSNotFound:
            pytest.skip("No pdfjs found")
        ver = version._pdfjs_version()
        assert ver.split()[0] not in ['no', 'unknown'], ver 
Example #24
Source File: test_runners.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def test_parse_all_with_alias(self, cmdline_test, monkeypatch,
                                  config_stub):
        if not cmdline_test.cmd:
            pytest.skip("Empty command")

        config_stub.val.aliases = {'alias_name': cmdline_test.cmd}

        parser = runners.CommandParser()
        if cmdline_test.valid:
            assert len(parser.parse_all("alias_name")) > 0
        else:
            with pytest.raises(cmdexc.NoSuchCommandError):
                parser.parse_all("alias_name") 
Example #25
Source File: test_invocations.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def test_launching_with_python2():
    try:
        proc = subprocess.run(
            ['python2', '-m', 'qutebrowser', '--no-err-windows'],
            stderr=subprocess.PIPE,
            check=False)
    except FileNotFoundError:
        pytest.skip("python2 not found")
    assert proc.returncode == 1
    error = "At least Python 3.5.2 is required to run qutebrowser"
    assert proc.stderr.decode('ascii').startswith(error) 
Example #26
Source File: test_invocations.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def test_webengine_download_suffix(request, quteproc_new, tmpdir):
    """Make sure QtWebEngine does not add a suffix to downloads."""
    if not request.config.webengine:
        pytest.skip()

    download_dir = tmpdir / 'downloads'
    download_dir.ensure(dir=True)

    (tmpdir / 'user-dirs.dirs').write(
        'XDG_DOWNLOAD_DIR={}'.format(download_dir))
    env = {'XDG_CONFIG_HOME': str(tmpdir)}
    args = (['--temp-basedir'] + _base_args(request.config))
    quteproc_new.start(args, env=env)

    quteproc_new.set_setting('downloads.location.prompt', 'false')
    quteproc_new.set_setting('downloads.location.directory', str(download_dir))
    quteproc_new.open_path('data/downloads/download.bin', wait=False)
    quteproc_new.wait_for(category='downloads', message='Download * finished')
    quteproc_new.open_path('data/downloads/download.bin', wait=False)
    quteproc_new.wait_for(message='Entering mode KeyMode.yesno *')
    quteproc_new.send_cmd(':prompt-accept yes')
    quteproc_new.wait_for(category='downloads', message='Download * finished')

    files = download_dir.listdir()
    assert len(files) == 1
    assert files[0].basename == 'download.bin' 
Example #27
Source File: test_invocations.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def test_webengine_inspector(request, quteproc_new):
    if not request.config.webengine:
        pytest.skip()
    args = (['--temp-basedir', '--enable-webengine-inspector'] +
            _base_args(request.config))
    quteproc_new.start(args)
    line = quteproc_new.wait_for(
        message='Remote debugging server started successfully. Try pointing a '
                'Chromium-based browser to http://127.0.0.1:*')
    port = int(line.message.split(':')[-1])

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('127.0.0.1', port))
    s.close() 
Example #28
Source File: quteprocess.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def after_test(self):
        """Handle unexpected/skip logging and clean up after each test."""
        __tracebackhide__ = lambda e: e.errisinstance(pytest.fail.Exception)
        bad_msgs = [msg for msg in self._data
                    if self._is_error_logline(msg) and not msg.expected]

        try:
            call = self.request.node.rep_call
        except AttributeError:
            pass
        else:
            if call.failed or hasattr(call, 'wasxfail'):
                super().after_test()
                return

        try:
            if bad_msgs:
                text = 'Logged unexpected errors:\n\n' + '\n'.join(
                    str(e) for e in bad_msgs)
                # We'd like to use pytrace=False here but don't as a WORKAROUND
                # for https://github.com/pytest-dev/pytest/issues/1316
                pytest.fail(text)
            else:
                self._maybe_skip()
        finally:
            super().after_test() 
Example #29
Source File: testprocess.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def _maybe_skip(self):
        """Can be overridden by subclasses to skip on certain log lines.

        We can't run pytest.skip directly while parsing the log, as that would
        lead to a pytest.skip.Exception error in a virtual Qt method, which
        means pytest-qt fails the test.

        Instead, we check for skip messages periodically in
        QuteProc._maybe_skip, and call _maybe_skip after every parsed message
        in wait_for (where it's most likely that new messages arrive).
        """ 
Example #30
Source File: testprocess.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def _wait_for_new(self, timeout, do_skip, **kwargs):
        """Wait for a log message which doesn't exist yet.

        Called via wait_for.
        """
        __tracebackhide__ = lambda e: e.errisinstance(WaitForTimeout)
        message = kwargs.get('message', None)
        if message is not None:
            elided = quteutils.elide(repr(message), 100)
            self._log("\n----> Waiting for {} in the log".format(elided))

        spy = QSignalSpy(self.new_data)
        elapsed_timer = QElapsedTimer()
        elapsed_timer.start()

        while True:
            # Skip if there are pending messages causing a skip
            self._maybe_skip()
            got_signal = spy.wait(timeout)
            if not got_signal or elapsed_timer.hasExpired(timeout):
                msg = "Timed out after {}ms waiting for {!r}.".format(
                    timeout, kwargs)
                if do_skip:
                    pytest.skip(msg)
                else:
                    raise WaitForTimeout(msg)

            match = self._wait_for_match(spy, kwargs)
            if match is not None:
                if message is not None:
                    self._log("----> found it")
                return match

        raise quteutils.Unreachable