Python pytest.fail() Examples

The following are 30 code examples for showing how to use pytest.fail(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module pytest , or try the search function .

Example 1
Project: python-template   Author: NLeSC   File: test_values.py    License: 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 2
Project: python-shamir-mnemonic   Author: trezor   File: test_shamir.py    License: MIT License 6 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 3
Project: python-template   Author: NLeSC   File: test_values.py    License: Apache License 2.0 6 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 4
Project: python-template   Author: NLeSC   File: test_values.py    License: 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 5
Project: python-template   Author: NLeSC   File: test_values.py    License: 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 6
Project: python-template   Author: NLeSC   File: test_project.py    License: 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 7
Project: python-template   Author: NLeSC   File: test_project.py    License: 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
Project: pywr   Author: pywr   File: test_parameters.py    License: 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 9
Project: tensortrade   Author: tensortrade-org   File: test_node_builder_patterns.py    License: 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 10
Project: bit   Author: ofek   File: test_format.py    License: 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 11
Project: shopify_python   Author: Shopify   File: test_functional.py    License: 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 12
Project: ftw   Author: CRS-support   File: test_cookie.py    License: 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 13
Project: ftw   Author: CRS-support   File: test_default.py    License: 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 14
Project: qutebrowser   Author: qutebrowser   File: logfail.py    License: 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 15
Project: snowflake-connector-python   Author: snowflakedb   File: test_results.py    License: 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
Project: snowflake-connector-python   Author: snowflakedb   File: test_results.py    License: 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 17
Project: calm-dsl   Author: nutanix   File: test_app_commands.py    License: 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 18
Project: calm-dsl   Author: nutanix   File: test_app_icon_commands.py    License: 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 19
Project: calm-dsl   Author: nutanix   File: test_app_icon_commands.py    License: 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 20
Project: calm-dsl   Author: nutanix   File: test_bp_commands.py    License: 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 21
Project: calm-dsl   Author: nutanix   File: test_bp_commands.py    License: 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 22
Project: cherrypy   Author: cherrypy   File: test_bus.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_log(bus, log_tracker):
    """Test that bus messages and errors are logged."""
    assert log_tracker.log_entries == []

    # Try a normal message.
    expected = []
    for msg_ in ["O mah darlin'"] * 3 + ['Clementiiiiiiiine']:
        bus.log(msg_)
        expected.append(msg_)
        assert log_tracker.log_entries == expected

    # Try an error message
    try:
        foo
    except NameError:
        bus.log('You are lost and gone forever', traceback=True)
        lastmsg = log_tracker.log_entries[-1]
        assert 'Traceback' in lastmsg and 'NameError' in lastmsg, (
            'Last log message %r did not contain '
            'the expected traceback.' % lastmsg
        )
    else:
        pytest.fail('NameError was not raised as expected.') 
Example 23
Project: cherrypy   Author: cherrypy   File: logtest.py    License: 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 24
Project: python-template   Author: NLeSC   File: test_project.py    License: Apache License 2.0 5 votes vote down vote up
def test_building_documentation_no_apidocs(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', 'build_sphinx'])
    except sh.ErrorReturnCode as e:
        pytest.fail(e)
    finally:
        os.chdir(cwd) 
Example 25
Project: comport   Author: codeforamerica   File: test_department_model_wpd.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_dataset_lookup(self):
        ''' The dataset lookup returns usable information
        '''
        # create a department
        department = Department.create(name="W Police Department", short_name="WPD", load_defaults=True)

        complaints_lookup = department.get_dataset_lookup("complaints")
        uof_lookup = department.get_dataset_lookup("uof")

        # TODO: how to test that paths are valid?

        # test that the var suffixes are valid
        try:
            getattr(department, "is_public_{}".format(complaints_lookup["var_suffix"]))
        except AttributeError:
            pytest.fail("Unexpected AttributeError")

        try:
            getattr(department, "is_public_{}".format(uof_lookup["var_suffix"]))
        except AttributeError:
            pytest.fail("Unexpected AttributeError")

        # test that the class prefixes are valid
        try:
            getattr(importlib.import_module("comport.data.models"), "{}{}".format(complaints_lookup["class_prefix"], department.short_name))
        except AttributeError:
            pytest.fail("Unexpected AttributeError")

        try:
            getattr(importlib.import_module("comport.data.models"), "{}{}".format(uof_lookup["class_prefix"], department.short_name))
        except AttributeError:
            pytest.fail("Unexpected AttributeError") 
Example 26
Project: botbuilder-python   Author: microsoft   File: storage_base_tests.py    License: MIT License 5 votes vote down vote up
def does_not_raise_when_writing_no_items(storage) -> bool:
        # noinspection PyBroadException
        try:
            await storage.write([])
        except:
            pytest.fail("Should not raise")

        return True 
Example 27
Project: botbuilder-python   Author: microsoft   File: storage_base_tests.py    License: MIT License 5 votes vote down vote up
def delete_unknown_object(storage) -> bool:
        # noinspection PyBroadException
        try:
            await storage.delete(["unknown_key"])
        except:
            pytest.fail("Should not raise")

        return True 
Example 28
Project: myhdl   Author: myhdl   File: helpers.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def __exit__(self, *tp):
        __tracebackhide__ = True
        if tp[0] is None:
            pytest.fail("DID NOT RAISE")
        assert tp[1].kind == self.kind
        return issubclass(tp[0], self.exc) 
Example 29
Project: hyper-h2   Author: python-hyper   File: coroutine_tests.py    License: MIT License 5 votes vote down vote up
def run_until_complete(self, *coroutines):
        """
        Executes a set of coroutines that communicate between each other. Each
        one is, in order, passed the output of the previous coroutine until
        one is exhausted. If a coroutine does not initially yield data (that
        is, its first action is to receive data), the calling code should prime
        it by using the 'server' decorator on this class.

        Once a coroutine is exhausted, the method performs a final check to
        ensure that all other coroutines are exhausted. This ensures that all
        assertions in those coroutines got executed.
        """
        looping_coroutines = itertools.cycle(coroutines)
        data = None

        for coro in looping_coroutines:
            try:
                data = coro.send(data)
            except StopIteration:
                break

        for coro in coroutines:
            try:
                next(coro)
            except StopIteration:
                continue
            else:
                pytest.fail("Coroutine %s not exhausted" % coro) 
Example 30
Project: scarlet   Author: pmelchior   File: test_docs.py    License: MIT License 5 votes vote down vote up
def test_docs(self):
        dirs = 'docs/', 'docs/tutorials/'
        cwd = os.getcwd()
        for dir in dirs:
            os.chdir(dir)
            files = sorted(glob.glob("*.ipynb"))
            for filename in files:
                errors = run_notebook(filename)
                if errors is not None:
                    pytest.fail("\nNotebook {}, Cell {} failed:\n{}".format(filename,errors[0], escape_ansi_control(errors[1])))
            os.chdir(cwd)