Python pytest.raises() Examples

The following are 30 code examples for showing how to use pytest.raises(). 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: clikit   Author: sdispater   File: test_question.py    License: MIT License 6 votes vote down vote up
def test_ask_and_validate(io):
    error = "This is not a color!"

    def validator(color):
        if color not in ["white", "black"]:
            raise Exception(error)

        return color

    question = Question("What color was the white horse of Henry IV?", "white")
    question.set_validator(validator)
    question.set_max_attempts(2)

    io.set_input("\nblack\n")
    assert "white" == question.ask(io)
    assert "black" == question.ask(io)

    io.set_input("green\nyellow\norange\n")

    with pytest.raises(Exception) as e:
        question.ask(io)

    assert error == str(e.value) 
Example 2
Project: clikit   Author: sdispater   File: test_exception_trace.py    License: MIT License 6 votes vote down vote up
def test_render_debug_better_error_message_recursion_error_with_multiple_duplicated_frames():
    io = BufferedIO()
    io.set_verbosity(VERBOSE)

    with pytest.raises(RecursionError) as e:
        first()

    trace = ExceptionTrace(e.value)

    trace.render(io)

    expected = r"...  Previous 2 frames repeated \d+ times".format(
        filename=re.escape(trace._get_relative_file_path(__file__)),
    )

    assert re.search(expected, io.fetch_output()) is not None 
Example 3
Project: unicorn-hat-hd   Author: pimoroni   File: test_setup.py    License: MIT License 5 votes vote down vote up
def test_invalid_text_colour():
    """Test valid text colour."""
    sys.modules['spidev'] = mock.MagicMock()
    import unicornhathd
    unicornhathd.setup()

    with pytest.raises(ValueError):
        unicornhathd.set_pixel(0, 0, "Octarine") 
Example 4
Project: django-rest-polymorphic   Author: apirobot   File: test_serializers.py    License: MIT License 5 votes vote down vote up
def test_model_serializer_mapping_is_none(self):
        class EmptyPolymorphicSerializer(PolymorphicSerializer):
            pass

        with pytest.raises(ImproperlyConfigured) as excinfo:
            EmptyPolymorphicSerializer()

        assert str(excinfo.value) == (
            '`EmptyPolymorphicSerializer` is missing a '
            '`EmptyPolymorphicSerializer.model_serializer_mapping` attribute'
        ) 
Example 5
Project: django-rest-polymorphic   Author: apirobot   File: test_serializers.py    License: MIT License 5 votes vote down vote up
def test_resource_type_field_name_is_not_string(self, mocker):
        class NotStringPolymorphicSerializer(PolymorphicSerializer):
            model_serializer_mapping = mocker.MagicMock
            resource_type_field_name = 1

        with pytest.raises(ImproperlyConfigured) as excinfo:
            NotStringPolymorphicSerializer()

        assert str(excinfo.value) == (
            '`NotStringPolymorphicSerializer.resource_type_field_name` must '
            'be a string'
        ) 
Example 6
Project: mutatest   Author: EvanKepner   File: test_api.py    License: MIT License 5 votes vote down vote up
def test_filter_codes_ValueError():
    """Setting invalid filter codes on the Genome raises a ValueError."""
    with pytest.raises(ValueError):
        genome = Genome()
        genome.filter_codes = ("asdf",) 
Example 7
Project: mutatest   Author: EvanKepner   File: test_api.py    License: MIT License 5 votes vote down vote up
def test_targets_TypeError():
    """Targets with a NoneType source_file raises a TypeError."""
    with pytest.raises(TypeError):
        genome = Genome()
        _ = genome.targets 
Example 8
Project: mutatest   Author: EvanKepner   File: test_api.py    License: MIT License 5 votes vote down vote up
def test_covered_targets_source_file_TypeError():
    """Targets with a NoneType source_file raises a TypeError."""
    with pytest.raises(TypeError):
        genome = Genome()
        _ = genome.covered_targets 
Example 9
Project: mutatest   Author: EvanKepner   File: test_api.py    License: MIT License 5 votes vote down vote up
def test_covered_targets_coverage_file_TypeError(binop_file):
    """Targets with a NoneType coverage_file but valid source_file raises a TypeError."""
    with pytest.raises(TypeError):
        genome = Genome(binop_file)
        genome.coverage_file = None
        _ = genome.covered_targets 
Example 10
Project: mutatest   Author: EvanKepner   File: test_api.py    License: MIT License 5 votes vote down vote up
def test_mutate_MutationException(binop_file, mock_LocIdx):
    """Mutate with an invalid operation raises a mutation exception."""
    genome = Genome(binop_file)
    with pytest.raises(MutationException):
        _ = genome.mutate(target_idx=mock_LocIdx, mutation_op="badoperation", write_cache=False) 
Example 11
Project: mutatest   Author: EvanKepner   File: test_api.py    License: MIT License 5 votes vote down vote up
def test_mutate_ValueError_target(binop_file, mock_LocIdx):
    """Mutate with a target_idx not in the targets raises a ValueError."""
    genome = Genome(binop_file)
    with pytest.raises(ValueError):
        _ = genome.mutate(target_idx=mock_LocIdx, mutation_op=ast.Div, write_cache=False) 
Example 12
Project: mutatest   Author: EvanKepner   File: test_api.py    License: MIT License 5 votes vote down vote up
def test_init_GenomeGroup_raise_TypeError():
    """Initialization with an non-file non-dir raises a TypeError."""
    with pytest.raises(TypeError):
        _ = GenomeGroup("somethingrandom") 
Example 13
Project: mutatest   Author: EvanKepner   File: test_api.py    License: MIT License 5 votes vote down vote up
def test_GenomeGroup_folder_exception():
    """Invalid folders raise a type error."""
    with pytest.raises(TypeError):
        ggrp = GenomeGroup()
        ggrp.add_folder("somethingrandom") 
Example 14
Project: mutatest   Author: EvanKepner   File: test_api.py    License: MIT License 5 votes vote down vote up
def test_GenomeGroup_key_TypeError(key, binop_file):
    """Values that are not Path type keys raise a type error."""
    with pytest.raises(TypeError):
        ggrp = GenomeGroup()
        ggrp[key] = Genome(binop_file) 
Example 15
Project: mutatest   Author: EvanKepner   File: test_api.py    License: MIT License 5 votes vote down vote up
def test_GenomeGroup_value_TypeError(value, binop_file):
    """Non-Genome values raise a type error."""
    with pytest.raises(TypeError):
        ggrp = GenomeGroup()
        ggrp[binop_file] = value 
Example 16
Project: mutatest   Author: EvanKepner   File: test_cli.py    License: MIT License 5 votes vote down vote up
def test_get_src_location_error(monkeypatch):
    """Mock a missing package scenario, FileNotFoundError is raised."""

    def mock_find_packages(*args, **kwargs):
        return []

    # because I use: from setuptools import find_packages
    # therefore the mock of the imported instance
    monkeypatch.setattr(mutatest.cli, "find_packages", mock_find_packages)

    with pytest.raises(FileNotFoundError):
        _ = cli.get_src_location() 
Example 17
Project: mutatest   Author: EvanKepner   File: test_cli.py    License: MIT License 5 votes vote down vote up
def test_get_src_location_missing_file(monkeypatch):
    """If a missing file is passed an exception is raised."""

    with pytest.raises(FileNotFoundError):
        _ = cli.get_src_location(Path("/tmp/filethatdoesnotexist/sdf/asdf/23rjsdfu.py")) 
Example 18
Project: mutatest   Author: EvanKepner   File: test_cli.py    License: MIT License 5 votes vote down vote up
def test_exception_raised(mock_trial_results):
    """Mock trials results should have 1 survivor"""
    with pytest.raises(SurvivingMutantException):
        cli.exception_processing(1, mock_trial_results) 
Example 19
Project: mutatest   Author: EvanKepner   File: test_cli.py    License: MIT License 5 votes vote down vote up
def test_read_config_key_error(mock_ini_file):
    """Ensure KeyError is raised if missing section from config file."""
    with pytest.raises(KeyError):
        _ = cli.read_ini_config(mock_ini_file.ini_file, sections=["missing"]) 
Example 20
Project: mutatest   Author: EvanKepner   File: test_cli.py    License: MIT License 5 votes vote down vote up
def test_syserror_negative_n_and_rseed(n, i):
    """Property:
        1. Given a negative n-value a SystemExit is raised.
    """
    with pytest.raises(SystemExit):
        _ = cli.cli_args([n, f"{i}"]) 
Example 21
Project: mutatest   Author: EvanKepner   File: test_filters.py    License: MIT License 5 votes vote down vote up
def test_invalid_code():
    """Invalid codes will raise a TypeError."""
    ccf = CategoryCodeFilter()
    with pytest.raises(ValueError):
        ccf.add_code("asdf") 
Example 22
Project: mutatest   Author: EvanKepner   File: test_cache.py    License: MIT License 5 votes vote down vote up
def test_check_cache_invalidation_mode_error(monkeypatch):
    """Ensure OS error is raised when SOURCE_DATE_EPOCH is set."""
    monkeypatch.setenv("SOURCE_DATE_EPOCH", "testvalue")

    with pytest.raises(EnvironmentError):
        check_cache_invalidation_mode() 
Example 23
Project: mutatest   Author: EvanKepner   File: test_cache.py    License: MIT License 5 votes vote down vote up
def test_get_cache_file_loc_invalid():
    """Empty string will raise a ValueError."""
    with pytest.raises(ValueError):
        _ = get_cache_file_loc(src_file="") 
Example 24
Project: mutatest   Author: EvanKepner   File: test_cache.py    License: MIT License 5 votes vote down vote up
def test_get_cache_file_loc_link_exception(monkeypatch):
    """Symlink existing cache files raise FileExistsError."""

    def mock_islink(x):
        return True

    monkeypatch.setattr(os.path, "islink", mock_islink)

    with pytest.raises(FileExistsError):
        _ = get_cache_file_loc("symlink.py") 
Example 25
Project: mutatest   Author: EvanKepner   File: test_cache.py    License: MIT License 5 votes vote down vote up
def test_get_cache_file_loc_not_file(monkeypatch):
    """Irregular existing cache files will raise FileExistsError"""

    def mock_exists(x):
        return True

    def mock_isfile(x):
        return False

    monkeypatch.setattr(os.path, "exists", mock_exists)
    monkeypatch.setattr(os.path, "isfile", mock_isfile)

    with pytest.raises(FileExistsError):
        _ = get_cache_file_loc("nonregularfile.py") 
Example 26
Project: mutatest   Author: EvanKepner   File: test_run.py    License: MIT License 5 votes vote down vote up
def test_clean_trial_exception(binop_file, monkeypatch):
    """Ensure clean trial raises a BaselineTestException on non-zero returncode"""

    def mock_subprocess_run(*args, **kwargs):
        return CompletedProcess(args="pytest", returncode=1)

    monkeypatch.setattr(subprocess, "run", mock_subprocess_run)

    with pytest.raises(BaselineTestException):
        run.clean_trial(binop_file.parent, ["pytest"]) 
Example 27
Project: mutatest   Author: EvanKepner   File: test_run.py    License: MIT License 5 votes vote down vote up
def test_get_mutation_sample_locations_ValueError(nloc, mock_LocIdx):
    """Zero and negative integer sample sizes raise a value error."""
    ggt = [GenomeGroupTarget(Path("src.py"), mock_LocIdx)]

    with pytest.raises(ValueError):
        _ = run.get_mutation_sample_locations(ggt, nloc) 
Example 28
Project: libTLDA   Author: wmkouw   File: test_util.py    License: MIT License 5 votes vote down vote up
def test_regularize_matrix():
    """Test whether function regularizes matrix correctly."""
    # Generate test matrix
    A = rnd.randn(3)

    # Check for inappropriate input argument
    with pytest.raises(ValueError):
        regularize_matrix(A, a=-1.0) 
Example 29
Project: clikit   Author: sdispater   File: test_args_format_builder.py    License: MIT License 5 votes vote down vote up
def test_add_command_fails_if_option_with_same_long_name_as_other_command_option(
    builder,
):
    builder.add_option(CommandOption("option", "a"))

    with pytest.raises(CannotAddOptionException):
        builder.add_command_option(CommandOption("option", "b")) 
Example 30
Project: clikit   Author: sdispater   File: test_args_format_builder.py    License: MIT License 5 votes vote down vote up
def test_add_command_fails_if_option_with_same_long_name_as_other_option(builder):
    builder.add_option(Option("option", "a"))

    with pytest.raises(CannotAddOptionException):
        builder.add_command_option(CommandOption("option", "b"))