Ejemplo n.º 1
0
 def test_config_exception_is_raised_if_trouble_reading_file(
         self, mock_toml: mock.MagicMock):
     mock_toml.side_effect = toml.TomlDecodeError("Bad TOML!", "foo", 42)
     with self.assertRaisesRegex(
             types.ConfigException,
             "Error reading configuration file: Bad TOML!"):
         config.load_config_from_path(self.data_dir)
Ejemplo n.º 2
0
def test_read_config_file_raises(mocker, monkeypatch):
    """Handle exceptions while reading pyproject.toml/setup.cfg, if any."""
    toml_error = toml.TomlDecodeError("toml error", doc="foo", pos=0)
    os_error = OSError("os error")
    mock_parse_pyproject_toml = mocker.Mock()
    mock_parse_pyproject_toml.side_effect = (toml_error, os_error)
    monkeypatch.setattr(config, "parse_pyproject_toml",
                        mock_parse_pyproject_toml)
    cfg_error = configparser.ParsingError("cfg parsing error")
    mock_parse_setup_cfg = mocker.Mock()
    mock_parse_setup_cfg.side_effect = (cfg_error, )
    monkeypatch.setattr(config, "parse_setup_cfg", mock_parse_setup_cfg)

    error_msg = "Error reading configuration file: toml error"
    with pytest.raises(click.FileError, match=error_msg):
        config.read_config_file({}, "foo", "pyproject.toml")

    error_msg = "Error reading configuration file: os error"
    with pytest.raises(click.FileError, match=error_msg):
        config.read_config_file({}, "foo", "pyproject.toml")

    error_msg = (
        "Error reading configuration file: Source contains parsing errors: "
        "'cfg parsing error'")
    with pytest.raises(click.FileError, match=error_msg):
        config.read_config_file({}, "foo", "setup.cfg")
Ejemplo n.º 3
0
 def parse_cargo_toml(self, dir_in_crate, tf):
     try:
         ti = tf.getmember(os.path.join(dir_in_crate, 'Cargo.toml'))
         assert ti.isfile()
     except KeyError:
         return {}
     except EOFError:
         return {}
     with tf.extractfile(ti) as toml_file:
         try:
             return toml.loads(toml_file.read().decode())
         except toml.TomlDecodeError:
             return {}
         except Exception as e:
             raise toml.TomlDecodeError('Failed unTOMLing Cargo.toml from {}'.format(tf.name))
Ejemplo n.º 4
0
def check(path=None, ppt='pyproject.toml'):
    if not path:
        f = ins.getouterframes(ins.currentframe(), 2)[2].filename
        path = os.path.join(os.path.dirname(os.path.dirname(f)), ppt)
    try:
        data = toml.load(path)
    except FileNotFoundError:
        raise FileNotFoundError(f"Path to {ppt} is not \
set or is incorrect, and default path didn't work. Broken filepath: {path}")
    except toml.TomlDecodeError:
        raise toml.TomlDecodeError(f'Your {ppt} is configured improperly.')
    try:
        data['tool']['django']
    except KeyError:
        raise KeyError(f"Your {ppt} doesn't have a [tool.django] section.")
    return data, path
Ejemplo n.º 5
0
def test_validate_pyproject_toml_invalid_toml(mocker):
    mocker.patch(
        'connect.cli.plugins.project.extension.validations.os.path.isfile',
        return_value=True,
    )
    mocker.patch(
        'connect.cli.plugins.project.extension.validations.toml.load',
        side_effect=toml.TomlDecodeError('error', 'error', 0),
    )

    result = validate_pyproject_toml(mocker.MagicMock(), 'fake_dir', None)

    assert isinstance(result, ValidationResult)
    assert result.must_exit is True
    assert len(result.items) == 1
    item = result.items[0]
    assert isinstance(item, ValidationItem)
    assert item.level == 'ERROR'
    assert 'The extension project descriptor file *pyproject.toml* is not valid.' in item.message
    assert item.file == 'fake_dir/pyproject.toml'
Ejemplo n.º 6
0
def test_read_pyproject_toml_raises(mocker, monkeypatch):
    """Handle expected exceptions while reading pyproject.toml, if any."""
    with pytest.raises(AssertionError, match="Invalid parameter type passed"):
        config.read_pyproject_toml({}, "foo", True)

    with pytest.raises(AssertionError, match="Invalid parameter type passed"):
        config.read_pyproject_toml({}, "foo", 123)

    toml_error = toml.TomlDecodeError("toml error", doc="foo", pos=0)
    os_error = OSError("os error")
    mock_parse_pyproject_toml = mocker.Mock()
    mock_parse_pyproject_toml.side_effect = (toml_error, os_error)
    monkeypatch.setattr(config, "parse_pyproject_toml",
                        mock_parse_pyproject_toml)

    error_msg = "Error reading configuration file: toml error"
    with pytest.raises(click.FileError, match=error_msg):
        config.read_pyproject_toml({}, "foo", "bar")

    error_msg = "Error reading configuration file: os error"
    with pytest.raises(click.FileError, match=error_msg):
        config.read_pyproject_toml({}, "foo", "bar")
Ejemplo n.º 7
0
            with patch("subprocess.call") as call_mock, patch("sys.exit") as exit_mock:
                helpers.execute_script("ls")
                call_mock.assert_called_with("ls", shell=True)
        with it("should execute a script with static arguments"):
            with patch("subprocess.call") as call_mock, patch("sys.exit") as exit_mock:
                helpers.execute_script("ls -l")
                call_mock.assert_called_with("ls -l", shell=True)
        with it(
            "should execute a script with dynamic arguments and escape them if necessary"
        ):
            with patch("subprocess.call") as call_mock, patch("sys.exit") as exit_mock:
                helpers.execute_script("ls", ["-l", "somefile; rm -rf ~"])
                call_mock.assert_called_with("ls -l 'somefile; rm -rf ~'", shell=True)
    with context("#read_config"):
        with it("should exit if the config is not present"):
            with patch("os.path.isfile", return_value=False) as isfile_mock, patch(
                "sys.exit"
            ) as exit_mock, patch("toml.load") as toml_mock:
                helpers.read_config()
                args, kwargs = exit_mock.call_args
                assert args[0] == 1
        with it("should exit if config is present but malformed"):
            with patch("os.path.isfile", return_value=True) as isfile_mock, patch(
                "sys.exit"
            ) as exit_mock, patch(
                "toml.load", side_effect=toml.TomlDecodeError("Error", "", 0)
            ) as toml_mock:
                helpers.read_config()
                args, kwargs = exit_mock.call_args
                assert args[0] == 1