Python pytest.fail() Examples

The following are 30 code examples of pytest.fail(). 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: test_shamir.py    From python-shamir-mnemonic with MIT License 7 votes vote down vote up
def test_vectors():
    with open("vectors.json", "r") as f:
        vectors = json.load(f)
    for description, mnemonics, secret in vectors:
        if secret:
            assert bytes.fromhex(secret) == shamir.combine_mnemonics(
                mnemonics, b"TREZOR"
            ), 'Incorrect secret for test vector "{}".'.format(description)
        else:
            with pytest.raises(MnemonicError):
                shamir.combine_mnemonics(mnemonics)
                pytest.fail(
                    'Failed to raise exception for test vector "{}".'.format(
                        description
                    )
                ) 
Example #2
Source File: test_values.py    From python-template with Apache License 2.0 7 votes vote down vote up
def test_double_quotes_in_name_and_description(cookies):
    ctx = {'project_short_description': '"double quotes"',
           'full_name': '"name"name'}
    project = cookies.bake(extra_context=ctx)

    assert project.exit_code == 0

    with open(os.path.join(str(project.project), 'setup.py')) as f:
        setup = f.read()
    print(setup)

    cwd = os.getcwd()
    os.chdir(str(project.project))

    try:
        sh.python(['setup.py', 'install'])
    except sh.ErrorReturnCode as e:
        pytest.fail(e)
    finally:
        os.chdir(cwd) 
Example #3
Source File: test_values.py    From python-template with Apache License 2.0 7 votes vote down vote up
def test_dash_in_project_slug(cookies):
    ctx = {'project_slug': "my-package"}
    project = cookies.bake(extra_context=ctx)

    assert project.exit_code == 0

    with open(os.path.join(str(project.project), 'setup.py')) as f:
        setup = f.read()
    print(setup)

    cwd = os.getcwd()
    os.chdir(str(project.project))

    try:
        sh.python(['setup.py', 'install'])
        sh.python(['setup.py', 'build_sphinx'])
    except sh.ErrorReturnCode as e:
        pytest.fail(e)
    finally:
        os.chdir(cwd) 
Example #4
Source File: test_default.py    From ftw with Apache License 2.0 6 votes vote down vote up
def test_default(ruleset, test, destaddr, port, protocol):
    """
    Default tester with no logger obj. Useful for HTML contains and Status code
    Not useful for testing loggers
    """
    runner = testrunner.TestRunner()
    try:
        for stage in test.stages:
            if destaddr is not None:
                stage.input.dest_addr = destaddr
            if port is not None:
                stage.input.port = port
            if protocol is not None:
                stage.input.protocol = protocol
            runner.run_stage(stage, None)
    except errors.TestError as e:
        e.args[1]['meta'] = ruleset.meta
        pytest.fail('Failure! Message -> {0}, Context -> {1}'.format(
                    e.args[0], e.args[1])) 
Example #5
Source File: test_app_icon_commands.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def test_get_app_icons(self):
        """Test for listing app icons"""

        runner = CliRunner()
        LOG.info("Testing 'calm get app_icons' command")
        result = runner.invoke(cli, ["get", "app_icons"])
        assert result.exit_code == 0
        if result.exit_code:
            pytest.fail("App icons get call failed")
        LOG.info("Success")

        LOG.info("Testing --marketplace_use flag")
        result = runner.invoke(cli, ["get", "app_icons", "--marketplace_use"])
        assert result.exit_code == 0
        if result.exit_code:
            pytest.fail("App icons get call failed")
        LOG.info("Success")

        LOG.info("Testing limit and offset filter")
        runner = CliRunner()
        result = runner.invoke(cli, ["get", "app_icons"])
        assert result.exit_code == 0
        if result.exit_code:
            pytest.fail("App icons get call failed")
        LOG.info("Success") 
Example #6
Source File: test_results.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def test_results_with_error(conn_cnx):
    """Gets results with error."""
    with conn_cnx() as cnx:
        cur = cnx.cursor()
        sfqid = None
        try:
            cur.execute("select blah")
            pytest.fail("Should fail here!")
        except ProgrammingError as e:
            sfqid = e.sfqid

        got_sfqid = None
        try:
            cur.query_result(sfqid)
            pytest.fail("Should fail here again!")
        except ProgrammingError as e:
            got_sfqid = e.sfqid

        assert got_sfqid is not None
        assert got_sfqid == sfqid 
Example #7
Source File: test_project.py    From python-template with Apache License 2.0 6 votes vote down vote up
def test_building_documentation_apidocs(cookies):
    project = cookies.bake(extra_context={'apidoc': 'yes'})

    assert project.exit_code == 0
    assert project.exception is None

    cwd = os.getcwd()
    os.chdir(str(project.project))

    try:
        sh.python(['setup.py', 'build_sphinx'])
    except sh.ErrorReturnCode as e:
        pytest.fail(e)
    finally:
        os.chdir(cwd)

    apidocs = project.project.join('docs', '_build', 'html', 'apidocs')

    assert apidocs.join('my_python_project.html').isfile()
    assert apidocs.join('my_python_project.my_python_project.html').isfile() 
Example #8
Source File: test_bp_commands.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def test_bps_list(self):
        runner = CliRunner()
        result = runner.invoke(cli, ["get", "bps"])
        if result.exit_code:
            cli_res_dict = {"Output": result.output, "Exception": str(result.exception)}
            LOG.debug(
                "Cli Response: {}".format(
                    json.dumps(cli_res_dict, indent=4, separators=(",", ": "))
                )
            )
            LOG.debug(
                "Traceback: \n{}".format(
                    "".join(traceback.format_tb(result.exc_info[2]))
                )
            )
            pytest.fail("BP Get failed")
        LOG.info("Success") 
Example #9
Source File: test_project.py    From python-template with Apache License 2.0 6 votes vote down vote up
def test_install(cookies):
    project = cookies.bake()

    assert project.exit_code == 0
    assert project.exception is None

    cwd = os.getcwd()
    os.chdir(str(project.project))

    try:
        sh.python(['setup.py', 'install'])
    except sh.ErrorReturnCode as e:
        pytest.fail(e)
    finally:
        os.chdir(cwd) 
Example #10
Source File: test_values.py    From python-template with Apache License 2.0 6 votes vote down vote up
def test_space_in_project_slug(cookies):
    ctx = {'project_slug': "my package"}
    project = cookies.bake(extra_context=ctx)

    assert project.exit_code == 0

    with open(os.path.join(str(project.project), 'setup.py')) as f:
        setup = f.read()
    print(setup)

    cwd = os.getcwd()
    os.chdir(str(project.project))

    try:
        sh.python(['setup.py', 'install'])
        sh.python(['setup.py', 'build_sphinx'])
    except sh.ErrorReturnCode as e:
        pytest.fail(e)
    finally:
        os.chdir(cwd) 
Example #11
Source File: test_values.py    From python-template with Apache License 2.0 6 votes vote down vote up
def test_single_quotes_in_name_and_description(cookies):
    ctx = {'project_short_description': "'single quotes'",
           'full_name': "Mr. O'Keeffe"}
    project = cookies.bake(extra_context=ctx)

    assert project.exit_code == 0

    with open(os.path.join(str(project.project), 'setup.py')) as f:
        setup = f.read()
    print(setup)

    cwd = os.getcwd()
    os.chdir(str(project.project))

    try:
        sh.python(['setup.py', 'install'])
    except sh.ErrorReturnCode as e:
        pytest.fail(e)
    finally:
        os.chdir(cwd) 
Example #12
Source File: integration_tests.py    From activitywatch with Mozilla Public License 2.0 6 votes vote down vote up
def test_integration(server_process):
    # This is just here so that the server_process fixture is initialized
    pass

    # exit_code = pytest.main(["./aw-server/tests", "-v"])
    # if exit_code != 0:
    #     pytest.fail("Tests exited with non-zero code: " + str(exit_code)) 
Example #13
Source File: test_app_icon_commands.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def _create_bp(self, name=None):

        self.created_dsl_bp_name = name or "Test_Existing_VM_DSL_{}".format(
            str(uuid.uuid4())[-10:]
        )
        LOG.info("Creating Bp {}".format(self.created_dsl_bp_name))

        runner = CliRunner()
        result = runner.invoke(
            cli,
            [
                "create",
                "bp",
                "--file={}".format(DSL_BP_FILEPATH),
                "--name={}".format(self.created_dsl_bp_name),
                "--description='Test DSL Blueprint; to delete'",
            ],
        )

        if result.exit_code:
            LOG.error(result.output)
            pytest.fail("Creation of blueprint failed")

        self.created_bp_list.append(self.created_dsl_bp_name) 
Example #14
Source File: test_app_commands.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def test_apps_list(self):
        runner = CliRunner()
        result = runner.invoke(cli, ["get", "apps"])
        if result.exit_code:
            cli_res_dict = {"Output": result.output, "Exception": str(result.exception)}
            LOG.debug(
                "Cli Response: {}".format(
                    json.dumps(cli_res_dict, indent=4, separators=(",", ": "))
                )
            )
            LOG.debug(
                "Traceback: \n{}".format(
                    "".join(traceback.format_tb(result.exc_info[2]))
                )
            )
            pytest.fail("BP Get failed")
        LOG.info("Success") 
Example #15
Source File: test_results.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def test_results_with_error(conn_cnx):
    """Gets results with error."""
    with conn_cnx() as cnx:
        cur = cnx.cursor()
        sfqid = None
        try:
            cur.execute("select blah")
            pytest.fail("Should fail here!")
        except ProgrammingError as e:
            sfqid = e.sfqid

        got_sfqid = None
        try:
            cur.query_result(sfqid)
            pytest.fail("Should fail here again!")
        except ProgrammingError as e:
            got_sfqid = e.sfqid

        assert got_sfqid is not None
        assert got_sfqid == sfqid 
Example #16
Source File: test_node_builder_patterns.py    From tensortrade with Apache License 2.0 6 votes vote down vote up
def test_log_returns():

    s1 = Stream([200.23, 198.35, 244.36, 266.30, 250.40], "price")
    assert s1.name == "price"

    lp = s1.log()
    lr = lp - lp.lag()

    feed = DataFeed([lr])
    feed.compile()

    while feed.has_next():
        print(feed.next())

    lr = s1.log().diff().rename("log_return")

    feed = DataFeed([lr])
    feed.compile()

    while feed.has_next():
        print(feed.next())

    # pytest.fail("Failed.") 
Example #17
Source File: logfail.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def emit(self, record):
        logger = logging.getLogger(record.name)
        root_logger = logging.getLogger()

        if logger.name == 'messagemock':
            return

        if (logger.level == record.levelno or
                root_logger.level == record.levelno):
            # caplog.at_level(...) was used with the level of this message,
            # i.e.  it was expected.
            return
        if record.levelno < self._min_level:
            return
        pytest.fail("Got logging message on logger {} with level {}: "
                    "{}!".format(record.name, record.levelname,
                                 record.getMessage())) 
Example #18
Source File: test_format.py    From bit with MIT License 6 votes vote down vote up
def test_multisig_to_redeemscript_too_long(self):
        # Maximum is 15 compressed keys in a multisig:
        try:
            public_keys = [b'\x00' * 33] * 15
            multisig_to_redeemscript(public_keys, 1)
        except ValueError:  # pragma: no cover
            pytest.fail("multisig_to_redeemscript did not accept 15 compressed public keys.")

        public_keys = [b'\x00' * 33] * 16
        with pytest.raises(ValueError):
            multisig_to_redeemscript(public_keys, 1)

        # Maximum is 7 uncompressed keys in a multisig
        try:
            public_keys = [b'\x00' * 65] * 7
            multisig_to_redeemscript(public_keys, 1)
        except ValueError:  # pragma: no cover
            pytest.fail("multisig_to_redeemscript did not accept 7 uncompressed public keys.")

        public_keys = [b'\x00' * 65] * 8
        with pytest.raises(ValueError):
            multisig_to_redeemscript(public_keys, 1) 
Example #19
Source File: test_functional.py    From shopify_python with MIT License 6 votes vote down vote up
def _runTest(self):
        self._linter.check([self._test_file.module])

        expected_messages, expected_text = self._get_expected()
        received_messages, received_text = self._get_received()

        if expected_messages != received_messages:
            msg = ['Wrong results for file "%s":' % (self._test_file.base)]
            missing, unexpected = multiset_difference(expected_messages,
                                                      received_messages)
            if missing:
                msg.append('\nExpected in testdata:')
                msg.extend(' %3d: %s' % msg for msg in sorted(missing))
            if unexpected:
                msg.append('\nUnexpected in testdata:')
                msg.extend(' %3d: %s' % msg for msg in sorted(unexpected))
            pytest.fail('\n'.join(msg))
        self._check_output_text(expected_messages, expected_text, received_text) 
Example #20
Source File: test_parameters.py    From pywr with GNU General Public License v3.0 6 votes vote down vote up
def test_orphaned_components(simple_linear_model):
    model = simple_linear_model
    model.nodes["Input"].max_flow = ConstantParameter(model, 10.0)

    result = model.find_orphaned_parameters()
    assert(not result)
    # assert that warning not raised by check
    with pytest.warns(None) as record:
        model.check()
    for w in record:
        if isinstance(w, OrphanedParameterWarning):
            pytest.fail("OrphanedParameterWarning raised unexpectedly!")

    # add some orphans
    orphan1 = ConstantParameter(model, 5.0)
    orphan2 = ConstantParameter(model, 10.0)
    orphans = {orphan1, orphan2}
    result = model.find_orphaned_parameters()
    assert(orphans == result)

    with pytest.warns(OrphanedParameterWarning):
        model.check() 
Example #21
Source File: test_cookie.py    From ftw with Apache License 2.0 6 votes vote down vote up
def test_default(ruleset, test, destaddr):
    """
    Default tester with no logger obj. Useful for HTML contains and Status code
    Not useful for testing loggers
    """
    runner = testrunner.TestRunner()
    try:
        last_ua = http.HttpUA()
        for stage in test.stages:
            if destaddr is not None:
                stage.input.dest_addr = destaddr
            if stage.input.save_cookie:
                runner.run_stage(stage, http_ua=last_ua)
            else:
                runner.run_stage(stage, logger_obj=None, http_ua=None)
    except errors.TestError as e:
        e.args[1]['meta'] = ruleset.meta
        pytest.fail('Failure! Message -> {0}, Context -> {1}'.format(
                    e.args[0], e.args[1])) 
Example #22
Source File: test_bp_commands.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def test_bps_list_with_limit_offset(self):
        runner = CliRunner()
        result = runner.invoke(cli, ["get", "bps", "--limit=15", "--offset=5"])
        if result.exit_code:
            cli_res_dict = {"Output": result.output, "Exception": str(result.exception)}
            LOG.debug(
                "Cli Response: {}".format(
                    json.dumps(cli_res_dict, indent=4, separators=(",", ": "))
                )
            )
            LOG.debug(
                "Traceback: \n{}".format(
                    "".join(traceback.format_tb(result.exc_info[2]))
                )
            )
            pytest.fail("BP list with limit call failed")
        LOG.info("Success") 
Example #23
Source File: _pytestplugin.py    From tox with MIT License 5 votes vote down vote up
def check_cwd_not_changed_by_test():
    old = os.getcwd()
    yield
    new = os.getcwd()
    if old != new:
        pytest.fail("test changed cwd: {!r} => {!r}".format(old, new)) 
Example #24
Source File: test_connection.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def test_privatelink(db_parameters):
    """Ensure the OCSP cache server URL is overridden if privatelink connection is used."""
    try:
        os.environ['SF_OCSP_FAIL_OPEN'] = 'false'
        os.environ['SF_OCSP_DO_RETRY'] = 'false'
        snowflake.connector.connect(
            account='testaccount',
            user='testuser',
            password='testpassword',
            region='eu-central-1.privatelink',
            login_timeout=5,
        )
        pytest.fail("should not make connection")
    except OperationalError:
        ocsp_url = os.getenv('SF_OCSP_RESPONSE_CACHE_SERVER_URL')
        assert ocsp_url is not None, "OCSP URL should not be None"
        assert ocsp_url == "http://ocsp.testaccount.eu-central-1." \
                           "privatelink.snowflakecomputing.com/" \
                           "ocsp_response_cache.json"

    cnx = snowflake.connector.connect(
        user=db_parameters['user'],
        password=db_parameters['password'],
        host=db_parameters['host'],
        port=db_parameters['port'],
        account=db_parameters['account'],
        database=db_parameters['database'],
        protocol=db_parameters['protocol'],
        timezone='UTC',
    )
    assert cnx, 'invalid cnx'

    ocsp_url = os.getenv('SF_OCSP_RESPONSE_CACHE_SERVER_URL')
    assert ocsp_url is None, "OCSP URL should be None: {}".format(ocsp_url)
    del os.environ['SF_OCSP_DO_RETRY']
    del os.environ['SF_OCSP_FAIL_OPEN'] 
Example #25
Source File: test_console.py    From python-zhmcclient with Apache License 2.0 5 votes vote down vote up
def test_console_shutdown(self, force):
        """Test Console.shutdown()."""

        console_mgr = self.client.consoles
        console = console_mgr.find(name=self.faked_console.name)

        # Note: The force parameter is passed in, but we expect the shutdown
        # to always succeed. This means we are not testing cases with other
        # HMC users being logged on, that would either cause a non-forced
        # shutdown to be rejected, or a forced shutdown to succeed despite
        # them.

        # Execute the code to be tested.
        ret = console.shutdown(force=force)

        assert ret is None

        # The HMC is expected to be offline, and therefore a simple operation
        # is expected to fail.
        try:
            self.client.query_api_version()
        except Error:
            pass
        except Exception as exc:
            pytest.fail(
                "Unexpected non-zhmcclient exception during "
                "query_api_version() after HMC shutdown: %s" % exc)
        else:
            pytest.fail(
                "Unexpected success of query_api_version() after HMC "
                "shutdown.") 
Example #26
Source File: logtest.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _handleLogError(self, msg, data, marker, pattern):
        print('')
        print('    ERROR: %s' % msg)

        if not self.interactive:
            raise pytest.fail(msg)

        p = ('    Show: '
             '[L]og [M]arker [P]attern; '
             '[I]gnore, [R]aise, or sys.e[X]it >> ')
        sys.stdout.write(p + ' ')
        # ARGH
        sys.stdout.flush()
        while True:
            i = getchar().upper()
            if i not in 'MPLIRX':
                continue
            print(i.upper())  # Also prints new line
            if i == 'L':
                for x, line in enumerate(data):
                    if (x + 1) % self.console_height == 0:
                        # The \r and comma should make the next line overwrite
                        sys.stdout.write('<-- More -->\r ')
                        m = getchar().lower()
                        # Erase our "More" prompt
                        sys.stdout.write('            \r ')
                        if m == 'q':
                            break
                    print(line.rstrip())
            elif i == 'M':
                print(repr(marker or self.lastmarker))
            elif i == 'P':
                print(repr(pattern))
            elif i == 'I':
                # return without raising the normal exception
                return
            elif i == 'R':
                raise pytest.fail(msg)
            elif i == 'X':
                self.exit()
            sys.stdout.write(p + ' ') 
Example #27
Source File: test_connection.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def test_privatelink(db_parameters):
    """Ensure the OCSP cache server URL is overridden if privatelink connection is used."""
    try:
        os.environ['SF_OCSP_FAIL_OPEN'] = 'false'
        os.environ['SF_OCSP_DO_RETRY'] = 'false'
        snowflake.connector.connect(
            account='testaccount',
            user='testuser',
            password='testpassword',
            region='eu-central-1.privatelink',
            login_timeout=5,
        )
        pytest.fail("should not make connection")
    except OperationalError:
        ocsp_url = os.getenv('SF_OCSP_RESPONSE_CACHE_SERVER_URL')
        assert ocsp_url is not None, "OCSP URL should not be None"
        assert ocsp_url == "http://ocsp.testaccount.eu-central-1." \
                           "privatelink.snowflakecomputing.com/" \
                           "ocsp_response_cache.json"

    cnx = snowflake.connector.connect(
        user=db_parameters['user'],
        password=db_parameters['password'],
        host=db_parameters['host'],
        port=db_parameters['port'],
        account=db_parameters['account'],
        database=db_parameters['database'],
        protocol=db_parameters['protocol'],
        timezone='UTC',
    )
    assert cnx, 'invalid cnx'

    ocsp_url = os.getenv('SF_OCSP_RESPONSE_CACHE_SERVER_URL')
    assert ocsp_url is None, "OCSP URL should be None: {}".format(ocsp_url)
    del os.environ['SF_OCSP_DO_RETRY']
    del os.environ['SF_OCSP_FAIL_OPEN'] 
Example #28
Source File: _pytestplugin.py    From tox with MIT License 5 votes vote down vote up
def check_os_environ_stable():
    old = os.environ.copy()

    to_clean = {
        k: os.environ.pop(k, None)
        for k in {
            PARALLEL_ENV_VAR_KEY_PRIVATE,
            PARALLEL_ENV_VAR_KEY_PUBLIC,
            str("TOX_WORK_DIR"),
            str("PYTHONPATH"),
        }
    }

    yield

    for key, value in to_clean.items():
        if value is not None:
            os.environ[key] = value

    new = os.environ
    extra = {k: new[k] for k in set(new) - set(old)}
    miss = {k: old[k] for k in set(old) - set(new)}
    diff = {
        "{} = {} vs {}".format(k, old[k], new[k])
        for k in set(old) & set(new)
        if old[k] != new[k] and not k.startswith("PYTEST_")
    }
    if extra or miss or diff:
        msg = "test changed environ"
        if extra:
            msg += " extra {}".format(extra)
        if miss:
            msg += " miss {}".format(miss)
        if diff:
            msg += " diff {}".format(diff)
        pytest.fail(msg) 
Example #29
Source File: verification.py    From django-rest-registration with MIT License 5 votes vote down vote up
def assert_valid_verification_url(
        url, expected_path=None, expected_fields=None,
        url_parser=None):
    if url_parser is None:
        url_parser = _parse_verification_url
    try:
        url_path, verification_data = url_parser(url, expected_fields)
    except ValueError as exc:
        pytest.fail(str(exc))
    if expected_path is not None:
        assert url_path == expected_path
    if expected_fields is not None:
        assert set(verification_data.keys()) == set(expected_fields)
    return verification_data 
Example #30
Source File: test_quickstart.py    From tox with MIT License 5 votes vote down vote up
def __call__(self, prompt):
        print("prompt: '{}'".format(prompt))
        try:
            answer = self._inputs.pop(0)
            print("user answer: '{}'".format(answer))
            return answer
        except IndexError:
            pytest.fail("missing user answer for '{}'".format(prompt))